Skip to content

h3: MiniMax-H3-Image's prompt encoder, transformer and decoder resident across pictures - #3718

Merged
ashhart merged 13 commits into
ashhart:mainfrom
plotarmordev:feat/66-upstream-pr-minimax-h3-image-resident-se
Nov 22, 2026
Merged

ashhart merged 13 commits into
ashhart:mainfrom
plotarmordev:feat/66-upstream-pr-minimax-h3-image-resident-se

Conversation

@plotarmordev

@plotarmordev plotarmordev commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Builds on #2766, #2775, #2778, #2779, #2780 and #2781; until those merge, this diff includes their commits; I'll rebase as they land. Rebased on main at e7ff97e13.

What this changes

Before, every picture made by the H3-Image tools loaded the prompt encoder, the transformer's weights and the decoder again, and macOS unwired idle GPU memory between stages. Now tf-h3-image-server loads the three once, serves one text-to-image request per stdin line, and keeps the weights wired with the shared idle keepalive; a request whose canvas, rows, references and tags match the last one's replaces only the prompt's text rows (Model.retext), and another layout binds anew over the same mapped checkpoint. If the weights cannot be held resident or the idle ticker cannot start, startup fails instead of serving requests unwarmed.

Checks on this head

  • Head commit: d4392a0c415bd1d85c950c1a1b628df66489f8f7.
  • Lean checker: python3 tools/pr_check.py --base refs/swarm/upstream/ashhart/TensorFold/main --pr 3718 exits 0: lean 221 on this head against 221 on base, 0 new. zig/build/metal_targets.zig is 589 lines; the H3-Image tools and FastH3's transformer register from zig/build/h3_metal.zig, so the registration no longer pushes the upstream file past 600. zig fmt --check zig and git diff --check pass; swarm scan is clean.
  • Tests run: zig build test-h3-image-server passes (the synthetic binding-reuse, failed-bind, idle-interval, over-long-line, and the two startup-refusal gates: weights past the residency limit and a ticker that cannot start). zig build test test-golden: 891/894 steps, 432/448 tests, 1 failed. The failure is inherited and untouched: net.test.stage expects AddressUnresolved for no-such-host.invalid, and this machine's resolver answers it with AddressInUse; the diff against main under zig/src/fabric is empty. Goldens: 55/55 and 322/335, 0 unexpected differences.
  • CI: not run yet.
  • Not run: a real picture-to-PNG run on the release checkpoint (needs the H3-Image checkpoint and a GPU window on the owner's machine).

Receipt

n/a: tf-h3-image-server is a developer tool beside the engine and changes no served path, tokens or arithmetic. No speed claim is made.

Checklist

  • The title and description match the head commit, including the stack.
  • New tests fail before the change, pass after it, and skip cleanly without tensor units.
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.

@plotarmordev
plotarmordev force-pushed the feat/66-upstream-pr-minimax-h3-image-resident-se branch 3 times, most recently from 7475720 to d4392a0 Compare November 17, 2026 19:46
@ashhart

ashhart commented Nov 18, 2026

Copy link
Copy Markdown
Owner

Thanks @plotarmordev. Keeping the three stages loaded is a clear win to aim for, and the resident-against-fresh tests in zig/tests/h3_image_server.zig check the right thing. I read the diff against current main, where it applies cleanly. Here is what we need before it can land:

  1. Stack and overlap with h3: MiniMax-H3-Image's prompt path and image decoder on CUDA, with their selftests and timings #3733. This diff still carries the h3: MiniMax-H3-Image's transformer on Metal from a picture case (tf-h3-image) #2766 to h3: MiniMax-H3-Image's text to image end to end: the prompt tool writes the canvas and the seed's starting rows #2781 picture stack. That is about 45 of its 50 files, and h3: MiniMax-H3-Image's prompt path and image decoder on CUDA, with their selftests and timings #3733 carries its own, different copy of the same files. Both PRs add zig/tests/h3_image.zig, zig/tests/h3_image_prompt.zig and docs/recipes/minimax-h3-image-metal.md as new files with different contents, so whichever lands second will not apply. They also replace the same tf-h3-dit block in zig/build/metal_targets.zig:407: here through the new zig/build/h3_metal.zig, in h3: MiniMax-H3-Image's prompt path and image decoder on CUDA, with their selftests and timings #3733 through h3_image_metal.zig. Once the stack is on main, please rebase so this diff holds only 63df3ed32 and d4392a0c4. h3: MiniMax-H3-Image's prompt path and image decoder on CUDA, with their selftests and timings #3733's zig/build/h3_image_prompt_cuda.zig:13 calls rope() from zig/build/h3_image_prompt.zig, and this PR's version of that file does not have it. Please say which version you expect to land.
  2. Real-checkpoint equality. The synthetic test shows that a reused binding matches a fresh one. Could you post a run on the release checkpoint at one head? Run the three one-shot tools, then tf-h3-image-server, on the same requests. Use two prompts with the same token count and canvas (so the second reuses the binding), then one on another canvas. The .latent.f32 and .png files must be byte-identical. Please include the per-stage seconds of both, since speed is what this PR is for. h3.zig:136-163 also changes how tf-h3-dit loads clip cases, and the clip-case run we asked for on h3: MiniMax-H3-Image's prompt path and image decoder on CUDA, with their selftests and timings #3733 covers that. If you are unable to run these, please say why.
  3. Unwinding a failed bind. zig/src/families/h3/h3.zig:154 zeroes the model and :156 calls release on failure. release (:272-284) then calls deinit on Metal objects that were never made. Their Id is a non-optional pointer (zig/src/metal/objc.zig:5), so this relies on a null in a non-optional pointer. The failed-bind test (zig/tests/h3_image_server.zig:461) fails only the last allocation, after every object exists. Could the unwind release only what was made, or could a test fail an earlier step, such as a malformed case?
  4. zig/src/families/moss_image/png.zig:48 changes MOSS-Image's PNG test to import through core. The description does not mention it. Please say why it is needed, or drop it.
  5. CI. The description says CI has not run yet. Please confirm that every job is green at d4392a0c.
  • Synthena

@AIFlowML

Copy link
Copy Markdown
Contributor

For the earlier bind failure in point 3, I ran zig build test-h3-image-server test-h3-image-prompt -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j3 --summary all at public head 10f51367 on M5 Max with Zig 0.17.0. All 18 tests passed.

I added the following before the late-allocation check in zig/tests/h3_image_server.zig in a scratch copy. This fails after the queue is created but before any pipelines or model buffers are initialized.

var no_weights = f.folder.ck;
no_weights.shards = no_weights.shards[0..0];
var early = std.testing.FailingAllocator.init(testing.allocator, .{ .fail_index = std.math.maxInt(usize) });
try testing.expectError(error.MissingTensor, h3.Model.bind(early.allocator(), no_weights, f.cases[0].case.file, .{}));
try testing.expectEqual(@as(usize, 1), early.alloc_index);
try testing.expectEqual(early.allocated_bytes, early.freed_bytes);
try testing.expect(device.allocated() <= ceiling);

With that check, zig build test-h3-image-server -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j3 --summary all passed 5/5. It gives a runnable early-error fixture for the unwind. It only exercises the missing-tensor path on this Mac. The release-checkpoint equality and #3733 integration still need their own runs. A trial merge against main 46c6ee22 was clean.

Igor Lessio - AIFLOW LABS

@AIFlowML

AIFlowML commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

I checked the combined #4276 landing train at 59f88df6a on M5 Max with Zig 0.17.0. Both commands exited 0.

zig build tf-h3-image-server -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j2 --summary all
zig build test-h3-image-prompt test-h3-geometry test-h3-boundaries -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j3 --summary all

The executable built and all 123 host tests passed. This run did not load the model. The train's check rollup currently shows only skipped jobs.

I also ran git merge-tree --write-tree 59f88df6a 5855d56a3 against #3733. It found 22 conflicts, including add/add conflicts in the shared prompt, decoder and their test files. That reproduces the overlap Ash flagged against the actual train. After this Metal stack lands, the first CUDA rebase check should be that it carries only the CUDA changes and uses the shared prompt and decoder files from the landed stack.

The same train subsequently passed all five test-h3-image-server tests on M5 Max using zig build test-h3-image-server -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j3 --summary all. The fixtures cover resident-versus-fresh binding and failed-bind cleanup.

After #2766 landed, I trial-restacked 10f513672 on 5f53c445e by replaying 304baf526^..10f513672. That skips the six older foundation commits and retains the prompt, decoder, encoder and resident-server commits. The encoder replay keeps main's h3_host.metalTools registration and adds the encoder tool. For the resident replay, I kept main's host build wiring, took the resident Folder.bind picture CLI, and called main's existing tool registration from h3_metal.targets.

On M5 Max with Zig 0.17.0, this scratch tree built both image executables and passed all 128 tests with:

zig build test-h3-image-prompt test-h3-geometry test-h3-boundaries   test-h3-image-server tf-h3-image-server tf-h3-image compile-h3-host   -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j3 --summary all

The standalone prompt, encoder and decoder tools also built. The checkpoint reference runs and the stack decision with #3733 remain open.

Igor Lessio - AIFLOW LABS

@ashhart
ashhart force-pushed the feat/66-upstream-pr-minimax-h3-image-resident-se branch from 10f5136 to a60e220 Compare November 21, 2026 07:39
@ashhart
ashhart force-pushed the feat/66-upstream-pr-minimax-h3-image-resident-se branch from a60e220 to 5dceb4c Compare November 21, 2026 20:03
@AIFlowML

Copy link
Copy Markdown
Contributor

I verified the current landing train #4445 at exact tip 942ffc580 on M5 Max (macOS 27.2, Zig 0.17.0).

zig build tf-h3-image-server test-h3-image-server test-h3-image-prompt test-h3-geometry test-h3-boundaries -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all

All 57 steps succeeded, with 128 tests passed and zero failures or skips. The H3 server built and all five resident-server tests ran, including the synthetic fresh-vs-resident Metal comparison and failed-bind unwind. The production checkpoint and a live image benchmark were outside this run.

Igor Lessio - AIFLOW LABS

@AIFlowML

Copy link
Copy Markdown
Contributor

The current published Metal head 5dceb4c8 trial-merges cleanly into main d21617008. On M5 Max with Zig 0.17.0, the native H3 image server built and the combined suite passed all 128 tests. All five resident-server checks ran, including fresh versus resident Metal execution on synthetic inputs and cleanup after a failed bind.

zig build tf-h3-image-server test-h3-image-server test-h3-image-prompt \
  test-h3-geometry test-h3-boundaries -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j2 --summary all

The current CUDA head #3733 at 096c2f46 still conflicts in 16 paths when applied after this Metal trial. The overlap includes shared H3 prompt, decoder and picture-writer files, so the individual green trials do not yet verify the combined stack. The production checkpoint and live image benchmark remain separate.

Igor Lessio - AIFLOW LABS

Each text segment is tokenised on its own and cut to 4,096 tokens; references enter as a label and a vision
block whose rows are tagged 0. Positions follow Qwen-VL's M-RoPE, and the rotary table rounds to bf16. The Qwen
copy of a reference keeps or scales its short edge to 1,024 with Pillow's LANCZOS. The text encoder's and the
refiner's configs are checked at the released geometry.
tf-h3-image-prompt turns a prompt into the text rows tf-h3-image reads: Qwen3-VL's text model to the hidden
state leaving layer index 49, then condition_proj, the two token-refiner blocks over every row and the final
norm. Weights are bf16 read in place; products run in simdgroup matrices with fp32 sums, so chips without
tensor units run it too. The encoder also takes a reference's vision rows and DeepStack features at their image
pads, ready for the edit's tower.

Its selftest writes a tiny synthetic checkpoint, loads it as a real run does, and gates each kernel alone and
each whole run against a float64 host reference with the same bf16 rounding points.
…d rotary table, unpatchify

image_decoder.zig: the 297 decoder tensors MiniMax-H3-Image's VAE file holds
(F32, checked by name and shape, decoder.mask_token left unread), their
places in one bf16 buffer, a tile's sequence (its cells, 4 registers, one
zero token), the 2D rotary ids in bf16 arithmetic and their angles, the
proj_out rows unpatchified to pixels, and the tile geometry the attention
holds (at most 16 cells a side). Host tests run in test-h3-geometry.
… on the host

image_decoder_metal.zig runs the VAE's 2D ViT decoder on a batch of tiles
a command buffer, on any Apple GPU (its kernels compile from source at
load, no tensor units): post_quant_conv and x_embedder, the 24 blocks
(RMSNorm, grouped q | k | v, q and k normed and turned half-style over
their first 32 dims, softmax attention at 1/8, LayerScale residuals, the
gated SiLU FFN), norm_out in fp32 and proj_out. Products are bf16 with
fp32 sums, rounded where the reference rounds. decode() blends the tiles
in fp32 with picture_vae's Assembler. image_decoder_reference.zig is the
same forward on the host with float64 sums, for the self-test.
…self-test

tf-h3-image-decoder MODEL_DIR latent.f32 ROWS COLUMNS out.png [WIDTHxHEIGHT]
reads vae/config.json and the decoder's tensors, denormalises the latent,
decodes it in tiles of up to 16 a pass, blends them, truncates to bytes,
resizes with Pillow's LANCZOS when asked and writes a PNG.

`selftest` runs the kernels on synthetic weights against the float64 host
reference: the embedding and proj_out within 1 bf16 ULP, each block
teacher-forced, two and all 24 blocks chained, batched decodes bit-identical
to the staged tiles, and the picture's bytes. It exits 1 past a bound.

zig build tf-h3-image-decoder builds it (shaders compile at load);
compile-h3-image-decoder-host compiles it without the Metal compiler and
joins the macOS nightly host checks. picture_writer.zig roots MOSS-Image's
PNG writer and core's resampler in one module for tools beside the engine.
…es the canvas and the seed's starting rows

tf-h3-image-prompt takes an optional size, seed and smallest area: it
writes the canvas, the requested size and the starting rows (the seed's
first torch CPU randn over the latent, patchified) beside the prompt's
rows, a whole text-to-image case. tf-h3-image's free run exits 0 with
nothing to gate. The recipe runs prompt, transformer and decoder in turn.
ashhart and others added 5 commits November 22, 2026 11:42
…nt across pictures

tf-h3-image-server loads the three tools' weights once and serves one
text-to-image request per stdin line. A request whose canvas, row count,
reference count and tags match the last one's keeps the bound transformer
and only replaces the prompt's text rows (Model.retext); another layout
releases it and binds anew over the same mapped weights. The weights sit
in one residency set across the three stages' queues, so macOS does not
re-wire them on every request, and the idle keepalive keeps them wired
between pictures while holding its ticks off during a request. A set that
cannot be held or a ticker that cannot start stops startup, so the server
never serves requests unwarmed.

Model.load splits into open (the checkpoint mapped and read ahead) and bind
(kernels and buffers for a case), and release leaves the checkpoint open; a
failed bind frees every Metal object it made. The three tools load their
weights once and run a picture as functions (Encoder, Folder, Vae), so the
server and the one-shot tools share the same steps.

The image tools' modules read safetensors and checkpoint fixtures through
core, following main's core module split.

metal_targets.zig was 613 lines once the H3-Image tools were registered,
over the 600-line limit. FastH3's transformer and the H3-Image tools now
register from h3_metal.zig, leaving metal_targets.zig at 589.
One process for every picture warm: the request line, binding reuse and
retext, the weights held in one residency set, and the synthetic gates.
Follow main 4d244a0
(h3: use the current reader and share Metal tool registration).
Keep its shared clip/picture tool constructors and register the incoming
encoder, prompt, decoder and resident server beside them.
@ashhart
ashhart force-pushed the feat/66-upstream-pr-minimax-h3-image-resident-se branch from 5dceb4c to 1e563e8 Compare November 22, 2026 11:42
@ashhart
ashhart merged commit 129094d into ashhart:main Nov 22, 2026
12 checks passed
@ashhart

ashhart commented Nov 22, 2026

Copy link
Copy Markdown
Owner

Thank you @plotarmordev. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

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.

3 participants