Repository navigation
Qwen3 vl - #107
Merged
Merged
Qwen3 vl#107
Conversation
Add flash_rt/models/qwen3_vl with the static dimension contract for Qwen3-VL-8B (text + vision). The language backbone is a strict superset of models/qwen3 (dense Qwen3-8B) and reuses that path's NVFP4 W4A4 decoder kernels unchanged; the vision tower (ViT depth 27 / DeepStack / interleaved-MRoPE) is recorded here ahead of the RTX frontend. Additive only: no existing kernels, bindings, or pipelines touched.
Add a general rotate_half (GPT-NeoX) RoPE kernel for Q/K, used by the Qwen3-VL ViT tower (head_dim 72) whose attention uses the split-half convention that the existing interleaved rope_apply and the norm-fused qwen3 rope kernels do not cover. Built into a separate flash_rt_qwen3_vl_kernels module gated by a new FLASHRT_BUILD_QWEN3_VL option (OFF by default), so the shared flash_rt_kernels.so is never rebuilt for this model. Additive only: no existing kernel, binding, target, or option is modified.
Add the Qwen3-VL vision tower forward: patch embed, learned position embedding, depth transformer blocks (rotate_half 2D-RoPE via the new rope_neox_qk kernel, full bidirectional FA2 attention, GELU-tanh MLP), 2x2 patch merger and DeepStack taps. All compute runs through flash_rt_kernels / flash_rt_fa2 / flash_rt_qwen3_vl_kernels; reshapes are metadata-only views. Grid-interpolated position embedding and the RoPE tables are caller inputs (built once per image). Validated vs the HF bf16 reference on FlashRT.png: image_embeds cos 0.9836, deepstack cos 0.9999 / 0.9986 / 0.9967.
Add tools/quantize_qwen3_vl_nvfp4.py, which turns a stock BF16 Qwen3-VL
checkpoint into a single self-contained FlashRT checkpoint: the language
linears are NVFP4-packed with the model.layers.* key schema the shared
_qwen3_rtx_nvfp4_weights loader already reads, the vision tower stays
BF16 (model.visual.*), and config.json hoists the text fields to top
level while keeping vision_config and the multimodal token ids. {q,k,v}
and {gate,up} share a per-layer global scale so the fused GEMM path stays
homogeneous.
Verified: the existing extractor loads the LLM (logits argmax matches HF)
and the vision tower loads from the same directory.
Add pure-torch reimplementations of the three deterministic geometry steps Qwen3-VL needs before the kernel pipeline, evaluated once per prompt and independent of the HF model: 3D MRoPE position ids over the text+image-grid sequence, interleaved-MRoPE cos/sin for the language stack, rotate_half 2D-RoPE cos/sin for the ViT patch grid, and the bilinear-interpolated learned vision position embedding in 2x2-merge order. Validated vs HF on FlashRT.png: position ids exact match, mrope and vision-rope cos 1.0, pos-embed cos 0.999994.
Wire the Qwen3-VL inference path end to end. The frontend reuses the dense-Qwen3 NVFP4 language core (Qwen3TorchFrontendRtx) unchanged and composes the kernelized ViT tower, the contiguous image-feature scatter, DeepStack injection into the first decoder layers, and interleaved-MRoPE. Per-prompt geometry is precomputed in set_prompt; the forward runs only kernels. Constructed directly, like the qwen3_rtx text sibling. Validated vs HF on an image+text prompt: next-token argmax matches HF, logits cos 0.981.
Add Qwen3VlTorchFrontendRtx.generate(): run the multimodal prefill, then the reused Qwen3 NVFP4 decode loop. After the image the MRoPE position is scalar, so the decode RoPE position continues from the prompt's max position while the KV-cache slot advances from the image-compressed prompt length. Returns decoded text. Produces a correct image description end to end on FlashRT.png.
Add examples/qwen3_vl_quickstart.py: load the FlashRT Qwen3-VL NVFP4 checkpoint, describe an image, and optionally report TTFT (prefill) and decode throughput. Baseline (eager, no CUDA graph) on a 5090 for a 1581-token image+text prompt: TTFT ~620 ms, decode ~38 tok/s.
Capture a per-cache-slot decode CUDA Graph that bakes the RoPE slice at the MRoPE-continuation position (which differs from the cache slot after an image), reusing the language core's static token buffer, capture stream and decode kernels. generate(use_graph=True) replays warm graphs. Bit-identical output to the eager path; warm decode 143 tok/s vs 38 tok/s eager on a 5090 (matches the qwen3-8B text-path ceiling).
The ViT intermediate (4304) is not 128-aligned, so fc2 fell back to the M=1-tuned arbitrary-K matmul, which dominated the tower at ~19 ms/call (88% of vision time). Zero-pad the intermediate to 4352 at load time (padded fc1 rows/bias and fc2 columns are zero, GELU(0)=0 keeps them inert) so every FFN GEMM runs on w16a16. Vision tower 582 -> 81 ms on a 5090, output cos unchanged (1.0 vs the eager path). Also add forward_graph(), a CUDA-Graph replay path for the tower (one graph per patch count) for the launch-bound small-image regime.
Measure decode with pre-captured (warm) CUDA Graphs replayed per step, matching how the path is served, instead of capturing lazily during the timed loop. On a 5090: TTFT ~121 ms, decode ~143 tok/s for a 1581-token image+text prompt.
Document the Qwen3-VL-8B RTX path: headline TTFT / decode table vs HF, quick start (checkpoint build + quickstart), inference architecture, the HF-reference correctness numbers, and the FFN padding / new rope kernel notes.
Add examples/qwen3_vl_openai_server.py: a small FastAPI server exposing POST /v1/chat/completions for image+text chat, translating OpenAI image_url content (http(s):// or data: base64) into the processor format and calling the frontend's generate(). Single-GPU, batch 1, requests serialised. Verified end to end against a base64 image request.
Run the per-block ViT GEMMs (qkv / proj / fc1 / fc2) as FP8 block-128 W8A8 (2x tensor-core vs bf16): the bf16 activation is dynamically quantized per GEMM, and the massive-activation outlier stays bf16 in the residual stream. patch_embed and the mergers stay bf16 (cheap; FP8 there is amplified through the whole tower), and the first 3 blocks stay bf16 because early-layer perturbations are amplified most by the late massive-activation channel. Vision tower 81 -> 63 ms, TTFT 121 -> 102 ms on a 5090; image_embeds cos 0.971 (vs 0.984 bf16), next-token argmax still matches HF, generated text unchanged.
Refresh the benchmark table and architecture notes for the FP8 block-128 ViT GEMMs (TTFT 121 -> 102 ms), record the image_embeds cosine under FP8 (0.971, argmax unchanged), and document the remaining compute-bound items (ViT full-attention, NVFP4 language prefill) and the next TTFT levers.
…FT 102 -> 99 ms) Add two general kernels in the separate flash_rt_qwen3_vl_kernels module, layer_norm_to_fp8_block128_bf16 and gelu_tanh_to_fp8_block128_bf16, that emit the per-token / per-128-K-block FP8 activation directly from the producing LayerNorm / GELU. The bf16 activation no longer round-trips to HBM before each FP8 GEMM, and one launch per GEMM input is removed. Standalone: ~2x over the unfused norm/gelu + quant chain, cos 0.9999 vs unfused (slightly higher accuracy, no intermediate bf16 rounding). The FP8 ViT blocks route through the fused path; the bf16 (massive-activation) blocks and the w16a16 mergers keep the plain norm path. image_embeds cos 0.970, E2E next-token argmax still matches HF.
Generalize the single-image prefill to any number of images. set_prompt now records one image-token span per image (contiguous runs, in image order) and the per-image patch counts; prefill runs the ViT tower once per image segment (each image is an independent attention window, which reproduces HF's block-diagonal cu_seqlens attention without a varlen kernel), scatters each image's features into its own span, and injects each image's DeepStack features into its span at the first decoder layers. The geometry builders already handled multiple grid rows, so MRoPE / vision-RoPE / position-embedding need no change. Single-image is the 1-segment case and is byte-identical (argmax 785). Two-image E2E argmax matches HF (8420).
Wire video through the same per-segment machinery as multi-image. The processor emits a video as per-frame vision spans separated by timestamp text tokens; set_prompt now walks image and video token runs together in sequence order, splitting each video grid (t,h,w) into t per-frame rows (t->1) so every frame is a vision segment encoded like an image, with its patches taken from pixel_values_videos. mrope_position_ids is generalized to HF get_rope_index: it dispatches image vs video spans by token position and uses the per-frame-split video grid, so each frame's temporal index is 0 and the inter-frame timestamp text tokens carry the temporal position (Qwen3-VL timestamp alignment). The ViT per-window attention, scatter and DeepStack inject are unchanged. Single-image (argmax 785) and two-image (8420) are unchanged; a synthetic 2-frame-group video matches HF next-token argmax (785).
The patch count (~ pixels / patch_size^2) sets both the ViT cost and the number of vision tokens the LLM prefills, so it is the dominant TTFT knob. The benchmark image (2172x724) patchifies to 6256 patches -> 1564 of 1581 LLM tokens at full resolution, which the default checkpoint config never caps. Add a max_pixels frontend parameter (+ --max-pixels in the quickstart and OpenAI server) that drives the processor's smart_resize: none(full) 6256 patch 99 ms | 1.0M 3888 patch 57 ms 0.5M 1824 patch 30 ms | 0.25M 972 patch 22 ms The generated description is unchanged across this range. Default is None (full resolution, behaviour unchanged); next-token argmax still matches HF (785) with no cap.
Document the input formats and the explicit, opt-in max_pixels resolution knob (default None = full resolution, behaviour unchanged). Also wrap one over-length line in the vision tower.
Address review robustness/convention gaps: - Fail-fast kernel-module check (_require_qwen3_vl_kernels) at the start of Qwen3VlTorchFrontendRtx.__init__, before any weights load, with a clear RuntimeError naming -DFLASHRT_BUILD_QWEN3_VL=ON when the module or any of its symbols is missing (instead of a first-forward crash). - Factor the image/video token-run walk into a pure geo.vision_segments(): it raises ValueError for a text-only prompt (use the Qwen3 text path) and for a span/grid mismatch, replacing the runtime assert (stripped by -O). The OpenAI server maps ValueError -> HTTP 400. - CMake: FLASHRT_BUILD_QWEN3_VL now FATAL_ERRORs on GPU_ARCH != 120, since the path depends on the SM120 Qwen3 NVFP4 / FP8 kernels. - Add tests/test_qwen3_vl_smoke.py (CI-friendly, no checkpoint): frontend import, fail-fast check, vision_segments walk + text-only/mismatch boundaries, and geometry builder shapes on synthetic image/multi-image/ video sequences. E2E argmax unchanged (single 785, two-image 8420, video 785).
This was referenced Jun 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
First-version baseline of the Qwen3-VL-8B multimodal inference path on
a single RTX 5090 (sm_120). The dense-Qwen3 language stack reuses the
existing NVFP4 W4A4 + CUDA-Graph path unchanged; this branch adds the
ViT tower, the image/multi-image/video geometry + scatter, DeepStack
injection, interleaved-MRoPE, and a self-contained checkpoint build tool.
Fully additive: no shared kernel source is modified. The one new CUDA
kernel lives in a separate, opt-in pybind module (
flash_rt_qwen3_vl_kernels,gated by
-DFLASHRT_BUILD_QWEN3_VL=ON); the sharedflash_rt_kernels.soisnever rebuilt.
What's included
_qwen3_vl_vision_rtx.py): patch-embed → interpolated posembed → 27 transformer blocks (rotate_half 2D-RoPE, bf16 FA2 full
attention, GELU-tanh MLP) → 2×2 merger, DeepStack taps at 8/16/24. Linears
run FP8 block-128 W8A8 with the activation quant fused into the producing
LayerNorm/GELU; the first 3 blocks + mergers stay bf16 to hold the
massive-activation channel.
qwen3_vl_rtx.py): per-prompt geometry precompute, visionscatter, DeepStack inject, interleaved-MRoPE, warm CUDA-Graph decode.
video (per-frame segments + Qwen3-VL timestamp-aligned MRoPE).
rope_neox_qk_bf16,layer_norm_to_fp8_block128_bf16,gelu_tanh_to_fp8_block128_bf16.harness), OpenAI-compatible vision server, and a usage doc.
Performance (RTX 5090, image+text)
TTFT is dominated by the patch count (the image patchifies to 6256 patches
→ 1564 of 1581 LLM tokens). The
max_pixelsknob (explicit, defaultNone= full resolution) trades resolution for latency — 99 → 30 ms at 0.5 MP
with the description unchanged:
max_pixelsCorrectness (vs HF bf16)
image_embeds cosine 0.971 (FP8).
2-frame-group video 785.
Notes (baseline scope)
max_seq).fps/metadatapassthrough yet).
prefill (the existing
fp4_w4a16GEMM is already ~3× faster than FP8block-128 at these shapes) and an INT8 ViT attention via sage2 (1.17×
faster but image_embeds cosine collapses 0.968 → 0.538). No FP8-e4m3-QK
FMHA exists for sm_120, so attention stays bf16 FA2.
Build & usage