
Qwen4-35B-A3B Video Q&A: Plan Frames Before You Send
Summary
Serve Qwen4-35B-A3B with vLLM, budget video tokens in Python, and run multi-turn Q&A on a recording.
Alibaba's Qwen team published Qwen4-35B-A3B on December 4, 2026: Apache-2.0 weights, text, image and video input, and a native context window of 1,048,576 tokens. It was on Hacker News within the hour, and it shipped with day-one instructions for transformers, vLLM, SGLang and llama.cpp, plus community MLX builds.
Most first-day posts will show you vllm serve and a chat prompt. This guide goes after the feature that is easiest to get wrong: video. A million-token window sounds like you can drop in an hour of screen recording and ask questions. You can, but the video token budget is fixed, so the longer the clip, the smaller each frame gets. At the default 2 fps, an hour-long recording works out to roughly 320x160 pixels per frame. Nobody is reading a stack trace at that size, and neither is the model.
You will build three things: a small Python planner that tells you what resolution the model will actually see for a given clip and frame rate, a streaming client that runs a multi-turn Q&A session over one video with per-turn reasoning effort, and a stub server so you can test the client on a laptop before you rent a GPU.
What you need
- Python 3.10+ and
pip install openaifor the client. The planner and stub use only the standard library. - For real inference: a Linux machine with NVIDIA GPUs and
pip install vllm(a release recent enough to know Qwen4; the model card links the official recipe at recipes.vllm.ai). - Enough memory. The model card lists 57B parameters in BF16: 35B main weights, about 20B of n-gram embedding and 2B for the multi-token prediction head. At 2 bytes per parameter that is roughly 114 GB before any KV cache. Neither the card nor the launch blog states a VRAM requirement, so treat that number as arithmetic, not a spec.
ffmpegif you want to trim or inspect clips.
One naming wrinkle before you start: the card says 3B parameters are active per token, the launch blog says about 3.8B. Both agree on the routing: 256 experts, with 8 routed and 1 shared expert active per token. Either way, compute per token is small, but all 57B parameters still have to live somewhere.
Step 1: Serve the model with video sampling turned on
The card's quickstart is a bare vllm serve. For video you need one extra flag. Without it, vLLM picks a fixed number of frames and ignores the per-request fps you send later.
pip install vllm
vllm serve "Qwen/Qwen4-35B-A3B" \
--media-io-kwargs '{"video": {"num_frames": -1}}' \
--port 8000
num_frames: -1 hands frame selection to the model's own processor, which samples by frames per second. The card is explicit that fps-based sampling is currently supported only in vLLM. SGLang, llama.cpp and MLX will run the model, but this guide's video path assumes vLLM.
If your recordings are on the same box, add vLLM's --allowed-local-media-path /data/videos and pass file:///data/videos/repro.mp4 as the URL. Otherwise serve the file over HTTP or send a base64 data:video/mp4;base64,... URL.
Step 2: Raise the video budget
The released video_preprocessor_config.json is, in the card's words, conservatively configured. For hour-scale video the card tells you to raise longest_edge to 469,762,048, which it describes as 224k video tokens. The simplest way is to download the repo, edit the file and serve from the local directory:
hf download Qwen/Qwen4-35B-A3B --local-dir ./qwen4-35b-a3b
# edit ./qwen4-35b-a3b/video_preprocessor_config.json so that "size" reads:
# {"longest_edge": 469762048, "shortest_edge": 4096}
vllm serve ./qwen4-35b-a3b \
--served-model-name "Qwen/Qwen4-35B-A3B" \
--media-io-kwargs '{"video": {"num_frames": -1}}' \
--port 8000
The card also mentions overriding these values with engine startup parameters and links the vLLM and SGLang pull requests, but it does not print the flag names. Editing the config file works today and is easy to diff.
Step 3: Work out what the model will actually see
Here is the part nobody tells you. That longest_edge number is not an edge length. Divide it by 2,048 and you get 229,376, which is exactly 224 x 1,024, the card's 224k tokens. And 2,048 is 32 x 32 x 2. The launch blog says 16x16 patches are merged 2x2 into one visual token and that consecutive frames are grouped in pairs. Put together: one video token covers a 32x32 pixel patch across two frames, and longest_edge is a total pixel volume (width x height x frames) for the whole clip.
That derivation is mine, not a sentence from the card, so Step 5 shows you how to check it against the real prompt_tokens your server reports. It leads to a planner you can run before you upload anything:
"""Plan a Qwen4-35B-A3B video request before you send it.
Token model (derived from the model card: longest_edge=469,762,048 is
described as 224k video tokens, and 469,762,048 / 2048 = 229,376 = 224 * 1024):
one video token covers a 32x32 pixel patch across 2 consecutive frames.
"""
import argparse
import math
PATCH = 32 # 16x16 patches merged 2x2 -> 32x32 px per token
FRAMES_PER_TOKEN = 2 # sampled frames are grouped in pairs
PX_PER_TOKEN = PATCH * PATCH * FRAMES_PER_TOKEN # 2048
CONTEXT = 1_048_576
def plan(duration_s, fps=2.0, longest_edge=469_762_048, aspect=16 / 9,
src=(1920, 1080), reasoning_budget=32_768, answer_budget=4_096,
prompt_tokens=300):
frames = max(2, math.floor(duration_s * fps))
frames -= frames % 2 # pairs only
px_per_frame = longest_edge / frames # pixel volume split across frames
h = math.sqrt(px_per_frame / aspect)
w = h * aspect
h = max(PATCH, int(h // PATCH) * PATCH) # snap down to the patch grid
w = max(PATCH, int(w // PATCH) * PATCH)
if w > src[0] or h > src[1]: # the budget never upscales
w = max(PATCH, src[0] // PATCH * PATCH)
h = max(PATCH, src[1] // PATCH * PATCH)
tokens_per_pair = (h // PATCH) * (w // PATCH)
video_tokens = (frames // 2) * tokens_per_pair
total = video_tokens + prompt_tokens + reasoning_budget + answer_budget
return {
"frames": frames, "frame_px": f"{w}x{h}",
"tokens_per_second": round(tokens_per_pair * fps / 2, 1),
"video_tokens": video_tokens, "total_tokens": total,
"fits": total <= CONTEXT, "headroom": CONTEXT - total,
}
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("duration_s", type=float)
ap.add_argument("--fps", type=float, default=2.0)
ap.add_argument("--longest-edge", type=int, default=469_762_048)
ap.add_argument("--src", default="1920x1080", help="source WxH")
a = ap.parse_args()
sw, sh = (int(x) for x in a.src.split("x"))
p = plan(a.duration_s, a.fps, a.longest_edge, aspect=sw / sh, src=(sw, sh))
for k, v in p.items():
print(f"{k:>18}: {v}")
Run it for a 4m12s 720p bug reproduction, then for a one-hour 1080p recording:
$ python video_budget.py 252 --src 1280x720
frames: 504
frame_px: 1280x704
tokens_per_second: 880.0
video_tokens: 221760
total_tokens: 258924
fits: True
headroom: 789652
$ python video_budget.py 3600 --src 1920x1080
frames: 7200
frame_px: 320x160
tokens_per_second: 50.0
video_tokens: 180000
total_tokens: 217164
fits: True
headroom: 831412
Both fit in the context window with room to spare, and that is the trap. fits: True says nothing about legibility. The short clip keeps its native resolution. The hour-long one is squeezed to 320x160, fine for "which app is open" and useless for "what does the error say".
The budget is fixed, so you trade time resolution for pixel resolution. Drop the hour-long recording to one frame every four seconds:
$ python video_budget.py 3600 --fps 0.25 --src 1920x1080
frames: 900
frame_px: 960x512
tokens_per_second: 60.0
video_tokens: 216000
total_tokens: 253164
fits: True
headroom: 795412
960x512 is readable for most UI text. For a slide deck or a terminal session, 0.25 fps loses almost nothing. For a fast UI interaction it loses the click you care about, and you are better off trimming to the two minutes that matter with ffmpeg -ss 00:41:00 -t 120 -c copy and sending that at 2 fps.
Step 4: Build the Q&A client
vLLM exposes the OpenAI Chat Completions API, so the stock openai package works. The Qwen-specific parts all travel in extra_body:
chat_template_kwargs.reasoning_effort:xhigh,high,loworoff. Default ishigh. The olderenable_thinking: falsestill works and meansoff.chat_template_kwargs.preserve_thinking: on by default. Earlier turns' reasoning stays in the prompt, provided you send it back.mm_processor_kwargs:fpsanddo_sample_frames, per request.
Reasoning arrives in a separate stream field. The card's example reads delta.reasoning_content and falls back to delta.reasoning, so the client does the same. Sampling values are the card's recommendations: temperature 1.0, top_p 0.95, top_k 20 with thinking on, and temperature 0.7, top_p 0.8, presence_penalty 1.5 with it off.
"""Multi-turn Q&A over one video with Qwen4-35B-A3B behind vLLM."""
import os
import sys
from openai import OpenAI
MODEL = "Qwen/Qwen4-35B-A3B"
client = OpenAI(
base_url=os.environ.get("OPENAI_BASE_URL", "http://localhost:8000/v1"),
api_key=os.environ.get("OPENAI_API_KEY", "EMPTY"),
)
def ask(messages, effort="high", fps=2.0, max_tokens=4096):
"""Stream one turn. Returns (answer, reasoning, usage)."""
thinking = effort != "off"
stream = client.chat.completions.create(
model=MODEL,
messages=messages,
max_tokens=max_tokens,
# model card sampling: thinking vs non-thinking
temperature=1.0 if thinking else 0.7,
top_p=0.95 if thinking else 0.8,
presence_penalty=0.0 if thinking else 1.5,
stream=True,
stream_options={"include_usage": True},
extra_body={
"top_k": 20,
"chat_template_kwargs": {
"reasoning_effort": effort, # xhigh | high | low | off
"preserve_thinking": True,
},
"mm_processor_kwargs": {"fps": fps, "do_sample_frames": True},
},
)
answer, reasoning, usage = [], [], None
for chunk in stream:
if chunk.usage:
usage = chunk.usage
if not chunk.choices:
continue
delta = chunk.choices[0].delta
r = getattr(delta, "reasoning_content", None) or getattr(delta, "reasoning", None)
if r:
reasoning.append(r)
if delta.content:
answer.append(delta.content)
print(delta.content, end="", flush=True)
print()
return "".join(answer), "".join(reasoning), usage
def main(video_url, fps):
messages = [{
"role": "user",
"content": [
{"type": "video_url", "video_url": {"url": video_url}},
{"type": "text", "text": (
"This is a screen recording of a bug reproduction. List every "
"user action as `mm:ss - action`, then state the first moment "
"the UI shows something wrong and what it shows.")},
],
}]
followups = [
("low", "Quote the exact error text visible on screen, character for character."),
("low", "Write a 5-line bug report: title, steps, expected, actual, timestamp."),
]
effort = "high"
while True:
answer, reasoning, usage = ask(messages, effort=effort, fps=fps)
if usage:
print(f"[effort={effort} prompt={usage.prompt_tokens} "
f"completion={usage.completion_tokens}]\n")
# keep the reasoning in history so preserve_thinking has something to preserve
turn = {"role": "assistant", "content": answer}
if reasoning:
turn["reasoning_content"] = reasoning
messages.append(turn)
if not followups:
break
effort, question = followups.pop(0)
messages.append({"role": "user", "content": question})
if __name__ == "__main__":
main(sys.argv[1], float(sys.argv[2]) if len(sys.argv) > 2 else 2.0)
Three details in there matter more than they look:
- The video goes in once. It lives in the first user message and every later turn reuses it from history. vLLM's prefix caching can reuse the work on that 220k-token prefix for follow-ups, as long as the earlier messages are byte-identical.
- Reasoning goes back into history.
preserve_thinkingcan only preserve what you return. If you append justcontent, turn two starts cold and often re-watches the whole clip in its head. - Effort drops after the first turn. The expensive question is the timeline. "Quote the error text" is a lookup against work already done, so
lowis enough.
Step 5: Test the client without a GPU
You do not want to discover a typo in extra_body while paying for a multi-GPU box. This stub speaks just enough of the streaming protocol to exercise the client. It asserts on the request shape and reports how many prior turns carried reasoning back.
"""Tiny stand-in for vLLM's /v1/chat/completions so you can test the client
without a GPU. It checks the request shape and streams a canned reply."""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
kw = body["chat_template_kwargs"]
assert kw["reasoning_effort"] in ("xhigh", "high", "low", "off"), kw
assert "fps" in body["mm_processor_kwargs"]
first = body["messages"][0]["content"]
assert first[0]["type"] == "video_url" and first[1]["type"] == "text"
turns = sum(m["role"] == "assistant" for m in body["messages"])
kept = sum("reasoning_content" in m for m in body["messages"])
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
def send(obj):
self.wfile.write(f"data: {json.dumps(obj)}\n\n".encode())
base = {"id": "stub", "object": "chat.completion.chunk", "model": body["model"]}
if kw["reasoning_effort"] != "off":
send({**base, "choices": [{"index": 0, "delta": {"reasoning_content": "(stub reasoning) "}}]})
text = f"stub turn {turns + 1}: effort={kw['reasoning_effort']}, prior reasoning kept={kept}"
for word in text.split(" "):
send({**base, "choices": [{"index": 0, "delta": {"content": word + " "}}]})
send({**base, "choices": [], "usage": {"prompt_tokens": 1000 + 50 * turns,
"completion_tokens": 12, "total_tokens": 0}})
self.wfile.write(b"data: [DONE]\n\n")
if __name__ == "__main__":
HTTPServer(("127.0.0.1", 8000), H).serve_forever()
$ python stub_server.py &
$ python ask_video.py https://example.com/repro.mp4 1
stub turn 1: effort=high, prior reasoning kept=0
[effort=high prompt=1000 completion=12]
stub turn 2: effort=low, prior reasoning kept=1
[effort=low prompt=1050 completion=12]
stub turn 3: effort=low, prior reasoning kept=2
[effort=low prompt=1100 completion=12]
That is real output from the code above. prior reasoning kept climbing from 0 to 2 confirms that the history round-trip works. If you see 0 on turn two, your client is dropping reasoning.
Worked example: a 4-minute bug repro to a bug report
Point the same script at the real server. Say QA recorded checkout-repro.mp4, 4m12s at 1280x720. The planner already said this clip keeps its native resolution at 2 fps and costs about 221,760 video tokens.
$ export OPENAI_BASE_URL=http://gpu-box:8000/v1
$ python ask_video.py file:///data/videos/checkout-repro.mp4 2
What to look for in the three turns:
- Turn 1, high effort: a timestamped action list and the first visibly wrong frame. Check
promptin the usage line. It should land near the planner'svideo_tokensplus a few hundred for text. If it is far lower, yourlongest_edgeedit did not take, or the server is not sampling by fps. - Turn 2, low effort: the literal on-screen error text. This is your legibility test. Compare it against the video by eye. If the model paraphrases or gets characters wrong, frames are too small: trim the clip or lower fps and rerun the planner.
- Turn 3, low effort: the five-line report.
promptshould grow only by the size of the earlier answers and reasoning.
I have not included a model transcript here because I ran the client against the stub, not against 114 GB of weights, and I would rather show you no output than invented output. The usage line is the part you should trust: it is the server's own count and it is how you verify the token model from Step 3 on your hardware.
Pitfalls
- "Fits in context" is not "readable". The video budget is a fixed pixel volume. Long clips get tiny frames. Run the planner and look at
frame_px, notfits. - Forgetting
--media-io-kwargs. Withoutnum_frames: -1your per-requestfpsdoes nothing and you will not get an error telling you so. - Leaving the default video config. The shipped
longest_edgeis conservative. The card does not print the default, so check your copy ofvideo_preprocessor_config.jsonand pass that number to the planner with--longest-edge. - Low effort can cost more in agent loops. The card notes that lower reasoning effort can raise total latency on multi-turn tasks because of retries. Use
lowfor lookups, not for the first pass over the video. - The model may skip thinking on its own. Even at
high, simple prompts can come back with no reasoning. Do not treat an empty reasoning field as an error, and do not append an emptyreasoning_content. - presence_penalty 1.5 with thinking off is deliberate. It curbs repetition. The card warns that high values can cause language mixing. If you see stray Chinese in an English answer, lower it.
- Tokenizer needs extra setup in transformers. The reference tokenizer requires
trust_remote_code=Trueand thetiktokenpackage. The Jinja template undertokenizer-compat/produces the same text but different token IDs, so do not mix the two when comparing token counts. - GGUF is not a shortcut for video.
ggml-org/Qwen4-35B-A3B-GGUFships Q4_K_M, Q6_K and Q8_0, and the launch blog reports about 22% faster generation with MTP draft tokens on an Apple M5. That is a good route for text and images. For fps-sampled video, the card points you at vLLM. - Changing fps between turns breaks the cache. A different fps means different frames and a different prompt prefix. Pick one fps per conversation.
Quick reference
| Thing | Value |
|---|---|
| Model ID | Qwen/Qwen4-35B-A3B (Apache-2.0) |
| Context | 1,048,576 tokens |
| Inputs / outputs | Text, image, video in; text out |
| Serve flag for fps sampling | --media-io-kwargs '{"video": {"num_frames": -1}}' |
| Per-request video | extra_body.mm_processor_kwargs: {fps, do_sample_frames} |
| Video content part | {"type": "video_url", "video_url": {"url": ...}} |
| Hour-scale video budget | longest_edge 469762048 (about 224k tokens) |
| Token rule of thumb (derived) | frames x width x height / 2048 |
| Reasoning control | chat_template_kwargs.reasoning_effort: xhigh, high, low, off |
| Reasoning stream field | delta.reasoning_content, else delta.reasoning |
| Sampling, thinking | temperature 1.0, top_p 0.95, top_k 20, presence_penalty 0 |
| Sampling, no thinking | temperature 0.7, top_p 0.8, top_k 20, presence_penalty 1.5 |
| Card's budget advice | 262,144 reasoning tokens, 131,072 response tokens |
Next steps
- Calibrate the planner. Send three clips of different lengths, log
prompt_tokens, and compare withvideo_tokens. If they diverge, your config or my derivation is off, and the usage numbers win. - Add a two-pass mode: first pass over the full recording at 0.25 fps to find the interesting minute, second pass over an ffmpeg-trimmed clip at 2 fps to read it.
- Try tool calling. In transformers you pass Python functions via
tools=[...]toapply_chat_template. Afile_bug(title, steps, timestamp)tool turns turn three into a real ticket. - Compare efforts on your own clips. Run turn one at
low,highandxhighand check which is the cheapest that still gets the first-wrong-frame timestamp right.
Sources
- Model card: https://huggingface.co/Qwen/Qwen4-35B-A3B
- Launch blog: https://huggingface.co/blog/qwen4
- vLLM recipe: https://recipes.vllm.ai/Qwen/Qwen4-35B-A3B
- GGUF builds: https://huggingface.co/ggml-org/Qwen4-35B-A3B-GGUF
- Hacker News thread: https://news.ycombinator.com/item?id=50755448
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,638 newsletter subscribers.