Repository navigation
Conversation
--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
marked this pull request as ready for review
November 22, 2026 07:56
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.
Type of Change
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)pixel_valuesas a pre-patchified[1, num_patches, patch_dim]input; the new SwiftVisionPatchifyproduces that buffer on the host.nn.Linearover the flattened patch vector, which is the form the Neural Engine compiler can map.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 the1/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 reusesprimitives/ios/rope.rotate_half. It stays in the VLM front end rather thanmodels/ios/because it keeps HF's[seq, heads, head_dim]layout and the tower's own weights; the channels-firstBidirectionalSDPAwould mean reauthoring the whole Qwen vision tower.--vision-neural-engine(single image only; implies--vision-dtype f16),--vision-dtype {f32,f16},--vision-compressiontaking the existingnone/4bit/4bit_weight_palettized_group32presets, and--vision-onlyfor checkpoints without a text-decoder recipe (the Qwen3.5-0.8B vision encoder).visionmetadata block whole, so re-exporting a single-image encoder over a video bundle drops the stale frame fields.VLMSpecgains an explicittext_decoder_class; a spec without one supports vision-only export and refuses text export with a clear error before any download.Runtime support (Swift)
VisionFrontEndreads the vision input's declared rank: a rank-4 input takes CHW pixels as before, a rank-3 input is filled with patch rows fromVisionPatchify, 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
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.exportof the f32 and f16 graph entries with and without4bitquantization, palettization preset dispatch, the rewrittenvisionmetadata 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.ruff check,ruff format --check,swift format lint --strict,pytest python/tests/test_model_units, andswift test --filter VisionPatchify, plus a one-off4bit_weight_palettized_group32palettization of a small Qwen3.5 vision tower in the Neural Engine form followed bytorch.export. Not run: an export of the real checkpoints to.aimodeland on-device Neural Engine execution.models/vlm/README.md.