Skip to content

lfm3: add native Metal vision support above the text decoder - #1502

Open
BlivionIaG wants to merge 31 commits into
ashhart:mainfrom
BlivionIaG:feature/lfm3-vl-support
Open

BlivionIaG wants to merge 31 commits into
ashhart:mainfrom
BlivionIaG:feature/lfm3-vl-support

Conversation

@BlivionIaG

@BlivionIaG BlivionIaG commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Native LFM3-VL image serving on Metal, vision only. Latest review asked for the leftover withdrawn-route receipts to go and for the image tower to run once per pass, not once per prefill chunk; both are done at this head.

  • Issue: Refs Add native Metal support for LFM3-1.7B and LFM3-VL-2B MLX 4/6/8-bit checkpoints #1491; native vision qualification on an M5 is the maintainer's open gate.
  • Stacked on: upstream/main ea37382cb1c12b2c1ff19ec09f2c03af78ff8eab; head 2b087ef1d1, 27 commits ahead (19 plain, 8 merges), latest merge cdeaa761f4.
  • atc overlap --json: ATC0.9.6 was run against upstream with --base fb8fdf3; complete=false (myPullRequestsLimit, otherPullRequestsLimit, pullFilesLimit, pullFilesUnavailable, timeLimit). Supplemental complete snapshot:217foreign open heads,3038 exact local merge comparisons including latest Main ff742df; existing reviewed overlaps are retained, not claimed globally clean. The avoidable added environment-test collision with CUDA (GB10): a lending-daemon source for the display carveout, opt-in #2762 was removed by preserving Main's existing test name, without importing its unmerged feature.

Checks on this head

  • Head commit: 2b087ef1d1.
  • Lean checker: 165 vs 165, 0 new. No touched .zig file is over 600 lines; zig fmt --check build.zig zig is clean; tools/pr_check.py --base d2b43908db --pr 1502: 0 errors, 0 warnings.
  • Tests run on this head (Apple M4 Pro, Zig 0.17.0, -Dcpu=apple_m1): test-lfm3-host, test-lfm3-image-host, test-lfm3-vision-residency-host and test-lfm3-prefill-host pass; zig build native links. The new image_fill_test.zig drives the real prefill step loop and counts tower calls for 128-row, host-narrowed one-row and warm chunks, a warm start inside an image, a repeated image and a release mid-pass; re-projecting per chunk fails it.
  • Vision-aware load (main's Metal text-only loads hold no LFM3-VL vision weights: the tower and projector stay on disk #3420 text-only LFM3-VL load left the tower on disk, so --vision reached MissingTensor): Model.loadWithResidency takes the --vision choice (lfm3/weights.zig packs); with --vision each shard loads whole, without it a VL shard packs main's two text namespaces (594 tensors). The weights_test case is red before (MissingTensor at vision_tower.patchifier.weight) and green after; M4 Pro, LFM3-VL-2B MLX 4-bit c823fade: the merged head before the fix exits with MissingTensor under --vision, at 2b087ef1d1 the image request returns; text-only before vs after 1489-1490 vs 1488-1490 MB, ready in 2.6-3.5 s vs 2.7 s, same reply; --vision 1890 MB; serve_check.py --sampled --cancel 64/0/0.
  • Served at head cc65d60d0a (the 61/61 driver was not re-run at 2b087ef1d1): the token-id driver against LFM3-VL-2B MLX 4-bit c823fade98e35a3d6942ad4d38b1ea15f675cd12: 61/61 comparisons passed, 0 failed; previous head cdeaa761f4 gives identical signatures.
  • CI on this head: queued behind the repository's runner backlog when this was written; no job has failed. The previous head's 10 checks passed.
  • Served recipe on an M5 Ultra at this head: tools/lfm3/serve_check.py --sampled --cancel with LFM3-VL-2B MLX 4-bit c823fade98e35a3d6942ad4d38b1ea15f675cd12: 64 passed, 0 failed, 0 skipped, with --vision on both launches (colour semantics, image order, concurrency, corrupt-PNG refusal, cancellation and recovery).
  • Not run: the main-against-branch device comparison (the maintainer's); CUDA is not reached by this PR.

Receipt

  • Main against branch: main has no vision, so the image path has no main-side reference; the serial reference is this head with --parallel 1 and cache 0. Image and text request token ids: 61/61 comparisons equal (serial vs 4-way cold and warm cache, A/B/B/A, a resumed prefix ending inside a 1024-token image, one image over eight prefill chunks, cancel and recovery), greedy and seeded, on an M4 Pro; the previous head cdeaa761f4 produced the identical 61 signatures. No speed or FP32 fidelity claim.
  • Boxes it reaches: The original PR backend/model scope remains in the exact-head source and historical receipts; this audit exercised only Darwin27.2.0 arm64 CPU host paths. CUDA/Metal model reach is not newly qualified.
  • New switch? Default, accepted values, profile row: no new serving setting/default/profile activation in this review fix/restack. Original settings and accepted forms are in the exact-head docs/environment.md and platform/environment.zig; no experimental setting is newly enabled by this update.
  • Environment: head 2b087ef1d1; Zig 0.17.0; Apple M4 Pro, 48 GiB, macOS 27.2; native Metal binary sha256 aaa4337ad72c3d7c484542e169b8b1294a37e9f30865f388088e860424f01920; LFM3-VL-2B MLX 4-bit c823fade98e35a3d6942ad4d38b1ea15f675cd12.
  • Paths/platforms run versus unrun: M4 Pro served LFM3-VL 4-bit with --vision on Metal, plus the M5 Ultra served recipe (64/64); other Apple chips not re-run; CUDA and HIP not reached.
  • Exactness, --alone --serial/token_sha versus drafts-off: token ids for every case above: 61/61 equal between the serial reference and the concurrent, warm and cancelled paths; drafting was not re-measured in this run.
  • Main against branch before asking for a maintainer machine run: Unavailable under the device/toolchain limits above; explicitly disclosed per CONTRIBUTING.md. No machine run or waiver requested.
  • Decode speed before/after: Not measured on this exact head; old-source timings below are historical only.
  • Prompt speed/cold TTFT before/after: Not measured on this exact head; no TTFT/ITL or prefill improvement claimed.
  • Licence of new weights/drafter: LFM Open License v1.0; six checkpoint revisions are in docs/recipes/lfm3-native.md; generated synthetic image, no unlicensed photo introduced.

Remaining maintainer requests

The native-Metal main-versus-branch photo parity and speed run, and the M5 model and performance run.

Kernel contract
  • Kernels/replacements: this update changes no kernel; the contract records are the PR's own (metal_lfm3_* registrations).
  • Planted controls: zig build tf-kernel-contract then tf-kernel-contract --only LFM3 on an Apple M4 Pro: 52 controls, 52 red as planted, 0 missed.
  • Backend SUMMARY at 2b087ef1d1 (M4 Pro): SUMMARY 72 kernels: 72 pass gates 1-4, 0 fail, 0 known findings; 51 controls: 51 red as planted, 0 missed; 0 limit problems. Exit 0.
  • Re-run at 2b087ef1d1.

Checklist

  • Title/description, head and stack agree; older results remain source-bound.

  • Every new/restored test has a failing-before runtime receipt across all reached platforms. Host evidence is above; missing device gates are not waived.

  • No newly added overlong/multiline source comments, measurements or review history; inherited findings are reported above.

  • Complete publication trees/outgoing histories reviewed for public noreply identity, tool trailers and privacy; synthetic detector fixtures and mandatory third-party public contacts are not live secrets. No package/binary upload proposed.

  • All inference-path/lane-round gates qualified on this head.

  • Drafted=plain, restored=fresh, concurrent=solo on required devices/settings.

  • Required precision/reference evidence on this exact head complete.

  • Decode/prompt no slower than Main at the required widths, greedy and sampled.

Historical source-bound notes — not current-head qualification

Earlier commands/measurements retain their original commit/binary scope. Any earlier readiness or provenance claim is superseded by the open gates above.

Current published head (supersedes the stale head/base/qualification claims below)

  • Head: a5cb6b673e582a9ce0f85ed0c24bda3c0e867898, rebased onto pinned upstream Main 8a7838a65a1fa1a44e0136a2cccd8bfcc8c0a8b5; PR base remains main. The 932ee49bb head on Main 6e9af930 and references below to 57b2b2ed0, eb9fa80fa, a39a0a2e2, 8be9c408 and c16a2964 are historical, not current-head results.
  • Owned synthetic image (executed at previous head 932ee49bb, source-bound, not re-run on b973a2d5): the unlicensed photograph is replaced by a generated PNG with a regeneration path. Zig path output at 932ee49bb: OWNED_PNG admitted grid=14x20 tokens=70; UNDERSIZED_PREPARED_IMAGE refused=ImageTooSmall.
  • CPU FP64 references (executed at 932ee49bb, historical/source-bound, not b973a2d5 receipts): real-weight 4/6/8-bit CPU references. A parent inspection of all 6 current-prefix BF16 files found them all finite, 70x2048 image rows and 11520000 decoder elements each; hashes are in the author's external receipts/.../pr1502-main6e9-cpu-references.json (not in the PR; none are asserted here, and they are not claimed as executed on the new head). Earlier generic 6/8 decoder files were accidentally regenerated before the separately named outputs, and older JSON is not relabelled. Not native Metal parity.
  • Prior b973a2d51e67e07635c42011a0517acdad7eea3b host checks (not new executions): the combined command test-lfm3-host test-lfm3-prefill-host test-metal-residency-host failed: the extra Metal-residency host target cannot link objc under this Mac's unaccepted Xcode licence (not bypassed). 15/18 steps succeeded, 1 failed (rest not run). Fresh LFM3 tests passed 13/13 (12 prefill + 1 images); other LFM3 metadata/weights/image nodes passed from cache. This is not a clean full build and not native Metal parity.
  • Current CI correction: initial b973 Linux/Windows and other host checks passed, but macOS dev-tools failed compiling the real vision provider: its generic find method was private. Current a5cb makes only the actual provider find/keys/iterator next contract public and updates the existing release note. A real production checkpoint/Metal Buffer consumer now compiles with zig build-exe -fno-emit-bin (exit0); no mocks, linking, Xcode invocation, native/device execution or licence bypass. Current contribution preflight:0errors/0warnings/0newlean. All eight current-source automatic checks passed, including native macOS compilation; exact head frozen. This is not native model parity.
  • Metal: no fresh native Metal receipts. The M4/M5 receipts and speed tables below are historical.
  • Remaining gates (open, unwaived): Ash's native-Metal main-versus-branch photo-parity/speed comparison and the M5/native-Metal model/performance gate (the owned image avoids the photo-licence problem). Automatic CI is green, but not merge-ready: these device/parity/performance gates remain open.

Current rebase and remaining landing gate

Published head: 57b2b2ed0e3208907d7990e2bec3864cbf43de8b on upstream main 8be9c408c2825102b475dc6049c6aa3cf5d9e910, including merged #2565, following Ash's latest request. The retired #1514 dependency commits are not replayed.

metal_limits.zig retains main's gate(..., only) selection and its single selected-launch list. The existing non-tensor-unit skip now includes LFM3 NAX prompt and LFM3 tiled attention alongside qwen27 q8 ; the three new launchOf branches remain beside the restored LFM3 branches. The credited release note remains under Unreleased after 1.2.5.

Ash's main-versus-rebased comparison remains owed on this exact head before the landing queue. Scoped M4 operator/launch checks below passed using the existing explicit Metal 4.0 build option. They do not replace his M5/model/performance gate. The local default Metal 4.1 build is not qualified: this Mac's installed Apple compiler rejects that language version. All older M5 and performance receipts below retain their recorded source/binary identities; historical receipt links remain pinned rather than pointing at the moving branch.

What changes

Native Metal image preparation, vision encoder and projector for LFM3-VL-2B from the official MLX 4/6/8-bit checkpoints. Projected image rows feed the LFM3 decoder and the existing lane engine (image order and content handling, prompt caching, verification, snapshots, concurrent serving). Python is used only for development references and clients.

Refs #1491. Rebased directly onto upstream main 8be9c408c2825102b475dc6049c6aa3cf5d9e910 after #1514 and #2565 landed. Only the vision change and its release/qualification documentation are replayed; the retired text dependency is not retained. Main-to-branch compare. The threaded-reference and GLM work remains in #1776.

This PR retains the LFM3 prompt/decode work shared by VL and text. The tensor-unit routes remain opt-in: lfm3-nax-prompt, lfm3-tiled-attention and 2048-row chunks are off by default; a default build keeps the row kernels. The retained speed numbers below are historical measurements of explicitly opt-in builds at the source/binary identities recorded in each receipt, not measurements of this rebased head. No fresh main-versus-branch speed claim is made.

  • lfm3-nax-prompt: every dense prompt projection (attention q/k/v/out, convolution in/out, FFN gate/up/down) runs on the tensor units through tf_qmmw_t_nax_win, Flash Next's tf_qmmw_t_nax tile with scales and biases loaded eight groups at a time (same output bytes, about 4% faster). Weights stay packed (4/6/8-bit, group 32 or 64) and are dequantized to BF16 per 64-wide K step in threadgroup memory, as MLX does; peak memory (text, 8k tokens) is the packed weights plus a width-independent 0.68 GB.
  • lfm3-tiled-attention: prompt segments of 9–2048 rows are one tiled launch (64-query/32-key tiles, FP32 online softmax, probabilities rounded once to BF16 for PV, as MLX does). Decode windows, shared decode rows and prompt tails of at most 8 rows use a key-parallel split kernel (≤64 parts of ≥128 keys, FP32 merge). Both replay through the exact path when a row is nonfinite.
  • Stepped prefill (prefill_step): the backend fills a prompt one chunk at a time and returns to the lane engine between chunks (prefill_step(ptr, stream, max_rows): 0 is the engine's own cut), so the engine's shortest-remaining-first policy and decode-between-chunks apply to LFM3. Cuts do not change state (tf-lfm3-nax-exact), so the backend declares chunk_invariant and --decode-share may cap chunks at 512 rows. A request cancelled between chunks releases its fill.
  • Release-version builds reject the two options. -Dlfm3-nax-prompt=true -Dlfm3-tiled-attention=true selects them; the residual-weight FFN experiment is removed.

Historical opt-in performance against mlx-vlm

One M5 Ultra, same checkpoints and prompts, --prompt-cache-gib 0, medians of 2–3 runs after a warm-up, opt-in build as above. Receipts: cold prefill, serving metrics, decode share.

Cold prefill TTFT, native / mlx-vlm (below 1 is faster):

2k 8k 32k 64k
text 4-bit 0.93 1.04 1.01 1.00
text 6-bit 0.88 1.00 0.99 0.98
text 8-bit 0.92 1.04 1.01 1.00
VL 4-bit 0.90 1.05 1.02 1.00
VL 6-bit 0.86 1.00 0.99 0.98
VL 8-bit 0.88 1.04 1.01 1.00

Serving, text 4-bit, native vs mlx-vlm (default scheduling, no flags):

context native mlx-vlm
decode tok/s, 1 stream short / 2k / 8k 433 / 426 / 381 393 / 334 / 318
ITL ms mean, 1 stream short / 2k / 8k 2.31 / 2.31 / 2.58 2.55 / 2.94 / 3.08
decode tok/s, 4 streams aggregate short / 2k / 8k 1069 / 1062 / 938 1151 / 902 / 753
ITL ms mean, 4 streams short / 2k / 8k 3.92 / 6.19 / 10.79 3.47 / 4.19 / 4.65
ITL ms p95, 4 streams short / 2k / 8k 3.63 / 10.76 / 45.83 3.56 / 4.51 / 5.25
prefill tok/s, 1 stream 2k / 8k 20465 / 22602 21636 / 23405
prefill tok/s, 4 streams aggregate 2k / 8k 19695 / 21941 22834 / 23388
TTFT s, 4 streams per request 2k / 8k 0.257 / 1.054 0.358 / 1.400

Across the six checkpoints: single-stream decode is 1.10–1.14× mlx-vlm at short context, 1.26–1.28× at 2k and 1.17–1.20× at 8k. Four-stream aggregate decode is 1.11–1.18× at 2k and 1.10–1.25× at 8k, and 0.93–1.00× at short context. Four-stream TTFT per request is 0.70–0.73× at 2k and 0.74–0.77× at 8k.

Open against mlx-vlm:

  1. Prefill throughput: single-stream 2k and 8k are 0.95–1.00× and 0.95–0.99× of mlx-vlm's tok/s. With four concurrent prompts the aggregate is 0.84–0.88× at 2k and 0.92–0.96× at 8k, because mlx-vlm batches the prompts and this route fills them one chunk at a time.
  2. Four-stream ITL at 2k and 8k is higher than mlx-vlm's (mean 5.5–6.2 ms against 4.2–4.6 at 2k, 7.9–10.8 against 4.7–5.3 at 8k) and p95 is far higher at 8k (13–46 ms against 5.3–5.6) because finished streams decode between chunks of the others' prompts.
  3. --decode-share closes the ITL gap at a cost. With chunks capped at 512 rows while replies decode (receipt, text 4-bit, four requests, 2k / 8k):
TTFT s / request mean ITL ms p95 ITL ms aggregate decode tok/s aggregate prefill tok/s
native, default 0.257 / 1.055 6.2 / 10.8 10.8 / 45.8 1059 / 936 19686 / 21946
native, --decode-share 0.5 0.467 / 1.246 4.4 / 5.1 22.1 / 26.8 1538 / 1523 10244 / 16030
native, --decode-share 0.75 0.520 / 1.346 3.1 / 3.7 2.7 / 2.6 1302 / 1530 11611 / 16378
mlx-vlm 0.358 / 1.401 4.2 / 4.6 4.5 / 5.2 901 / 755 22829 / 23377

With the flag, mean and p95 ITL and aggregate decode beat mlx-vlm at both lengths; the price is aggregate prefill and 2k TTFT. serve_check --cancel --sampled with --decode-share 0.5 passes 40 checks per text width and 61 per VL width, so the cap changes no tokens.

Historical fidelity (policy of #1491)

Independent FP32 forward and official MLX BF16 as references. Receipt. No pass rule is applied here; the differences are listed.

  • 237 prompt-boundary rows over 9 sweeps: RMS to FP32 of the native route over official BF16, median 0.99, mean 1.04, 8.9% of rows above 1.5×.
  • Top-1 differences from FP32 in the canonical phases (every one listed in the receipt with margins): VL 6-bit prompt row 0 (FP32 margin 0.046; official BF16 misses it too), and VL 4-bit teacher-forced continuation row 3, which only the native route misses: two tokens tie at the BF16 maximum (margin 0.0) and the first index wins, while FP32 prefers the other by 0.110. The sweeps add the VL 6-bit prompt row at length 90 (same row, BF16 also misses).
  • Prompt rows and decode rows are reported separately in the receipt.

Historical kernel-contract receipts

New kernels are registered in zig/src/core/contract/registry.zig and lfm3_records.zig: tf_qmmw_t_nax_win probes for q4g64, q6g64, q8g64, q4g32 (nonfinite, repeat, shapes, sums; planted bad-bias and bad-nonfinite controls red) and the split attention (full and sliding; bad-tail and bad-nonfinite controls red). The 11 image-tower kernels each have a planted control (metal_lfm3_vision_controls.zig), and so do the 16 base text probes (metal_lfm3_controls.zig, in #1514). Local --only LFM3 on an M4 Pro: SUMMARY 74 kernels: 74 pass gates 1-4, 0 fail, 0 known findings; 52 controls: 52 red as planted, 0 missed. Full M5 Ultra run on the historical source recorded in the linked receipts (tf-kernel-contract --rotary-accuracy rotary.json): SUMMARY 468 kernels: 468 pass gates 1-4, 0 fail, 3 known findings; 420 controls: 420 red as planted, 0 missed; 0 limit problems. The three known findings are two affine_mm infinity classes and the Nemotron relu2 NaN; none is an LFM3 kernel. Receipt.

Checks on the current CI-correction head

Source 57b2b2ed0e3208907d7990e2bec3864cbf43de8b is a fast-forward test/documentation-only correction above the rebased eb9 head. Linux CI on eb9 passed six checks, including Windows and macOS dev-tools, but failed root pytest collection: three PR-added reference-test modules required optional NumPy at import time. This was our bug.

Following the existing repository convention, only an absent top-level numpy now raises unittest.SkipTest; other import failures propagate. All numerical assertions remain. Verification on this head:

python3 -m pytest --collect-only -q -p no:cacheprovider
python3 -m unittest discover -s tools/lfm3 -p 'test_*.py'

The root collection command exits zero with 416 tests collected without NumPy. In a separate NumPy-enabled environment, the actual unittest CLI runs 64 tests, all passing, zero skipped. Contributor preflight reports 0 errors, 0 warnings; lean 398 versus 398, zero new. The local full root pytest invocation was cancelled and is not claimed passed; the automatic Linux CI run remains the full-suite gate. No workflow, timeout, assertion or numerical tolerance changed.

Only three Python test modules and their reference guide changed. All native/Zig/shader inputs are unchanged from the exact eb9 binaries and M4 receipts below; those receipts retain their eb9 source identity and are not represented as rerun on this head. The current default Metal 4.1 toolchain limitation and Ash's main-versus-branch gate remain unwaived. Fresh automatic CI for this exact head finished: all seven checks passed, including Linux zig (its root pytest step now succeeds), Windows, macOS dev-tools, release paths, both benchmark-client jobs and formatting. The two scheduled host-nightly jobs were skipped, not passed. GitHub reports CLEAN / MERGEABLE. Ash's main-versus-branch hardware gate is still owed; CI green is not that gate.

Earlier eb9 native and M4 checks

Exact source eb9fa80fafdb20ccc153ad34ed481628a6fd0782, base 8be9c408c2825102b475dc6049c6aa3cf5d9e910. Apple M4 Pro / 48 GiB, macOS 27.2, Zig 0.17.0, Xcode 26.6 / Apple Metal compiler 32023.883:

zig build test-lfm3-host test-kernel-contract tf-kernel-contract tf-lfm3-vision tf-lfm3-exact tf-lfm3-nax-exact native -Dcpu=apple_m1 -Dmetal-std=metal4.0 -j2 --summary all
./zig-out/native/bin/tensorfold-native --version
./zig-out/native/bin/tensorfold-native --help
./zig-out/bin/tf-kernel-contract --only LFM3
./zig-out/bin/tf-kernel-contract --only lfm3 --no-gates

The explicit Metal 4.0 build passed 124/124 steps; 192 executed tests passed, with other host-test nodes cached. Actual native version (1.2.5) and help exited zero. The case-sensitive scopes are separate:

SUMMARY 74 kernels: 74 pass gates 1-4, 0 fail, 0 known findings; 52 controls: 52 red as planted, 0 missed; 0 limit problems; gates 71883 ms, limits 105 ms
SUMMARY 0 kernels: 0 pass gates 1-4, 0 fail, 0 known findings; 0 controls: 0 red as planted, 0 missed; 0 limit problems; gates 0 ms, limits 409 ms

Both diagnostics exited zero. The uppercase scope selected four launch-limit registrations; the lowercase limits-only scope selected 67. The second SUMMARY's zero kernels is intentional: it is limits-only, not numerical coverage. Tensor-unit-only launches and tiled probes are skipped on this M4. These filtered diagnostics are not a full global Metal contract, M5 qualification, real-weight receipt or performance claim.

Executed native SHA-256: 303e18f60fbee30a65149e5fff3138d3c0ce83b636bc3a8c5ddcbdd4d68b1a67; contract runner: e0497c2a5c71c6f90bca76e9c8633a93ddda21856fe4bf8a28153c592a925c3b.

Whole-Zig formatting passes. tools/pr_check.py --base 8be9c408c2825102b475dc6049c6aa3cf5d9e910 --pr 1502 reports 0 errors, 0 warnings; lean 398 versus 398, zero new. No defaults, checks, tolerances or workflows were changed.

Default-build limitation, not waived: the initial attempt at code-identical c7506ca0364c29c9df201e7df324ddcb39377e60 (the later change only moves the changelog note) hit invalid value 'metal4.1' in upstream's offline shaders. On macOS 27, upstream selects Metal 4.1; the installed compiler supports Metal 4.0. Apple's official component download still supplied 17F109 / compiler 32023.883. That attempt passed its host scopes (292 tests, three skipped) but failed the native/runner build. The explicit supported-language build above does not turn that default attempt green.

Post-rebase atc overlap --json remains incomplete (myPullRequestsLimit, pullFilesLimit), so its result alone is not clearance. An independent fully paginated snapshot covered 192 open PRs and all 180 foreign PR heads, comparing their complete Git trees against both main and this candidate. Eight foreign PRs have runtime-source conflict paths beyond main alone (#2529, #2373, #2062, #2045, #1437, #1436, #1435, #1434); every such path already conflicted on the previous public a39 head. No new runtime conflict path was introduced by this rebase. Existing runtime overlaps and release-note ordering still require normal landing coordination; this is not a zero-conflict or local-worktree-clearance claim, and no other PR/worktree was edited.

Automatic CI on this eb9 head finished: six checks passed (including Windows and macOS dev-tools); Linux zig failed at root pytest collection because three PR-added LFM3 reference-test modules imported optional NumPy unconditionally. This is an owned issue, not an inherited failure. The test-import correction is now published at 57b2b2ed0e3208907d7990e2bec3864cbf43de8b with the with/without-NumPy proof above; no workflow, timeout, assertion or numerical tolerance was changed. The c16 CI results below remain historical. Ash's main-versus-branch run remains owed.

Earlier c16 rebase checks

Exact source a39a0a2e26944fca15fa0a65b9c16d6edee012f9, based on main c16a296407deda1de8d1266c63cd141705643312:

zig build test-lfm3-host test-kernel-contract tf-kernel-contract tf-lfm3-vision tf-lfm3-exact tf-lfm3-nax-exact native -Dcpu=apple_m1 -j2 --summary all
./zig-out/native/bin/tensorfold-native --version
./zig-out/native/bin/tensorfold-native --help
./zig-out/bin/tf-kernel-contract --only LFM3

On Apple M4 Pro / 48 GiB: 119/119 build steps, 279 tests passed and three skipped; actual native version/help exited zero. Actual Metal summary: 74/74 kernels, 52/52 planted controls red, zero missed, zero limit problems. Tensor-unit tiled probes were explicitly skipped on M4; this does not qualify their M5 path or a real-weight/performance gate.

zig fmt --check build.zig zig passes. Current main's tools/pr_check.py --base c16a296407deda1de8d1266c63cd141705643312 --pr 1502 reports 0 errors, 0 warnings; 116 inherited lean findings, zero new. The credited #1502 note is under Unreleased; the historical 1.2.4 note is unchanged. Fresh automatic CI for a39a0a2e26944fca15fa0a65b9c16d6edee012f9: six checks passed (fmt, zig, macOS dev tools, release paths, and both benchmark-client jobs). Windows was cancelled after its one-hour limit during zig build test; golden/fuzz/security steps were skipped. That job checked out GitHub's merge 143c06c3467933023c8d769cfff49ba1c64ab597 (this head into ca33d5bb4baf8dafcab629f2b5154975f6e40c1c), not the bare head. No complete test summary identifies a failing test; the cause is unresolved and the gate is not waived. No timeout increase or manual rerun was made. The pinned base c16's own Windows job was manually cancelled by the maintainer, so it supplies no baseline Windows pass. The older a00 head's seven successful checks remain historical.

Licence: the official LFM3 exports remain license: other (lfm1.0), as the recipe states. No fresh real-weight result is claimed; no LFM3 checkpoint was reported in this Mac's native cache discovery.

Historical model receipts from #1491

Receipts: exactness, serving, image rows, 32k.

  • Seams and chunk boundaries (tf-lfm3-nax-exact): 43 byte-equality cases pass at all six widths on the historical source recorded in the linked receipts: prompts cut at 1 to 2047 rows and at five cut sets equal 2048-row chunks, resuming from a saved prefix equals a fresh run, and verification windows of 2 to 32 rows equal one-row decode. The check found one bug, fixed in this PR: windows of 9 or more rows ran the tiled prompt attention, so they differed from decode (9 of 43 cases failed). Windows now use the decode kernel.
  • Cancellation and concurrency: serve_check.py --cancel --sampled on the historical source recorded in the linked receipts passes 40 checks per text width and 61 per VL width with 0 failures (drafted/plain, concurrent 1/2/4 vs solo, cache reuse, image order and content, cancel then recover). With 31k-token prompts at --context 40000, a request cancelled mid-prefill leaves the server answering the next request in 42–54 ms with the same output as fresh, and a short request sent while three 31k prompts prefill is answered in 0.67–0.74 s (3.3–3.5 s before prefill was stepped) while the three prompts still finish in 4.7–4.9 s.
  • Real-image projected rows: five images (photograph, wide banners, square logo), 70 rows each. Pooled over the images, native RMS to the independent FP64 graph is 0.95× official MLX BF16 at 4-bit and 0.94× at 6 and 8 bits (8-bit shares 6-bit's tower). Native is better on 4 of 5 images at 4-bit and 3 of 5 at 6-bit; the worst image is 1.23× and 1.18×. The canonical input is real-image-fp64-input.png.
  • 32k tier: 32768-token prompt boundary plus 16 teacher-forced rows per checkpoint, six checkpoints, 102 rows. Pooled RMS to FP32 is 0.96× official BF16; 6 rows exceed 1.5×. Top-1 differences: VL 4-bit prompt row (native and official BF16 tie at the BF16 maximum and both miss FP32 by 0.085), and VL 6-bit continuation row 0, native only: tie at the BF16 maximum, FP32 prefers the other token by 0.134 while official BF16 prefers it by 0.125.

Dense GEMM: what was measured and not adopted

Isolated 4-bit prompt GEMM at M=2048 on the M5 Ultra, TFLOPs (the new windowed-scale kernel against the previous one and MLX's qmm4; the outputs of the first two are byte-identical on four shapes):

shape (N x K) tf_qmmw_t_nax_win previous tf_qmmw_t_nax MLX qmm4
7680 x 2048 86.8 83.2 82.0
2048 x 7680 78.8 74.2 81.2
2048 x 2048 83.7 78.5 72.4
6144 x 2048 85.7 82.0 79.2

In the model the dense layers run at the same efficiency as this bench (24 layers; no unexplained gap), and a ring of cold weights shows no loss, so weight-from-DRAM latency is not the limit. Tried and rejected, each measured against the same baseline: 64x128 and BM 128/192/256 tiles (no better, or register spills); the SWZ swizzle (neutral once scales are windowed); a 128-deep K step (+4% on wide shapes, -7% on square ones); register prefetch of four weight steps (-2 to -7%); threadgroup staging of weights (-2 to -14%); a fused gate+up+SwiGLU GEMM (13% slower than two GEMMs); fusing SwiGLU and the paired q/gate projection into the decode dispatches (+1.1 to +1.6% on one stream, -1.6 to -2.0% on four; receipt).

Open

The prefill and four-stream ITL gaps against mlx-vlm described above. Fusing the FFN SwiGLU and the attention query/gate projections into one dispatch each (26 fewer of about 250 dispatches per decoded token) gained 1–2% on one stream and lost 2% on four; not adopted (receipt). The pass rule for making the tensor-unit route the default is on #1491.

Terminal current-source CI ata5cb6b673e582a9ce0f85ed0c24bda3c0e867898:all8automatic checks passed,2scheduled-only skips,0failures. Native macOSdev-tools10m42s,Linux34m13s,Windows18m23s,pytest8m11s,release-paths2m47s,both benchmark clients andfmt passed. Provider fix verified by actual CI; exact head frozen. No manual rerun or source change. Device/photo/synthetic parity and performance gates remain open; historical results retain their original pins.

@ashhart

ashhart commented Oct 27, 2026

Copy link
Copy Markdown
Owner

Thanks @BlivionIaG for a careful port and an honest receipt. The same-engine checks are thorough (231 served, with cancellation and recovery), and the rotary fix comes with a test that fails on the old formula.

The merge with main is clean. Here is our answer on the gates.

Fidelity:

  • Compare teacher-forced against an FP64 forward of the dequantized checkpoint. MLX is a second opinion, not the reference.
  • Compare prompt rows and one-row decode rows separately, on identical input rows, at 4, 6 and 8 bits.
  • List every top-1 difference with both tokens and both margins, and report the worst rows, not only an average.
  • A difference passes only as a near-tie that a reference rounding where the engine rounds reproduces, as lfm3: serve LFM3-1.7B on CUDA: NVFP4 and FP8 weight-only, MLX 4-bit (stacked on #1513, #1492 and #1503) #1508 does for the CUDA side. The 18 rows with disjoint top sets need tracing first.
  • For VL: the projected rows of real images against FP64, then teacher-forced text after them.

Performance, on the same Mac and checkpoint against mlx-lm (mlx-vlm for VL), at each width:

  • one-stream decode and the 4-stream aggregate, with outputs of equal length;
  • cold prefill at 2k, 8k, 32k and 64k. Decode should be at least the standard server's. Cold prefill should take the prompt tiles, as below; a remaining prefill gap is fine to track as its own issue, as we do for the 27B.

Before this leaves draft:

  1. Prompt rows go through the row kernels and the decode attention (zig/src/families/lfm3/forward.zig:39-49, :196-216). That is why cold prefill is 7 to 18 times slower than mlx-lm's. LFM2's Metal family takes tile_qmm's prompt tiles with a decode twin of the same bits (zig/src/families/lfm2_moe/forward.zig:30), and the tensor-unit prompt attention on an M5 (:244). Please build on those, and on LFM2: shared-round decode #1377's shared rounds for the 4-stream aggregate.
  2. Please split the PR: the admission and the text decoder first, with VL stacked on them. lfm3: serve LFM3-1.7B on CUDA: NVFP4 and FP8 weight-only, MLX 4-bit (stacked on #1513, #1492 and #1503) #1508 already builds on the admission.
  3. Please state the weights' licence, and the Macs it was checked on, in the recipe.

Once the gates hold, we'll run the full Metal contract and the served checks on our M5 Ultra.

@jschmied

Copy link
Copy Markdown
Contributor

@BlivionIaG, one small pixel-parity note on families/lfm3/image.zig's patchify, from the LFM3-VL processor work on CUDA.

transformers' Lfm3VlImageProcessor (5.19, torchvision backend) folds the rescale into the normalization. It computes (x - mean / rescale) / (std / rescale) in float32, which for LFM3 is (x - 127.5) / 127.5. The lookup table here computes x * f32(1/255) first and then (v - 0.5) / 0.5. The two disagree on 207 of the 256 entries, by at most 1.2e-7 (one ulp near ±1). So the patches can't be bit-equal to the processor's pixel_values.

The resize (.torch) and the geometry already match. Fixing it is one line in the table:

value.* = (@as(f32, @floatFromInt(i)) - 127.5) / 127.5;

With that, the processor's output should be reproduced bit for bit.

@cwschroeder

Copy link
Copy Markdown
Contributor

The Linux CI failure at 484a96f68c26befe7ae0a8755ce2a680b9afda27 is in test_every_declared_option_is_accepted. It passes -Dlfm3-prompt-rows=value, but build.zig:83 declares that option as u32 and accepts only 128, 256 or 2048. tools/zig/build_options_test.py has no entry for it in VALUES, so it falls back to the string placeholder.

Adding "lfm3-prompt-rows": "128" to that test mapping should address this argument mismatch; the full test still needs rerunning. This is from the source and CI log, not a local reproduction.

jschmied added a commit to jschmied/TensorFold that referenced this pull request Oct 31, 2026
's image tests from a build file of ours

C11 put test-lfm3-image-host and a sys import into zig/build/lfm3_host.zig, a file ashhart#1502 edits too.
That file is back to its version below C11, so ashhart#1502's own edit of it applies. zig/build/lfm3_xpu_host.zig
declares the step instead, and only while no lfm3_host.zig declares it; build/sys.zig's walk gives the
test root its sys import, so none is named here.
jschmied added a commit to jschmied/TensorFold that referenced this pull request Oct 31, 2026
…s within 1.7e-3 of float64

Every activation of the tower and the projector stays fp32 (weights bf16 as stored, sums fp32 as
before); only the image rows go to the decoder in bf16, as ashhart#1502's rows buffer holds them. Each
kernel keeps a rounding flag for transformers' bf16 points (vision.Round, Tower.round; 0 by
default): with every bit set the forward is C11's bit for bit.

The ablation on ashhart#1502's 14 x 20 fixture against vision_fp64_reference.py in plain float64: no one
rounding point carries the gap (any one alone in fp32 leaves the rows at 2.7e-2 to 7.0e-2); taken
together they do: the linear outputs, the conv's inner points and the attention path to 7.5e-3,
the projector's three points to 3.3e-3, the pixels to 1.65e-3 (layer 13 at 4.3e-6).

- fixture: image rows rel 1.65e-3, cos 0.999999 (C11: 4.21e-2, 0.99912); transposed grid 0.82;
- the 3000 x 4000 form photo at 1,024 tokens: rel 1.66e-3, cos 0.999999; transposed 1.09.
tf-xpu-lfm3_vit-test now runs the kernels with fp32 in and out, within 1e-5 of float64 (at most
1.6e-6), and its controls still fail, GELU's tanh form among them. tf-xpu-lfm3_tower-test dumps
fp32 and the first layers' stages by ashhart#1502's trace names; LFM3_VIT_ROUND sets the rounding points.
jschmied added a commit to jschmied/TensorFold that referenced this pull request Oct 31, 2026
…ed row for ashhart#1502's compare_logits.py

tf-xpu-lfm3_vl_logits-test runs ashhart#1502's real-image fixture (90 tokens, 70 image rows at 4, the
suffix "Describe this image." -> "The image contains a cat.") through the tower and the decoder in
windows of 16 rows, and writes each row's logits as bf16, the projected rows and the patches.

On a stand-in for ashhart#1502's cat (placecats.com/300/200 serves another JPEG now: 14 x 20 patches, 70
rows), against ashhart#1502's fp64_reference.py, compare_logits.py and vision_fp64_reference.py, unchanged:
- the XPU's own rows into float64 (decoder alone): rel 1.72e-2 over 90 rows (ashhart#1502: 1.30e-2),
  3 top-1 differences, 1 disjoint top set, all at image positions; the suffix: rel 1.17e-2, none;
- float64's own vision (whole pipeline): rel 3.74e-2, 3 disjoint top sets over 90 rows (ashhart#1502: 7),
  all at image positions; the suffix: rel 1.30e-2, no top-1 difference (ashhart#1502: 2 disjoint).
@cwschroeder

Copy link
Copy Markdown
Contributor

@BlivionIaG, the macOS dev-tools job on 493311113f86169ddf9f167260e4e39e8ae3de67 now fails compiling tf-lfm3-deferred-head: zig/src/families/lfm3/backend.zig:104 assigns prefillStepFn with two parameters to a callback requiring three (*anyopaque, *stream.Stream, u32). The stepped-prefill callback needs to match that interface, then the dev-tools build needs rerunning.

This is from the CI compiler log, without a local build. The other failed jobs still report sources.zig:232's trailing blank line and the new over-600-line finding in zig/tests/contract/metal_main.zig.

@ashhart

ashhart commented Nov 1, 2026

Copy link
Copy Markdown
Owner

Thanks @BlivionIaG. The new description is what we asked for, and stepped prefill is a real gain: a short request
answered in under 0.8 s while three 31k prompts fill, with tf-lfm3-nax-exact covering the cut points. Thanks also
for taking @cwschroeder's build-options fix. Three things:

  1. The macOS dev-tools build still fails as @cwschroeder found: prefillStepFn in families/lfm3/backend.zig
    takes (ptr, stream), and main's prefill_step callback also passes max_rows. zig/kernels/metal/sources.zig
    also still ends with a blank line.
  2. One default for source builds and releases. build.zig turns the NAX prompt, the tiled attention and
    2,048-row chunks on in unversioned builds and refuses them in releases. Then a source build and a release serve
    the same checkpoint with different arithmetic (the tiled attention rounds probabilities to bf16). Could all three
    default off everywhere for now? Once the tiled route meets the Add native Metal support for LFM3-1.7B and LFM3-VL-2B MLX 4/6/8-bit checkpoints #1491 bar, it can become the default for releases
    too, in its own change.
  3. Planted controls for the vision kernels in metal_lfm3_vision.zig (all 11 kinds), as for the base text
    kernels in lfm3: serve the MLX text decoder on Metal #1514.

On fidelity, we'll judge the two rows only the native route misses (VL 4-bit row 3, and VL 6-bit at 32K) against
the bar on #1491. This lands after #1514, squashed, and then we'll run the VL cells on our M5 Ultra and M3 Ultra.

@jschmied

jschmied commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

@BlivionIaG, a small request for a like-for-like check. I'm porting LFM3-VL's vision path to Intel's XPU backend, taking image.zig and your receipts' tools unchanged (fp64_reference.py, vision_fp64_reference.py, compare_logits.py at 484a96f68).

Could you attach the canonical PNG from docs/receipts/lfm3/real-image-fp64.json (sha256 005500792ee8…, the sips conversion of the placecats JPEG) to this thread? placecats.com/300/200 now serves a different picture (12cd0df3…, not d1b324f5…), so the image-context logits can't be rerun on your input. With the PNG, run (a), same projected rows into float64, and run (b), float64's own vision, become directly comparable to your 1.30e-2 and 2.22e-2.

No change to #1502 is needed for this.

@BlivionIaG

BlivionIaG commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @ashhart. The three options are off in every build in this PR (pushing now), and the speed numbers will be labelled as the opt-in build. For your call on the two rows, here is what the receipts say about the tiled route against the two references on #1491 (independent FP32 forward, official MLX BF16). No pass rule is applied; every difference is listed in the receipts.

RMS to FP32, native route over official BF16 (below 1 is closer to FP32):

  • 237 prompt-boundary rows over 9 sweeps: median 0.99, mean 1.04, 8.9% of rows above 1.5x (route fidelity).
  • Real-image projected rows, five images, pooled: 0.95x at 4-bit, 0.94x at 6 and 8 bits. Native is closer on 4 of 5 images at 4-bit and 3 of 5 at 6-bit; the worst image is 1.23x and 1.18x (image rows).
  • 32k tier, six checkpoints, 102 rows: 0.96x pooled, 6 rows above 1.5x (32k).

The two rows only the native route misses:

  • VL 4-bit teacher-forced continuation row 3: two tokens tie at the BF16 maximum (margin 0.0) and the first index wins; FP32 prefers the other token by 0.110.
  • VL 6-bit at 32K, continuation row 0: the same kind of tie at the BF16 maximum; FP32 prefers the other token by 0.134 while official BF16 prefers the FP32 token by 0.125.

A tie at the BF16 maximum is decided by index, not by the arithmetic. The receipts also list the rows both routes miss, for example the VL 4-bit 32K prompt row where native and official BF16 tie and both miss FP32 by 0.085.

@BlivionIaG

Copy link
Copy Markdown
Contributor Author

@jschmied here is the canonical PNG, committed at docs/receipts/lfm3/real-image-fp64-input.png: 300x200 RGB, sha256 005500792ee8ea6f35ac369d900fc788cd77667f145e7100c2cff57fae5355d9, the value real-image-fp64.json records as canonical_png_sha256. It is the sips conversion of the placecats JPEG that the receipt's native and float64 runs read, so (a) and (b) can be rerun on the same input.

jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 1, 2026
…hes file

An optional fifth argument, fp32 [patches][1536] for the picture's grid, replaces the decoded pixels:
a receipt's own patches go through the tower and the decoder unchanged, e.g. ashhart#1502's real-image fixture
made with the pixel normalization before 50b4e0d (patches sha f1c55a0dd28b as its .npy).
@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Thanks @ashhart. All three are done on this head.

  1. macOS dev-tools. prefillStepFn now takes (ptr, stream, max_rows): 0 means the engine's own cut, otherwise the chunk is at most max_rows. The backend declares chunk_invariant (cut-invariance is what tf-lfm3-nax-exact proves), and the lane host receives --decode-share. sources.zig no longer ends with a blank line, and metal_main.zig is 458 lines (the LFM3 probes register through metal_lfm3_suite.zig). zig build test test-golden dev-tools test-lfm3-host passes locally.
  2. One default. lfm3-nax-prompt, lfm3-tiled-attention and 2048-row chunks default off in every build. The recipe now calls them opt-in, and the PR body labels the speed numbers as the opt-in build (-Dlfm3-nax-prompt=true -Dlfm3-tiled-attention=true).
  3. Planted controls for the vision kernels. All 11 kinds in metal_lfm3_vision.zig have one (metal_lfm3_vision_controls.zig), each red at its named gate with the real probe still passing: --only "LFM3 vision" reports 11 kernels pass gates 1-4 and 11 controls red as planted, 0 missed.

With chunks capped at 512 rows the server's tokens are unchanged (serve_check --cancel --sampled with --decode-share 0.5: 40/40 per text width and 61/61 per VL width). Four concurrent text 4-bit requests, native with and without the flag against mlx-vlm (receipt):

TTFT s / request, 2k / 8k mean ITL ms, 2k / 8k p95 ITL ms, 2k / 8k aggregate decode tok/s, 2k / 8k
native, default 0.257 / 1.055 6.2 / 10.8 10.8 / 45.8 1059 / 936
native, --decode-share 0.75 0.520 / 1.346 3.1 / 3.7 2.7 / 2.6 1302 / 1530
mlx-vlm 0.358 / 1.401 4.2 / 4.6 4.5 / 5.2 901 / 755

The flag trades prompt throughput for inter-token latency (aggregate prefill 11.6k and 16.4k tok/s at 2k and 8k, against 22.8k and 23.4k for mlx-vlm). Without it, stepped prefill leaves p95 ITL at 45.8 ms at 8k, which is the cost of finishing prompts first.

@jschmied

jschmied commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Thanks @BlivionIaG, the PNG was exactly what was needed. Here is the rerun of real-image-fp64.json on the Intel XPU port (Iris Xe). The decoder is unchanged, the vision tower and projector keep fp32 between kernels, and only the final rows are rounded to bf16. Your three tools ran unchanged at 484a96f68.

The receipt's patches_sha256 (f1c55a0dd28b…) comes from the normalization before 50b4e0d. So I fed those exact patches to both sides, and the prompt's token ids equal 54c970db8c6b…:

XPU this PR
(a) same projected rows, all 90 rows, rel 1.33e-2 1.30e-2
(b) float64's own vision, all 90 rows rel 2.09e-2, 1 disjoint 2.22e-2, 7 disjoint
(b), the 16-token suffix 0 disjoint 2 disjoint

There is no top-1 difference at a text row in either run. They are all at image positions. With the current, corrected patches (9d39c11551f1…, your corrected-pixel-vision.json input), (a) is 1.49e-2 and (b) is 2.01e-2, again with 0 disjoint in the suffix.

So real-image-fp64.json predates the pixel fix. That changes nothing here, but a regenerated receipt would let the next port compare against today's patches directly. Your call; no change to #1502 is needed for ours.

@BlivionIaG
BlivionIaG marked this pull request as ready for review November 1, 2026 11:05
jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 1, 2026
zig/src/families/lfm3/image.zig and its test root zig/src/lfm3_image_tests.zig byte-identical to
ashhart#1502 at f066644, so they drop out when ashhart#1502 lands.
jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 1, 2026
…ild file of ours

zig/build/lfm3_xpu_host.zig declares the step only while no other build file has, so ashhart#1502's own
lfm3_host.zig step takes over when it lands; build/sys.zig's walk gives the test root its sys import.
jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 1, 2026
…ainst ashhart#1502's float64 reference

xpu_vision.zig loads the 138 bf16 tensors by ashhart#1502's names and shapes and runs one picture's
merge-order patches to its gh * gw / 4 image rows: patchifier and embedding norm, the 14 layers
(gated depthwise conv or GQA attention with QK norm and axial RoPE, each with the SwiGLU FFN), then
the projector (LayerNorm a patch, 2 x 2 blocks as 4096-wide rows, linear_1, GELU, linear_2).
zig/src/lfm3_image.zig roots ashhart#1502's image.zig where its relative imports reach.

tf-xpu-lfm3_tower-test writes the patches, every layer's rows and the image rows, and the same
patches with the grid passed transposed. tools/lfm3/vision_check.py runs ashhart#1502's numpy reference
(vision_fp64_reference.py, unchanged) with its bf16 points and in plain float64:
- 14 x 20 synthetic picture: image rows rel 4.21e-2, cos 0.99912 against float64 (the reference's
  bf16 points: rel 6.55e-2); the transposed grid: rel 0.82, cos 0.67;
- a 3000 x 4000 photo of a form at 1,024 image tokens (72 x 54 patches): rel 2.84e-2, cos 0.99960
  (bf16 points: rel 3.13e-2); transposed: rel 1.09, cos 0.41.
The tower takes 164 ms on the synthetic picture and 2.97 s on the photo on Iris Xe.
jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 1, 2026
…ed in place of the image tokens

xpu-native reads lfm3_vl checkpoints with the LFM3 family (vl_model_type) and offers image input as
request unless --vision-image-tokens names 64 to 4096; LFM3-1.7B still refuses --vision. The engine
loads the tower with scratch for that budget. Before a stream's prompt windows, the adapter hands its
pictures to the engine (pictures, when the engine has it): the tower writes their rows, and each
prompt window copies the rows over the embeddings of the image tokens it holds. Decode, copy drafts,
streams and the prompt cache are unchanged; a kept state after a picture is keyed by the lane host's
image hash.

The server's core module owns core/picture, so ashhart#1502's image.zig, which reaches it by relative path,
is compiled from a copy the build writes with those two imports read as core's; the file itself stays
byte-identical to ashhart#1502's.

tf-xpu-lfm3_vl-test runs one picture without the server (tower, projector, text prefill, decode).
Through the server on Iris Xe, greedy: a vaccination record photo, a receipt and an A4 page give the
same replies twice (the second from the prompt cache) and with --parallel 2 all at once; a receipt
after another picture with the same text equals it on a cold server. LFM3-1.7B's gates do not move:
B2's tokens, --parallel 1/2/4 against the pinned solo replies, the cache resume.
jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 1, 2026
…s within 1.7e-3 of float64

Every activation of the tower and the projector stays fp32 (weights bf16 as stored, sums fp32 as
before); only the image rows go to the decoder in bf16, as ashhart#1502's rows buffer holds them. Each
kernel keeps a rounding flag for transformers' bf16 points (vision.Round, Tower.round; 0 by
default): with every bit set the forward is C11's bit for bit.

The ablation on ashhart#1502's 14 x 20 fixture against vision_fp64_reference.py in plain float64: no one
rounding point carries the gap (any one alone in fp32 leaves the rows at 2.7e-2 to 7.0e-2); taken
together they do: the linear outputs, the conv's inner points and the attention path to 7.5e-3,
the projector's three points to 3.3e-3, the pixels to 1.65e-3 (layer 13 at 4.3e-6).

- fixture: image rows rel 1.65e-3, cos 0.999999 (C11: 4.21e-2, 0.99912); transposed grid 0.82;
- the 3000 x 4000 form photo at 1,024 tokens: rel 1.66e-3, cos 0.999999; transposed 1.09.
tf-xpu-lfm3_vit-test now runs the kernels with fp32 in and out, within 1e-5 of float64 (at most
1.6e-6), and its controls still fail, GELU's tanh form among them. tf-xpu-lfm3_tower-test dumps
fp32 and the first layers' stages by ashhart#1502's trace names; LFM3_VIT_ROUND sets the rounding points.
jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 1, 2026
…ed row for ashhart#1502's compare_logits.py

tf-xpu-lfm3_vl_logits-test runs ashhart#1502's real-image fixture (90 tokens, 70 image rows at 4, the
suffix "Describe this image." -> "The image contains a cat.") through the tower and the decoder in
windows of 16 rows, and writes each row's logits as bf16, the projected rows and the patches.

On a stand-in for ashhart#1502's cat (placecats.com/300/200 serves another JPEG now: 14 x 20 patches, 70
rows), against ashhart#1502's fp64_reference.py, compare_logits.py and vision_fp64_reference.py, unchanged:
- the XPU's own rows into float64 (decoder alone): rel 1.72e-2 over 90 rows (ashhart#1502: 1.30e-2),
  3 top-1 differences, 1 disjoint top set, all at image positions; the suffix: rel 1.17e-2, none;
- float64's own vision (whole pipeline): rel 3.74e-2, 3 disjoint top sets over 90 rows (ashhart#1502: 7),
  all at image positions; the suffix: rel 1.30e-2, no top-1 difference (ashhart#1502: 2 disjoint).
jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 1, 2026
…hes file

An optional fifth argument, fp32 [patches][1536] for the picture's grid, replaces the decoded pixels:
a receipt's own patches go through the tower and the decoder unchanged, e.g. ashhart#1502's real-image fixture
made with the pixel normalization before 50b4e0d (patches sha f1c55a0dd28b as its .npy).
@BlivionIaG

BlivionIaG commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @AIFlowML. tools/lfm3/serve_check.py now appends --vision to both server launches when the checkpoint is lfm3_vl, and the image requests are only sent when it does (and --skip-images is not given). Head e040a1658a, a merge of main at b192eaa298. Checks: test-lfm3-host and test-lfm3-image-host and the other named steps pass (80 of 85, 5 skipped); zig build native -Dcpu=apple_m1 links; CI is green.

Not run: the served serve_check.py recipe itself. It needs a VL checkpoint, which I did not have on a machine; the tower on/off token receipts from the description therefore still stand as they were.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Hi @BlivionIaG, thank you for the care you have put into the vision-only scope and for the quick turns on the residency and launch-record checks. Two small things are still open on this head.

First, a few receipts from withdrawn development routes are still in the tree, including the provisional tiled prompt, deferred-head observation and private tiled producer entries, along with the matching joint-gate and private-gate siblings. The receipts README already says the tensor-unit prompt, tiled attention and deferred-head work is not part of this PR, so these read as leftovers from that earlier scope. Please remove them; no source change is needed.

Second, the image tower is currently re-run for every prefill chunk. The chunk path calls the image provider on each chunk, and the provider projects the whole image before the row splice, so one image is projected once for every chunk it overlaps: about 32 times for a 4,096-token image at 128 rows, and more with one-row warm chunks. Current main instead prepares those projected rows once per pass. Please keep the projected rows prepared once per pass, or cached per distinct uncached image, including when a kept prefix ends inside an image, and add a small test that counts tower calls: one execution per distinct uncached image across ordinary, host-narrowed and warm chunks.

That is all we need from you. The rebase and the main-against-branch device run are on our side.

  • Synthena

Drop the provisional tiled-prompt, deferred-head, private/joint gate and
residual-FFN/SwiGLU experiment receipts; none of those routes is in this
branch, and the README already excludes them.
The chunk path ran the tower for every chunk an image overlapped. Open
the pass's images once, in the backend's fill, and let each chunk splice
the spans it reads: ordinary, host-narrowed and warm chunks run the tower
once per distinct image, and a kept prefix inside an image re-projects
only that image. A duplicate image reuses the first projection's rows.
releaseFn dropped a mid-pass fill without ending its image pass, and
shutdown dropped any remaining fill; both now close the pass so the
provider frees its rows and spans.
Remove the composed-attention held-input receipt and the development
contract tail that listed the removed residual FFN kernel, and the
retired Qgate note; none of those routes is in this branch.
@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @BlivionIaG. Both points are fixed on bbb678d5de:

  • Receipts: the withdrawn prompt and attention routes' receipts are gone, along with their gate siblings, and no source changed with them.
  • Tower calls: the pass's images are projected once, when the pass opens, and every chunk splices from those rows. A kept prefix that ends inside an image projects that image again, and a repeated image reuses the first one's rows. The new test counts tower calls under ordinary, one-row and resumed cuts.
  • Cleanup: a stream that leaves mid-pass, and shutdown, now end the pass, so its rows and spans are freed.

That's everything from our last note.

  • Synthena

# Conflicts:
#	CHANGELOG.md
#	zig/src/native/lfm3.zig
The pass lifecycle moves to image_fill: begin projects the distinct images
once, chunk splices what the pass opened, close frees them. The host test
drives the real step loop through ordinary 128-row, host-narrowed one-row
and warm chunks, a repeat image and a release mid-pass, and counts the
tower calls; it fails if a chunk projects again.
@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Thanks @ashhart. Both points are addressed at head 22a8b66156.

Receipts. Removed the last two from the withdrawn routes, docs/receipts/lfm3/m5-composed-attention-held-input.json and m5-full-contract-tail.json (it listed the removed residual-FFN kernel), plus the retired Qgate note in final-fourbit-artifact.json. With the earlier removals in 54c78cd243 that clears the leftover set; nothing references them and no source changed.

Tower once per pass. A pass opens its images once in image_fill.Fill.begin, every chunk reads fill.chunk(at, end), and close ends them; Run.run splices what the pass opened. A kept prefix ending inside an image re-projects only that image, and a repeated image (same bytes and grid) reuses the first one's rows. The new host test drives the real steps.step loop for 128-row chunks, host-narrowed one-row chunks, a warm pass starting inside an image, a repeated image and a release mid-pass, and counts begin, end and tower calls. Red proof: putting per-chunk projection back in Fill.chunk fails the 128-row case (expected 1 begin, found 5) and the narrow case (expected 1, found 41).

Merge. Merged upstream/main at ea37382cb1 as cdeaa761f4 (no rebase, as you said). Conflicts in CHANGELOG.md and zig/src/native/lfm3.zig kept main's warm-turn lines beside the --vision hookup. GitHub reports it mergeable.

Checks. The four test-lfm3-* host steps pass, zig build native -Dcpu=apple_m1 links, and tools/pr_check.py --base ea37382cb1 --pr 1502 reports 0 errors and 0 warnings, lean 165 vs 165, 0 new.

Served recipe (AIFlowML's open point). tools/lfm3/serve_check.py --sampled --cancel on an M5 Ultra with LFM3-VL-2B MLX 4-bit c823fade98e35a3d6942ad4d38b1ea15f675cd12 and this head's binary: 64 passed, 0 failed, 0 skipped, with --vision on both launches.

CI on 22a8b66156 is queued behind the runner backlog; I'll report the job results when it runs. The main-against-branch device run stays yours.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

A correction from our side, @BlivionIaG: earlier we said we would run the device check for this PR, but we do not hold an LFM3-VL checkpoint, so we cannot. The remaining evidence, generated token IDs for image requests on this head equal to the serial reference (one stream and several, with a resumed prefix), will need to come from your side. Sorry for the mix-up.

  • Synthena

@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Token-id receipt for the image path on 22a8b6615605b7c320fa23444a7b64abfa8a6397, LFM3-VL-2B MLX 4-bit
c823fade98e35a3d6942ad4d38b1ea15f675cd12, native Metal on an M4 Pro (48 GiB, macOS 27.2), Zig 0.17.0,
return_token_ids on, 24 tokens per reply, greedy and seeded (seed 1234, temp 0.7, top_k 20, top_p 0.95).

Serial reference: --parallel 1, one request at a time, --prompt-cache-gib 0. Compared token ids
(61 comparisons, 61 passed, 0 failed):

  • 9 request kinds: text, 256x256 red, blue, red+blue, blue+red, red+red, 1024x1024 image (1024 image
    tokens over eight 128-row prefill chunks), seeded text, seeded image.
  • 4 concurrent streams, cold and warm cache, three 4-way batches: mixed text+image, different images,
    and the same PNG four times at once.
  • A/B/B/A: serial, 4-way cold, 4-way warm, serial; all equal.
  • Resumed prefix: a second turn whose kept 1024-token prefix ends inside the 1024-token image equals the
    same turn with the cache cold (cached_tokens 1024 of 1079); warm and cold prompt cache agree.
  • A cancelled stream followed by the same request (256x256 image and the multi-chunk image) equals its
    serial reply.
  • Previous head cdeaa761f4, same requests: 61/61 passed and all 61 reply signatures identical.

Binary sha256 aaa4337a...f01920; no commit was added for this run. Driver: vision_tokens.py
(starts each server, sets return_token_ids, compares ids); can be added to the PR if wanted.
This is token equality on this head, not an independent FP32 fidelity or speed claim.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @BlivionIaG. The pass now projects each pending image once, reuses those rows across chunks and frees them when the pass ends. The cleanup, receipt removals and new 61/61 image-token comparison close our last requests.

One small recipe correction remains: the LFM3-VL launch example omits --vision, while the next paragraph tells readers to send images. Please add the flag and make the opt-in clear; that launch currently serves text only. The newer serving harness already handles the flag correctly.

The reported image equality is credited at its stated scope. Current integrated performance and the separately documented numerical qualification remain open; we have no VL checkpoint for a maintainer run.

  • Synthena

@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Thanks. Fixed in bb92054094: the LFM3-VL launch example in docs/recipes/lfm3-native.md now passes --vision, and the next paragraph says the VL checkpoint loads its image tower only with --vision and that without it the server is text-only (this matches native/lfm3.zig, which opens the tower only when --vision is given, and the CHANGELOG line). Docs only: pr_check.py --base ea37382cb1 --pr 1502 reports 0 errors and 0 warnings, lean 165 vs 165 (0 new).

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thanks, @BlivionIaG. The recipe now enables vision explicitly, closing that request. The earlier projection, cleanup and image-token results remain credited; this documentation change needs no repeat run.

There is one current-main integration issue on our side: its newer text-only loader removes the tower and projector tensors before the vision opener reads them. Combined as-is, --vision reaches MissingTensor. We need a vision-aware load choice that preserves the lean text-only path and retains the validated image tensors when requested. The integrated numerical and performance gates remain open.

  • Synthena

@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Merged upstream/main 4c79cfe346 (a one-sentence conflict in docs/api.md; main's text is kept and 'LFM3 Metal' re-added). Head cc65d60d0a; fmt, lean (165 vs 165, 0 new) and pr_check 0/0 clean; on an M4 Pro test-lfm3-host, test-lfm3-image-host, test-lfm3-vision-residency-host, test-lfm3-prefill-host and native pass, and tf-kernel-contract --only LFM3 has 72 kernels passing and 51 controls red as planted, 0 missed. Your integration point (the text-only loader dropping the tower and projector tensors before the vision opener reads them, so --vision reaches MissingTensor) is noted; I will look at a vision-aware load choice on top of current main and post it separately.

…s on disk

Since ashhart#3420 a VL checkpoint packs only its language model, so the vision opener stopped at MissingTensor.
Model.loadWithResidency takes the --vision choice: with it each shard loads whole, as before ashhart#3420; without it
the shard packs the same two text namespaces as main. The host test reads an official VL header through the
choice: the tower layout loads with --vision and is MissingTensor without it, the text set unchanged.
@AIFlowML

Copy link
Copy Markdown
Contributor

I verified the loader integration at 2b087ef1d1 on current main 4beda42498. The trial merge had only a changelog conflict, which I resolved locally by retaining both entries.

zig build test-lfm3-host test-lfm3-image-host test-lfm3-vision-residency-host test-lfm3-prefill-host native -Dfixed-cpu -j2 --summary all
python3 tools/lfm3/serve_check.py --binary ./zig-out/native/bin/tensorfold-native \
  --model-dir MODEL_DIR --sampled --cancel --output served.json

On M5 Max with LiquidAI/LFM3-VL-2B-MLX-4bit pinned at c823fade98e35a3d6942ad4d38b1ea15f675cd12, the native build succeeded and the build's tests reported 94 passes and five skips. The served suite passed 64/64, including concurrent images, corrupt PNG refusal and cancellation/recovery. As an explicit flag check, two inline 256×256 PNGs gave HTTP 200 with the correct color names (Red, Blue) with --vision, and both gave HTTP 400 with it omitted. The text-only prompt returned 4 in both modes, and both smoke-test servers drained cleanly.

This verifies the current integration and flag behavior for the 4-bit checkpoint. It leaves served performance and 6-/8-bit checkpoint validation open.

Igor Lessio - AIFLOW LABS

@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Thanks. Fixed at 2b087ef1d1: main d2b43908db merged (only CHANGELOG.md conflicted), then one separate commit. Model.loadWithResidency now takes the --vision choice (lfm3/weights.zig packs). With --vision each shard loads whole, as before #3420; without it a VL shard packs the same language_model./model. namespaces as main, so the text-only load is unchanged.

  • Host test (test-lfm3-host): an official VL header (594 text and 138 tower tensors, bare and wrapped namespaces) read through the choice. With the old choice --vision stops at MissingTensor (vision_tower.patchifier.weight); now the tower loads. Without --vision the set is main's 594 text tensors.
  • M4 Pro, LFM3-VL-2B MLX 4-bit c823fade: the merged head before the fix exits with MissingTensor under --vision; at 2b087ef1d1 the image request returns. Text-only, before vs after: 1489-1490 vs 1488-1490 MB, ready in 2.6-3.5 s vs 2.7 s, same reply. --vision adds the tower (1890 MB). Main itself cannot open a VL checkpoint natively, so the pre-fix head (main's loader) stands in for it.
  • test-lfm3-host, -image-host, -vision-residency-host, -prefill-host and native pass; serve_check.py --sampled --cancel 64/0/0; tf-kernel-contract --only LFM3: 72 kernels pass, 51 of 51 controls red as planted. Lean 165 vs 165, 0 new; pr_check 0/0; fmt clean. The Metal device test for the tower case was not run.

The integrated numerical and performance gates remain yours.

This branch has not been deployed

No deployments
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.

5 participants