[GH-ISSUE #4067] [Engine] Qwen3.8 native video: token/PLE validation and reference patch #1762

Closed
opened 2026-11-04 01:53:50 +07:00 by bsakaguchi · 4 comments
Owner

Originally created by @RAFOLIE on GitHub (Oct 25, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/4067

Area

[Engine] (server, vision reader and inference engine)

What do you want to do?

Send a short video from an OpenAI-compatible chat client to Qwen3.8-Flash-Next, retaining temporal-pair encoding, video token IDs and timestamps through inference.

I am sharing an AI-assisted, experimental local implementation and its measured results for scope discussion. Maintainers are welcome to inspect, adapt or reimplement useful parts under this repository's MIT license. This is reference material, not a claim that the implementation is ready to merge.

There is already video-input work in #1609, with related work/discussion in #2023 and the closed #2421. This issue supplies additional CUDA evidence and a complete patch for that effort, particularly around preserving video_pad IDs for PLE. I have not run those PR branches and am not reporting a reproduced bug in them or claiming this is the first video implementation.

What do you do today instead?

My earlier workaround sampled a video into separate still-image inputs. The attached prototype instead sends pairs of frames through the existing temporal encoder and preserves their video representation in the engine. Audio is not processed. PDF conversion is separate and is outside this patch.

Reference implementation

Base: v0.2.4.2, commit dfa3f4025c9f1bc4af8cee201b20a2d223061813. The patch contains six implementation files and three test files. No model weights or llama.cpp dependency pin were changed.

  • Opt-in video.enabled, restricted to the verified qwen4exp architecture. Both rebuilt binaries must confirm support: reader VIDEO_PAIR1, engine native_video=1.
  • Chat Completions accepts inline base64 video_url content. Remote video URLs, local video paths and video input through the other API formats are not supported by this prototype.
  • FFmpeg/ffprobe decode and uniformly sample the entire clip, including both ends. Default sampling is approximately 2 fps, with real presentation timestamps. An odd last frame is duplicated.
  • Each pair is jointly encoded through the existing pinned mtmd implementation. The reader's new ENCV <frame0> <frame1> <output> protocol takes two decoded frames; it is not wire-compatible with whole-video ENCV proposals. The original image ENC command remains available.
  • Each pair expands into a timestamp followed by a vision group containing video_pad (248057) tokens. Original IDs remain available to PLE. The position helper handles per-group [1,H,W] M-RoPE grids and mixed image/video order.
  • Limits include 64 MiB per clip, at most two videos and 64 pairs / 16,384 video tokens per request, and bounded decoding/cancellation. The default 256-token pair budget is deliberately small. Clips exceeding the pair budget are rejected rather than silently dropping their tail. The 300-second absolute duration cap does not mean a 300-second clip fits at the default 2 fps.

The token/timestamp/position choices were checked against the pinned model configuration, Qwen3-VL processor, and Qwen4Exp implementation. This source comparison is not a numerical parity result.

How to try the prototype

Apply the three patch parts below in numbered order to the base commit, then rebuild both strata and strata-vision using the repository's build instructions. Keep the existing pinned llama.cpp revision 3cf03257f219afbe7334045ff7c6a06ac68c627d. FFmpeg and ffprobe must be on the server's PATH.

Point an existing working server configuration at the rebuilt engine and vision reader, then merge this fragment into that configuration (it is not a complete configuration):

{
  "arch": "qwen4exp",
  "video": {
    "enabled": true,
    "fps": 2,
    "tokens_per_pair": 256,
    "max_pairs": 64
  }
}

The server adds the native-video flags to its subprocesses. Confirm that /health advertises video support before sending a request. The final local inference checks used --vram-reserve-mib 3072; that is a tested setting for this machine, not a universal recommendation.

Example Chat Completions content, with a placeholder that must be replaced by an actual clip's base64 data:

[
  {"type": "text", "text": "Describe the events in this video in order."},
  {"type": "video_url", "video_url": {"url": "data:video/mp4;base64,<BASE64_DATA>"}}
]

Validation: passed

Environment: Windows x64, RTX 4090 24 GB, Ryzen 9 5950X, 64 GB RAM; CUDA 13.0.48, MSVC 19.44.35229. Model: Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S with BF16 mmproj. Context configured to 131,072, int8 KV, speculative depth 4. Setting a context limit is not evidence of testing that full length.

  • Both Release CUDA SM89 binaries compiled and were used for the inference checks. All nine exported source files match the source recorded for those builds.

  • Relevant Python tests: 455 cases, 451 passed, 4 skipped. Commands below are the executed suite commands with the local Python executable paths normalized to python. The decoder suite used an environment with FFmpeg/ffprobe available.

    python -m unittest serve.test_server -q
    # Ran 352: 349 passed, 3 skipped (Windows signal tests)
    python -m unittest serve.test_frontend serve.test_responses -q
    # Ran 66: 65 passed, 1 skipped (optional jsonschema absent)
    python -m unittest serve.test_native_video_api -q
    # Ran 24: all passed
    python -m unittest serve.test_video -q
    # Ran 13: all passed
    
  • The standalone tools/vision/native_video_positions_test.cpp compiled with MSVC and ran successfully: native video/image M-RoPE position tests passed. It checks text/image positions, video IDs and positions, mixed spans and malformed inputs. It is one additional executable check, not included in the Python count.

  • Actual GPU reader comparison: ordinary image A and duplicated temporal pair AA produced bit-identical embeddings. AA versus AB relative L2 was 0.77521067; AB versus BA was 0.82118547. All outputs were finite, 252 tokens, grid 12x21, embedding width 2560. This demonstrates that the second frame and its ordering affect encoding; it does not establish reference-encoder parity or video-answer accuracy.

  • A private 15.04-second, 720x1280, 24 fps clip produced 32 sampled frames / 16 pairs / 4,032 video tokens. Normal and streaming Chat Completions completed. The final streaming run, with 3,072 MiB VRAM reserve, returned reasoning, nonempty answer content and [DONE] (4,190 input / 155 output tokens, 7.984 seconds). This is a single observed run, not a speedup benchmark.

  • A separate 34,554-token synthetic text input completed with reasoning and an answer using the same reserve. It was not a replay of the earlier failing client request.

  • The full exported patch passed git apply --check against files from the stated base. Applying it reproduced all nine local source files after line-ending normalization. This check does not establish applicability to current main.

Validation: failed / observed limitations

An earlier configuration with an explicit 0 MiB VRAM reserve reached zero request-time VRAM headroom and watchdog exit on a roughly 34K-token client request. Later checks used 3,072 MiB reserve. The successful synthetic input does not establish that every long-request failure is fixed. A Windows commit-memory warning was also observed.

The video answers sometimes omit events or misidentify objects. No accuracy benchmark was performed. The existing text/image tests and duplicate-frame comparison passed; exhaustive byte-identical regression coverage of all default behavior has not been established.

Validation: not run

HIP, SYCL, Metal and Linux builds; other GPUs/models; full Transformers embedding parity; long-video quality; full 128K stress; audio; native PDF; side-by-side comparison against the related PR branches. Cross-backend validation remains necessary before an implementation can be proposed for merging.

Complete source patch

Patch part 1/3 · Patch part 2/3 · Patch part 3/3

The three numbered comments contain the complete unified diff, including the five newly added files. Concatenate only the fenced diff contents in order as UTF-8 with LF endings, preserving the final newline, then use git apply --check native-video.patch followed by git apply native-video.patch in a disposable checkout of the base revision.

Full patch: 95,134 bytes, SHA256:

24f5c4d051667dc14070deb1471deda94c013932fdcdc7f0d4d5371c72aea880

Only source and test code is shared here; the private clip, model files, binaries, crash dump and raw local logs are excluded.

Would preserving video token IDs through PLE and adding these temporal-pair checks be useful to the existing video-input effort? Please feel free to take only the useful pieces; I am sharing the implementation through this issue so maintainers can decide the appropriate integration and scope.

Originally created by @RAFOLIE on GitHub (Oct 25, 2026). Original GitHub issue: https://github.com/Niko1221/Strata/issues/4067 ### Area [Engine] (server, vision reader and inference engine) ### What do you want to do? Send a short video from an OpenAI-compatible chat client to Qwen3.8-Flash-Next, retaining temporal-pair encoding, video token IDs and timestamps through inference. I am sharing an **AI-assisted, experimental local implementation and its measured results** for scope discussion. Maintainers are welcome to inspect, adapt or reimplement useful parts under this repository's MIT license. This is reference material, not a claim that the implementation is ready to merge. There is already video-input work in #1609, with related work/discussion in #2023 and the closed #2421. This issue supplies additional CUDA evidence and a complete patch for that effort, particularly around preserving `video_pad` IDs for PLE. I have **not run those PR branches** and am not reporting a reproduced bug in them or claiming this is the first video implementation. ### What do you do today instead? My earlier workaround sampled a video into separate still-image inputs. The attached prototype instead sends pairs of frames through the existing temporal encoder and preserves their video representation in the engine. Audio is not processed. PDF conversion is separate and is outside this patch. ### Reference implementation Base: **v0.2.4.2**, commit `dfa3f4025c9f1bc4af8cee201b20a2d223061813`. The patch contains six implementation files and three test files. No model weights or llama.cpp dependency pin were changed. - Opt-in `video.enabled`, restricted to the verified `qwen4exp` architecture. Both rebuilt binaries must confirm support: reader `VIDEO_PAIR1`, engine `native_video=1`. - Chat Completions accepts inline base64 `video_url` content. Remote video URLs, local video paths and video input through the other API formats are not supported by this prototype. - FFmpeg/ffprobe decode and uniformly sample the entire clip, including both ends. Default sampling is approximately 2 fps, with real presentation timestamps. An odd last frame is duplicated. - Each pair is jointly encoded through the existing pinned mtmd implementation. The reader's new `ENCV <frame0> <frame1> <output>` protocol takes two decoded frames; it is **not wire-compatible** with whole-video ENCV proposals. The original image `ENC` command remains available. - Each pair expands into a timestamp followed by a vision group containing `video_pad` (`248057`) tokens. Original IDs remain available to PLE. The position helper handles per-group `[1,H,W]` M-RoPE grids and mixed image/video order. - Limits include 64 MiB per clip, at most two videos and 64 pairs / 16,384 video tokens per request, and bounded decoding/cancellation. The default 256-token pair budget is deliberately small. Clips exceeding the pair budget are rejected rather than silently dropping their tail. The 300-second absolute duration cap does **not** mean a 300-second clip fits at the default 2 fps. The token/timestamp/position choices were checked against the pinned [model configuration](https://huggingface.co/Qwen/Qwen3.8-Flash-Next/blob/de4b8e4d43b917e7706784d8bb445c9af86a3540/config.json), [Qwen3-VL processor](https://github.com/huggingface/transformers/blob/50e35cc0ca18ec19b80653690de553e6decf74f5/src/transformers/models/qwen3_vl/processing_qwen3_vl.py), and [Qwen4Exp implementation](https://github.com/huggingface/transformers/blob/50e35cc0ca18ec19b80653690de553e6decf74f5/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py). This source comparison is not a numerical parity result. ### How to try the prototype Apply the three patch parts below **in numbered order** to the base commit, then rebuild both `strata` and `strata-vision` using the repository's build instructions. Keep the existing pinned llama.cpp revision `3cf03257f219afbe7334045ff7c6a06ac68c627d`. FFmpeg and ffprobe must be on the server's PATH. Point an existing working server configuration at the rebuilt engine and vision reader, then merge this fragment into that configuration (it is not a complete configuration): ```json { "arch": "qwen4exp", "video": { "enabled": true, "fps": 2, "tokens_per_pair": 256, "max_pairs": 64 } } ``` The server adds the native-video flags to its subprocesses. Confirm that `/health` advertises video support before sending a request. The final local inference checks used `--vram-reserve-mib 3072`; that is a tested setting for this machine, not a universal recommendation. Example Chat Completions content, with a placeholder that must be replaced by an actual clip's base64 data: ```json [ {"type": "text", "text": "Describe the events in this video in order."}, {"type": "video_url", "video_url": {"url": "data:video/mp4;base64,<BASE64_DATA>"}} ] ``` ### Validation: passed Environment: Windows x64, RTX 4090 24 GB, Ryzen 9 5950X, 64 GB RAM; CUDA 13.0.48, MSVC 19.44.35229. Model: `Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S` with BF16 mmproj. Context configured to 131,072, int8 KV, speculative depth 4. Setting a context limit is not evidence of testing that full length. - Both Release CUDA SM89 binaries compiled and were used for the inference checks. All nine exported source files match the source recorded for those builds. - Relevant Python tests: **455 cases, 451 passed, 4 skipped**. Commands below are the executed suite commands with the local Python executable paths normalized to `python`. The decoder suite used an environment with FFmpeg/ffprobe available. ```text python -m unittest serve.test_server -q # Ran 352: 349 passed, 3 skipped (Windows signal tests) python -m unittest serve.test_frontend serve.test_responses -q # Ran 66: 65 passed, 1 skipped (optional jsonschema absent) python -m unittest serve.test_native_video_api -q # Ran 24: all passed python -m unittest serve.test_video -q # Ran 13: all passed ``` - The standalone `tools/vision/native_video_positions_test.cpp` compiled with MSVC and ran successfully: `native video/image M-RoPE position tests passed`. It checks text/image positions, video IDs and positions, mixed spans and malformed inputs. It is one additional executable check, not included in the Python count. - Actual GPU reader comparison: ordinary image A and duplicated temporal pair AA produced **bit-identical** embeddings. AA versus AB relative L2 was `0.77521067`; AB versus BA was `0.82118547`. All outputs were finite, 252 tokens, grid 12x21, embedding width 2560. This demonstrates that the second frame and its ordering affect encoding; it does not establish reference-encoder parity or video-answer accuracy. - A private 15.04-second, 720x1280, 24 fps clip produced 32 sampled frames / 16 pairs / 4,032 video tokens. Normal and streaming Chat Completions completed. The final streaming run, with 3,072 MiB VRAM reserve, returned reasoning, nonempty answer content and `[DONE]` (4,190 input / 155 output tokens, 7.984 seconds). This is a single observed run, not a speedup benchmark. - A separate 34,554-token **synthetic text** input completed with reasoning and an answer using the same reserve. It was not a replay of the earlier failing client request. - The full exported patch passed `git apply --check` against files from the stated base. Applying it reproduced all nine local source files after line-ending normalization. This check does not establish applicability to current main. ### Validation: failed / observed limitations An earlier configuration with an explicit 0 MiB VRAM reserve reached zero request-time VRAM headroom and watchdog exit on a roughly 34K-token client request. Later checks used 3,072 MiB reserve. The successful synthetic input does not establish that every long-request failure is fixed. A Windows commit-memory warning was also observed. The video answers sometimes omit events or misidentify objects. No accuracy benchmark was performed. The existing text/image tests and duplicate-frame comparison passed; exhaustive byte-identical regression coverage of all default behavior has not been established. ### Validation: not run HIP, SYCL, Metal and Linux builds; other GPUs/models; full Transformers embedding parity; long-video quality; full 128K stress; audio; native PDF; side-by-side comparison against the related PR branches. Cross-backend validation remains necessary before an implementation can be proposed for merging. ### Complete source patch [Patch part 1/3](https://github.com/Niko1221/Strata/issues/4067#issuecomment-6394891438) · [Patch part 2/3](https://github.com/Niko1221/Strata/issues/4067#issuecomment-6394891718) · [Patch part 3/3](https://github.com/Niko1221/Strata/issues/4067#issuecomment-6394892031) The three numbered comments contain the complete unified diff, including the five newly added files. Concatenate only the fenced diff contents in order as UTF-8 with LF endings, preserving the final newline, then use `git apply --check native-video.patch` followed by `git apply native-video.patch` in a disposable checkout of the base revision. Full patch: **95,134 bytes**, SHA256: ```text 24f5c4d051667dc14070deb1471deda94c013932fdcdc7f0d4d5371c72aea880 ``` Only source and test code is shared here; the private clip, model files, binaries, crash dump and raw local logs are excluded. Would preserving video token IDs through PLE and adding these temporal-pair checks be useful to the existing video-input effort? Please feel free to take only the useful pieces; I am sharing the implementation through this issue so maintainers can decide the appropriate integration and scope.
Author
Owner

@RAFOLIE commented on GitHub (Oct 25, 2026):

Reference patch — part 1/3

Save the fenced diff as native-video-part-1.patch (UTF-8, LF). Concatenate the parts in numbered order before applying. This is part of the AI-assisted local prototype described in the issue.

Part SHA256: 27b7533f072c342ae1629621a441a1305494a944f1df50ced0bdb85d7363f205

diff --git a/serve/frontend.py b/serve/frontend.py
index 53f2b4599d08f1a2ca2b056b5d6380c708341810..1412898f4978e9562060ec71ce59b839995f9ff4 100644
--- a/serve/frontend.py
+++ b/serve/frontend.py
@@ -128,6 +128,7 @@ def _text_of(content) -> str:
 
 
 IMAGE_PARTS = ("image_url", "input_image", "image")
+VIDEO_PARTS = ("video_url",)
 
 # Thinking levels.  The model's template knows low, medium and xhigh (its default; "high" means xhigh), and
 # enable_thinking=false for none.  Clients spell these many ways; everything maps onto those four.
@@ -182,6 +183,20 @@ def _has_image(content) -> bool:
     return isinstance(content, list) and any(isinstance(p, dict) and p.get("type") in IMAGE_PARTS for p in content)
 
 
+def _has_video(content) -> bool:
+    return isinstance(content, list) and any(isinstance(p, dict) and p.get("type") in VIDEO_PARTS for p in content)
+
+
+def _video_source(part: dict) -> str:
+    """ZCode/OpenAI-compatible inline video; never turn a video into image parts."""
+    value = part.get("video_url")
+    if isinstance(value, dict):
+        value = value.get("url")
+    if not isinstance(value, str) or not value.startswith("data:video/") or ";base64," not in value:
+        raise ValueError("video_url.url must be an inline data:video/*;base64 URL; remote URLs and local paths are not supported")
+    return value
+
+
 def _image_source(part: dict) -> str:
     """An image part's source as one string: a data: URL, an http(s) URL or a local file path.
     OpenAI: {"type": "image_url", "image_url": {"url": ...}} (or "image_url": "..."), Responses-style
@@ -201,7 +216,7 @@ def _image_source(part: dict) -> str:
 def _parts_of(content):
     """Message content for the template: a string when there is no image (unchanged behaviour), otherwise the
     template's list form - text items and image items, in order - whose image items carry their source."""
-    if not _has_image(content):
+    if not _has_image(content) and not _has_video(content):
         return _text_of(content)
     items = []
     for part in content:
@@ -209,6 +224,8 @@ def _parts_of(content):
             continue
         if part.get("type") in IMAGE_PARTS:
             items.append({"type": "image", "source": _image_source(part)})
+        elif part.get("type") in VIDEO_PARTS:
+            items.append({"type": "video", "source": _video_source(part)})
         elif part.get("type") in TEXT_PARTS and "text" in part:
             items.append({"type": "text", "text": part.get("text", "")})
     return items
@@ -240,6 +257,8 @@ def _check_parts(content, path: str, kinds):
             if out is content:
                 out = list(content)
             out[j] = {"type": "text", "text": part.get("refusal") or ""}
+        elif kind in VIDEO_PARTS and kind not in kinds:
+            raise ValueError(f"{path}[{j}]: native video_url input is supported only by Chat Completions")
         elif kind not in kinds:
             LOGGER.debug("%s[%d].type: content part of type %r is not read by this server; left out of the prompt",
                          path, j, kind)
@@ -253,6 +272,12 @@ def images_of(messages: list[dict]) -> list[str]:
             for item in m["content"] if item.get("type") == "image"]
 
 
+def media_of(messages: list[dict]) -> list[dict]:
+    """Canonical image/video items in the exact order their template markers occur."""
+    return [item for m in messages if isinstance(m.get("content"), list)
+            for item in m["content"] if item.get("type") in ("image", "video")]
+
+
 # #537: a literal <think> / </think> inside a message's text is plain text, not the model's reasoning markers.  The
 # tokenizer matches those two strings as their special tokens everywhere (GGUF token type 4, as llama.cpp does), so
 # a user quoting "</think>" used to hand the model a real end-of-reasoning token.  Before the template is rendered
@@ -548,8 +573,10 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:
             role = "system"
         # an image is read in a user, tool or assistant message; the system prompt takes text only, as _text_of reads
         images = role in ("user", "tool", "assistant")
+        if _has_video(m.get("content")) and not images:
+            raise ValueError(f"messages[{i}]: video input is supported only in user, assistant, or tool messages")
         content = _check_parts(m.get("content"), f"messages[{i}].content",
-                               TEXT_PARTS + IMAGE_PARTS if images else TEXT_PARTS)
+                               TEXT_PARTS + IMAGE_PARTS + VIDEO_PARTS if images else TEXT_PARTS)
         out = {"role": role, "content": _parts_of(content) if images else _text_of(content)}
         if m.get("reasoning_content"):
             out["reasoning_content"] = m["reasoning_content"]
diff --git a/serve/server.py b/serve/server.py
index 71a55e1f0f9c8c95239396c2dd18297dee08e6df..2412a66057051b930a6181b9a6336cf2a9a2284d 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -61,7 +61,7 @@ ROOT = Path(__file__).resolve().parents[1]
 sys.path.insert(0, str(ROOT / "tools"))
 sys.path.insert(0, str(ROOT))   # run as a script (run-<model>.bat) as well as a module
 from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthropic_to_messages,  # noqa: E402
-                            forced_call, images_of, literal_tags, mark_think_literals, openai_to_messages,
+                            forced_call, images_of, literal_tags, mark_think_literals, media_of, openai_to_messages,
                             tool_choice_of, unmark_think_literals)
 from serve.mcp import McpCancelled, hub_from_config  # noqa: E402
 from serve import runconfig  # noqa: E402
@@ -87,6 +87,7 @@ from serve import images as images_api  # noqa: E402
 
 IM_END = "<|im_end|>"
 IMAGE_PAD = "<|image_pad|>"
+VIDEO_PAD = "<|video_pad|>"
 
 
 def popen(what: str, args: list, role: str = "engine", **kw):
@@ -2574,6 +2575,36 @@ def vision_start_error(line: str, log=None, code: int | None = None, waited: flo
     return msg
 
 
+def native_video_config(cfg: dict) -> dict | None:
+    """Validate the opt-in Qwen3.8 native two-frame video path before loading weights."""
+    value = cfg.get("video")
+    if value is None:
+        return None
+    if not isinstance(value, dict) or not isinstance(value.get("enabled", False), bool):
+        raise ValueError('"video" must be an object with "enabled": true or false')
+    if not value.get("enabled", False):
+        return None
+    if cfg.get("arch") != "qwen4exp":
+        raise ValueError("native video is supported only for the verified qwen4exp model architecture")
+    if not isinstance(cfg.get("vision"), dict):
+        raise ValueError("native video requires a configured vision encoder")
+    result = {"enabled": True, "fps": 2.0, "max_pairs": 64, "max_duration_seconds": 300.0,
+              "max_bytes": 64 * 1024 * 1024, "tokens_per_pair": 256}
+    limits = {"fps": (0.1, 8.0), "max_pairs": (1, 64), "max_duration_seconds": (0.1, 300.0),
+              "max_bytes": (1, 64 * 1024 * 1024), "tokens_per_pair": (8, 256)}
+    integers = {"max_pairs", "max_bytes", "tokens_per_pair"}
+    for key, (minimum, maximum) in limits.items():
+        if key not in value:
+            continue
+        number = value[key]
+        if (isinstance(number, bool) or not isinstance(number, (int, float))
+                or not math.isfinite(number) or not minimum <= number <= maximum
+                or key in integers and not isinstance(number, int)):
+            raise ValueError(f"video.{key} must be {'an integer' if key in integers else 'a number'} between {minimum} and {maximum}")
+        result[key] = number
+    return result
+
+
 class Vision:
     """The resident image encoder: `strata-vision` (llama.cpp mtmd + the mmproj file) reads `ENC <image> <out>`
     lines and writes each image's embeddings; results are cached by the image's hash, so a conversation that
@@ -2611,6 +2642,8 @@ class Vision:
         self.stopped = True
         self.lock = threading.Lock()
         self.cache: dict[str, tuple[Path, int]] = {}
+        self.native_video = cfg.get("native_video") is True
+        self.supports_video = False
         # opt-in (the vision section's "elastic": true, with the config's "vram_elastic"): the encoder starts with the
         # first picture and stops after elastic_idle_s without one; while it runs, the engine's expert cache keeps
         # elastic_mib of VRAM free for it (Service._vision_up / _vision_idle_down)
@@ -2649,6 +2682,8 @@ class Vision:
             args += ["--max-tokens", str(limit)]
         if cfg.get("min_tokens"):                       # #767: mtmd's image_min_tokens (a hand-edited key)
             args += ["--min-tokens", str(cfg["min_tokens"])]
+        if cfg.get("native_video") is True:
+            args += ["--native-video", "--video-max-tokens", str(cfg.get("video_tokens_per_pair", 256))]
         return args
 
     def _ensure_dir(self):
@@ -2700,6 +2735,10 @@ class Vision:
                 code = getattr(proc, "returncode", None)
             raise RuntimeError(vision_start_error(line, log, code))
         self.stopped = False
+        self.supports_video = "VIDEO_PAIR1" in line.split()
+        if getattr(self, "native_video", False) and not self.supports_video:
+            self.close()
+            raise RuntimeError("native video was enabled, but this vision encoder does not support the VIDEO_PAIR1 protocol")
 
     def _readline(self, timeout: float, what: str) -> str:
         """One line from the encoder, waiting at most `timeout` s (#1317).  On a timeout the encoder is killed, so the
@@ -2874,6 +2913,76 @@ class Vision:
                     self.cache.pop(old)[0].unlink(missing_ok=True)
             return self.cache[key]
 
+    def encode_video(self, source: str | bytes, config: dict, cancel=None, keep=()) -> list[tuple[Path, int, float]]:
+        """Encode real temporal pairs through ENCV; no frame is sent through ENC/image_pad."""
+        from serve.video import VideoCancelled
+        try:
+            return self._encode_video(source, config, cancel, keep)
+        except VideoCancelled:
+            raise ClientGone() from None
+
+    def _encode_video(self, source: str | bytes, config: dict, cancel=None, keep=()) -> list[tuple[Path, int, float]]:
+        if not self.native_video or not self.supports_video:
+            raise ValueError("this vision encoder does not support native video; use a VIDEO_PAIR1 build")
+        from serve.video import prepare_video
+        result = []
+        deadline = time.monotonic() + 240.0
+        self._ensure_dir()
+        with prepare_video(source, config, cancel, directory=self.dir) as video:
+            for pair in video.pairs:
+                if cancel is not None and cancel.is_set():
+                    raise ClientGone()
+                if time.monotonic() >= deadline:
+                    raise ValueError("native video decoding and encoding exceeded 240 seconds; send a shorter clip")
+                digest = hashlib.sha256(b"strata-native-video-pair-v1\0")
+                for frame in (pair.first, pair.second):
+                    data = Path(frame).read_bytes()
+                    digest.update(len(data).to_bytes(8, "little"))
+                    digest.update(data)
+                key = digest.hexdigest()[:32]
+                with self.lock:
+                    if key in self.cache:
+                        self.cache[key] = self.cache.pop(key)
+                        out, tokens = self.cache[key]
+                    else:
+                        if not self.alive() or self.proc.stdin is None:
+                            raise ValueError("the native video reader is not running")
+                        out = self.dir / f"{key}.sve"
+                        # std::quoted in the opt-in reader handles spaces; POSIX
+                        # separators also avoid ambiguous Windows backslash escapes.
+                        paths = [Path(pair.first).resolve().as_posix(), Path(pair.second).resolve().as_posix(),
+                                 out.resolve().as_posix()]
+                        command = "ENCV " + " ".join(json.dumps(p, ensure_ascii=False) for p in paths) + "\n"
+                        try:
+                            self.proc.stdin.write(command)
+                            self.proc.stdin.flush()
+                            left = max(0.001, deadline - time.monotonic())
+                            line = self._readline(min(left, VISION_ENCODE_S or left), "the video pair could not be read").strip()
+                        except (RuntimeError, OSError) as exc:
+                            self.stopped = True
+                            out.unlink(missing_ok=True)
+                            raise ValueError(str(exc)) from None
+                        if not line.startswith("OK "):
+                            out.unlink(missing_ok=True)
+                            raise ValueError("the native video pair could not be read: " + (line[4:] if line.startswith("ERR ") else "encoder stopped"))
+                        try:
+                            tokens = int(line.split()[1])
+                        except (ValueError, IndexError):
+                            out.unlink(missing_ok=True)
+                            raise ValueError("the native video reader returned an invalid token count") from None
+                        if not 1 <= tokens <= config["tokens_per_pair"] or not out.is_file():
+                            out.unlink(missing_ok=True)
+                            raise ValueError("the native video pair exceeded its token budget or returned no embeddings")
+                        self.cache[key] = out, tokens
+                    result.append((out, tokens, float(pair.timestamp)))
+                    held = {str(p) for p in keep} | {str(p) for p, _, _ in result}
+                    for old in list(self.cache):
+                        if len(self.cache) <= 64:
+                            break
+                        if str(self.cache[old][0]) not in held:
+                            self.cache.pop(old)[0].unlink(missing_ok=True)
+        return result
+
     def warn_if_over_limit(self, tokens: int) -> None:
         """I7: one picture that became more than 4 times the limit is logged with the numbers, so the next report has them (the reader's own
         stderr has the warm-up line).  A reader built before the limit was enforced inside it (strata-vision refuses these now) still lets them by."""
@@ -3112,6 +3221,8 @@ def engine_args(cfg: dict) -> list[str]:
             note += " and --vram-reserve-mib 700"
         print(f'[strata] the config has a "vision" section but no --vision in its args: {note} (run setup again with '
               "--vision to write them)", flush=True)
+    if isinstance(cfg.get("video"), dict) and cfg["video"].get("enabled") is True and "--native-video" not in args:
+        args.append("--native-video")
     if layer_split_of(cfg) and "--layer-split" not in args:
         args += ["--layer-split", layer_split_value(cfg)]
     # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV
@@ -3650,7 +3761,8 @@ def vision_env(cfg: dict, env: dict, archs: dict[int, str] | None = None) -> dic
 
 class ByteTokenizer:
     """Tiny stand-in tokenizer for tests without the pack: one id per UTF-8 byte, specials as ids >= 256."""
-    SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"]
+    SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>",
+                "<|video_pad|>"]
 
     ALWAYS = ()                                     # specials matched without parse_special (type 4, as <think>)
 
@@ -3821,7 +3933,7 @@ def slot_save_dir(value, base: str | None = None) -> str:
 class Service:
     def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next",
                  vision: Vision | None = None, sampling_defaults: dict | None = None,
-                 fit_max_tokens: bool = True):
+                 fit_max_tokens: bool = True, video_config: dict | None = None):
         self.engine, self.tok, self.template, self.model, self.vision = engine, tokenizer, template, model_name, vision
         self.literals = literal_tags(getattr(tokenizer, "control_tokens", ()))   # texts that stay text inside a message
         self.fit_max_tokens = fit_max_tokens          # default: clamp the output cap to the room left; False (--no-fit-max-tokens) = 400
@@ -3832,6 +3944,7 @@ class Service:
         self.codex_thread_titles = False              # #923 (opt-in): answer Codex's thread-title turns without the engine
         self.sampling_defaults = dict(sampling_defaults or {})   # the run config's `sampling` block
         self.model_arch = None                        # the config's family ("qwen4exp", "qwen35moe"): None = no model-card defaults
+        self.video_config = dict(video_config) if video_config else None
         self.shared = {}                              # the web app's Chat settings for every client (POST /settings)
         self.shared_path = None                       # where they are kept between starts (next to the config)
         self.config_effort = None                     # #1641: the config's "reasoning_effort": the level for requests with none
@@ -4817,8 +4930,132 @@ class Service:
         if self.prompts is not None:
             self.prompts.forget(ids)
 
+    def native_video_available(self) -> bool:
+        """Only advertise the opt-in path after both resident binaries confirm it."""
+        return bool(self.video_config and self.video_config.get("enabled") is True
+                    and self.model_arch == "qwen4exp" and self.vision is not None
+                    and getattr(self.vision, "supports_video", False)
+                    and getattr(self.engine, "info", {}).get("native_video") == 1
+                    and shutil.which("ffmpeg") and shutil.which("ffprobe"))
+
+    def _require_native_video(self):
+        if not self.video_config or self.video_config.get("enabled") is not True:
+            raise ValueError('native video input is disabled; enable "video": {"enabled": true} in a native-video profile')
+        if self.model_arch != "qwen4exp":
+            raise ValueError("native video is not verified for this model architecture")
+        if self.vision is None or not hasattr(self.vision, "encode_video"):
+            raise ValueError("native video requires a VIDEO_PAIR1 vision encoder")
+        if getattr(self.engine, "info", {}).get("native_video") != 1:
+            raise ValueError("the text engine has no native video support; use a native-video build and --native-video")
+        video_ids = self.tok.encode(VIDEO_PAD, parse_special=True)
+        if len(video_ids) != 1 or (not isinstance(self.tok, ByteTokenizer) and video_ids[0] != 248057):
+            raise ValueError("this tokenizer does not have the verified Qwen3.8 video token")
+
+    def _encode_native_media(self, ids, media, fetched, cancel):
+        """Expand whole video placeholders using the model's temporal-pair processor format.
+
+        A group is `<t.t seconds><vision_start><video_pad>...<vision_end>`.
+        Its SVE1 rows come from two actual frames encoded together. Image entries
+        remain image_pad groups, and both kinds share their original prompt order.
+        """
+        self._require_native_video()
+        if sum(item["type"] == "video" for item in media) > 2:
+            raise ValueError("at most two native video attachments are allowed in one request")
+        if len(media) > 32:
+            raise ValueError("a mixed video request permits at most 32 media attachments")
+        sources = []
+        for item in media:
+            source = item["source"]
+            if item["type"] == "image" and source.startswith(("http://", "https://")):
+                if self.offline:
+                    raise ValueError("offline mode cannot download an image URL; send a data: image instead")
+                source = fetched[source] if source in fetched else Vision.download(source)
+            sources.append((item["type"], source))
+        start = self.tok.encode(VISION_START, parse_special=True)[0]
+        end = self.tok.encode("<|vision_end|>", parse_special=True)[0]
+        image_pad = self.tok.encode(IMAGE_PAD, parse_special=True)[0]
+        video_pad = self.tok.encode(VIDEO_PAD, parse_special=True)[0]
+        encoded, groups, pair_count, video_tokens = [], [], 0, 0
+        with self._turn(cancel):
+            self._vision_up()
+            if not getattr(self.vision, "supports_video", False):
+                raise ValueError("the resident vision encoder did not confirm VIDEO_PAIR1 native video support")
+            try:
+                for kind, source in sources:
+                    if cancel is not None and cancel.is_set():
+                        raise ClientGone()
+                    keep = [path for path, _ in encoded]
+                    if kind == "image":
+                        path, count = self.vision.encode(source, keep=keep)
+                        pairs = [(path, count, None)]
+                    else:
+                        if pair_count >= 64:
+                            raise ValueError("native videos exceed the per-request budget of 64 temporal pairs; split the clips")
+                        remaining = {**self.video_config, "max_pairs": min(self.video_config["max_pairs"], 64 - pair_count)}
+                        pairs = self.vision.encode_video(source, remaining, cancel, keep=keep)
+                        if not pairs:
+                            raise ValueError("the native video contains no temporal pairs")
+                        last_timestamp = -1.0
+                        for _, count, timestamp in pairs:
+                            if (not isinstance(count, int) or not 1 <= count <= self.video_config["tokens_per_pair"]
+                                    or not isinstance(timestamp, (int, float)) or not math.isfinite(timestamp)
+                                    or timestamp < 0 or timestamp < last_timestamp):
+                                raise ValueError("the native video encoder returned invalid temporal-pair metadata")
+                            last_timestamp = timestamp
+                        pair_count += len(pairs)
+                        video_tokens += sum(count for _, count, _ in pairs)
+                        if pair_count > 64 or video_tokens > 16384:
+                            raise ValueError("native videos exceed the per-request budget of 64 temporal pairs or 16384 video tokens; split the clips")
+                    encoded.extend((path, count) for path, count, _ in pairs)
+                    groups.append((kind, pairs))
+                out, index, cursor = [], 0, 0
+                while cursor < len(ids):
+                    triple = ids[cursor:cursor + 3]
+                    if len(triple) == 3 and triple[0] == start and triple[2] == end and triple[1] in (image_pad, video_pad):
+                        if index >= len(groups):
+                            raise ValueError("the prompt and its native media markers do not match")
+                        kind, pairs = groups[index]
+                        wanted = image_pad if kind == "image" else video_pad
+                        if triple[1] != wanted:
+                            raise ValueError("the prompt's image/video order does not match its embeddings")
+                        for _, count, timestamp in pairs:
+                            if kind == "video":
+                                out.extend(self.tok.encode(f"<{timestamp:.1f} seconds>", parse_special=False))
+                            out.extend([start] + [wanted] * count + [end])
+                        index += 1
+                        cursor += 3
+                    else:
+                        if ids[cursor] in (image_pad, video_pad):
+                            # An unpaired user-written marker is ordinary text.
+                            token = IMAGE_PAD if ids[cursor] == image_pad else VIDEO_PAD
+                            out.extend(self.tok.encode(token, parse_special=False, plain=((0, len(token)),)))
+                        else:
+                            out.append(ids[cursor])
+                        cursor += 1
+                if index != len(groups):
+                    raise ValueError("the template did not render every native media marker")
+                # Copy before releasing the FIFO: another request may evict cached
+                # pairs immediately. prepare() cleans this file on any later error.
+                combined = combined_embeddings_path(self.vision.dir, sum(Path(path).stat().st_size for path, _ in encoded))
+                self.embeddings.path = combined
+                self.embeddings.keys = [Path(path).stem[:16] for path, _ in encoded]
+                write_temporary(combined, [path for path, _ in encoded])
+                print(f"[strata] native video: videos={sum(kind == 'video' for kind, _ in sources)} "
+                      f"temporal_pairs={pair_count} video_tokens={video_tokens} media_items={len(media)}", flush=True)
+                return out, encoded
+            finally:
+                self.last_image_at = time.time()
 
     def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, cancel=None):
+        if not any(item["type"] == "video" for item in media_of(messages)):
+            return self._prepare(messages, tools, kwargs, max_new, force, req, cancel)
+        try:
+            return self._prepare(messages, tools, kwargs, max_new, force, req, cancel)
+        except BaseException:
+            self.drop_embeddings()
+            raise
+
+    def _prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, cancel=None):
         """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited":
         the rest of the context.  `force` (forced_call): without thinking the reply starts with it, so it ends the
         prompt; with thinking, Service.run writes it once the thinking is over."""
@@ -4831,7 +5068,11 @@ class Service:
         self.embeddings.path = None
         self.embeddings.keys = None
         images = images_of(messages)
-        if images:
+        media = media_of(messages)
+        has_video = any(item["type"] == "video" for item in media)
+        if has_video:
+            ids, encoded = self._encode_native_media(ids, media, fetched, cancel)
+        elif images:
             if self.offline and any(src.startswith(("http://", "https://")) for src in images):
                 raise ValueError("offline mode cannot download an image URL; send a data: image instead")
             if self.vision is None:
@@ -4907,7 +5148,7 @@ class Service:
             print(f"[strata] max_tokens {max_new} shortened to {max(1, room)}: the prompt ({len(ids)} tokens) leaves that much "
                   f"of the context ({ctx}); \"fit_max_tokens\": false answers 400 instead", flush=True)
             max_new = max(1, room)          # a shorter completion beats a 400 (the default)
-        if images:
+        if images and not has_video:
             # The request's images in one file for GENI (~10 MB a picture), written once nothing above refuses the
             # request: one refused after it (the engine starting, no room) left it in the vision directory for good,
             # one more for every retry of a 503.  run() deletes it; drop_embeddings() if run() never starts.
@@ -4918,12 +5159,12 @@ class Service:
             # (an encoder restart, the cache's eviction) with other bits still matches its checkpoints
             self.embeddings.keys = [Path(p).stem[:16] for p, _ in encoded]
             write_temporary(combined, [p for p, _ in encoded])
-        if self.family == "deepseek41" and req is not None and req.get("strata_prefix") is None and not images:
+        if self.family == "deepseek41" and req is not None and req.get("strata_prefix") is None and not images and not has_video:
             lead = self.deepseek_shared_start(messages)
             if lead:
                 req["strata_prefix"] = {"messages": lead}
         if req is not None and req.get("strata_prefix") is not None:
-            req["strata_prefix"] = self.resolve_prefix(req["strata_prefix"], messages, tools, kwargs, ids, bool(images))
+            req["strata_prefix"] = self.resolve_prefix(req["strata_prefix"], messages, tools, kwargs, ids, bool(images) or has_video)
         return ids, kwargs.get("enable_thinking", True) is not False, max_new
 
     @staticmethod
@@ -6635,7 +6876,9 @@ def make_handler(svc: Service):
                 self.wfile.write(body)
             elif path in ("/health", "/api/health"):
                 self._json(200, {"status": "ok", "max_context": svc.reported_ctx(), "model": svc.model,
-                                 "images": svc.vision is not None, "api_key": bool(svc.api_key),
+                                 "images": svc.vision is not None,
+                                 **({"videos": svc.native_video_available()} if svc.video_config else {}),
+                                 "api_key": bool(svc.api_key),
                                  "image_generation": svc.images is not None,
                                  "loaded": svc.loaded(), "service": "strata"})
             elif path.startswith("/v1/images/files/"):
@@ -6670,7 +6913,8 @@ def make_handler(svc: Service):
                     loaded = svc.loaded()
                     model = {"id": svc.model, "object": "model", "status": {"value": "loaded"},
                              "meta": {"n_ctx": svc.reported_ctx()},
-                             "architecture": {"input_modalities": ["text", "image"] if svc.vision is not None else ["text"],
+                             "architecture": {"input_modalities": (["text", "image"] if svc.vision is not None else ["text"])
+                                              + (["video"] if svc.native_video_available() else []),
                                               "output_modalities": ["text"]}}
                     if not loaded and (svc.idle_unload_s or getattr(svc.engine, "unloaded", False)):
                         model["status"] = {"value": "unloaded"}   # like llama-server's router: listed, loads on use
@@ -8339,6 +8583,10 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
             blocked = []
         if blocked:
             ap.error("--offline cannot be strict for this profile: " + "; ".join(blocked))
+    try:
+        video_cfg = native_video_config(cfg)
+    except ValueError as e:
+        ap.error(f"native video config: {e}")
     lazy = False
     if a.engine == "strata":
         if not cfg:
@@ -8371,6 +8619,9 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
                 print('[strata] the vision section\'s "elastic" needs "vram_elastic": true (the expert cache gives the '
                       "encoder its VRAM): the encoder starts with the model instead", flush=True)
                 vcfg["elastic"] = False
+            if video_cfg:
+                vcfg["native_video"] = True
+                vcfg["video_tokens_per_pair"] = video_cfg["tokens_per_pair"]
             vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None,
                             env=vision_env(cfg, env), lazy=lazy)
         print("model unloaded; the first request loads it ..." if lazy else
@@ -8438,7 +8689,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
                   "using the V4.1 template so tool calls come back as real calls", flush=True)
     svc = Service(engine, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja"),
                   model_name=default_model_name(cfg), vision=vision,
-                  sampling_defaults=sampling_defaults,
+                  sampling_defaults=sampling_defaults, video_config=video_cfg,
                   fit_max_tokens=a.fit_max_tokens or (not a.no_fit_max_tokens and cfg.get("fit_max_tokens") is not False))
     svc.launch_attestation = launch_attestation
     svc.offline = a.offline
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 7bafd685073a102d2ad099d623643615b6cffc1f..11e08b957d7ff6f18262bae991a2177d439f805c 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -85,6 +85,7 @@
 #include "strata/program/prefill_plan.hpp"
 #include "strata/program/draft_kv_plan.hpp"
 #include "strata/program/message_boundary.hpp"
+#include "strata/program/visual_prompt.hpp"
 #include "strata/spec/draft_policy.hpp"
 #include "strata/spec/draft_source.hpp"
 #include "strata/spec/suffix_drafter.hpp"
@@ -721,6 +722,8 @@ struct Options {
     bool serve = false;
     /// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests.
     bool vision = false;
+    /// Opt-in Qwen3-VL temporal video patches; keeps the image-only path unchanged.
+    bool native_video = false;
     int adapt_swaps = 96;
     /// --serve: how many conversation checkpoints to keep between requests (0 = every request reads its whole
     /// prompt again, the v0.1.2 behaviour).  One is the GDN recurrence of the 36 layers, the QSA indexer tails and
@@ -888,6 +891,7 @@ void usage() {
                  "  --shared-late        A/B: shared expert after the CPU pool (default: overlapped with it)\n"
                  "  --keep-canonical     A/B: also load canonical copies of natively served tensors (more VRAM)\n"
                  "  --vision             --serve takes images too (GENI requests; embeddings from strata-vision)\n"
+                 "  --native-video       with --vision: native Qwen video temporal patches and video_pad IDs\n"
                  "  --prompt-cache N     --serve: keep N conversation checkpoints between requests (default 6, ~118 MB\n"
                  "                       of RAM each; 0 = read every prompt from the start)\n"
                  "  --conversation-cache-mib N  --serve: RAM budget for parked conversations (default: sized from the free RAM, up to 8192; 0 = off)\n"
@@ -2636,6 +2640,7 @@ int main(int argc, char** argv) {
         else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode");
         else if (a == "--serve") o.serve = true;
         else if (a == "--vision") o.vision = true;
+        else if (a == "--native-video") o.native_video = true;
         else if (a == "--session-save-reclaim") o.session_save_reclaim = true;
         else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache")));
         else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" ||
@@ -2793,6 +2798,10 @@ int main(int argc, char** argv) {
         }
         }
     }
+    if (o.native_video && (!o.vision || !o.serve)) {
+        std::fprintf(stderr, "--native-video requires --vision and --serve\n");
+        return 2;
+    }
 #if defined(STRATA_USE_HIP)
     {   // gfx1151 (Strix Halo): the switches that are exact there are on by default (strata/core/arch_defaults.hpp); before
         // any engine code reads its switches (they are read at first use), and the user's own settings are kept
@@ -11165,6 +11174,7 @@ int main(int argc, char** argv) {
         }
         strata::core::pin_sim_report("at READY");
         strata::core::pin_reserve_release_hard();   // the load is over: nothing else needs the headroom
+        if (o.native_video && o.vision) std::printf("INFO native_video=1\n");
         std::printf("READY %lld stop\n", (long long) o.max_context);   // "stop": this engine honours STOP
         std::fflush(stdout);
         std::string line;
@@ -11188,9 +11198,9 @@ int main(int argc, char** argv) {
             });
         // The vision path (--vision): GENI <max_new> <embeddings file> <id,id,...> carries images.  The file is one
         // or more strata-vision records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt order;
-        // each image's rows go to its run of <|image_pad|> tokens, whose M-RoPE positions are mtmd's: t = p,
-        // h = p + y, w = p + x, and the text after the image continues at p + max(nx, ny).
-        constexpr int64_t kImagePad = 248056;   // qwen4exp.ple.image_token_id: the PLE hash reads it for image cells
+        // each image's rows go to image_pad; with --native-video a video temporal patch goes to video_pad.
+        // Qwen3-VL splits video_grid_thw into [1,H,W] groups: t=p, h=p+y, w=p+x, then p += max(nx,ny).
+        // Its timestamp is text before each group. Original image/video token IDs are retained for PLE.
         bool mrope_identity = true;
         std::vector<float> img_rows;
         std::vector<const float*> row_ptr;
@@ -12418,41 +12428,39 @@ int main(int argc, char** argv) {
                             break;
                         }
                         const size_t off = img_rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4];
+                        if ((uint64_t) hdr[1] > (uint64_t) n ||
+                            off / (size_t) g.n_embd + (size_t) hdr[1] > (size_t) n) {
+                            ve = "embeddings contain more visual rows than prompt tokens";
+                            break;
+                        }
                         img_rows.resize(off + cnt);
                         if (std::fread(img_rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; }
                         imgs.push_back({hdr[1], hdr[2], hdr[3], off});
                     }
                     if (f) std::fclose(f);
-                    int64_t p = 0, i = 0;
-                    size_t k = 0;
-                    while (ve.empty() && i < n) {
-                        if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; }
-                        if (k >= imgs.size()) { ve = "the prompt has more images than the embeddings file"; break; }
-                        const Img& im = imgs[k++];
+                    std::vector<strata::program::VisualGrid> grids;
+                    grids.reserve(imgs.size());
+                    for (const Img& im : imgs) grids.push_back({im.n, im.nx, im.ny});
+                    std::vector<strata::program::VisualSpan> spans;
+                    if (ve.empty())
+                        strata::program::visual_prompt_positions(ids, grids, o.native_video,
+                            mrope_host.data(), (size_t) cells, spans, ve);
+                    for (size_t k = 0; ve.empty() && k < imgs.size(); ++k) {
+                        const Img& im = imgs[k];
+                        const int64_t i = spans[k].start;
                         {   // what the conversation cache compares: a picture is its grid and its embeddings
                             const int64_t grid[3] = {im.n, im.nx, im.ny};
                             uint64_t h = fnv1a(grid, sizeof grid);
                             if (req_img_keys.size() == imgs.size())   // #2228: the server's key for picture k
-                                h = fnv1a(&req_img_keys[k - 1], sizeof(uint64_t), h);
+                                h = fnv1a(&req_img_keys[k], sizeof(uint64_t), h);
                             else
                                 h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h);
                             req_imgs.push_back({i, h});
                         }
-                        for (int64_t j = 0; j < im.n && ve.empty(); ++j)
-                            if (i + j >= n || ids[(size_t) (i + j)] != kImagePad)
-                                ve = "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) +
-                                     " rows but fewer <|image_pad|> tokens";
                         for (int64_t j = 0; j < im.n && ve.empty(); ++j) {
-                            const int64_t y = j / im.nx, x = j % im.nx;
-                            put(i + j, p, p + y, p + x);
                             row_ptr[(size_t) (i + j)] = img_rows.data() + im.off + (size_t) j * (size_t) g.n_embd;
                         }
-                        i += im.n;
-                        p += std::max(im.nx, im.ny);
                     }
-                    if (ve.empty() && k != imgs.size()) ve = "the embeddings file has more images than the prompt";
-                    if (ve.empty() && n > 0 && ids[(size_t) (n - 1)] == kImagePad) ve = "the prompt cannot end in an image";
-                    for (int64_t c = n; ve.empty() && c < cells; ++c) put(c, p + (c - n), p + (c - n), p + (c - n));
                 }
                 tr("positions built", (long long) img_rows.size());
                 cudaDeviceSynchronize();
<!-- gh-comment-id:6394891438 --> @RAFOLIE commented on GitHub (Oct 25, 2026): ### Reference patch — part 1/3 Save the fenced diff as `native-video-part-1.patch` (UTF-8, LF). Concatenate the parts in numbered order before applying. This is part of the AI-assisted local prototype described in the issue. Part SHA256: `27b7533f072c342ae1629621a441a1305494a944f1df50ced0bdb85d7363f205` ````diff diff --git a/serve/frontend.py b/serve/frontend.py index 53f2b4599d08f1a2ca2b056b5d6380c708341810..1412898f4978e9562060ec71ce59b839995f9ff4 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -128,6 +128,7 @@ def _text_of(content) -> str: IMAGE_PARTS = ("image_url", "input_image", "image") +VIDEO_PARTS = ("video_url",) # Thinking levels. The model's template knows low, medium and xhigh (its default; "high" means xhigh), and # enable_thinking=false for none. Clients spell these many ways; everything maps onto those four. @@ -182,6 +183,20 @@ def _has_image(content) -> bool: return isinstance(content, list) and any(isinstance(p, dict) and p.get("type") in IMAGE_PARTS for p in content) +def _has_video(content) -> bool: + return isinstance(content, list) and any(isinstance(p, dict) and p.get("type") in VIDEO_PARTS for p in content) + + +def _video_source(part: dict) -> str: + """ZCode/OpenAI-compatible inline video; never turn a video into image parts.""" + value = part.get("video_url") + if isinstance(value, dict): + value = value.get("url") + if not isinstance(value, str) or not value.startswith("data:video/") or ";base64," not in value: + raise ValueError("video_url.url must be an inline data:video/*;base64 URL; remote URLs and local paths are not supported") + return value + + def _image_source(part: dict) -> str: """An image part's source as one string: a data: URL, an http(s) URL or a local file path. OpenAI: {"type": "image_url", "image_url": {"url": ...}} (or "image_url": "..."), Responses-style @@ -201,7 +216,7 @@ def _image_source(part: dict) -> str: def _parts_of(content): """Message content for the template: a string when there is no image (unchanged behaviour), otherwise the template's list form - text items and image items, in order - whose image items carry their source.""" - if not _has_image(content): + if not _has_image(content) and not _has_video(content): return _text_of(content) items = [] for part in content: @@ -209,6 +224,8 @@ def _parts_of(content): continue if part.get("type") in IMAGE_PARTS: items.append({"type": "image", "source": _image_source(part)}) + elif part.get("type") in VIDEO_PARTS: + items.append({"type": "video", "source": _video_source(part)}) elif part.get("type") in TEXT_PARTS and "text" in part: items.append({"type": "text", "text": part.get("text", "")}) return items @@ -240,6 +257,8 @@ def _check_parts(content, path: str, kinds): if out is content: out = list(content) out[j] = {"type": "text", "text": part.get("refusal") or ""} + elif kind in VIDEO_PARTS and kind not in kinds: + raise ValueError(f"{path}[{j}]: native video_url input is supported only by Chat Completions") elif kind not in kinds: LOGGER.debug("%s[%d].type: content part of type %r is not read by this server; left out of the prompt", path, j, kind) @@ -253,6 +272,12 @@ def images_of(messages: list[dict]) -> list[str]: for item in m["content"] if item.get("type") == "image"] +def media_of(messages: list[dict]) -> list[dict]: + """Canonical image/video items in the exact order their template markers occur.""" + return [item for m in messages if isinstance(m.get("content"), list) + for item in m["content"] if item.get("type") in ("image", "video")] + + # #537: a literal <think> / </think> inside a message's text is plain text, not the model's reasoning markers. The # tokenizer matches those two strings as their special tokens everywhere (GGUF token type 4, as llama.cpp does), so # a user quoting "</think>" used to hand the model a real end-of-reasoning token. Before the template is rendered @@ -548,8 +573,10 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: role = "system" # an image is read in a user, tool or assistant message; the system prompt takes text only, as _text_of reads images = role in ("user", "tool", "assistant") + if _has_video(m.get("content")) and not images: + raise ValueError(f"messages[{i}]: video input is supported only in user, assistant, or tool messages") content = _check_parts(m.get("content"), f"messages[{i}].content", - TEXT_PARTS + IMAGE_PARTS if images else TEXT_PARTS) + TEXT_PARTS + IMAGE_PARTS + VIDEO_PARTS if images else TEXT_PARTS) out = {"role": role, "content": _parts_of(content) if images else _text_of(content)} if m.get("reasoning_content"): out["reasoning_content"] = m["reasoning_content"] diff --git a/serve/server.py b/serve/server.py index 71a55e1f0f9c8c95239396c2dd18297dee08e6df..2412a66057051b930a6181b9a6336cf2a9a2284d 100644 --- a/serve/server.py +++ b/serve/server.py @@ -61,7 +61,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) sys.path.insert(0, str(ROOT)) # run as a script (run-<model>.bat) as well as a module from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 - forced_call, images_of, literal_tags, mark_think_literals, openai_to_messages, + forced_call, images_of, literal_tags, mark_think_literals, media_of, openai_to_messages, tool_choice_of, unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve import runconfig # noqa: E402 @@ -87,6 +87,7 @@ from serve import images as images_api # noqa: E402 IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" +VIDEO_PAD = "<|video_pad|>" def popen(what: str, args: list, role: str = "engine", **kw): @@ -2574,6 +2575,36 @@ def vision_start_error(line: str, log=None, code: int | None = None, waited: flo return msg +def native_video_config(cfg: dict) -> dict | None: + """Validate the opt-in Qwen3.8 native two-frame video path before loading weights.""" + value = cfg.get("video") + if value is None: + return None + if not isinstance(value, dict) or not isinstance(value.get("enabled", False), bool): + raise ValueError('"video" must be an object with "enabled": true or false') + if not value.get("enabled", False): + return None + if cfg.get("arch") != "qwen4exp": + raise ValueError("native video is supported only for the verified qwen4exp model architecture") + if not isinstance(cfg.get("vision"), dict): + raise ValueError("native video requires a configured vision encoder") + result = {"enabled": True, "fps": 2.0, "max_pairs": 64, "max_duration_seconds": 300.0, + "max_bytes": 64 * 1024 * 1024, "tokens_per_pair": 256} + limits = {"fps": (0.1, 8.0), "max_pairs": (1, 64), "max_duration_seconds": (0.1, 300.0), + "max_bytes": (1, 64 * 1024 * 1024), "tokens_per_pair": (8, 256)} + integers = {"max_pairs", "max_bytes", "tokens_per_pair"} + for key, (minimum, maximum) in limits.items(): + if key not in value: + continue + number = value[key] + if (isinstance(number, bool) or not isinstance(number, (int, float)) + or not math.isfinite(number) or not minimum <= number <= maximum + or key in integers and not isinstance(number, int)): + raise ValueError(f"video.{key} must be {'an integer' if key in integers else 'a number'} between {minimum} and {maximum}") + result[key] = number + return result + + class Vision: """The resident image encoder: `strata-vision` (llama.cpp mtmd + the mmproj file) reads `ENC <image> <out>` lines and writes each image's embeddings; results are cached by the image's hash, so a conversation that @@ -2611,6 +2642,8 @@ class Vision: self.stopped = True self.lock = threading.Lock() self.cache: dict[str, tuple[Path, int]] = {} + self.native_video = cfg.get("native_video") is True + self.supports_video = False # opt-in (the vision section's "elastic": true, with the config's "vram_elastic"): the encoder starts with the # first picture and stops after elastic_idle_s without one; while it runs, the engine's expert cache keeps # elastic_mib of VRAM free for it (Service._vision_up / _vision_idle_down) @@ -2649,6 +2682,8 @@ class Vision: args += ["--max-tokens", str(limit)] if cfg.get("min_tokens"): # #767: mtmd's image_min_tokens (a hand-edited key) args += ["--min-tokens", str(cfg["min_tokens"])] + if cfg.get("native_video") is True: + args += ["--native-video", "--video-max-tokens", str(cfg.get("video_tokens_per_pair", 256))] return args def _ensure_dir(self): @@ -2700,6 +2735,10 @@ class Vision: code = getattr(proc, "returncode", None) raise RuntimeError(vision_start_error(line, log, code)) self.stopped = False + self.supports_video = "VIDEO_PAIR1" in line.split() + if getattr(self, "native_video", False) and not self.supports_video: + self.close() + raise RuntimeError("native video was enabled, but this vision encoder does not support the VIDEO_PAIR1 protocol") def _readline(self, timeout: float, what: str) -> str: """One line from the encoder, waiting at most `timeout` s (#1317). On a timeout the encoder is killed, so the @@ -2874,6 +2913,76 @@ class Vision: self.cache.pop(old)[0].unlink(missing_ok=True) return self.cache[key] + def encode_video(self, source: str | bytes, config: dict, cancel=None, keep=()) -> list[tuple[Path, int, float]]: + """Encode real temporal pairs through ENCV; no frame is sent through ENC/image_pad.""" + from serve.video import VideoCancelled + try: + return self._encode_video(source, config, cancel, keep) + except VideoCancelled: + raise ClientGone() from None + + def _encode_video(self, source: str | bytes, config: dict, cancel=None, keep=()) -> list[tuple[Path, int, float]]: + if not self.native_video or not self.supports_video: + raise ValueError("this vision encoder does not support native video; use a VIDEO_PAIR1 build") + from serve.video import prepare_video + result = [] + deadline = time.monotonic() + 240.0 + self._ensure_dir() + with prepare_video(source, config, cancel, directory=self.dir) as video: + for pair in video.pairs: + if cancel is not None and cancel.is_set(): + raise ClientGone() + if time.monotonic() >= deadline: + raise ValueError("native video decoding and encoding exceeded 240 seconds; send a shorter clip") + digest = hashlib.sha256(b"strata-native-video-pair-v1\0") + for frame in (pair.first, pair.second): + data = Path(frame).read_bytes() + digest.update(len(data).to_bytes(8, "little")) + digest.update(data) + key = digest.hexdigest()[:32] + with self.lock: + if key in self.cache: + self.cache[key] = self.cache.pop(key) + out, tokens = self.cache[key] + else: + if not self.alive() or self.proc.stdin is None: + raise ValueError("the native video reader is not running") + out = self.dir / f"{key}.sve" + # std::quoted in the opt-in reader handles spaces; POSIX + # separators also avoid ambiguous Windows backslash escapes. + paths = [Path(pair.first).resolve().as_posix(), Path(pair.second).resolve().as_posix(), + out.resolve().as_posix()] + command = "ENCV " + " ".join(json.dumps(p, ensure_ascii=False) for p in paths) + "\n" + try: + self.proc.stdin.write(command) + self.proc.stdin.flush() + left = max(0.001, deadline - time.monotonic()) + line = self._readline(min(left, VISION_ENCODE_S or left), "the video pair could not be read").strip() + except (RuntimeError, OSError) as exc: + self.stopped = True + out.unlink(missing_ok=True) + raise ValueError(str(exc)) from None + if not line.startswith("OK "): + out.unlink(missing_ok=True) + raise ValueError("the native video pair could not be read: " + (line[4:] if line.startswith("ERR ") else "encoder stopped")) + try: + tokens = int(line.split()[1]) + except (ValueError, IndexError): + out.unlink(missing_ok=True) + raise ValueError("the native video reader returned an invalid token count") from None + if not 1 <= tokens <= config["tokens_per_pair"] or not out.is_file(): + out.unlink(missing_ok=True) + raise ValueError("the native video pair exceeded its token budget or returned no embeddings") + self.cache[key] = out, tokens + result.append((out, tokens, float(pair.timestamp))) + held = {str(p) for p in keep} | {str(p) for p, _, _ in result} + for old in list(self.cache): + if len(self.cache) <= 64: + break + if str(self.cache[old][0]) not in held: + self.cache.pop(old)[0].unlink(missing_ok=True) + return result + def warn_if_over_limit(self, tokens: int) -> None: """I7: one picture that became more than 4 times the limit is logged with the numbers, so the next report has them (the reader's own stderr has the warm-up line). A reader built before the limit was enforced inside it (strata-vision refuses these now) still lets them by.""" @@ -3112,6 +3221,8 @@ def engine_args(cfg: dict) -> list[str]: note += " and --vram-reserve-mib 700" print(f'[strata] the config has a "vision" section but no --vision in its args: {note} (run setup again with ' "--vision to write them)", flush=True) + if isinstance(cfg.get("video"), dict) and cfg["video"].get("enabled") is True and "--native-video" not in args: + args.append("--native-video") if layer_split_of(cfg) and "--layer-split" not in args: args += ["--layer-split", layer_split_value(cfg)] # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV @@ -3650,7 +3761,8 @@ def vision_env(cfg: dict, env: dict, archs: dict[int, str] | None = None) -> dic class ByteTokenizer: """Tiny stand-in tokenizer for tests without the pack: one id per UTF-8 byte, specials as ids >= 256.""" - SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"] + SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>", + "<|video_pad|>"] ALWAYS = () # specials matched without parse_special (type 4, as <think>) @@ -3821,7 +3933,7 @@ def slot_save_dir(value, base: str | None = None) -> str: class Service: def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next", vision: Vision | None = None, sampling_defaults: dict | None = None, - fit_max_tokens: bool = True): + fit_max_tokens: bool = True, video_config: dict | None = None): self.engine, self.tok, self.template, self.model, self.vision = engine, tokenizer, template, model_name, vision self.literals = literal_tags(getattr(tokenizer, "control_tokens", ())) # texts that stay text inside a message self.fit_max_tokens = fit_max_tokens # default: clamp the output cap to the room left; False (--no-fit-max-tokens) = 400 @@ -3832,6 +3944,7 @@ class Service: self.codex_thread_titles = False # #923 (opt-in): answer Codex's thread-title turns without the engine self.sampling_defaults = dict(sampling_defaults or {}) # the run config's `sampling` block self.model_arch = None # the config's family ("qwen4exp", "qwen35moe"): None = no model-card defaults + self.video_config = dict(video_config) if video_config else None self.shared = {} # the web app's Chat settings for every client (POST /settings) self.shared_path = None # where they are kept between starts (next to the config) self.config_effort = None # #1641: the config's "reasoning_effort": the level for requests with none @@ -4817,8 +4930,132 @@ class Service: if self.prompts is not None: self.prompts.forget(ids) + def native_video_available(self) -> bool: + """Only advertise the opt-in path after both resident binaries confirm it.""" + return bool(self.video_config and self.video_config.get("enabled") is True + and self.model_arch == "qwen4exp" and self.vision is not None + and getattr(self.vision, "supports_video", False) + and getattr(self.engine, "info", {}).get("native_video") == 1 + and shutil.which("ffmpeg") and shutil.which("ffprobe")) + + def _require_native_video(self): + if not self.video_config or self.video_config.get("enabled") is not True: + raise ValueError('native video input is disabled; enable "video": {"enabled": true} in a native-video profile') + if self.model_arch != "qwen4exp": + raise ValueError("native video is not verified for this model architecture") + if self.vision is None or not hasattr(self.vision, "encode_video"): + raise ValueError("native video requires a VIDEO_PAIR1 vision encoder") + if getattr(self.engine, "info", {}).get("native_video") != 1: + raise ValueError("the text engine has no native video support; use a native-video build and --native-video") + video_ids = self.tok.encode(VIDEO_PAD, parse_special=True) + if len(video_ids) != 1 or (not isinstance(self.tok, ByteTokenizer) and video_ids[0] != 248057): + raise ValueError("this tokenizer does not have the verified Qwen3.8 video token") + + def _encode_native_media(self, ids, media, fetched, cancel): + """Expand whole video placeholders using the model's temporal-pair processor format. + + A group is `<t.t seconds><vision_start><video_pad>...<vision_end>`. + Its SVE1 rows come from two actual frames encoded together. Image entries + remain image_pad groups, and both kinds share their original prompt order. + """ + self._require_native_video() + if sum(item["type"] == "video" for item in media) > 2: + raise ValueError("at most two native video attachments are allowed in one request") + if len(media) > 32: + raise ValueError("a mixed video request permits at most 32 media attachments") + sources = [] + for item in media: + source = item["source"] + if item["type"] == "image" and source.startswith(("http://", "https://")): + if self.offline: + raise ValueError("offline mode cannot download an image URL; send a data: image instead") + source = fetched[source] if source in fetched else Vision.download(source) + sources.append((item["type"], source)) + start = self.tok.encode(VISION_START, parse_special=True)[0] + end = self.tok.encode("<|vision_end|>", parse_special=True)[0] + image_pad = self.tok.encode(IMAGE_PAD, parse_special=True)[0] + video_pad = self.tok.encode(VIDEO_PAD, parse_special=True)[0] + encoded, groups, pair_count, video_tokens = [], [], 0, 0 + with self._turn(cancel): + self._vision_up() + if not getattr(self.vision, "supports_video", False): + raise ValueError("the resident vision encoder did not confirm VIDEO_PAIR1 native video support") + try: + for kind, source in sources: + if cancel is not None and cancel.is_set(): + raise ClientGone() + keep = [path for path, _ in encoded] + if kind == "image": + path, count = self.vision.encode(source, keep=keep) + pairs = [(path, count, None)] + else: + if pair_count >= 64: + raise ValueError("native videos exceed the per-request budget of 64 temporal pairs; split the clips") + remaining = {**self.video_config, "max_pairs": min(self.video_config["max_pairs"], 64 - pair_count)} + pairs = self.vision.encode_video(source, remaining, cancel, keep=keep) + if not pairs: + raise ValueError("the native video contains no temporal pairs") + last_timestamp = -1.0 + for _, count, timestamp in pairs: + if (not isinstance(count, int) or not 1 <= count <= self.video_config["tokens_per_pair"] + or not isinstance(timestamp, (int, float)) or not math.isfinite(timestamp) + or timestamp < 0 or timestamp < last_timestamp): + raise ValueError("the native video encoder returned invalid temporal-pair metadata") + last_timestamp = timestamp + pair_count += len(pairs) + video_tokens += sum(count for _, count, _ in pairs) + if pair_count > 64 or video_tokens > 16384: + raise ValueError("native videos exceed the per-request budget of 64 temporal pairs or 16384 video tokens; split the clips") + encoded.extend((path, count) for path, count, _ in pairs) + groups.append((kind, pairs)) + out, index, cursor = [], 0, 0 + while cursor < len(ids): + triple = ids[cursor:cursor + 3] + if len(triple) == 3 and triple[0] == start and triple[2] == end and triple[1] in (image_pad, video_pad): + if index >= len(groups): + raise ValueError("the prompt and its native media markers do not match") + kind, pairs = groups[index] + wanted = image_pad if kind == "image" else video_pad + if triple[1] != wanted: + raise ValueError("the prompt's image/video order does not match its embeddings") + for _, count, timestamp in pairs: + if kind == "video": + out.extend(self.tok.encode(f"<{timestamp:.1f} seconds>", parse_special=False)) + out.extend([start] + [wanted] * count + [end]) + index += 1 + cursor += 3 + else: + if ids[cursor] in (image_pad, video_pad): + # An unpaired user-written marker is ordinary text. + token = IMAGE_PAD if ids[cursor] == image_pad else VIDEO_PAD + out.extend(self.tok.encode(token, parse_special=False, plain=((0, len(token)),))) + else: + out.append(ids[cursor]) + cursor += 1 + if index != len(groups): + raise ValueError("the template did not render every native media marker") + # Copy before releasing the FIFO: another request may evict cached + # pairs immediately. prepare() cleans this file on any later error. + combined = combined_embeddings_path(self.vision.dir, sum(Path(path).stat().st_size for path, _ in encoded)) + self.embeddings.path = combined + self.embeddings.keys = [Path(path).stem[:16] for path, _ in encoded] + write_temporary(combined, [path for path, _ in encoded]) + print(f"[strata] native video: videos={sum(kind == 'video' for kind, _ in sources)} " + f"temporal_pairs={pair_count} video_tokens={video_tokens} media_items={len(media)}", flush=True) + return out, encoded + finally: + self.last_image_at = time.time() def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, cancel=None): + if not any(item["type"] == "video" for item in media_of(messages)): + return self._prepare(messages, tools, kwargs, max_new, force, req, cancel) + try: + return self._prepare(messages, tools, kwargs, max_new, force, req, cancel) + except BaseException: + self.drop_embeddings() + raise + + def _prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, cancel=None): """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the prompt; with thinking, Service.run writes it once the thinking is over.""" @@ -4831,7 +5068,11 @@ class Service: self.embeddings.path = None self.embeddings.keys = None images = images_of(messages) - if images: + media = media_of(messages) + has_video = any(item["type"] == "video" for item in media) + if has_video: + ids, encoded = self._encode_native_media(ids, media, fetched, cancel) + elif images: if self.offline and any(src.startswith(("http://", "https://")) for src in images): raise ValueError("offline mode cannot download an image URL; send a data: image instead") if self.vision is None: @@ -4907,7 +5148,7 @@ class Service: print(f"[strata] max_tokens {max_new} shortened to {max(1, room)}: the prompt ({len(ids)} tokens) leaves that much " f"of the context ({ctx}); \"fit_max_tokens\": false answers 400 instead", flush=True) max_new = max(1, room) # a shorter completion beats a 400 (the default) - if images: + if images and not has_video: # The request's images in one file for GENI (~10 MB a picture), written once nothing above refuses the # request: one refused after it (the engine starting, no room) left it in the vision directory for good, # one more for every retry of a 503. run() deletes it; drop_embeddings() if run() never starts. @@ -4918,12 +5159,12 @@ class Service: # (an encoder restart, the cache's eviction) with other bits still matches its checkpoints self.embeddings.keys = [Path(p).stem[:16] for p, _ in encoded] write_temporary(combined, [p for p, _ in encoded]) - if self.family == "deepseek41" and req is not None and req.get("strata_prefix") is None and not images: + if self.family == "deepseek41" and req is not None and req.get("strata_prefix") is None and not images and not has_video: lead = self.deepseek_shared_start(messages) if lead: req["strata_prefix"] = {"messages": lead} if req is not None and req.get("strata_prefix") is not None: - req["strata_prefix"] = self.resolve_prefix(req["strata_prefix"], messages, tools, kwargs, ids, bool(images)) + req["strata_prefix"] = self.resolve_prefix(req["strata_prefix"], messages, tools, kwargs, ids, bool(images) or has_video) return ids, kwargs.get("enable_thinking", True) is not False, max_new @staticmethod @@ -6635,7 +6876,9 @@ def make_handler(svc: Service): self.wfile.write(body) elif path in ("/health", "/api/health"): self._json(200, {"status": "ok", "max_context": svc.reported_ctx(), "model": svc.model, - "images": svc.vision is not None, "api_key": bool(svc.api_key), + "images": svc.vision is not None, + **({"videos": svc.native_video_available()} if svc.video_config else {}), + "api_key": bool(svc.api_key), "image_generation": svc.images is not None, "loaded": svc.loaded(), "service": "strata"}) elif path.startswith("/v1/images/files/"): @@ -6670,7 +6913,8 @@ def make_handler(svc: Service): loaded = svc.loaded() model = {"id": svc.model, "object": "model", "status": {"value": "loaded"}, "meta": {"n_ctx": svc.reported_ctx()}, - "architecture": {"input_modalities": ["text", "image"] if svc.vision is not None else ["text"], + "architecture": {"input_modalities": (["text", "image"] if svc.vision is not None else ["text"]) + + (["video"] if svc.native_video_available() else []), "output_modalities": ["text"]}} if not loaded and (svc.idle_unload_s or getattr(svc.engine, "unloaded", False)): model["status"] = {"value": "unloaded"} # like llama-server's router: listed, loads on use @@ -8339,6 +8583,10 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in blocked = [] if blocked: ap.error("--offline cannot be strict for this profile: " + "; ".join(blocked)) + try: + video_cfg = native_video_config(cfg) + except ValueError as e: + ap.error(f"native video config: {e}") lazy = False if a.engine == "strata": if not cfg: @@ -8371,6 +8619,9 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in print('[strata] the vision section\'s "elastic" needs "vram_elastic": true (the expert cache gives the ' "encoder its VRAM): the encoder starts with the model instead", flush=True) vcfg["elastic"] = False + if video_cfg: + vcfg["native_video"] = True + vcfg["video_tokens_per_pair"] = video_cfg["tokens_per_pair"] vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, env=vision_env(cfg, env), lazy=lazy) print("model unloaded; the first request loads it ..." if lazy else @@ -8438,7 +8689,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in "using the V4.1 template so tool calls come back as real calls", flush=True) svc = Service(engine, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja"), model_name=default_model_name(cfg), vision=vision, - sampling_defaults=sampling_defaults, + sampling_defaults=sampling_defaults, video_config=video_cfg, fit_max_tokens=a.fit_max_tokens or (not a.no_fit_max_tokens and cfg.get("fit_max_tokens") is not False)) svc.launch_attestation = launch_attestation svc.offline = a.offline diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7bafd685073a102d2ad099d623643615b6cffc1f..11e08b957d7ff6f18262bae991a2177d439f805c 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -85,6 +85,7 @@ #include "strata/program/prefill_plan.hpp" #include "strata/program/draft_kv_plan.hpp" #include "strata/program/message_boundary.hpp" +#include "strata/program/visual_prompt.hpp" #include "strata/spec/draft_policy.hpp" #include "strata/spec/draft_source.hpp" #include "strata/spec/suffix_drafter.hpp" @@ -721,6 +722,8 @@ struct Options { bool serve = false; /// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests. bool vision = false; + /// Opt-in Qwen3-VL temporal video patches; keeps the image-only path unchanged. + bool native_video = false; int adapt_swaps = 96; /// --serve: how many conversation checkpoints to keep between requests (0 = every request reads its whole /// prompt again, the v0.1.2 behaviour). One is the GDN recurrence of the 36 layers, the QSA indexer tails and @@ -888,6 +891,7 @@ void usage() { " --shared-late A/B: shared expert after the CPU pool (default: overlapped with it)\n" " --keep-canonical A/B: also load canonical copies of natively served tensors (more VRAM)\n" " --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n" + " --native-video with --vision: native Qwen video temporal patches and video_pad IDs\n" " --prompt-cache N --serve: keep N conversation checkpoints between requests (default 6, ~118 MB\n" " of RAM each; 0 = read every prompt from the start)\n" " --conversation-cache-mib N --serve: RAM budget for parked conversations (default: sized from the free RAM, up to 8192; 0 = off)\n" @@ -2636,6 +2640,7 @@ int main(int argc, char** argv) { else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode"); else if (a == "--serve") o.serve = true; else if (a == "--vision") o.vision = true; + else if (a == "--native-video") o.native_video = true; else if (a == "--session-save-reclaim") o.session_save_reclaim = true; else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache"))); else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" || @@ -2793,6 +2798,10 @@ int main(int argc, char** argv) { } } } + if (o.native_video && (!o.vision || !o.serve)) { + std::fprintf(stderr, "--native-video requires --vision and --serve\n"); + return 2; + } #if defined(STRATA_USE_HIP) { // gfx1151 (Strix Halo): the switches that are exact there are on by default (strata/core/arch_defaults.hpp); before // any engine code reads its switches (they are read at first use), and the user's own settings are kept @@ -11165,6 +11174,7 @@ int main(int argc, char** argv) { } strata::core::pin_sim_report("at READY"); strata::core::pin_reserve_release_hard(); // the load is over: nothing else needs the headroom + if (o.native_video && o.vision) std::printf("INFO native_video=1\n"); std::printf("READY %lld stop\n", (long long) o.max_context); // "stop": this engine honours STOP std::fflush(stdout); std::string line; @@ -11188,9 +11198,9 @@ int main(int argc, char** argv) { }); // The vision path (--vision): GENI <max_new> <embeddings file> <id,id,...> carries images. The file is one // or more strata-vision records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt order; - // each image's rows go to its run of <|image_pad|> tokens, whose M-RoPE positions are mtmd's: t = p, - // h = p + y, w = p + x, and the text after the image continues at p + max(nx, ny). - constexpr int64_t kImagePad = 248056; // qwen4exp.ple.image_token_id: the PLE hash reads it for image cells + // each image's rows go to image_pad; with --native-video a video temporal patch goes to video_pad. + // Qwen3-VL splits video_grid_thw into [1,H,W] groups: t=p, h=p+y, w=p+x, then p += max(nx,ny). + // Its timestamp is text before each group. Original image/video token IDs are retained for PLE. bool mrope_identity = true; std::vector<float> img_rows; std::vector<const float*> row_ptr; @@ -12418,41 +12428,39 @@ int main(int argc, char** argv) { break; } const size_t off = img_rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4]; + if ((uint64_t) hdr[1] > (uint64_t) n || + off / (size_t) g.n_embd + (size_t) hdr[1] > (size_t) n) { + ve = "embeddings contain more visual rows than prompt tokens"; + break; + } img_rows.resize(off + cnt); if (std::fread(img_rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; } imgs.push_back({hdr[1], hdr[2], hdr[3], off}); } if (f) std::fclose(f); - int64_t p = 0, i = 0; - size_t k = 0; - while (ve.empty() && i < n) { - if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; } - if (k >= imgs.size()) { ve = "the prompt has more images than the embeddings file"; break; } - const Img& im = imgs[k++]; + std::vector<strata::program::VisualGrid> grids; + grids.reserve(imgs.size()); + for (const Img& im : imgs) grids.push_back({im.n, im.nx, im.ny}); + std::vector<strata::program::VisualSpan> spans; + if (ve.empty()) + strata::program::visual_prompt_positions(ids, grids, o.native_video, + mrope_host.data(), (size_t) cells, spans, ve); + for (size_t k = 0; ve.empty() && k < imgs.size(); ++k) { + const Img& im = imgs[k]; + const int64_t i = spans[k].start; { // what the conversation cache compares: a picture is its grid and its embeddings const int64_t grid[3] = {im.n, im.nx, im.ny}; uint64_t h = fnv1a(grid, sizeof grid); if (req_img_keys.size() == imgs.size()) // #2228: the server's key for picture k - h = fnv1a(&req_img_keys[k - 1], sizeof(uint64_t), h); + h = fnv1a(&req_img_keys[k], sizeof(uint64_t), h); else h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); req_imgs.push_back({i, h}); } - for (int64_t j = 0; j < im.n && ve.empty(); ++j) - if (i + j >= n || ids[(size_t) (i + j)] != kImagePad) - ve = "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) + - " rows but fewer <|image_pad|> tokens"; for (int64_t j = 0; j < im.n && ve.empty(); ++j) { - const int64_t y = j / im.nx, x = j % im.nx; - put(i + j, p, p + y, p + x); row_ptr[(size_t) (i + j)] = img_rows.data() + im.off + (size_t) j * (size_t) g.n_embd; } - i += im.n; - p += std::max(im.nx, im.ny); } - if (ve.empty() && k != imgs.size()) ve = "the embeddings file has more images than the prompt"; - if (ve.empty() && n > 0 && ids[(size_t) (n - 1)] == kImagePad) ve = "the prompt cannot end in an image"; - for (int64_t c = n; ve.empty() && c < cells; ++c) put(c, p + (c - n), p + (c - n), p + (c - n)); } tr("positions built", (long long) img_rows.size()); cudaDeviceSynchronize(); ````
Author
Owner

@RAFOLIE commented on GitHub (Oct 25, 2026):

Reference patch — part 2/3

Save the fenced diff as native-video-part-2.patch (UTF-8, LF). Concatenate the parts in numbered order before applying. This is part of the AI-assisted local prototype described in the issue.

Part SHA256: 3c5a12eb15dc3688b8b28626a8b5ba353f5ceefe1421df28f1bc164730a31846

diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp
index feae414533face08a24b672be6cebfcb778092a8..5c4537ca2b2acb8390dc2d0512c4f54901604afd 100644
--- a/tools/vision/strata_vision.cpp
+++ b/tools/vision/strata_vision.cpp
@@ -10,6 +10,7 @@
 //
 // Resident: prints "READY <n_embd>", then per stdin line
 //   ENC <image path> <output path>   ->  "OK <n_tokens> <nx> <ny> <ms>"  or  "ERR <message>"
+// With --native-video: READY also advertises VIDEO_PAIR1; ENCV <frame0> <frame1> <out> encodes a real temporal pair.
 //   QUIT
 // The output file is  int32 {0x31455653 'SVE1', n_tokens, nx, ny, n_embd}  then float32 [n_tokens][n_embd],
 // row i at grid position (x = i % nx, y = i / nx).  The text model is opened vocab-only (no weights).
@@ -36,6 +37,7 @@
 #include <cstdlib>
 #include <cstring>
 #include <iostream>
+#include <iomanip>
 #include <sstream>
 #include <string>
 #include <thread>
@@ -66,6 +68,14 @@ bool parse_enc(const std::string& line, std::string& img, std::string& out) {
     return !img.empty() && !out.empty();
 }
 
+bool parse_encv(const std::string& line, std::string& first, std::string& second, std::string& out) {
+    if (line.rfind("ENCV ", 0) != 0) return false;
+    std::istringstream in(line.substr(5));
+    std::string extra;
+    return bool(in >> std::quoted(first) >> std::quoted(second) >> std::quoted(out)) &&
+           !(in >> extra) && !first.empty() && !second.empty() && !out.empty();
+}
+
 }  // namespace
 
 int main(int argc, char** argv) {
@@ -86,7 +96,8 @@ int main(int argc, char** argv) {
     }
 #endif
     std::string mmproj, model;
-    bool gpu = false;
+    bool gpu = false, native_video = false;
+    int video_max_tokens = 256;
     int threads = 0, max_tokens = 0, min_tokens = 0;
     llama_flash_attn_type fa = LLAMA_FLASH_ATTN_TYPE_AUTO;
     bool fa_given = false;
@@ -99,6 +110,8 @@ int main(int argc, char** argv) {
         if (a == "--mmproj") mmproj = next();
         else if (a == "--model") model = next();
         else if (a == "--gpu") gpu = true;
+        else if (a == "--native-video") native_video = true;
+        else if (a == "--video-max-tokens") video_max_tokens = std::atoi(next().c_str());
         else if (a == "--version") {
 #ifdef STRATA_VISION_HIP
             std::printf("strata-vision hip (GPU architectures: %s)\n", STRATA_VISION_HIP_ARCHS);
@@ -124,7 +137,12 @@ int main(int argc, char** argv) {
     }
     if (mmproj.empty() || model.empty()) {
         std::fprintf(stderr, "usage: strata-vision --mmproj <mmproj.gguf> --model <model.gguf> [--gpu] [--threads N] "
-                             "[--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto]\n");
+                             "[--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto] "
+                             "[--native-video] [--video-max-tokens N]\n");
+        return 2;
+    }
+    if (native_video && (video_max_tokens < 8 || video_max_tokens > 1024)) {
+        std::fprintf(stderr, "--video-max-tokens must be between 8 and 1024\n");
         return 2;
     }
     // On the CPU the GPU stays unseen: a CUDA build otherwise opens a context there (measured: 0.4-0.7 GB of VRAM,
@@ -238,14 +256,22 @@ int main(int argc, char** argv) {
                  std::chrono::duration<double>(std::chrono::steady_clock::now() - load_t0).count());
     // a vocab-only model reports no hparams, so the width comes from the projector: its output is the model's input
     int n_embd = 0;
+    bool qwen_temporal_pair = false;
     {
         gguf_init_params gp{true, nullptr};
         gguf_context* gg = gguf_init_from_file(mmproj.c_str(), gp);
         const int64_t k = gg ? gguf_find_key(gg, "clip.vision.projection_dim") : -1;
         if (k >= 0) n_embd = (int) gguf_get_val_u32(gg, k);
+        const int64_t projector = gg ? gguf_find_key(gg, "clip.projector_type") : -1;
+        if (projector >= 0 && gguf_get_kv_type(gg, projector) == GGUF_TYPE_STRING)
+            qwen_temporal_pair = std::string(gguf_get_val_str(gg, projector)) == "qwen3vl_merger";
         if (gg) gguf_free(gg);
     }
     if (n_embd <= 0) { std::printf("ERR the vision encoder has no projection_dim\n"); std::fflush(stdout); return 1; }
+    if (native_video && !qwen_temporal_pair) {
+        std::printf("ERR native video requires the Qwen3VL temporal-pair projector\n");
+        std::fflush(stdout); mtmd_free(ctx); llama_model_free(text); llama_backend_free(); return 1;
+    }
     // Warm up at the LARGEST picture before READY: the encoder's GPU work buffers are allocated now, not at the first
     // real picture.  The server starts this process before the engine, so the engine sizes its expert cache from
     // what is really left; allocating ~1 GB later, on a GPU the engine has filled, made Windows page GPU memory and
@@ -280,31 +306,58 @@ int main(int argc, char** argv) {
         mtmd_input_chunks_free(chunks);
         if (bm) mtmd_bitmap_free(bm);
     }
-    std::printf("READY %d\n", n_embd);
+    std::printf(native_video ? "READY %d VIDEO_PAIR1\n" : "READY %d\n", n_embd);
     std::fflush(stdout);
 
     std::string line;
     while (std::getline(std::cin, line)) {
         while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back();
         if (line == "QUIT") break;
-        std::string img, out;
-        if (!parse_enc(line, img, out)) { std::printf("ERR expected: ENC <image> <output>\n"); std::fflush(stdout); continue; }
+        std::string img, second, out;
+        const bool pair = line.rfind("ENCV ", 0) == 0;
+        if ((pair && (!native_video || !parse_encv(line, img, second, out))) ||
+            (!pair && !parse_enc(line, img, out))) {
+            std::printf(pair ? "ERR ENCV requires --native-video and two frames plus output\n" :
+                               "ERR expected: ENC <image> <output>\n");
+            std::fflush(stdout); continue;
+        }
         const auto t0 = std::chrono::steady_clock::now();
         mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(ctx, img.c_str(), false,
                                                                             mtmd_helper_init_opt_default());
         if (!bw.bitmap) { std::printf("ERR cannot read the image %s\n", img.c_str()); std::fflush(stdout); continue; }
+        mtmd_helper_bitmap_wrapper bw2{};
+        if (pair) {
+            bw2 = mtmd_helper_bitmap_init_from_file(ctx, second.c_str(), false, mtmd_helper_init_opt_default());
+            if (!bw2.bitmap || bw.video_ctx || bw2.video_ctx ||
+                mtmd_bitmap_get_nx(bw.bitmap) != mtmd_bitmap_get_nx(bw2.bitmap) ||
+                mtmd_bitmap_get_ny(bw.bitmap) != mtmd_bitmap_get_ny(bw2.bitmap)) {
+                std::printf("ERR ENCV requires two equally sized decoded image frames\n"); std::fflush(stdout);
+                mtmd_bitmap_free(bw.bitmap);
+                if (bw2.bitmap) mtmd_bitmap_free(bw2.bitmap);
+                if (bw.video_ctx) mtmd_helper_video_free(bw.video_ctx);
+                if (bw2.video_ctx) mtmd_helper_video_free(bw2.video_ctx);
+                continue;
+            }
+            mtmd_bitmap_set_mergeable(bw.bitmap, true);
+            mtmd_bitmap_set_mergeable(bw2.bitmap, true);
+        }
         mtmd_input_chunks* chunks = mtmd_input_chunks_init();
-        const std::string prompt = mtmd_default_marker();
+        const std::string marker = mtmd_default_marker();
+        const std::string prompt = pair ? marker + marker : marker;
         mtmd_input_text txt{prompt.c_str(), prompt.size(), false, true};
-        const mtmd_bitmap* bm[1] = {bw.bitmap};
+        const mtmd_bitmap* bm[2] = {bw.bitmap, bw2.bitmap};
         std::string err;
         const mtmd_input_chunk* ichunk = nullptr;
-        if (mtmd_tokenize(ctx, chunks, &txt, bm, 1) != 0) err = "the image could not be preprocessed";
+        int image_chunks = 0;
+        if (mtmd_tokenize(ctx, chunks, &txt, bm, pair ? 2 : 1) != 0) err = "the image could not be preprocessed";
         for (size_t c = 0; err.empty() && c < mtmd_input_chunks_size(chunks); ++c) {
             const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c);
-            if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE) ichunk = ch;
+            if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE) { ichunk = ch; ++image_chunks; }
         }
         if (err.empty() && !ichunk) err = "no image chunk";
+        if (err.empty() && pair && image_chunks != 1) err = "the temporal frame pair did not merge into one chunk";
+        if (err.empty() && pair && mtmd_input_chunk_get_n_tokens(ichunk) > (size_t) video_max_tokens)
+            err = "the temporal pair exceeds --video-max-tokens; reduce video resolution or image min_tokens";
         if (err.empty() && mtmd_encode_chunk(ctx, ichunk) != 0) err = "the vision encoder failed";
         if (err.empty()) {
             const mtmd_image_tokens* it = mtmd_input_chunk_get_tokens_image(ichunk);
@@ -314,7 +367,7 @@ int main(int argc, char** argv) {
             const int nx = (int) last.x + 1, ny = (int) last.y + 1;
             if (nx * ny != n) err = "the image grid is not rectangular (" + std::to_string(n) + " tokens)";
             // never silently produce many times the budget (I7, #3690): over the limit (a rounding margin of an eighth) the picture is refused
-            if (err.empty() && max_tokens > 0 && n > max_tokens + max_tokens / 8)
+            if (err.empty() && !pair && max_tokens > 0 && n > max_tokens + max_tokens / 8)
                 err = "the picture became " + std::to_string(n) + " image tokens, over the limit of " + std::to_string(max_tokens) +
                       " (vision.max_tokens); send a smaller picture or raise the limit";
             const float* embd = mtmd_get_output_embd(ctx);
@@ -335,6 +388,8 @@ int main(int argc, char** argv) {
         mtmd_input_chunks_free(chunks);
         mtmd_bitmap_free(bw.bitmap);
         if (bw.video_ctx) mtmd_helper_video_free(bw.video_ctx);
+        if (bw2.bitmap) mtmd_bitmap_free(bw2.bitmap);
+        if (bw2.video_ctx) mtmd_helper_video_free(bw2.video_ctx);
     }
     mtmd_free(ctx);
     llama_model_free(text);
diff --git a/include/strata/program/visual_prompt.hpp b/include/strata/program/visual_prompt.hpp
new file mode 100644
--- /dev/null
+++ b/include/strata/program/visual_prompt.hpp
@@ -0,0 +1,76 @@
+// Qwen3-VL/Qwen4Exp visual prompt positions. A video temporal patch has the
+// same [1, H, W] geometry as an image; its timestamp is preceding text and its
+// token ID remains video_pad (including for the PLE lookup).
+#pragma once
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <limits>
+#include <string>
+#include <vector>
+
+namespace strata::program {
+constexpr int64_t image_pad_token = 248056;
+constexpr int64_t video_pad_token = 248057;
+struct VisualGrid { int64_t n, nx, ny; };
+struct VisualSpan { int64_t start, pad; };
+
+inline bool visual_pad(int64_t token, bool native_video) {
+    return token == image_pad_token || (native_video && token == video_pad_token);
+}
+
+// Fills the prompt and future decode positions. Token IDs are never rewritten.
+// Callers discard partial output on failure, as with an invalid SVE record.
+inline bool visual_prompt_positions(const std::vector<int64_t>& ids,
+                                    const std::vector<VisualGrid>& grids,
+                                    bool native_video, int32_t* positions, size_t cells,
+                                    std::vector<VisualSpan>& spans, std::string& error) {
+    spans.clear();
+    if (ids.size() > cells || cells > (size_t) std::numeric_limits<int32_t>::max()) {
+        error = "visual prompt exceeds the rotary position table";
+        return false;
+    }
+    auto put = [&](size_t cell, int64_t t, int64_t h, int64_t w) {
+        positions[cell * 3] = (int32_t)t;
+        positions[cell * 3 + 1] = (int32_t)h;
+        positions[cell * 3 + 2] = (int32_t)w;
+    };
+    int64_t p = 0;
+    size_t i = 0, k = 0;
+    while (i < ids.size()) {
+        const int64_t pad = ids[i];
+        if (!visual_pad(pad, native_video)) { put(i++, p, p, p); ++p; continue; }
+        if (k == grids.size()) {
+            error = "the prompt has more visual groups than the embeddings file";
+            return false;
+        }
+        const VisualGrid& grid = grids[k++];
+        if (grid.n < 1 || grid.nx < 1 || grid.ny < 1 || grid.nx > grid.n / grid.ny ||
+            grid.nx * grid.ny != grid.n || (uint64_t)grid.n > ids.size() - i) {
+            error = "invalid or incomplete visual grid";
+            return false;
+        }
+        for (int64_t j = 0; j < grid.n; ++j) {
+            if (ids[i + (size_t)j] != pad) {
+                error = "visual group " + std::to_string(k) + " must contain exactly its grid's homogeneous image_pad or video_pad tokens";
+                return false;
+            }
+            put(i + (size_t)j, p, p + j / grid.nx, p + j % grid.nx);
+        }
+        spans.push_back({(int64_t)i, pad});
+        i += (size_t)grid.n;
+        p += std::max(grid.nx, grid.ny);
+    }
+    if (k != grids.size()) {
+        error = "the embeddings file has more visual groups than the prompt";
+        return false;
+    }
+    if (!ids.empty() && visual_pad(ids.back(), native_video)) {
+        error = "the prompt cannot end inside a visual group";
+        return false;
+    }
+    for (size_t cell = ids.size(); cell < cells; ++cell)
+        put(cell, p + (cell - ids.size()), p + (cell - ids.size()), p + (cell - ids.size()));
+    return true;
+}
+} // namespace strata::program
diff --git a/serve/video.py b/serve/video.py
new file mode 100644
--- /dev/null
+++ b/serve/video.py
@@ -0,0 +1,316 @@
+"""Bounded video decoding for native Qwen3VL temporal-pair encoding.
+
+This module produces RGB frame pairs, not image chat content. The reader must
+encode each pair jointly and the server must use video_pad, with the pair's
+mean timestamp, as specified by Qwen3VLProcessor. Audio is not processed.
+"""
+from __future__ import annotations
+
+import base64
+from contextlib import contextmanager
+from dataclasses import dataclass
+import json
+import math
+import os
+from pathlib import Path
+import queue
+import re
+import shutil
+import subprocess
+import tempfile
+import threading
+import time
+
+MAX_BYTES = 64 * 1024 * 1024
+MAX_PAIRS = 64
+MAX_SECONDS = 300
+MAX_SOURCE_PIXELS = 16_777_216
+MAX_SOURCE_EDGE = 8192
+DECODE_SECONDS = 120
+FORMATS = "mov,matroska,webm,avi,mpeg,mpegts,ogg,gif,asf"
+
+
+class VideoError(ValueError):
+    pass
+
+
+class VideoCancelled(VideoError):
+    pass
+
+
+@dataclass(frozen=True)
+class VideoPair:
+    first: Path
+    second: Path
+    timestamp: float
+
+
+@dataclass(frozen=True)
+class PreparedVideo:
+    pairs: list[VideoPair]
+    duration: float
+    sample_fps: float
+    sampled_timestamps: tuple[float, ...]
+
+
+def _check(deadline, cancel):
+    if cancel is not None and cancel.is_set():
+        raise VideoCancelled("Video decoding was cancelled.")
+    if time.monotonic() >= deadline:
+        raise VideoError("Video decoding exceeded 120 seconds; send a shorter or smaller video.")
+
+
+def _spawn(command, **kwargs):
+    process = subprocess.Popen(command, stdin=subprocess.DEVNULL,
+                               creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0, **kwargs)
+    if os.name == "nt":
+        from . import winjob
+        winjob.contain(process)
+    return process
+
+
+def _finish(process):
+    if process.poll() is None:
+        process.kill()
+    process.wait(timeout=5)
+
+
+def _read_output(stream, limit):
+    stream.seek(0, 2)
+    if stream.tell() > limit:
+        raise VideoError("Video decoder output exceeded its resource limit.")
+    stream.seek(0)
+    return stream.read()
+
+
+def _command(command, deadline, cancel):
+    with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err:
+        process = _spawn(command, stdout=out, stderr=err)
+        try:
+            while process.poll() is None:
+                _check(deadline, cancel)
+                time.sleep(0.05)
+            if process.returncode:
+                raise VideoError("The video could not be probed; it may be damaged or use an unsupported format.")
+            return _read_output(out, 1024 * 1024)
+        finally:
+            _finish(process)
+
+
+def _positive(value):
+    try:
+        number = float(value)
+        return number if math.isfinite(number) and number > 0 else None
+    except (TypeError, ValueError, OverflowError):
+        return None
+
+
+def _options(config):
+    config = config or {}
+    values = {}
+    for name, default, maximum in (("max_pairs", 64, MAX_PAIRS), ("max_bytes", MAX_BYTES, MAX_BYTES),
+                                   ("tokens_per_pair", 256, 1024)):
+        value = config.get(name, default)
+        minimum = 8 if name == "tokens_per_pair" else 1
+        if type(value) is not int or not minimum <= value <= maximum:
+            raise VideoError(f"video.{name} must be an integer from {minimum} to {maximum}.")
+        values[name] = value
+    for name, default, maximum in (("fps", 2, 8), ("max_duration_seconds", 300, MAX_SECONDS)):
+        value = config.get(name, default)
+        number = _positive(value)
+        if isinstance(value, bool) or number is None or number > maximum:
+            raise VideoError(f"video.{name} must be positive and at most {maximum}.")
+        values[name] = number
+    return values
+
+
+def _inline(source, max_bytes):
+    if isinstance(source, bytes):
+        data = source
+    elif isinstance(source, str) and source.lower().startswith("data:video/"):
+        header, comma, encoded = source.partition(",")
+        if not comma or not header.lower().endswith(";base64"):
+            raise VideoError("Video input requires an inline base64 video data URL.")
+        if len(encoded) > 4 * ((max_bytes + 2) // 3):
+            raise VideoError("The video exceeds the configured byte limit.")
+        try:
+            data = base64.b64decode(encoded, validate=True)
+        except (ValueError, UnicodeError):
+            raise VideoError("Video input contains invalid base64 data.") from None
+    else:
+        raise VideoError("Video input requires inline video bytes; remote URLs and local paths are not supported.")
+    if not data or len(data) > max_bytes:
+        raise VideoError("The video is empty or exceeds the configured byte limit.")
+    return data
+
+
+def _sample_indices(total_frames, duration, fps, max_pairs):
+    # An explicit native-video sampling budget; retain both ends, never truncate
+    # the tail. An odd final source frame is duplicated by temporal padding.
+    desired = max(4, 2 * math.ceil(duration * fps / 2))
+    count = min(total_frames, desired)
+    if (count + 1) // 2 > max_pairs:
+        raise VideoError(f"This video needs {(count + 1) // 2} frame pairs at {fps:g} fps; "
+                         f"the limit is {max_pairs}. Split the video or lower video.fps explicitly.")
+    if count == 1:
+        return [0]
+    return [round(i * (total_frames - 1) / (count - 1)) for i in range(count)]
+
+
+def _resize_shape(width, height, tokens):
+    # Qwen's smart-resize spatial rule, factor=patch16*merge2. The native
+    # video budget caps a pair rather than borrowing the still-image budget.
+    factor, minimum, maximum = 32, 8 * 1024, tokens * 1024
+    if max(width, height) / min(width, height) > 200:
+        raise VideoError("Video aspect ratio exceeds 200.")
+    if min(width, height) < factor:
+        scale = factor / min(width, height)
+        width, height = int(width * scale), int(height * scale)
+    w, h = round(width / factor) * factor, round(height / factor) * factor
+    if w * h > maximum:
+        scale = math.sqrt(width * height / maximum)
+        w, h = max(factor, math.floor(width / scale / factor) * factor), max(factor, math.floor(height / scale / factor) * factor)
+    elif w * h < minimum:
+        scale = math.sqrt(minimum / (width * height))
+        w, h = math.ceil(width * scale / factor) * factor, math.ceil(height * scale / factor) * factor
+    if w * h > maximum:
+        raise VideoError("Video aspect ratio cannot fit the temporal-pair token budget.")
+    return w, h
+
+
+def _frames(command, root, width, height, rotation, target, count, deadline, cancel):
+    """Drain raw RGB one frame at a time, so source-size images never accumulate."""
+    from PIL import Image
+
+    channel = queue.Queue(maxsize=1)
+    stop = threading.Event()
+    frame_bytes = width * height * 3
+    with tempfile.TemporaryFile() as errors:
+        process = _spawn(command, stdout=subprocess.PIPE, stderr=errors)
+
+        def reader():
+            try:
+                while not stop.is_set():
+                    item = process.stdout.read(frame_bytes)
+                    while not stop.is_set():
+                        try:
+                            channel.put(item, timeout=0.1)
+                            break
+                        except queue.Full:
+                            pass
+                    if not item:
+                        return
+            except (OSError, ValueError):
+                # Main thread kills the process and closes the pipe on cancellation.
+                return
+
+        thread = threading.Thread(target=reader, name="strata-video-frames", daemon=True)
+        thread.start()
+        paths = []
+        try:
+            while True:
+                _check(deadline, cancel)
+                try:
+                    raw = channel.get(timeout=0.1)
+                except queue.Empty:
+                    if not thread.is_alive():
+                        raise VideoError("Video decoder stopped before completing its frames.")
+                    continue
+                if not raw:
+                    break
+                if len(raw) != frame_bytes or len(paths) >= count:
+                    raise VideoError("Video decoding produced incomplete or unexpected frames.")
+                with Image.frombytes("RGB", (width, height), raw) as original:
+                    rotated = original.rotate(rotation, expand=True) if rotation else original
+                    try:
+                        with rotated.resize(target, resample=Image.Resampling.BICUBIC) as resized:
+                            path = root / f"frame-{len(paths):04d}.png"
+                            resized.save(path, format="PNG")
+                            paths.append(path)
+                    finally:
+                        if rotated is not original:
+                            rotated.close()
+            while process.poll() is None:
+                _check(deadline, cancel)
+                time.sleep(0.05)
+            if process.returncode or len(paths) != count:
+                raise VideoError("The video could not be decoded completely; no partial video was accepted.")
+            log = _read_output(errors, 2 * 1024 * 1024).decode("utf-8", "replace")
+            timestamps = [float(value) for value in re.findall(r"\bn:\s*\d+\s+pts:.*?\bpts_time:([-+0-9.eE]+)", log)]
+            if (len(timestamps) != count or any(not math.isfinite(v) or v < 0 for v in timestamps)
+                    or any(b < a for a, b in zip(timestamps, timestamps[1:]))):
+                raise VideoError("Could not determine the selected video frames' timestamps.")
+            return paths, timestamps
+        finally:
+            stop.set()
+            _finish(process)
+            thread.join(timeout=2)
+            process.stdout.close()
+
+
+@contextmanager
+def prepare_video(source, config=None, cancel=None, *, directory=None):
+    """Yield temporary RGB frame pairs and actual relative timestamps; clean on exit.
+
+    Sources are bytes or inline data:video/*;base64. Parameters may tighten the
+    fixed resource ceilings. The decoder cannot open network/playlist resources.
+    """
+    options = _options(config)
+    data = _inline(source, options["max_bytes"])
+    ffprobe, ffmpeg = shutil.which("ffprobe"), shutil.which("ffmpeg")
+    if not ffprobe or not ffmpeg:
+        raise VideoError("Native video input requires ffprobe and ffmpeg on PATH.")
+    deadline = time.monotonic() + DECODE_SECONDS
+    _check(deadline, cancel)
+    with tempfile.TemporaryDirectory(prefix="native-video-", dir=directory) as temp:
+        root = Path(temp)
+        source_path = root / "attachment.bin"
+        source_path.write_bytes(data)
+        del data
+        limits = ["-protocol_whitelist", "file,pipe", "-format_whitelist", FORMATS,
+                  "-max_alloc", "134217728", "-threads", "2", "-max_pixels", str(MAX_SOURCE_PIXELS),
+                  "-probesize", "8388608", "-analyzeduration", "10000000"]
+        probe = [ffprobe, "-v", "error", *limits, "-select_streams", "v",
+                 "-show_entries", "stream=index,codec_type,width,height,duration,nb_frames:stream_disposition=attached_pic:stream_side_data=rotation:format=duration",
+                 "-of", "json", str(source_path)]
+        try:
+            metadata = json.loads(_command(probe, deadline, cancel))
+            stream = next(s for s in metadata.get("streams", []) if s.get("codec_type") == "video"
+                          and not s.get("disposition", {}).get("attached_pic", 0))
+            width, height, index = int(stream["width"]), int(stream["height"]), int(stream["index"])
+            duration = _positive(stream.get("duration")) or _positive(metadata.get("format", {}).get("duration"))
+            rotation = float(next((s["rotation"] for s in stream.get("side_data_list", []) if "rotation" in s), 0))
+        except VideoError:
+            raise
+        except (ValueError, TypeError, KeyError, StopIteration):
+            raise VideoError("The attachment has no readable video stream.") from None
+        if width < 1 or height < 1 or max(width, height) > MAX_SOURCE_EDGE or width * height > MAX_SOURCE_PIXELS:
+            raise VideoError("Video dimensions exceed the decoder limit.")
+        if duration is None or duration > options["max_duration_seconds"]:
+            raise VideoError("Video duration is unknown or exceeds the configured limit; split the video.")
+        if not math.isfinite(rotation) or abs(rotation / 90 - round(rotation / 90)) > 0.001:
+            raise VideoError("Video display rotation must be a multiple of 90 degrees.")
+        total = _positive(stream.get("nb_frames"))
+        if total is None:
+            count_cmd = [ffprobe, "-v", "error", *limits, "-select_streams", str(index), "-count_frames",
+                         "-show_entries", "stream=nb_read_frames", "-of", "json", str(source_path)]
+            counts = json.loads(_command(count_cmd, deadline, cancel))
+            total = _positive(counts.get("streams", [{}])[0].get("nb_read_frames"))
+        if total is None or total != int(total) or total > 1_000_000:
+            raise VideoError("Could not determine a bounded video frame count.")
+        indices = _sample_indices(int(total), duration, options["fps"], options["max_pairs"])
+        display_shape = (height, width) if round(rotation / 90) % 2 else (width, height)
+        target = _resize_shape(*display_shape, options["tokens_per_pair"])
+        select = "+".join(f"eq(n\\,{i})" for i in indices)
+        command = [ffmpeg, "-hide_banner", "-loglevel", "info", "-nostdin", *limits,
+                   "-noautorotate", "-i", str(source_path), "-map", f"0:{index}", "-an", "-sn", "-dn",
+                   "-vf", f"select={select},setpts=PTS-STARTPTS,showinfo", "-filter_threads", "1",
+                   "-frames:v", str(len(indices)), "-fps_mode", "passthrough", "-c:v", "rawvideo",
+                   "-threads", "2", "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1"]
+        paths, timestamps = _frames(command, root, width, height, rotation, target, len(indices), deadline, cancel)
+        if len(paths) % 2:
+            paths.append(paths[-1])
+            timestamps.append(timestamps[-1])
+        pairs = [VideoPair(paths[i], paths[i + 1], (timestamps[i] + timestamps[i + 1]) / 2)
+                 for i in range(0, len(paths), 2)]
+        yield PreparedVideo(pairs, duration, options["fps"], tuple(timestamps))
diff --git a/serve/test_video.py b/serve/test_video.py
new file mode 100644
--- /dev/null
+++ b/serve/test_video.py
@@ -0,0 +1,140 @@
+"""Native-video preparation checks; tiny synthetic clips, no model or GPU."""
+import base64
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import threading
+import unittest
+from unittest.mock import patch
+
+from PIL import Image
+
+from . import video
+
+
+class VideoUnitTests(unittest.TestCase):
+    def test_inline_only_and_byte_budget(self):
+        for source in ("https://example.invalid/v.mp4", "C:/private.mp4", "file:///private.mp4",
+                       "data:video/mp4,abc", "data:application/pdf;base64,AAAA", "data:video/mp4;base64,!"):
+            with self.subTest(source=source), self.assertRaises(video.VideoError):
+                video._inline(source, 10)
+        self.assertEqual(video._inline("data:video/mp4;base64,YWJj", 3), b"abc")
+        for data in (b"", b"abcd", "data:video/mp4;base64,YWJjZA=="):
+            with self.assertRaises(video.VideoError):
+                video._inline(data, 3)
+
+    def test_config_cannot_disable_resource_limits(self):
+        for options in ({"fps": 0}, {"fps": float("nan")}, {"max_pairs": 65}, {"tokens_per_pair": 7},
+                        {"max_bytes": video.MAX_BYTES + 1}, {"max_duration_seconds": 301}, {"fps": True}):
+            with self.subTest(options=options), self.assertRaises(video.VideoError):
+                video._options(options)
+
+    def test_sampling_spans_both_ends_and_uses_even_frame_budget(self):
+        indices = video._sample_indices(361, 15.04, 2, 64)
+        self.assertEqual(len(indices), 32)
+        self.assertEqual((indices[0], indices[-1]), (0, 360))
+        self.assertEqual(len(indices), len(set(indices)))
+
+    def test_too_many_pairs_rejects_instead_of_dropping_tail(self):
+        with self.assertRaisesRegex(video.VideoError, "Split the video"):
+            video._sample_indices(3600, 120, 2, 64)
+
+    def test_short_clips_keep_available_frames(self):
+        self.assertEqual(video._sample_indices(1, 0.04, 2, 64), [0])
+        self.assertEqual(video._sample_indices(3, 0.12, 2, 64), [0, 1, 2])
+
+    def test_resize_is_aligned_and_bounded(self):
+        for shape in ((720, 1280), (1920, 1080), (16, 32), (512, 512)):
+            width, height = video._resize_shape(*shape, 256)
+            self.assertEqual(width % 32, 0)
+            self.assertEqual(height % 32, 0)
+            self.assertLessEqual(width * height // 1024, 256)
+            self.assertGreaterEqual(width * height // 1024, 8)
+        self.assertEqual(video._resize_shape(720, 1280, 256), (384, 672))
+
+    def test_cancellation_before_decode(self):
+        cancel = threading.Event()
+        cancel.set()
+        with self.assertRaises(video.VideoCancelled):
+            with video.prepare_video(b"synthetic", cancel=cancel):
+                self.fail("cancelled input yielded")
+
+    def test_tools_missing_is_clear(self):
+        with patch.object(video.shutil, "which", return_value=None), self.assertRaisesRegex(video.VideoError, "ffprobe and ffmpeg"):
+            with video.prepare_video(b"synthetic"):
+                pass
+
+
+@unittest.skipUnless(shutil.which("ffmpeg") and shutil.which("ffprobe"), "FFmpeg is not installed")
+class VideoDecodeTests(unittest.TestCase):
+    @classmethod
+    def setUpClass(cls):
+        cls.temp = tempfile.TemporaryDirectory(prefix="strata-native-video-test-")
+        cls.root = Path(cls.temp.name)
+        cls.clip = cls.root / "clip.mp4"
+        result = subprocess.run([
+            shutil.which("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin",
+            "-f", "lavfi", "-i", "color=c=red:s=160x96:r=5:d=1",
+            "-f", "lavfi", "-i", "color=c=blue:s=160x96:r=5:d=1",
+            "-filter_complex", "[0:v][1:v]concat=n=2:v=1:a=0[v]", "-filter_complex_threads", "1",
+            "-map", "[v]", "-c:v", "libx264", "-threads", "2", "-pix_fmt", "yuv420p", str(cls.clip)],
+            stdin=subprocess.DEVNULL, capture_output=True, timeout=20,
+            creationflags=subprocess.CREATE_NO_WINDOW if video.os.name == "nt" else 0)
+        if result.returncode:
+            raise RuntimeError(result.stderr.decode("utf-8", "replace"))
+        cls.data = cls.clip.read_bytes()
+
+    @classmethod
+    def tearDownClass(cls):
+        cls.temp.cleanup()
+
+    def test_real_pairs_keep_actual_timestamps_colors_and_cleanup(self):
+        with video.prepare_video(self.data, directory=self.root) as prepared:
+            self.assertEqual(len(prepared.pairs), 2)
+            self.assertEqual(prepared.sampled_timestamps, (0.0, 0.6, 1.2, 1.8))
+            self.assertAlmostEqual(prepared.pairs[0].timestamp, 0.3)
+            self.assertAlmostEqual(prepared.pairs[1].timestamp, 1.5)
+            first, last = prepared.pairs[0].first, prepared.pairs[-1].second
+            with Image.open(first) as image:
+                self.assertEqual(image.mode, "RGB")
+                self.assertEqual(image.size, (160, 96))
+                self.assertGreater(image.getpixel((40, 40))[0], 240)
+            with Image.open(last) as image:
+                self.assertGreater(image.getpixel((40, 40))[2], 240)
+        self.assertFalse(first.exists())
+        self.assertFalse(first.parent.exists())
+
+    def test_data_url_and_distinct_frames_inside_pair(self):
+        source = "data:video/mp4;base64," + base64.b64encode(self.data).decode("ascii")
+        # Four frames minimum: the middle selected frames straddle the change.
+        with video.prepare_video(source, {"fps": 3}, directory=self.root) as prepared:
+            self.assertEqual(len(prepared.pairs), 3)
+            middle = prepared.pairs[1]
+            self.assertNotEqual(middle.first.read_bytes(), middle.second.read_bytes())
+
+    def test_rejects_duration_and_cleans_temp(self):
+        before = set(self.root.iterdir())
+        with self.assertRaisesRegex(video.VideoError, "duration"):
+            with video.prepare_video(self.data, {"max_duration_seconds": 1}, directory=self.root):
+                pass
+        self.assertEqual(set(self.root.iterdir()), before)
+
+    def test_rejects_damaged_and_playlist_input(self):
+        inputs = (b"damaged video", b"#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nhttp://127.0.0.1:9/private.ts\n#EXT-X-ENDLIST\n")
+        for data in inputs:
+            with self.subTest(data=data[:10]), self.assertRaises(video.VideoError):
+                with video.prepare_video(data, directory=self.root):
+                    pass
+
+    def test_cancellation_during_command_reaps_child(self):
+        cancelled = threading.Event()
+        cancelled.set()
+        with self.assertRaises(video.VideoCancelled):
+            video._command([shutil.which("ffmpeg"), "-hide_banner", "-loglevel", "error", "-re", "-f", "lavfi",
+                            "-i", "color=s=16x16:r=1:d=60", "-f", "null", "-"],
+                           video.time.monotonic() + 120, cancelled)
+
+
+if __name__ == "__main__":
+    unittest.main()
<!-- gh-comment-id:6394891718 --> @RAFOLIE commented on GitHub (Oct 25, 2026): ### Reference patch — part 2/3 Save the fenced diff as `native-video-part-2.patch` (UTF-8, LF). Concatenate the parts in numbered order before applying. This is part of the AI-assisted local prototype described in the issue. Part SHA256: `3c5a12eb15dc3688b8b28626a8b5ba353f5ceefe1421df28f1bc164730a31846` ````diff diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index feae414533face08a24b672be6cebfcb778092a8..5c4537ca2b2acb8390dc2d0512c4f54901604afd 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -10,6 +10,7 @@ // // Resident: prints "READY <n_embd>", then per stdin line // ENC <image path> <output path> -> "OK <n_tokens> <nx> <ny> <ms>" or "ERR <message>" +// With --native-video: READY also advertises VIDEO_PAIR1; ENCV <frame0> <frame1> <out> encodes a real temporal pair. // QUIT // The output file is int32 {0x31455653 'SVE1', n_tokens, nx, ny, n_embd} then float32 [n_tokens][n_embd], // row i at grid position (x = i % nx, y = i / nx). The text model is opened vocab-only (no weights). @@ -36,6 +37,7 @@ #include <cstdlib> #include <cstring> #include <iostream> +#include <iomanip> #include <sstream> #include <string> #include <thread> @@ -66,6 +68,14 @@ bool parse_enc(const std::string& line, std::string& img, std::string& out) { return !img.empty() && !out.empty(); } +bool parse_encv(const std::string& line, std::string& first, std::string& second, std::string& out) { + if (line.rfind("ENCV ", 0) != 0) return false; + std::istringstream in(line.substr(5)); + std::string extra; + return bool(in >> std::quoted(first) >> std::quoted(second) >> std::quoted(out)) && + !(in >> extra) && !first.empty() && !second.empty() && !out.empty(); +} + } // namespace int main(int argc, char** argv) { @@ -86,7 +96,8 @@ int main(int argc, char** argv) { } #endif std::string mmproj, model; - bool gpu = false; + bool gpu = false, native_video = false; + int video_max_tokens = 256; int threads = 0, max_tokens = 0, min_tokens = 0; llama_flash_attn_type fa = LLAMA_FLASH_ATTN_TYPE_AUTO; bool fa_given = false; @@ -99,6 +110,8 @@ int main(int argc, char** argv) { if (a == "--mmproj") mmproj = next(); else if (a == "--model") model = next(); else if (a == "--gpu") gpu = true; + else if (a == "--native-video") native_video = true; + else if (a == "--video-max-tokens") video_max_tokens = std::atoi(next().c_str()); else if (a == "--version") { #ifdef STRATA_VISION_HIP std::printf("strata-vision hip (GPU architectures: %s)\n", STRATA_VISION_HIP_ARCHS); @@ -124,7 +137,12 @@ int main(int argc, char** argv) { } if (mmproj.empty() || model.empty()) { std::fprintf(stderr, "usage: strata-vision --mmproj <mmproj.gguf> --model <model.gguf> [--gpu] [--threads N] " - "[--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto]\n"); + "[--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto] " + "[--native-video] [--video-max-tokens N]\n"); + return 2; + } + if (native_video && (video_max_tokens < 8 || video_max_tokens > 1024)) { + std::fprintf(stderr, "--video-max-tokens must be between 8 and 1024\n"); return 2; } // On the CPU the GPU stays unseen: a CUDA build otherwise opens a context there (measured: 0.4-0.7 GB of VRAM, @@ -238,14 +256,22 @@ int main(int argc, char** argv) { std::chrono::duration<double>(std::chrono::steady_clock::now() - load_t0).count()); // a vocab-only model reports no hparams, so the width comes from the projector: its output is the model's input int n_embd = 0; + bool qwen_temporal_pair = false; { gguf_init_params gp{true, nullptr}; gguf_context* gg = gguf_init_from_file(mmproj.c_str(), gp); const int64_t k = gg ? gguf_find_key(gg, "clip.vision.projection_dim") : -1; if (k >= 0) n_embd = (int) gguf_get_val_u32(gg, k); + const int64_t projector = gg ? gguf_find_key(gg, "clip.projector_type") : -1; + if (projector >= 0 && gguf_get_kv_type(gg, projector) == GGUF_TYPE_STRING) + qwen_temporal_pair = std::string(gguf_get_val_str(gg, projector)) == "qwen3vl_merger"; if (gg) gguf_free(gg); } if (n_embd <= 0) { std::printf("ERR the vision encoder has no projection_dim\n"); std::fflush(stdout); return 1; } + if (native_video && !qwen_temporal_pair) { + std::printf("ERR native video requires the Qwen3VL temporal-pair projector\n"); + std::fflush(stdout); mtmd_free(ctx); llama_model_free(text); llama_backend_free(); return 1; + } // Warm up at the LARGEST picture before READY: the encoder's GPU work buffers are allocated now, not at the first // real picture. The server starts this process before the engine, so the engine sizes its expert cache from // what is really left; allocating ~1 GB later, on a GPU the engine has filled, made Windows page GPU memory and @@ -280,31 +306,58 @@ int main(int argc, char** argv) { mtmd_input_chunks_free(chunks); if (bm) mtmd_bitmap_free(bm); } - std::printf("READY %d\n", n_embd); + std::printf(native_video ? "READY %d VIDEO_PAIR1\n" : "READY %d\n", n_embd); std::fflush(stdout); std::string line; while (std::getline(std::cin, line)) { while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back(); if (line == "QUIT") break; - std::string img, out; - if (!parse_enc(line, img, out)) { std::printf("ERR expected: ENC <image> <output>\n"); std::fflush(stdout); continue; } + std::string img, second, out; + const bool pair = line.rfind("ENCV ", 0) == 0; + if ((pair && (!native_video || !parse_encv(line, img, second, out))) || + (!pair && !parse_enc(line, img, out))) { + std::printf(pair ? "ERR ENCV requires --native-video and two frames plus output\n" : + "ERR expected: ENC <image> <output>\n"); + std::fflush(stdout); continue; + } const auto t0 = std::chrono::steady_clock::now(); mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(ctx, img.c_str(), false, mtmd_helper_init_opt_default()); if (!bw.bitmap) { std::printf("ERR cannot read the image %s\n", img.c_str()); std::fflush(stdout); continue; } + mtmd_helper_bitmap_wrapper bw2{}; + if (pair) { + bw2 = mtmd_helper_bitmap_init_from_file(ctx, second.c_str(), false, mtmd_helper_init_opt_default()); + if (!bw2.bitmap || bw.video_ctx || bw2.video_ctx || + mtmd_bitmap_get_nx(bw.bitmap) != mtmd_bitmap_get_nx(bw2.bitmap) || + mtmd_bitmap_get_ny(bw.bitmap) != mtmd_bitmap_get_ny(bw2.bitmap)) { + std::printf("ERR ENCV requires two equally sized decoded image frames\n"); std::fflush(stdout); + mtmd_bitmap_free(bw.bitmap); + if (bw2.bitmap) mtmd_bitmap_free(bw2.bitmap); + if (bw.video_ctx) mtmd_helper_video_free(bw.video_ctx); + if (bw2.video_ctx) mtmd_helper_video_free(bw2.video_ctx); + continue; + } + mtmd_bitmap_set_mergeable(bw.bitmap, true); + mtmd_bitmap_set_mergeable(bw2.bitmap, true); + } mtmd_input_chunks* chunks = mtmd_input_chunks_init(); - const std::string prompt = mtmd_default_marker(); + const std::string marker = mtmd_default_marker(); + const std::string prompt = pair ? marker + marker : marker; mtmd_input_text txt{prompt.c_str(), prompt.size(), false, true}; - const mtmd_bitmap* bm[1] = {bw.bitmap}; + const mtmd_bitmap* bm[2] = {bw.bitmap, bw2.bitmap}; std::string err; const mtmd_input_chunk* ichunk = nullptr; - if (mtmd_tokenize(ctx, chunks, &txt, bm, 1) != 0) err = "the image could not be preprocessed"; + int image_chunks = 0; + if (mtmd_tokenize(ctx, chunks, &txt, bm, pair ? 2 : 1) != 0) err = "the image could not be preprocessed"; for (size_t c = 0; err.empty() && c < mtmd_input_chunks_size(chunks); ++c) { const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c); - if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE) ichunk = ch; + if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE) { ichunk = ch; ++image_chunks; } } if (err.empty() && !ichunk) err = "no image chunk"; + if (err.empty() && pair && image_chunks != 1) err = "the temporal frame pair did not merge into one chunk"; + if (err.empty() && pair && mtmd_input_chunk_get_n_tokens(ichunk) > (size_t) video_max_tokens) + err = "the temporal pair exceeds --video-max-tokens; reduce video resolution or image min_tokens"; if (err.empty() && mtmd_encode_chunk(ctx, ichunk) != 0) err = "the vision encoder failed"; if (err.empty()) { const mtmd_image_tokens* it = mtmd_input_chunk_get_tokens_image(ichunk); @@ -314,7 +367,7 @@ int main(int argc, char** argv) { const int nx = (int) last.x + 1, ny = (int) last.y + 1; if (nx * ny != n) err = "the image grid is not rectangular (" + std::to_string(n) + " tokens)"; // never silently produce many times the budget (I7, #3690): over the limit (a rounding margin of an eighth) the picture is refused - if (err.empty() && max_tokens > 0 && n > max_tokens + max_tokens / 8) + if (err.empty() && !pair && max_tokens > 0 && n > max_tokens + max_tokens / 8) err = "the picture became " + std::to_string(n) + " image tokens, over the limit of " + std::to_string(max_tokens) + " (vision.max_tokens); send a smaller picture or raise the limit"; const float* embd = mtmd_get_output_embd(ctx); @@ -335,6 +388,8 @@ int main(int argc, char** argv) { mtmd_input_chunks_free(chunks); mtmd_bitmap_free(bw.bitmap); if (bw.video_ctx) mtmd_helper_video_free(bw.video_ctx); + if (bw2.bitmap) mtmd_bitmap_free(bw2.bitmap); + if (bw2.video_ctx) mtmd_helper_video_free(bw2.video_ctx); } mtmd_free(ctx); llama_model_free(text); diff --git a/include/strata/program/visual_prompt.hpp b/include/strata/program/visual_prompt.hpp new file mode 100644 --- /dev/null +++ b/include/strata/program/visual_prompt.hpp @@ -0,0 +1,76 @@ +// Qwen3-VL/Qwen4Exp visual prompt positions. A video temporal patch has the +// same [1, H, W] geometry as an image; its timestamp is preceding text and its +// token ID remains video_pad (including for the PLE lookup). +#pragma once +#include <algorithm> +#include <cstddef> +#include <cstdint> +#include <limits> +#include <string> +#include <vector> + +namespace strata::program { +constexpr int64_t image_pad_token = 248056; +constexpr int64_t video_pad_token = 248057; +struct VisualGrid { int64_t n, nx, ny; }; +struct VisualSpan { int64_t start, pad; }; + +inline bool visual_pad(int64_t token, bool native_video) { + return token == image_pad_token || (native_video && token == video_pad_token); +} + +// Fills the prompt and future decode positions. Token IDs are never rewritten. +// Callers discard partial output on failure, as with an invalid SVE record. +inline bool visual_prompt_positions(const std::vector<int64_t>& ids, + const std::vector<VisualGrid>& grids, + bool native_video, int32_t* positions, size_t cells, + std::vector<VisualSpan>& spans, std::string& error) { + spans.clear(); + if (ids.size() > cells || cells > (size_t) std::numeric_limits<int32_t>::max()) { + error = "visual prompt exceeds the rotary position table"; + return false; + } + auto put = [&](size_t cell, int64_t t, int64_t h, int64_t w) { + positions[cell * 3] = (int32_t)t; + positions[cell * 3 + 1] = (int32_t)h; + positions[cell * 3 + 2] = (int32_t)w; + }; + int64_t p = 0; + size_t i = 0, k = 0; + while (i < ids.size()) { + const int64_t pad = ids[i]; + if (!visual_pad(pad, native_video)) { put(i++, p, p, p); ++p; continue; } + if (k == grids.size()) { + error = "the prompt has more visual groups than the embeddings file"; + return false; + } + const VisualGrid& grid = grids[k++]; + if (grid.n < 1 || grid.nx < 1 || grid.ny < 1 || grid.nx > grid.n / grid.ny || + grid.nx * grid.ny != grid.n || (uint64_t)grid.n > ids.size() - i) { + error = "invalid or incomplete visual grid"; + return false; + } + for (int64_t j = 0; j < grid.n; ++j) { + if (ids[i + (size_t)j] != pad) { + error = "visual group " + std::to_string(k) + " must contain exactly its grid's homogeneous image_pad or video_pad tokens"; + return false; + } + put(i + (size_t)j, p, p + j / grid.nx, p + j % grid.nx); + } + spans.push_back({(int64_t)i, pad}); + i += (size_t)grid.n; + p += std::max(grid.nx, grid.ny); + } + if (k != grids.size()) { + error = "the embeddings file has more visual groups than the prompt"; + return false; + } + if (!ids.empty() && visual_pad(ids.back(), native_video)) { + error = "the prompt cannot end inside a visual group"; + return false; + } + for (size_t cell = ids.size(); cell < cells; ++cell) + put(cell, p + (cell - ids.size()), p + (cell - ids.size()), p + (cell - ids.size())); + return true; +} +} // namespace strata::program diff --git a/serve/video.py b/serve/video.py new file mode 100644 --- /dev/null +++ b/serve/video.py @@ -0,0 +1,316 @@ +"""Bounded video decoding for native Qwen3VL temporal-pair encoding. + +This module produces RGB frame pairs, not image chat content. The reader must +encode each pair jointly and the server must use video_pad, with the pair's +mean timestamp, as specified by Qwen3VLProcessor. Audio is not processed. +""" +from __future__ import annotations + +import base64 +from contextlib import contextmanager +from dataclasses import dataclass +import json +import math +import os +from pathlib import Path +import queue +import re +import shutil +import subprocess +import tempfile +import threading +import time + +MAX_BYTES = 64 * 1024 * 1024 +MAX_PAIRS = 64 +MAX_SECONDS = 300 +MAX_SOURCE_PIXELS = 16_777_216 +MAX_SOURCE_EDGE = 8192 +DECODE_SECONDS = 120 +FORMATS = "mov,matroska,webm,avi,mpeg,mpegts,ogg,gif,asf" + + +class VideoError(ValueError): + pass + + +class VideoCancelled(VideoError): + pass + + +@dataclass(frozen=True) +class VideoPair: + first: Path + second: Path + timestamp: float + + +@dataclass(frozen=True) +class PreparedVideo: + pairs: list[VideoPair] + duration: float + sample_fps: float + sampled_timestamps: tuple[float, ...] + + +def _check(deadline, cancel): + if cancel is not None and cancel.is_set(): + raise VideoCancelled("Video decoding was cancelled.") + if time.monotonic() >= deadline: + raise VideoError("Video decoding exceeded 120 seconds; send a shorter or smaller video.") + + +def _spawn(command, **kwargs): + process = subprocess.Popen(command, stdin=subprocess.DEVNULL, + creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0, **kwargs) + if os.name == "nt": + from . import winjob + winjob.contain(process) + return process + + +def _finish(process): + if process.poll() is None: + process.kill() + process.wait(timeout=5) + + +def _read_output(stream, limit): + stream.seek(0, 2) + if stream.tell() > limit: + raise VideoError("Video decoder output exceeded its resource limit.") + stream.seek(0) + return stream.read() + + +def _command(command, deadline, cancel): + with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err: + process = _spawn(command, stdout=out, stderr=err) + try: + while process.poll() is None: + _check(deadline, cancel) + time.sleep(0.05) + if process.returncode: + raise VideoError("The video could not be probed; it may be damaged or use an unsupported format.") + return _read_output(out, 1024 * 1024) + finally: + _finish(process) + + +def _positive(value): + try: + number = float(value) + return number if math.isfinite(number) and number > 0 else None + except (TypeError, ValueError, OverflowError): + return None + + +def _options(config): + config = config or {} + values = {} + for name, default, maximum in (("max_pairs", 64, MAX_PAIRS), ("max_bytes", MAX_BYTES, MAX_BYTES), + ("tokens_per_pair", 256, 1024)): + value = config.get(name, default) + minimum = 8 if name == "tokens_per_pair" else 1 + if type(value) is not int or not minimum <= value <= maximum: + raise VideoError(f"video.{name} must be an integer from {minimum} to {maximum}.") + values[name] = value + for name, default, maximum in (("fps", 2, 8), ("max_duration_seconds", 300, MAX_SECONDS)): + value = config.get(name, default) + number = _positive(value) + if isinstance(value, bool) or number is None or number > maximum: + raise VideoError(f"video.{name} must be positive and at most {maximum}.") + values[name] = number + return values + + +def _inline(source, max_bytes): + if isinstance(source, bytes): + data = source + elif isinstance(source, str) and source.lower().startswith("data:video/"): + header, comma, encoded = source.partition(",") + if not comma or not header.lower().endswith(";base64"): + raise VideoError("Video input requires an inline base64 video data URL.") + if len(encoded) > 4 * ((max_bytes + 2) // 3): + raise VideoError("The video exceeds the configured byte limit.") + try: + data = base64.b64decode(encoded, validate=True) + except (ValueError, UnicodeError): + raise VideoError("Video input contains invalid base64 data.") from None + else: + raise VideoError("Video input requires inline video bytes; remote URLs and local paths are not supported.") + if not data or len(data) > max_bytes: + raise VideoError("The video is empty or exceeds the configured byte limit.") + return data + + +def _sample_indices(total_frames, duration, fps, max_pairs): + # An explicit native-video sampling budget; retain both ends, never truncate + # the tail. An odd final source frame is duplicated by temporal padding. + desired = max(4, 2 * math.ceil(duration * fps / 2)) + count = min(total_frames, desired) + if (count + 1) // 2 > max_pairs: + raise VideoError(f"This video needs {(count + 1) // 2} frame pairs at {fps:g} fps; " + f"the limit is {max_pairs}. Split the video or lower video.fps explicitly.") + if count == 1: + return [0] + return [round(i * (total_frames - 1) / (count - 1)) for i in range(count)] + + +def _resize_shape(width, height, tokens): + # Qwen's smart-resize spatial rule, factor=patch16*merge2. The native + # video budget caps a pair rather than borrowing the still-image budget. + factor, minimum, maximum = 32, 8 * 1024, tokens * 1024 + if max(width, height) / min(width, height) > 200: + raise VideoError("Video aspect ratio exceeds 200.") + if min(width, height) < factor: + scale = factor / min(width, height) + width, height = int(width * scale), int(height * scale) + w, h = round(width / factor) * factor, round(height / factor) * factor + if w * h > maximum: + scale = math.sqrt(width * height / maximum) + w, h = max(factor, math.floor(width / scale / factor) * factor), max(factor, math.floor(height / scale / factor) * factor) + elif w * h < minimum: + scale = math.sqrt(minimum / (width * height)) + w, h = math.ceil(width * scale / factor) * factor, math.ceil(height * scale / factor) * factor + if w * h > maximum: + raise VideoError("Video aspect ratio cannot fit the temporal-pair token budget.") + return w, h + + +def _frames(command, root, width, height, rotation, target, count, deadline, cancel): + """Drain raw RGB one frame at a time, so source-size images never accumulate.""" + from PIL import Image + + channel = queue.Queue(maxsize=1) + stop = threading.Event() + frame_bytes = width * height * 3 + with tempfile.TemporaryFile() as errors: + process = _spawn(command, stdout=subprocess.PIPE, stderr=errors) + + def reader(): + try: + while not stop.is_set(): + item = process.stdout.read(frame_bytes) + while not stop.is_set(): + try: + channel.put(item, timeout=0.1) + break + except queue.Full: + pass + if not item: + return + except (OSError, ValueError): + # Main thread kills the process and closes the pipe on cancellation. + return + + thread = threading.Thread(target=reader, name="strata-video-frames", daemon=True) + thread.start() + paths = [] + try: + while True: + _check(deadline, cancel) + try: + raw = channel.get(timeout=0.1) + except queue.Empty: + if not thread.is_alive(): + raise VideoError("Video decoder stopped before completing its frames.") + continue + if not raw: + break + if len(raw) != frame_bytes or len(paths) >= count: + raise VideoError("Video decoding produced incomplete or unexpected frames.") + with Image.frombytes("RGB", (width, height), raw) as original: + rotated = original.rotate(rotation, expand=True) if rotation else original + try: + with rotated.resize(target, resample=Image.Resampling.BICUBIC) as resized: + path = root / f"frame-{len(paths):04d}.png" + resized.save(path, format="PNG") + paths.append(path) + finally: + if rotated is not original: + rotated.close() + while process.poll() is None: + _check(deadline, cancel) + time.sleep(0.05) + if process.returncode or len(paths) != count: + raise VideoError("The video could not be decoded completely; no partial video was accepted.") + log = _read_output(errors, 2 * 1024 * 1024).decode("utf-8", "replace") + timestamps = [float(value) for value in re.findall(r"\bn:\s*\d+\s+pts:.*?\bpts_time:([-+0-9.eE]+)", log)] + if (len(timestamps) != count or any(not math.isfinite(v) or v < 0 for v in timestamps) + or any(b < a for a, b in zip(timestamps, timestamps[1:]))): + raise VideoError("Could not determine the selected video frames' timestamps.") + return paths, timestamps + finally: + stop.set() + _finish(process) + thread.join(timeout=2) + process.stdout.close() + + +@contextmanager +def prepare_video(source, config=None, cancel=None, *, directory=None): + """Yield temporary RGB frame pairs and actual relative timestamps; clean on exit. + + Sources are bytes or inline data:video/*;base64. Parameters may tighten the + fixed resource ceilings. The decoder cannot open network/playlist resources. + """ + options = _options(config) + data = _inline(source, options["max_bytes"]) + ffprobe, ffmpeg = shutil.which("ffprobe"), shutil.which("ffmpeg") + if not ffprobe or not ffmpeg: + raise VideoError("Native video input requires ffprobe and ffmpeg on PATH.") + deadline = time.monotonic() + DECODE_SECONDS + _check(deadline, cancel) + with tempfile.TemporaryDirectory(prefix="native-video-", dir=directory) as temp: + root = Path(temp) + source_path = root / "attachment.bin" + source_path.write_bytes(data) + del data + limits = ["-protocol_whitelist", "file,pipe", "-format_whitelist", FORMATS, + "-max_alloc", "134217728", "-threads", "2", "-max_pixels", str(MAX_SOURCE_PIXELS), + "-probesize", "8388608", "-analyzeduration", "10000000"] + probe = [ffprobe, "-v", "error", *limits, "-select_streams", "v", + "-show_entries", "stream=index,codec_type,width,height,duration,nb_frames:stream_disposition=attached_pic:stream_side_data=rotation:format=duration", + "-of", "json", str(source_path)] + try: + metadata = json.loads(_command(probe, deadline, cancel)) + stream = next(s for s in metadata.get("streams", []) if s.get("codec_type") == "video" + and not s.get("disposition", {}).get("attached_pic", 0)) + width, height, index = int(stream["width"]), int(stream["height"]), int(stream["index"]) + duration = _positive(stream.get("duration")) or _positive(metadata.get("format", {}).get("duration")) + rotation = float(next((s["rotation"] for s in stream.get("side_data_list", []) if "rotation" in s), 0)) + except VideoError: + raise + except (ValueError, TypeError, KeyError, StopIteration): + raise VideoError("The attachment has no readable video stream.") from None + if width < 1 or height < 1 or max(width, height) > MAX_SOURCE_EDGE or width * height > MAX_SOURCE_PIXELS: + raise VideoError("Video dimensions exceed the decoder limit.") + if duration is None or duration > options["max_duration_seconds"]: + raise VideoError("Video duration is unknown or exceeds the configured limit; split the video.") + if not math.isfinite(rotation) or abs(rotation / 90 - round(rotation / 90)) > 0.001: + raise VideoError("Video display rotation must be a multiple of 90 degrees.") + total = _positive(stream.get("nb_frames")) + if total is None: + count_cmd = [ffprobe, "-v", "error", *limits, "-select_streams", str(index), "-count_frames", + "-show_entries", "stream=nb_read_frames", "-of", "json", str(source_path)] + counts = json.loads(_command(count_cmd, deadline, cancel)) + total = _positive(counts.get("streams", [{}])[0].get("nb_read_frames")) + if total is None or total != int(total) or total > 1_000_000: + raise VideoError("Could not determine a bounded video frame count.") + indices = _sample_indices(int(total), duration, options["fps"], options["max_pairs"]) + display_shape = (height, width) if round(rotation / 90) % 2 else (width, height) + target = _resize_shape(*display_shape, options["tokens_per_pair"]) + select = "+".join(f"eq(n\\,{i})" for i in indices) + command = [ffmpeg, "-hide_banner", "-loglevel", "info", "-nostdin", *limits, + "-noautorotate", "-i", str(source_path), "-map", f"0:{index}", "-an", "-sn", "-dn", + "-vf", f"select={select},setpts=PTS-STARTPTS,showinfo", "-filter_threads", "1", + "-frames:v", str(len(indices)), "-fps_mode", "passthrough", "-c:v", "rawvideo", + "-threads", "2", "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1"] + paths, timestamps = _frames(command, root, width, height, rotation, target, len(indices), deadline, cancel) + if len(paths) % 2: + paths.append(paths[-1]) + timestamps.append(timestamps[-1]) + pairs = [VideoPair(paths[i], paths[i + 1], (timestamps[i] + timestamps[i + 1]) / 2) + for i in range(0, len(paths), 2)] + yield PreparedVideo(pairs, duration, options["fps"], tuple(timestamps)) diff --git a/serve/test_video.py b/serve/test_video.py new file mode 100644 --- /dev/null +++ b/serve/test_video.py @@ -0,0 +1,140 @@ +"""Native-video preparation checks; tiny synthetic clips, no model or GPU.""" +import base64 +from pathlib import Path +import shutil +import subprocess +import tempfile +import threading +import unittest +from unittest.mock import patch + +from PIL import Image + +from . import video + + +class VideoUnitTests(unittest.TestCase): + def test_inline_only_and_byte_budget(self): + for source in ("https://example.invalid/v.mp4", "C:/private.mp4", "file:///private.mp4", + "data:video/mp4,abc", "data:application/pdf;base64,AAAA", "data:video/mp4;base64,!"): + with self.subTest(source=source), self.assertRaises(video.VideoError): + video._inline(source, 10) + self.assertEqual(video._inline("data:video/mp4;base64,YWJj", 3), b"abc") + for data in (b"", b"abcd", "data:video/mp4;base64,YWJjZA=="): + with self.assertRaises(video.VideoError): + video._inline(data, 3) + + def test_config_cannot_disable_resource_limits(self): + for options in ({"fps": 0}, {"fps": float("nan")}, {"max_pairs": 65}, {"tokens_per_pair": 7}, + {"max_bytes": video.MAX_BYTES + 1}, {"max_duration_seconds": 301}, {"fps": True}): + with self.subTest(options=options), self.assertRaises(video.VideoError): + video._options(options) + + def test_sampling_spans_both_ends_and_uses_even_frame_budget(self): + indices = video._sample_indices(361, 15.04, 2, 64) + self.assertEqual(len(indices), 32) + self.assertEqual((indices[0], indices[-1]), (0, 360)) + self.assertEqual(len(indices), len(set(indices))) + + def test_too_many_pairs_rejects_instead_of_dropping_tail(self): + with self.assertRaisesRegex(video.VideoError, "Split the video"): + video._sample_indices(3600, 120, 2, 64) + + def test_short_clips_keep_available_frames(self): + self.assertEqual(video._sample_indices(1, 0.04, 2, 64), [0]) + self.assertEqual(video._sample_indices(3, 0.12, 2, 64), [0, 1, 2]) + + def test_resize_is_aligned_and_bounded(self): + for shape in ((720, 1280), (1920, 1080), (16, 32), (512, 512)): + width, height = video._resize_shape(*shape, 256) + self.assertEqual(width % 32, 0) + self.assertEqual(height % 32, 0) + self.assertLessEqual(width * height // 1024, 256) + self.assertGreaterEqual(width * height // 1024, 8) + self.assertEqual(video._resize_shape(720, 1280, 256), (384, 672)) + + def test_cancellation_before_decode(self): + cancel = threading.Event() + cancel.set() + with self.assertRaises(video.VideoCancelled): + with video.prepare_video(b"synthetic", cancel=cancel): + self.fail("cancelled input yielded") + + def test_tools_missing_is_clear(self): + with patch.object(video.shutil, "which", return_value=None), self.assertRaisesRegex(video.VideoError, "ffprobe and ffmpeg"): + with video.prepare_video(b"synthetic"): + pass + + +@unittest.skipUnless(shutil.which("ffmpeg") and shutil.which("ffprobe"), "FFmpeg is not installed") +class VideoDecodeTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temp = tempfile.TemporaryDirectory(prefix="strata-native-video-test-") + cls.root = Path(cls.temp.name) + cls.clip = cls.root / "clip.mp4" + result = subprocess.run([ + shutil.which("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin", + "-f", "lavfi", "-i", "color=c=red:s=160x96:r=5:d=1", + "-f", "lavfi", "-i", "color=c=blue:s=160x96:r=5:d=1", + "-filter_complex", "[0:v][1:v]concat=n=2:v=1:a=0[v]", "-filter_complex_threads", "1", + "-map", "[v]", "-c:v", "libx264", "-threads", "2", "-pix_fmt", "yuv420p", str(cls.clip)], + stdin=subprocess.DEVNULL, capture_output=True, timeout=20, + creationflags=subprocess.CREATE_NO_WINDOW if video.os.name == "nt" else 0) + if result.returncode: + raise RuntimeError(result.stderr.decode("utf-8", "replace")) + cls.data = cls.clip.read_bytes() + + @classmethod + def tearDownClass(cls): + cls.temp.cleanup() + + def test_real_pairs_keep_actual_timestamps_colors_and_cleanup(self): + with video.prepare_video(self.data, directory=self.root) as prepared: + self.assertEqual(len(prepared.pairs), 2) + self.assertEqual(prepared.sampled_timestamps, (0.0, 0.6, 1.2, 1.8)) + self.assertAlmostEqual(prepared.pairs[0].timestamp, 0.3) + self.assertAlmostEqual(prepared.pairs[1].timestamp, 1.5) + first, last = prepared.pairs[0].first, prepared.pairs[-1].second + with Image.open(first) as image: + self.assertEqual(image.mode, "RGB") + self.assertEqual(image.size, (160, 96)) + self.assertGreater(image.getpixel((40, 40))[0], 240) + with Image.open(last) as image: + self.assertGreater(image.getpixel((40, 40))[2], 240) + self.assertFalse(first.exists()) + self.assertFalse(first.parent.exists()) + + def test_data_url_and_distinct_frames_inside_pair(self): + source = "data:video/mp4;base64," + base64.b64encode(self.data).decode("ascii") + # Four frames minimum: the middle selected frames straddle the change. + with video.prepare_video(source, {"fps": 3}, directory=self.root) as prepared: + self.assertEqual(len(prepared.pairs), 3) + middle = prepared.pairs[1] + self.assertNotEqual(middle.first.read_bytes(), middle.second.read_bytes()) + + def test_rejects_duration_and_cleans_temp(self): + before = set(self.root.iterdir()) + with self.assertRaisesRegex(video.VideoError, "duration"): + with video.prepare_video(self.data, {"max_duration_seconds": 1}, directory=self.root): + pass + self.assertEqual(set(self.root.iterdir()), before) + + def test_rejects_damaged_and_playlist_input(self): + inputs = (b"damaged video", b"#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nhttp://127.0.0.1:9/private.ts\n#EXT-X-ENDLIST\n") + for data in inputs: + with self.subTest(data=data[:10]), self.assertRaises(video.VideoError): + with video.prepare_video(data, directory=self.root): + pass + + def test_cancellation_during_command_reaps_child(self): + cancelled = threading.Event() + cancelled.set() + with self.assertRaises(video.VideoCancelled): + video._command([shutil.which("ffmpeg"), "-hide_banner", "-loglevel", "error", "-re", "-f", "lavfi", + "-i", "color=s=16x16:r=1:d=60", "-f", "null", "-"], + video.time.monotonic() + 120, cancelled) + + +if __name__ == "__main__": + unittest.main() ````
Author
Owner

@RAFOLIE commented on GitHub (Oct 25, 2026):

Reference patch — part 3/3

Save the fenced diff as native-video-part-3.patch (UTF-8, LF). Concatenate the parts in numbered order before applying. This is part of the AI-assisted local prototype described in the issue.

Part SHA256: 02fc4c4b053b6a313d6a8ae572294db8bd4cde599c99ef4ff92886b812c6e920

diff --git a/serve/test_native_video_api.py b/serve/test_native_video_api.py
new file mode 100644
--- /dev/null
+++ b/serve/test_native_video_api.py
@@ -0,0 +1,301 @@
+"""Native video API/prompt integration tests; no model or user video is loaded."""
+import contextlib
+import copy
+import io
+import http.client
+import json
+from pathlib import Path
+import shlex
+import tempfile
+import threading
+from types import SimpleNamespace
+import unittest
+from unittest import mock
+
+from serve.frontend import ChatTemplate, media_of, openai_to_messages
+from serve.server import (ByteTokenizer, ClientGone, MockEngine, Service, Vision,
+                          native_video_config, serve)
+
+ROOT = Path(__file__).resolve().parents[1]
+SOURCE = "data:video/mp4;base64,AAAA"
+CONFIG = native_video_config({"arch": "qwen4exp", "vision": {}, "video": {"enabled": True}})
+
+
+class FakeVision:
+    native_video = supports_video = True
+
+    def __init__(self, root):
+        self.dir = Path(root)
+        self.calls = []
+
+    def encode(self, source, keep=()):
+        self.calls.append(("image", source))
+        path = self.dir / ("a" * 32 + ".sve")
+        path.write_bytes(b"IMAGE")
+        return path, 3
+
+    def encode_video(self, source, config, cancel=None, keep=()):
+        self.calls.append(("video", source))
+        result = []
+        for key, count, timestamp, data in (("b", 2, .25, b"PAIR0"), ("c", 4, .75, b"PAIR1")):
+            path = self.dir / (key * 32 + ".sve")
+            path.write_bytes(data)
+            result.append((path, count, timestamp))
+        return result
+
+
+class NativeVideoAPI(unittest.TestCase):
+    def setUp(self):
+        self.directory = tempfile.TemporaryDirectory()
+        self.addCleanup(self.directory.cleanup)
+        self.tokenizer = ByteTokenizer()
+        self.vision = FakeVision(self.directory.name)
+        engine = MockEngine(self.tokenizer, "ok", max_context=10000)
+        engine.info = {"native_video": 1}
+        self.service = Service(engine, self.tokenizer, ChatTemplate(ROOT / "serve/chat_template.jinja"),
+                               vision=self.vision, video_config=CONFIG)
+        self.service.model_arch = "qwen4exp"
+        self.addCleanup(self.service.drop_embeddings)
+
+    def messages(self, parts=None):
+        return openai_to_messages({"messages": [{"role": "user", "content": parts or [
+            {"type": "text", "text": "Describe the motion."},
+            {"type": "video_url", "video_url": {"url": SOURCE}}]}]})[0]
+
+    def test_video_stays_a_video_item(self):
+        messages = self.messages()
+        self.assertEqual(media_of(messages), [{"type": "video", "source": SOURCE}])
+        prompt = self.service.template.render(messages)
+        self.assertIn("<|vision_start|><|video_pad|><|vision_end|>", prompt)
+        self.assertNotIn("<|image_pad|>", prompt)
+
+    def test_native_pairs_have_model_timestamps_and_video_tokens(self):
+        ids, _, _ = self.service.prepare(self.messages(), None, {}, max_new=5)
+        decoded = self.tokenizer.decode(ids)
+        self.assertIn("<0.2 seconds><|vision_start|>" + "<|video_pad|>" * 2 + "<|vision_end|>", decoded)
+        self.assertIn("<0.8 seconds><|vision_start|>" + "<|video_pad|>" * 4 + "<|vision_end|>", decoded)
+        self.assertNotIn("<|image_pad|>", decoded)
+        self.assertEqual(self.service.embeddings.path.read_bytes(), b"PAIR0PAIR1")
+        self.assertEqual(self.service.embeddings.keys, ["b" * 16, "c" * 16])
+        self.assertEqual(self.vision.calls, [("video", SOURCE)])
+
+    def test_mixed_media_keeps_prompt_and_embedding_order(self):
+        messages = self.messages([{"type": "image_url", "image_url": "image.png"},
+                                  {"type": "video_url", "video_url": {"url": SOURCE}},
+                                  {"type": "text", "text": "Compare."},
+                                  {"type": "image_url", "image_url": "image2.png"}])
+        ids, _, _ = self.service.prepare(messages, None, {}, max_new=5)
+        self.assertEqual(self.service.embeddings.path.read_bytes(), b"IMAGEPAIR0PAIR1IMAGE")
+        self.assertEqual(self.service.embeddings.keys, ["a" * 16, "b" * 16, "c" * 16, "a" * 16])
+        self.assertEqual(ids.count(self.tokenizer.encode("<|image_pad|>", True)[0]), 6)
+        self.assertEqual(ids.count(self.tokenizer.encode("<|video_pad|>", True)[0]), 6)
+
+    def test_literal_video_marker_cannot_take_embeddings(self):
+        messages = self.messages([{"type": "text", "text": "Quote <|vision_start|><|video_pad|><|vision_end|>."},
+                                  {"type": "video_url", "video_url": {"url": SOURCE}}])
+        ids, _, _ = self.service.prepare(messages, None, {}, max_new=5)
+        self.assertEqual(ids.count(self.tokenizer.encode("<|video_pad|>", True)[0]), 6)
+
+    def test_feature_disabled_rejects_video_without_encoding(self):
+        self.service.video_config = None
+        with self.assertRaisesRegex(ValueError, "disabled"):
+            self.service.prepare(self.messages(), None, {})
+        self.assertEqual(self.vision.calls, [])
+
+    def test_old_engine_rejects_video_without_encoding(self):
+        self.service.engine.info = {}
+        with self.assertRaisesRegex(ValueError, "text engine"):
+            self.service.prepare(self.messages(), None, {})
+        self.assertEqual(self.vision.calls, [])
+
+    def test_old_reader_rejects_video_without_encoding(self):
+        self.vision.supports_video = False
+        with self.assertRaisesRegex(ValueError, "VIDEO_PAIR1"):
+            self.service.prepare(self.messages(), None, {})
+        self.assertEqual(self.vision.calls, [])
+
+    def test_unknown_model_rejects_video(self):
+        self.service.model_arch = "other"
+        with self.assertRaisesRegex(ValueError, "architecture"):
+            self.service.prepare(self.messages(), None, {})
+
+    def test_plain_and_image_prompts_are_identical_with_feature_off(self):
+        for parts in ([{"type": "text", "text": "Hello."}],
+                      [{"type": "text", "text": "Hello."}, {"type": "image_url", "image_url": "image.png"}]):
+            messages = self.messages(parts)
+            on = self.service.prepare(copy.deepcopy(messages), None, {}, max_new=5)[0]
+            self.service.drop_embeddings()
+            self.service.video_config = None
+            off = self.service.prepare(copy.deepcopy(messages), None, {}, max_new=5)[0]
+            self.assertEqual(on, off)
+            self.service.drop_embeddings()
+            self.service.video_config = CONFIG
+
+    def test_context_rejection_cleans_combined_rows(self):
+        self.service.engine.max_context = 1
+        with self.assertRaisesRegex(ValueError, "context"):
+            self.service.prepare(self.messages(), None, {})
+        self.assertIsNone(self.service.embeddings.path)
+        self.assertEqual(sorted(path.name for path in self.vision.dir.iterdir()), ["b" * 32 + ".sve", "c" * 32 + ".sve"])
+
+    def test_missing_template_video_marker_rejects(self):
+        with mock.patch.object(self.service, "encode_prompt", return_value=self.tokenizer.encode("plain")):
+            with self.assertRaisesRegex(ValueError, "template"):
+                self.service.prepare(self.messages(), None, {})
+
+    def test_advertising_requires_all_native_capabilities(self):
+        with mock.patch("serve.server.shutil.which", return_value="ffmpeg"):
+            self.assertTrue(self.service.native_video_available())
+            self.service.engine.info = {}
+            self.assertFalse(self.service.native_video_available())
+            self.service.engine.info = {"native_video": 1}
+            self.vision.supports_video = False
+            self.assertFalse(self.service.native_video_available())
+
+    def test_paths_and_remote_video_urls_are_rejected(self):
+        for source in ("https://example.com/video.mp4", r"C:\private\clip.mp4", "", None):
+            with self.subTest(source=source), self.assertRaisesRegex(ValueError, "inline"):
+                self.messages([{"type": "video_url", "video_url": {"url": source}}])
+
+    def test_three_videos_are_rejected(self):
+        with self.assertRaisesRegex(ValueError, "two"):
+            self.service.prepare(self.messages([{"type": "video_url", "video_url": {"url": SOURCE}}] * 3), None, {})
+
+
+class VideoConfiguration(unittest.TestCase):
+    def test_default_is_off(self):
+        self.assertIsNone(native_video_config({}))
+        self.assertIsNone(native_video_config({"video": {"enabled": False}}))
+
+    def test_opt_in_requires_explicit_known_model_and_vision(self):
+        for config in ({"video": {"enabled": True}}, {"arch": "other", "vision": {}, "video": {"enabled": True}},
+                       {"arch": "qwen4exp", "video": {"enabled": True}}):
+            with self.subTest(config=config), self.assertRaises(ValueError):
+                native_video_config(config)
+
+    def test_resource_limits_cannot_be_bypassed(self):
+        for key, value in (("fps", 0), ("max_pairs", 65), ("tokens_per_pair", 1024),
+                           ("max_bytes", 65 * 1024 * 1024), ("max_duration_seconds", 301), ("fps", True)):
+            with self.subTest(key=key), self.assertRaises(ValueError):
+                native_video_config({"arch": "qwen4exp", "vision": {}, "video": {"enabled": True, key: value}})
+
+    def test_reader_video_flags_are_opt_in(self):
+        base = {"exe": "reader", "model": "m", "mmproj": "p"}
+        self.assertNotIn("--native-video", Vision.reader_args(base))
+        active = Vision.reader_args({**base, "native_video": True, "video_tokens_per_pair": 128})
+        self.assertEqual(active[-3:], ["--native-video", "--video-max-tokens", "128"])
+
+
+class NativeReaderProtocol(unittest.TestCase):
+    def setUp(self):
+        self.directory = tempfile.TemporaryDirectory()
+        self.addCleanup(self.directory.cleanup)
+        self.reader = Vision.__new__(Vision)
+        self.reader.dir = Path(self.directory.name)
+        self.reader.cache = {}
+        self.reader.native_video = self.reader.supports_video = True
+        self.reader.stopped = False
+        self.reader.lock = threading.Lock()
+        self.reader.proc = SimpleNamespace(stdin=io.StringIO(), poll=lambda: None)
+        self.reader.encode = mock.Mock(side_effect=AssertionError("native video must not use image encoding"))
+        first, second = self.reader.dir / "first.png", self.reader.dir / "second.png"
+        first.write_bytes(b"first frame pixels")
+        second.write_bytes(b"second frame pixels")
+        self.pair = SimpleNamespace(first=first, second=second, timestamp=.5)
+        self.prepared = SimpleNamespace(pairs=[self.pair])
+
+    def response(self, count=4):
+        def reply(timeout, what):
+            command = self.reader.proc.stdin.getvalue().splitlines()[-1]
+            args = shlex.split(command)
+            self.assertEqual(args[0], "ENCV")
+            self.assertEqual((Path(args[1]), Path(args[2])), (self.pair.first, self.pair.second))
+            Path(args[3]).write_bytes(b"temporal embeddings")
+            return f"OK {count} 2 2 1.0"
+        self.reader._readline = reply
+
+    def test_pair_uses_both_frames_and_one_encv_then_reuses_cache(self):
+        self.response()
+        with mock.patch("serve.video.prepare_video", side_effect=lambda *a, **kw: contextlib.nullcontext(self.prepared)):
+            first = self.reader.encode_video(SOURCE, CONFIG)
+            second = self.reader.encode_video(SOURCE, CONFIG)
+        self.assertEqual(first, second)
+        self.assertEqual(first[0][1:], (4, .5))
+        self.assertEqual(len(self.reader.proc.stdin.getvalue().splitlines()), 1)
+        self.reader.encode.assert_not_called()
+
+    def test_encoder_token_overflow_is_rejected_and_file_removed(self):
+        self.response(count=999)
+        with mock.patch("serve.video.prepare_video", return_value=contextlib.nullcontext(self.prepared)):
+            with self.assertRaisesRegex(ValueError, "budget"):
+                self.reader.encode_video(SOURCE, CONFIG)
+        self.assertEqual(list(self.reader.dir.glob("*.sve")), [])
+
+    def test_decoder_cancellation_becomes_client_gone(self):
+        from serve.video import VideoCancelled
+        with mock.patch("serve.video.prepare_video", side_effect=VideoCancelled("cancelled")):
+            with self.assertRaises(ClientGone):
+                self.reader.encode_video(SOURCE, CONFIG)
+
+
+class NativeVideoHTTP(unittest.TestCase):
+    def setUp(self):
+        self.directory = tempfile.TemporaryDirectory()
+        self.addCleanup(self.directory.cleanup)
+        self.tokenizer = ByteTokenizer()
+        self.engine = MockEngine(self.tokenizer, "ok", max_context=10000)
+        self.engine.info = {"native_video": 1}
+        self.vision = FakeVision(self.directory.name)
+        self.service = Service(self.engine, self.tokenizer, ChatTemplate(ROOT / "serve/chat_template.jinja"),
+                               vision=self.vision, video_config=CONFIG)
+        self.service.model_arch = "qwen4exp"
+        self.httpd = serve(self.service, port=0)
+        self.addCleanup(self.httpd.server_close)
+        self.addCleanup(self.httpd.shutdown)
+        self.port = self.httpd.server_address[1]
+
+    def request(self, path="/v1/chat/completions", body=None):
+        connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5)
+        try:
+            connection.request("POST" if body is not None else "GET", path,
+                               body=json.dumps(body).encode() if body is not None else None,
+                               headers={"Content-Type": "application/json"})
+            response = connection.getresponse()
+            return response.status, json.loads(response.read())
+        finally:
+            connection.close()
+
+    def payload(self):
+        return {"messages": [{"role": "user", "content": [
+            {"type": "video_url", "video_url": {"url": SOURCE}}]}], "max_tokens": 4,
+            "chat_template_kwargs": {"enable_thinking": False}}
+
+    def test_zcode_payload_reaches_native_encoder_over_http(self):
+        status, response = self.request(body=self.payload())
+        self.assertEqual(status, 200, response)
+        self.assertEqual(self.vision.calls, [("video", SOURCE)])
+        self.assertEqual(response["choices"][0]["message"]["content"], "ok")
+
+    def test_missing_native_capabilities_are_http_400(self):
+        for mode in ("disabled", "old-reader", "old-engine"):
+            self.service.video_config = CONFIG if mode != "disabled" else None
+            self.vision.supports_video = mode != "old-reader"
+            self.engine.info = {} if mode == "old-engine" else {"native_video": 1}
+            with self.subTest(mode=mode):
+                status, response = self.request(body=self.payload())
+                self.assertEqual(status, 400, response)
+        self.assertEqual(self.vision.calls, [])
+
+    def test_models_add_video_input_but_never_video_output(self):
+        with mock.patch("serve.server.shutil.which", return_value="ffmpeg"):
+            status, response = self.request("/v1/models")
+            self.assertEqual(status, 200)
+            self.assertEqual(response["data"][0]["architecture"]["input_modalities"], ["text", "image", "video"])
+            self.assertEqual(response["data"][0]["architecture"]["output_modalities"], ["text"])
+            self.service.video_config = None
+            self.assertEqual(self.request("/v1/models")[1]["data"][0]["architecture"]["input_modalities"], ["text", "image"])
+            self.assertNotIn("videos", self.request("/health")[1])
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tools/vision/native_video_positions_test.cpp b/tools/vision/native_video_positions_test.cpp
new file mode 100644
--- /dev/null
+++ b/tools/vision/native_video_positions_test.cpp
@@ -0,0 +1,45 @@
+#include "strata/program/visual_prompt.hpp"
+#include <cassert>
+#include <iostream>
+#include <vector>
+
+using namespace strata::program;
+int main() {
+    constexpr int64_t I = image_pad_token, V = video_pad_token;
+    std::vector<int32_t> positions(32 * 3, -1);
+    std::vector<VisualSpan> spans;
+    std::string error;
+    auto run = [&](const std::vector<int64_t>& ids, const std::vector<VisualGrid>& grids, bool enabled) {
+        error.clear();
+        return visual_prompt_positions(ids, grids, enabled, positions.data(), 32, spans, error);
+    };
+    auto cell = [&](size_t i, int t, int h, int w) {
+        assert(positions[i*3] == t && positions[i*3+1] == h && positions[i*3+2] == w);
+    };
+    // Text and the existing image path keep their old positions.
+    assert(run({10,11,12}, {}, false));
+    for (size_t i=0;i<32;++i) cell(i,(int)i,(int)i,(int)i);
+    assert(run({10,I,I,I,I,20}, {{4,2,2}}, false));
+    cell(1,1,1,1); cell(2,1,1,2); cell(3,1,2,1); cell(4,1,2,2); cell(5,3,3,3); cell(6,4,4,4);
+    // Timestamp text and vision delimiters surround each temporal patch.
+    const std::vector<int64_t> ids={10,248053,V,V,V,V,248054,11,248053,V,V,V,V,248054,20};
+    const auto original=ids;
+    assert(run(ids, {{4,2,2},{4,2,2}}, true));
+    assert(ids==original); // video_pad survives unchanged for PLE.
+    assert(spans.size()==2 && spans[0].start==2 && spans[1].start==9);
+    assert(spans[0].pad==V && spans[1].pad==V);
+    cell(2,2,2,2); cell(5,2,3,3); cell(6,4,4,4);
+    cell(9,7,7,7); cell(12,7,8,8); cell(13,9,9,9); cell(15,11,11,11);
+    // Images and videos may be interleaved without relabelling either.
+    assert(run({10,I,I,20,V,V,30}, {{2,2,1},{2,1,2}}, true));
+    cell(1,1,1,1); cell(2,1,1,2); cell(4,4,4,4); cell(5,4,5,4); cell(6,6,6,6);
+    assert(!run(ids, {{4,2,2},{4,2,2}}, false));
+    assert(!run({10,V,I,20}, {{2,2,1}}, true));
+    assert(!run({10,V,20}, {{2,2,1}}, true));
+    assert(!run({10,V,V,20}, {}, true));
+    assert(!run({10,20}, {{2,2,1}}, true));
+    assert(!run({10,V,V}, {{2,2,1}}, true));
+    assert(!run({10,V,V,20}, {{2,3,1}}, true));
+    assert(!visual_prompt_positions(ids,{},true,positions.data(),1,spans,error));
+    std::cout << "native video/image M-RoPE position tests passed\n";
+}
<!-- gh-comment-id:6394892031 --> @RAFOLIE commented on GitHub (Oct 25, 2026): ### Reference patch — part 3/3 Save the fenced diff as `native-video-part-3.patch` (UTF-8, LF). Concatenate the parts in numbered order before applying. This is part of the AI-assisted local prototype described in the issue. Part SHA256: `02fc4c4b053b6a313d6a8ae572294db8bd4cde599c99ef4ff92886b812c6e920` ````diff diff --git a/serve/test_native_video_api.py b/serve/test_native_video_api.py new file mode 100644 --- /dev/null +++ b/serve/test_native_video_api.py @@ -0,0 +1,301 @@ +"""Native video API/prompt integration tests; no model or user video is loaded.""" +import contextlib +import copy +import io +import http.client +import json +from pathlib import Path +import shlex +import tempfile +import threading +from types import SimpleNamespace +import unittest +from unittest import mock + +from serve.frontend import ChatTemplate, media_of, openai_to_messages +from serve.server import (ByteTokenizer, ClientGone, MockEngine, Service, Vision, + native_video_config, serve) + +ROOT = Path(__file__).resolve().parents[1] +SOURCE = "data:video/mp4;base64,AAAA" +CONFIG = native_video_config({"arch": "qwen4exp", "vision": {}, "video": {"enabled": True}}) + + +class FakeVision: + native_video = supports_video = True + + def __init__(self, root): + self.dir = Path(root) + self.calls = [] + + def encode(self, source, keep=()): + self.calls.append(("image", source)) + path = self.dir / ("a" * 32 + ".sve") + path.write_bytes(b"IMAGE") + return path, 3 + + def encode_video(self, source, config, cancel=None, keep=()): + self.calls.append(("video", source)) + result = [] + for key, count, timestamp, data in (("b", 2, .25, b"PAIR0"), ("c", 4, .75, b"PAIR1")): + path = self.dir / (key * 32 + ".sve") + path.write_bytes(data) + result.append((path, count, timestamp)) + return result + + +class NativeVideoAPI(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.tokenizer = ByteTokenizer() + self.vision = FakeVision(self.directory.name) + engine = MockEngine(self.tokenizer, "ok", max_context=10000) + engine.info = {"native_video": 1} + self.service = Service(engine, self.tokenizer, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=self.vision, video_config=CONFIG) + self.service.model_arch = "qwen4exp" + self.addCleanup(self.service.drop_embeddings) + + def messages(self, parts=None): + return openai_to_messages({"messages": [{"role": "user", "content": parts or [ + {"type": "text", "text": "Describe the motion."}, + {"type": "video_url", "video_url": {"url": SOURCE}}]}]})[0] + + def test_video_stays_a_video_item(self): + messages = self.messages() + self.assertEqual(media_of(messages), [{"type": "video", "source": SOURCE}]) + prompt = self.service.template.render(messages) + self.assertIn("<|vision_start|><|video_pad|><|vision_end|>", prompt) + self.assertNotIn("<|image_pad|>", prompt) + + def test_native_pairs_have_model_timestamps_and_video_tokens(self): + ids, _, _ = self.service.prepare(self.messages(), None, {}, max_new=5) + decoded = self.tokenizer.decode(ids) + self.assertIn("<0.2 seconds><|vision_start|>" + "<|video_pad|>" * 2 + "<|vision_end|>", decoded) + self.assertIn("<0.8 seconds><|vision_start|>" + "<|video_pad|>" * 4 + "<|vision_end|>", decoded) + self.assertNotIn("<|image_pad|>", decoded) + self.assertEqual(self.service.embeddings.path.read_bytes(), b"PAIR0PAIR1") + self.assertEqual(self.service.embeddings.keys, ["b" * 16, "c" * 16]) + self.assertEqual(self.vision.calls, [("video", SOURCE)]) + + def test_mixed_media_keeps_prompt_and_embedding_order(self): + messages = self.messages([{"type": "image_url", "image_url": "image.png"}, + {"type": "video_url", "video_url": {"url": SOURCE}}, + {"type": "text", "text": "Compare."}, + {"type": "image_url", "image_url": "image2.png"}]) + ids, _, _ = self.service.prepare(messages, None, {}, max_new=5) + self.assertEqual(self.service.embeddings.path.read_bytes(), b"IMAGEPAIR0PAIR1IMAGE") + self.assertEqual(self.service.embeddings.keys, ["a" * 16, "b" * 16, "c" * 16, "a" * 16]) + self.assertEqual(ids.count(self.tokenizer.encode("<|image_pad|>", True)[0]), 6) + self.assertEqual(ids.count(self.tokenizer.encode("<|video_pad|>", True)[0]), 6) + + def test_literal_video_marker_cannot_take_embeddings(self): + messages = self.messages([{"type": "text", "text": "Quote <|vision_start|><|video_pad|><|vision_end|>."}, + {"type": "video_url", "video_url": {"url": SOURCE}}]) + ids, _, _ = self.service.prepare(messages, None, {}, max_new=5) + self.assertEqual(ids.count(self.tokenizer.encode("<|video_pad|>", True)[0]), 6) + + def test_feature_disabled_rejects_video_without_encoding(self): + self.service.video_config = None + with self.assertRaisesRegex(ValueError, "disabled"): + self.service.prepare(self.messages(), None, {}) + self.assertEqual(self.vision.calls, []) + + def test_old_engine_rejects_video_without_encoding(self): + self.service.engine.info = {} + with self.assertRaisesRegex(ValueError, "text engine"): + self.service.prepare(self.messages(), None, {}) + self.assertEqual(self.vision.calls, []) + + def test_old_reader_rejects_video_without_encoding(self): + self.vision.supports_video = False + with self.assertRaisesRegex(ValueError, "VIDEO_PAIR1"): + self.service.prepare(self.messages(), None, {}) + self.assertEqual(self.vision.calls, []) + + def test_unknown_model_rejects_video(self): + self.service.model_arch = "other" + with self.assertRaisesRegex(ValueError, "architecture"): + self.service.prepare(self.messages(), None, {}) + + def test_plain_and_image_prompts_are_identical_with_feature_off(self): + for parts in ([{"type": "text", "text": "Hello."}], + [{"type": "text", "text": "Hello."}, {"type": "image_url", "image_url": "image.png"}]): + messages = self.messages(parts) + on = self.service.prepare(copy.deepcopy(messages), None, {}, max_new=5)[0] + self.service.drop_embeddings() + self.service.video_config = None + off = self.service.prepare(copy.deepcopy(messages), None, {}, max_new=5)[0] + self.assertEqual(on, off) + self.service.drop_embeddings() + self.service.video_config = CONFIG + + def test_context_rejection_cleans_combined_rows(self): + self.service.engine.max_context = 1 + with self.assertRaisesRegex(ValueError, "context"): + self.service.prepare(self.messages(), None, {}) + self.assertIsNone(self.service.embeddings.path) + self.assertEqual(sorted(path.name for path in self.vision.dir.iterdir()), ["b" * 32 + ".sve", "c" * 32 + ".sve"]) + + def test_missing_template_video_marker_rejects(self): + with mock.patch.object(self.service, "encode_prompt", return_value=self.tokenizer.encode("plain")): + with self.assertRaisesRegex(ValueError, "template"): + self.service.prepare(self.messages(), None, {}) + + def test_advertising_requires_all_native_capabilities(self): + with mock.patch("serve.server.shutil.which", return_value="ffmpeg"): + self.assertTrue(self.service.native_video_available()) + self.service.engine.info = {} + self.assertFalse(self.service.native_video_available()) + self.service.engine.info = {"native_video": 1} + self.vision.supports_video = False + self.assertFalse(self.service.native_video_available()) + + def test_paths_and_remote_video_urls_are_rejected(self): + for source in ("https://example.com/video.mp4", r"C:\private\clip.mp4", "", None): + with self.subTest(source=source), self.assertRaisesRegex(ValueError, "inline"): + self.messages([{"type": "video_url", "video_url": {"url": source}}]) + + def test_three_videos_are_rejected(self): + with self.assertRaisesRegex(ValueError, "two"): + self.service.prepare(self.messages([{"type": "video_url", "video_url": {"url": SOURCE}}] * 3), None, {}) + + +class VideoConfiguration(unittest.TestCase): + def test_default_is_off(self): + self.assertIsNone(native_video_config({})) + self.assertIsNone(native_video_config({"video": {"enabled": False}})) + + def test_opt_in_requires_explicit_known_model_and_vision(self): + for config in ({"video": {"enabled": True}}, {"arch": "other", "vision": {}, "video": {"enabled": True}}, + {"arch": "qwen4exp", "video": {"enabled": True}}): + with self.subTest(config=config), self.assertRaises(ValueError): + native_video_config(config) + + def test_resource_limits_cannot_be_bypassed(self): + for key, value in (("fps", 0), ("max_pairs", 65), ("tokens_per_pair", 1024), + ("max_bytes", 65 * 1024 * 1024), ("max_duration_seconds", 301), ("fps", True)): + with self.subTest(key=key), self.assertRaises(ValueError): + native_video_config({"arch": "qwen4exp", "vision": {}, "video": {"enabled": True, key: value}}) + + def test_reader_video_flags_are_opt_in(self): + base = {"exe": "reader", "model": "m", "mmproj": "p"} + self.assertNotIn("--native-video", Vision.reader_args(base)) + active = Vision.reader_args({**base, "native_video": True, "video_tokens_per_pair": 128}) + self.assertEqual(active[-3:], ["--native-video", "--video-max-tokens", "128"]) + + +class NativeReaderProtocol(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.reader = Vision.__new__(Vision) + self.reader.dir = Path(self.directory.name) + self.reader.cache = {} + self.reader.native_video = self.reader.supports_video = True + self.reader.stopped = False + self.reader.lock = threading.Lock() + self.reader.proc = SimpleNamespace(stdin=io.StringIO(), poll=lambda: None) + self.reader.encode = mock.Mock(side_effect=AssertionError("native video must not use image encoding")) + first, second = self.reader.dir / "first.png", self.reader.dir / "second.png" + first.write_bytes(b"first frame pixels") + second.write_bytes(b"second frame pixels") + self.pair = SimpleNamespace(first=first, second=second, timestamp=.5) + self.prepared = SimpleNamespace(pairs=[self.pair]) + + def response(self, count=4): + def reply(timeout, what): + command = self.reader.proc.stdin.getvalue().splitlines()[-1] + args = shlex.split(command) + self.assertEqual(args[0], "ENCV") + self.assertEqual((Path(args[1]), Path(args[2])), (self.pair.first, self.pair.second)) + Path(args[3]).write_bytes(b"temporal embeddings") + return f"OK {count} 2 2 1.0" + self.reader._readline = reply + + def test_pair_uses_both_frames_and_one_encv_then_reuses_cache(self): + self.response() + with mock.patch("serve.video.prepare_video", side_effect=lambda *a, **kw: contextlib.nullcontext(self.prepared)): + first = self.reader.encode_video(SOURCE, CONFIG) + second = self.reader.encode_video(SOURCE, CONFIG) + self.assertEqual(first, second) + self.assertEqual(first[0][1:], (4, .5)) + self.assertEqual(len(self.reader.proc.stdin.getvalue().splitlines()), 1) + self.reader.encode.assert_not_called() + + def test_encoder_token_overflow_is_rejected_and_file_removed(self): + self.response(count=999) + with mock.patch("serve.video.prepare_video", return_value=contextlib.nullcontext(self.prepared)): + with self.assertRaisesRegex(ValueError, "budget"): + self.reader.encode_video(SOURCE, CONFIG) + self.assertEqual(list(self.reader.dir.glob("*.sve")), []) + + def test_decoder_cancellation_becomes_client_gone(self): + from serve.video import VideoCancelled + with mock.patch("serve.video.prepare_video", side_effect=VideoCancelled("cancelled")): + with self.assertRaises(ClientGone): + self.reader.encode_video(SOURCE, CONFIG) + + +class NativeVideoHTTP(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.tokenizer = ByteTokenizer() + self.engine = MockEngine(self.tokenizer, "ok", max_context=10000) + self.engine.info = {"native_video": 1} + self.vision = FakeVision(self.directory.name) + self.service = Service(self.engine, self.tokenizer, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=self.vision, video_config=CONFIG) + self.service.model_arch = "qwen4exp" + self.httpd = serve(self.service, port=0) + self.addCleanup(self.httpd.server_close) + self.addCleanup(self.httpd.shutdown) + self.port = self.httpd.server_address[1] + + def request(self, path="/v1/chat/completions", body=None): + connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5) + try: + connection.request("POST" if body is not None else "GET", path, + body=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json"}) + response = connection.getresponse() + return response.status, json.loads(response.read()) + finally: + connection.close() + + def payload(self): + return {"messages": [{"role": "user", "content": [ + {"type": "video_url", "video_url": {"url": SOURCE}}]}], "max_tokens": 4, + "chat_template_kwargs": {"enable_thinking": False}} + + def test_zcode_payload_reaches_native_encoder_over_http(self): + status, response = self.request(body=self.payload()) + self.assertEqual(status, 200, response) + self.assertEqual(self.vision.calls, [("video", SOURCE)]) + self.assertEqual(response["choices"][0]["message"]["content"], "ok") + + def test_missing_native_capabilities_are_http_400(self): + for mode in ("disabled", "old-reader", "old-engine"): + self.service.video_config = CONFIG if mode != "disabled" else None + self.vision.supports_video = mode != "old-reader" + self.engine.info = {} if mode == "old-engine" else {"native_video": 1} + with self.subTest(mode=mode): + status, response = self.request(body=self.payload()) + self.assertEqual(status, 400, response) + self.assertEqual(self.vision.calls, []) + + def test_models_add_video_input_but_never_video_output(self): + with mock.patch("serve.server.shutil.which", return_value="ffmpeg"): + status, response = self.request("/v1/models") + self.assertEqual(status, 200) + self.assertEqual(response["data"][0]["architecture"]["input_modalities"], ["text", "image", "video"]) + self.assertEqual(response["data"][0]["architecture"]["output_modalities"], ["text"]) + self.service.video_config = None + self.assertEqual(self.request("/v1/models")[1]["data"][0]["architecture"]["input_modalities"], ["text", "image"]) + self.assertNotIn("videos", self.request("/health")[1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/vision/native_video_positions_test.cpp b/tools/vision/native_video_positions_test.cpp new file mode 100644 --- /dev/null +++ b/tools/vision/native_video_positions_test.cpp @@ -0,0 +1,45 @@ +#include "strata/program/visual_prompt.hpp" +#include <cassert> +#include <iostream> +#include <vector> + +using namespace strata::program; +int main() { + constexpr int64_t I = image_pad_token, V = video_pad_token; + std::vector<int32_t> positions(32 * 3, -1); + std::vector<VisualSpan> spans; + std::string error; + auto run = [&](const std::vector<int64_t>& ids, const std::vector<VisualGrid>& grids, bool enabled) { + error.clear(); + return visual_prompt_positions(ids, grids, enabled, positions.data(), 32, spans, error); + }; + auto cell = [&](size_t i, int t, int h, int w) { + assert(positions[i*3] == t && positions[i*3+1] == h && positions[i*3+2] == w); + }; + // Text and the existing image path keep their old positions. + assert(run({10,11,12}, {}, false)); + for (size_t i=0;i<32;++i) cell(i,(int)i,(int)i,(int)i); + assert(run({10,I,I,I,I,20}, {{4,2,2}}, false)); + cell(1,1,1,1); cell(2,1,1,2); cell(3,1,2,1); cell(4,1,2,2); cell(5,3,3,3); cell(6,4,4,4); + // Timestamp text and vision delimiters surround each temporal patch. + const std::vector<int64_t> ids={10,248053,V,V,V,V,248054,11,248053,V,V,V,V,248054,20}; + const auto original=ids; + assert(run(ids, {{4,2,2},{4,2,2}}, true)); + assert(ids==original); // video_pad survives unchanged for PLE. + assert(spans.size()==2 && spans[0].start==2 && spans[1].start==9); + assert(spans[0].pad==V && spans[1].pad==V); + cell(2,2,2,2); cell(5,2,3,3); cell(6,4,4,4); + cell(9,7,7,7); cell(12,7,8,8); cell(13,9,9,9); cell(15,11,11,11); + // Images and videos may be interleaved without relabelling either. + assert(run({10,I,I,20,V,V,30}, {{2,2,1},{2,1,2}}, true)); + cell(1,1,1,1); cell(2,1,1,2); cell(4,4,4,4); cell(5,4,5,4); cell(6,6,6,6); + assert(!run(ids, {{4,2,2},{4,2,2}}, false)); + assert(!run({10,V,I,20}, {{2,2,1}}, true)); + assert(!run({10,V,20}, {{2,2,1}}, true)); + assert(!run({10,V,V,20}, {}, true)); + assert(!run({10,20}, {{2,2,1}}, true)); + assert(!run({10,V,V}, {{2,2,1}}, true)); + assert(!run({10,V,V,20}, {{2,3,1}}, true)); + assert(!visual_prompt_positions(ids,{},true,positions.data(),1,spans,error)); + std::cout << "native video/image M-RoPE position tests passed\n"; +} ````
Author
Owner

@Niko1221 commented on GitHub (Nov 5, 2026):

Thanks for taking the time to report this.

Strata has changed a lot since this was opened, and 0.2.11 is out now, so many older reports no longer apply. We're closing issues older than a week that have had no new reports in the last week. Closed here does not mean rejected.

To reopen it takes about two minutes:

  1. Re-test on 0.2.11. It may already be fixed. Write down what you see.
  2. Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other].
  3. Fill in the parts of the issue form: what happened, the Strata version, your graphics card, memory and system.
  4. Comment /reopen. A check runs and either reopens the issue or lists what is still missing.

The rules are in CONTRIBUTING.md.

<!-- gh-comment-id:6659941125 --> @Niko1221 commented on GitHub (Nov 5, 2026): Thanks for taking the time to report this. Strata has changed a lot since this was opened, and 0.2.11 is out now, so many older reports no longer apply. We're closing issues older than a week that have had no new reports in the last week. Closed here does not mean rejected. To reopen it takes about two minutes: 1. Re-test on 0.2.11. It may already be fixed. Write down what you see. 2. Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. 3. Fill in the parts of the issue form: what happened, the Strata version, your graphics card, memory and system. 4. Comment `/reopen`. A check runs and either reopens the issue or lists what is still missing. The rules are in [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md).
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#1762
No description provided.