Skip to content

Add a Neural Engine Qwen VL vision encoder export with host-side patchify - #566

Open
baozzz1 wants to merge 8 commits into
apple:mainfrom
baozzz1:qwen35-vlm
Open

baozzz1 wants to merge 8 commits into
apple:mainfrom
baozzz1:qwen35-vlm

Conversation

@baozzz1

@baozzz1 baozzz1 commented Nov 22, 2026 •

Copy link
Copy Markdown

Type of Change

  • Bug fix
  • Small feature (agreed in an issue)
  • New model (export recipe only)
  • New model (export recipe and new runtime support)
  • Documentation update

Motivation and Context

The Qwen3.5 tracking discussion in #56 included a concrete VLM request ("We do need VLMs, most importantly (Qwen3.5) 0.8b, 2b, 4b"); when it closed, the Neural Engine export path for the Qwen VL family's vision encoders was still missing. This PR adds that export path and the runtime support that feeds it.

Neural Engine vision encoder export (python/src/coreai_models/vlm/export.py)

  • Host-side patchify: the rank-9 Qwen patch rearrangement exceeds the Neural Engine compiler's rank-5 limit, so the Neural Engine form declares pixel_values as a pre-patchified [1, num_patches, patch_dim] input; the new Swift VisionPatchify produces that buffer on the host.
  • Linearized patch embedding: a Conv3d whose kernel size equals its stride is an exact nn.Linear over the flattened patch vector, which is the form the Neural Engine compiler can map.
  • Dtype-preserving f16 attention: HF's eager vision attention contains inline fp32 upcasts (RoPE q/k.float(), fp32 softmax) that split the compiled graph into dozens of Neural Engine regions. The replacement keeps the whole layer in the input dtype, with rotary tensors pre-tiled to exact shapes and the 1/sqrt(head_dim) scale folded into q so the f16 softmax stays bounded. It is bound per attention instance of the Hugging Face tower, so other models in the same process keep HF's implementation, and it reuses primitives/ios/rope.rotate_half. It stays in the VLM front end rather than models/ios/ because it keeps HF's [seq, heads, head_dim] layout and the tower's own weights; the channels-first BidirectionalSDPA would mean reauthoring the whole Qwen vision tower.
  • New CLI flags: --vision-neural-engine (single image only; implies --vision-dtype f16), --vision-dtype {f32,f16}, --vision-compression taking the existing none / 4bit / 4bit_weight_palettized_group32 presets, and --vision-only for checkpoints without a text-decoder recipe (the Qwen3.5-0.8B vision encoder).
  • A vision export rewrites the bundle's vision metadata block whole, so re-exporting a single-image encoder over a video bundle drops the stale frame fields.
  • VLMSpec gains an explicit text_decoder_class; a spec without one supports vision-only export and refuses text export with a clear error before any download.

Runtime support (Swift)

  • VisionFrontEnd reads the vision input's declared rank: a rank-4 input takes CHW pixels as before, a rank-3 input is filled with patch rows from VisionPatchify, whose geometry is derived from the bundle's vision config and checked against the declared shape. The runner now also checks that the pixel buffer fills the declared input exactly, so a multi-frame ([1, 3N, H, W]) vision asset fed one video frame at a time fails with an explicit error instead of running on a partly filled input.

Testing

  • Added/updated tests:
    • test_vlm_export.py: grid-t geometry, patchify output shapes, per-spec text-decoder dispatch, vision-only refusal of text export, vision-only manifest seeding, the Neural Engine form's single-image and f16 requirements, the attention swap's scope, parity of the Neural Engine form against the plain encoder for both the Qwen3-VL and Qwen3.5 vision towers (f32 to 1e-4, f16 to 2e-2), torch.export of the f32 and f16 graph entries with and without 4bit quantization, palettization preset dispatch, the rewritten vision metadata block, and the patch rows the Swift tests assert.
    • VisionPatchifyTests.swift: geometry derivation, patch-row parity with the Python exporter (including no-merge / single-temporal cases), rank-based binding of the pixel input, and rejection of inconsistent declared shapes.
  • Tested locally on macOS (Apple silicon): ruff check, ruff format --check, swift format lint --strict, pytest python/tests/test_model_units, and swift test --filter VisionPatchify, plus a one-off 4bit_weight_palettized_group32 palettization of a small Qwen3.5 vision tower in the Neural Engine form followed by torch.export. Not run: an export of the real checkpoints to .aimodel and on-device Neural Engine execution.
  • Added/updated docs: models/vlm/README.md.

baozzz1 and others added 8 commits November 22, 2026 12:37
--vision-dtype f16 runs the whole vision graph in half precision;
--vision-ane-friendly additionally exports the form the ANE compiler can
map to a single region:

- Pre-patchified [1, num_patches, patch_dim] input: the patchify rank-9
  reshape exceeds anec's rank-5 limit, so the host does it (also removes
  ~340ms of in-graph rearrangement from the GPU path: 751.6 -> 333.5ms
  on iPhone 16 Pro Max at 448px).
- Conv3d patch embed replaced by its exact Linear equivalent
  (kernel_size == stride sees one window per output position).
- Dtype-preserving eager attention with pre-tiled RoPE constants and the
  1/sqrt(d) scale folded into q: HF's eager path upcasts to fp32 inline
  twice per layer (RoPE q/k.float() and softmax(dtype=fp32)), and each
  inline cast cuts the ANE graph - 2 x 24 layers left 49 regions whose
  boundary traffic made hybrid execution slower than pure GPU.

Measured on iPhone 16 Pro Max (448px, 196 tokens): single ANE region,
forward 142-145ms vs 328-334ms pure GPU; output cos vs HF fp32 reference
0.999971 (Mac fp16) / 0.999438 (device ANE round-trip).

The Muse Glimmer encoder does not go through StaticVisionEncoder, so
--vision-dtype f16 and --vision-ane-friendly are refused for it rather
than ignored.
Callers can force a preferred compute unit at specialization time, which
is how the vision encoder is pinned to the Neural Engine or the GPU for
measurement. The chosen specialization options are logged.
Registers the qwen3.5-0.8b spec (12-layer vision tower, image token
248056). The ANE-friendly export path now loads through
AutoModelForImageTextToText and patches the attention class of whatever
vision tower the checkpoint carries, so the single-region graph applies
across Qwen3-VL and Qwen3.5 alike.

--vision-compression takes 4bit / 8bit (the macOS per-block int preset
with an int4 / int8 dtype) and 4bit-palettized / 8bit-palettized (k-means
palettization, group size 32), the palettized forms being the compression
the iOS presets use. The palettization worker pool is sized to memory
rather than core count.
ANE-mappable vision exports declare pixel_values as [1, num_patches,
patch_dim]. VisionPatchify derives the patch geometry from the bundle's
vision config and the declared shape and rearranges normalized CHW pixels
into the exporter's patch order.

VisionFrontEnd reads the encoder's pixel input when it loads. A rank-3
input gets the host patchify on both the image and the video-frame path;
a rank-4 [1, 3, H, W] input takes the CHW pixels unchanged. A fully
static input is bound at its declared shape, and a buffer whose element
count does not match it is rejected before the encoder runs.

CoreAISequentialEngine exposes preprocessing, rearrangement and the
encoder forward on their own (preprocessImage(cgImage:),
visionInput(fromCHW:), visionForward(pixels:)), so a caller can time
them apart.

The tests check the patch order against the exporter's reshape and
permute, the geometry checks, and how the pixel input is bound by rank.
export_text_bundle picked the decoder class from the spec's short name.
qwen3.5-0.8b is registered for its vision tower and has no decoder class
here, so its text export loaded Qwen3.5 weights into the Qwen3-VL layout
and failed on the shapes after the download.

VLMSpec.text_decoder_class names the reauthored decoder a spec's text
bundle is built from. It has no default, so every entry states its
decoder. A spec without one is refused by name before anything is
downloaded or loaded.

--vision-only exports the vision encoder into <output-dir>/<bundle>/
without the text bundle, and writes a metadata.json with the spec's
vision block when the bundle has none. Such a bundle holds the vision
asset alone, so the Swift runner cannot load it by itself. The switch
excludes --skip-vision, and the CLI names it when a model without a
text decoder is exported without it.
StaticVisionEncoder replaced `forward` on the attention class, so every
vision tower of that class in the process ran the f16 implementation.
That implementation takes rotary tensors tiled to [seq, heads,
head_dim]; a plain encoder built afterwards passes [seq, head_dim] and
failed on the shapes.

The replacement is bound to the attention module of each block of the
encoder being exported. nn.Module.__call__ reads `forward` from the
instance, so eager runs and torch.export both go through it.

The tests build Qwen3-VL and Qwen3.5 towers from small random configs:
a plain encoder's output is bit-identical before and after an ANE
encoder is built, the attention class keeps its own forward, and the
ANE encoder runs the replacement both eagerly and when exported.
iOS: a static-shape Qwen3.5 variant with a chunked gated delta
recurrence (exact at Horner order chunk - 1), interleaved M-RoPE, and
conv / recurrent states next to the key / value cache. Rope's cos and
sin are graph inputs, because the rope composite can be applied only
once per graph. This is the export side only: the graph needs a caller
that supplies those rows, carries the two extra states, and sends 16
real tokens per call, and CoreAIStaticShapeEngine does none of the
three yet. spike_qwen35/SPIKE.md lists the contract.

The registry's qwen3_5 entry takes it as its ios_class; qwen3_5_moe has
none, as the variant has no expert routing. --num-layers lowers
num_hidden_layers and leaves layer_types whole, so every count by layer
type reads only the first num_hidden_layers entries, the convention the
macOS decoder follows. The linear-attention recurrence runs at the
value head count: with fewer key heads than value heads, query and key
are expanded with repeat_interleave first, as transformers does. Export
rejects a stack with no full-attention layer to write the key/value
cache.

BaseForCausalLMForiOS.build_compression_inputs derives the arguments
the palettizer runs forward with from the model's own export contract,
and build_model passes them on, so a forward that takes rope rows and
extra states is calibrated with them. The palettizer's worker-pool
comment spells out the spawn start method's per-worker memory and the
__main__ guard a calling script needs.

VLM: Qwen3_5ForCausalLMEmbeddings enters Qwen3_5ForCausalLM at the
merged embedding sequence the VLM runtime builds. The layers, the four
states, the prefill entrypoint, the logits and the weight loading are
that decoder's; only the first input differs. It has a module of its
own beside qwen3_5.py.

Unit tests run tiny random checkpoints. The iOS variant is compared
with transformers at fp32 (the linear-attention layer, a run carried
across two calls, the logits) with equal and with grouped head counts;
they also cover the linear-attention-only rejection, the states each
trace writes, state shapes under --num-layers through resolve_model and
build_model, and the palettizer's inputs binding to forward. Fed
embed_tokens(input_ids), the embeddings decoder matches the token
decoder's logits and all four states bit for bit across a chunked
prefill and decode steps and in prefill mode, and its trace writes
every state.

spike_qwen35/ holds the parity gates (chunked recurrence against the
MLX oracle, the iOS class against the macOS decoder, the embeddings
decoder against Hugging Face on an image prompt), the embeddings
decoder's export, and the probes used to check which iOS lanes compile.

coreai.vlm.export builds the Qwen3.5 vision encoder only;
models/vlm/README.md points to spike.py for the embeddings-input
decoder.
Leave the Qwen3.5 embeddings decoder, the iOS compression-input plumbing and the engine's staged vision API for their own changes. Name the export form after the Neural Engine, require f16 for it, take vision compression from the existing presets, rewrite the vision metadata block on every export, refuse option combinations a run would ignore, and test the Neural Engine form against the plain encoder.
@baozzz1 baozzz1 changed the title Add an ANE-mappable Qwen3-VL vision encoder export and the Qwen3.5 VLM embeddings decoder Add a Neural Engine Qwen VL vision encoder export with host-side patchify Nov 22, 2026
@baozzz1
baozzz1 marked this pull request as ready for review November 22, 2026 07:56
@baozzz1
baozzz1 requested a review from a team as a code owner November 22, 2026 07:56
@tjia1818
tjia1818 requested a review from carinapeng December 1, 2026 18:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant