Skip to content

feat(imagegen): add the MOSS-Image family (verified on Metal) - #3107

Merged
inureyes merged 19 commits into
lablup:mainfrom
georgiedekker:moss-image-upstream
Nov 19, 2026
Merged

inureyes merged 19 commits into
lablup:mainfrom
georgiedekker:moss-image-upstream

Conversation

@georgiedekker

Copy link
Copy Markdown
Contributor

feat(imagegen): the MOSS-Image family, plus six fixes the first Metal render found

Ports MOSS-Image (OpenMOSS's 5B bilingual text-rendering DiT with JSON layout control) as an
image family, verified end to end on real hardware rather than only by compilation.

What lands

  • src/imagegen/moss_image/ — the 42-block, 3072-wide single-stream transformer (shared adaLN
    modulation per timestep, 4-axis RoPE over the joint image-then-text sequence, per-head q/k
    RMSNorm, SiTU-gated feed-forwards), the Qwen3.5-9B prompt conditioner over its final-norm hidden
    states, the FLUX.2 VAE decoder, and the sigma-snapped flow-match sampler with CFG and the
    negative branch's block-22 skip.
  • One FAMILIES row, probe markers (MOSSImagePipeline), and docs/image-generation.md.
  • Qwen35Model gained a head-free prefill-hidden path (skips the [B, L, vocab] projection, ~2 GB
    at 4096 tokens) and explicit quantisation for exported checkpoints.

Why six more commits

The family compiled and its pure-math tests passed, but the first real render on Metal (M4, 16 GiB,
macOS 27, Xcode 27) walked into six defects in order. Each is a small, self-contained fix; together
they are the difference between "compiles" and "renders".

# symptom cause
1 Weight not found: model.embed_tokens.weight the exported conditioner is the inner Qwen3_5TextModel, saved without the model. wrapper — restore it for embed_tokens.*, layers.*, norm.*
2 same load the same export carries no lm_head.weight and tie_word_embeddings=false; accept the head-free shape (the model already falls back to the tied path for logits) and warn
3 index out of bounds: len 528000, index 528000 at transformer.rs the RoPE table strided by a whole head where the four axes only fill half of it
4 Shapes (1,1024,3072) and (1,2,1536) cannot be broadcast split_last splits the LAST axis, so the two head-modulation ROWS were split into halves
5 cannot load VAE weights from …/vae/vae Flux2Vae::load takes the model root and appends vae/ itself
6 unsupported convolution weight shape [384, 3, 3, 32] detect_conv_layout probed with the encoder's widths; a checkpoint that narrows the decoder (decoder_block_out_channels) stores the decoder's own channels there
7 this VAE has no bn.* statistics the published checkpoint ships the decoder alone (142 tensors), so its latents are not batch-norm normalised — unpatchify and decode directly

Evidence

Checkpoint VisualInference/MOSS-Image-SFT-MLX-compact (transformer 8-bit/gs64, conditioner
6-bit/gs64, 12.08 GB), rendered through mlxcel-server --image-model on an M4:

  • 512×512, 4 steps, no CFG — 37 s.
  • 512×512, 12 steps, CFG 3.0 — 103 s; the prompt "A clean poster with the words MOSS WORKS in bold
    white capitals on a deep blue background"
    renders MOSS WORKS legibly, which is the capability
    the model was chosen for.
  • 512×512, 50 steps, CFG 3.0 — 415 s (~8.2 s/step).
  • 1024×1024, 50 steps — exceeds the image worker's 900 s budget on this host.

Both the three-stage load/free (conditioner → transformer → VAE) and the negative-branch block skip
behave as documented.

Build note (not a defect in this change)

mlx.metallib from the lablup/tap/mlxcel 0.8.1 release is built against MLX 7ca40033; this tree
pins 9f806b36. MLX renamed every quantized kernel in between (_hgs_0 suffix), so an overlay
build that reuses the released metallib cannot run a quantized checkpoint. The renders above were
made by compiling MLX's kernels with a real Metal toolchain
(MLXCEL_PREBUILT_METALLIB=0 in the host's build script). Worth knowing before anyone tries to
serve a quantized model from a Command-Line-Tools-only host.

🤖 Generated with Claude Code

georgiedekker and others added 8 commits November 15, 2026 21:41
OpenMOSS's 5B bilingual text-rendering DiT with JSON layout control, ported
from felix-ab/moss-image-mlx: the 42-block single-stream transformer (shared
adaLN modulation, 4-axis RoPE, per-head q/k RMSNorm, SiTU), the Qwen3.5-9B
conditioner over the post-final-norm hidden states, the FLOW-matching
schedule snapped to the training grid with CFG and the negative branch's
block skip, and the FLUX.2 VAE decoder.

Sampling stages conditioner -> transformer -> VAE so one request peaks at the
largest stage rather than their sum, which is what the 16 GiB hosts this
family targets can hold.

Enablers: Qwen35Model gains a head-free prefill-hidden path and an explicit
quantization block for exported checkpoints; Flux2VaeConfig reads
decoder_block_out_channels, so the distilled small decoder (96/192/384/384)
loads over the 128/256/512/512 encoder.

Co-Authored-By: Claude Code <[email protected]>
The family table row, the staging and prompt notes, and the two recorded
deviations (MLX noise instead of the reference's torch generator; no
precise fp32 mode). Parity is explicitly unmeasured: this host has no Metal
toolchain, so only the config, schedule, probe and template tests ran.

Co-Authored-By: Claude Code <[email protected]>
… allow a head-free checkpoint

MOSS-Image's conditioner ships the inner `Qwen3_5TextModel`, so its tensors are
`embed_tokens.*`, `layers.*`, `norm.*` at the top level where every HF
checkpoint wraps them under `model.`. The loader reads the wrapped names, so
the first real load failed with `Weight not found: model.embed_tokens.weight` —
which cargo check could not see.

`restore_text_model_prefix` re-wraps exactly those three positions and leaves
`lm_head.*` alone (top-level in both layouts) and anything already wrapped.

The same export drops the vocabulary projection: 924 tensors, no
`lm_head.weight`, and `tie_word_embeddings=false`. `from_weights` now accepts
that shape instead of erroring, warning when it does, because the model already
treats "no head" as the tied path wherever it computes logits — and a chat
checkpoint that lost its head to a bad conversion should still say so.

Co-Authored-By: Claude Code <[email protected]>
… whole one

The four axes contribute `4 * head_dim / 8 = head_dim / 2` values per token and
the concatenation doubles them back into a full head, so the per-token stride is
half a head. Striding by the full `head_dim` made the second write of the last
row land one head past the end of the buffer — the first real render on Metal
panicked at transformer.rs:144 with `len is 528000 but the index is 528000`
(n = 4125 tokens, head_dim = 128), which no type-level pass and no pure-math
test could see.

Co-Authored-By: Claude Code <[email protected]>
…lves

`split_last` splits the LAST axis, so `split_last(&head_mod, 2)` on `[1, 2, dim]`
returned two `[1, 2, dim / 2]` tensors. Broadcasting that against
`[1, n_img, dim]` aborted the process inside MLX:
`[broadcast_shapes] Shapes (1,1024,3072) and (1,2,1536) cannot be broadcast`
— measured on the first 512x512 Metal render after the RoPE fix.

The head modulation carries two ROWS; slice them along axis 1. The other two
`split_last` uses in this file (qkv, ffn_up_gate) genuinely split the last axis
and are correct.

Co-Authored-By: Claude Code <[email protected]>
`Flux2Vae::load_with_dtype` takes the MODEL root and appends `vae/` itself, so
`root.join("vae")` resolved to `…/moss-image-compact/vae/vae` and the decode
failed with `cannot load VAE weights from …/vae/vae`. It surfaces last, after the
conditioner and the whole denoise loop have already run on the GPU, so the first
two stages looked healthy and the third never started.

Co-Authored-By: Claude Code <[email protected]>
…encoder's

`detect_conv_layout` probed `decoder.conv_in` with `block_out_channels.last()`.
A checkpoint that narrows the decoder — MOSS-Image's VAE is 96/192/384/384 over
a 128/256/512/512 encoder — stores 384 there, so the MLX-layout shape
`[384, 3, 3, 32]` matched neither the torch nor the MLX probe and the decode
bailed with `Unsupported convolution weight shape for decoder.conv_in.weight`.

Probe with `decoder_channels()`, which already prefers
`decoder_block_out_channels` when the checkpoint declares it. Same for
`conv_out`'s input width, which is the decoder's FIRST channel.

Co-Authored-By: Claude Code <[email protected]>
…tion

The published MOSS checkpoint ships the VAE decoder alone — 142 tensors, no
`bn.*` running statistics — so its latents are not batch-norm normalized and
`decode_packed_latents` refuses: "this VAE has no bn.* statistics". Unpatchify
and call `decode` directly; the config's scaling/shift factors still apply.

Co-Authored-By: Claude Code <[email protected]>
@cla-assistant

cla-assistant Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@cla-assistant

cla-assistant Bot commented Nov 16, 2026

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

* claim: lane/rust-1-100 — toolchain pin 1.97.1 -> 1.100.0 (owner: 1.100.x for all Rust repos)

Signed-off-by: georgiedekker <[email protected]>

* chore(rust): toolchain 1.97.1 -> 1.100.0 on the MOSS image branch

Owner direction 2026-11-17: "we use 1.100.x rust now, for all rust repos". 1.100.0 is the only
1.100.x release that exists (the 1.100.1/1.100.2 channel manifests 404), and agent,
strata_ingest, strata_rag, care-bus-agents and nonagenticai_mcp_server already pin it.

Targeted at `moss-image-upstream` rather than `main` because that is where this fork's live
work is; `main` is lablup upstream's line. Revert if the MLX prebuilt metallib pin requires
the older compiler — that pin is the one known trap here.

⚠️ Not built for this commit: an MLX build needs the full metallib path, which was not run.
Whoever next builds MOSS-Image proves it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: georgiedekker <[email protected]>
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata labels Nov 19, 2026
The MOSS-Image PR bumped rust-toolchain.toml to 1.100.0. The pin is shared with the internal development repo and is bumped deliberately, with a tree-wide cargo fmt, in its own change, so it does not belong in a model-family PR. The family builds and passes fmt and clippy on 1.97.1.

Refs lablup#3107
…nges

The conditioner encoded the positive and negative prompts through the model's internal caches, so the negative prompt was prefilled after the positive one's tokens and every later request continued from the previous request's state. forward_prefill_hidden now runs each prompt on fresh caches.

The Qwen3.5 loader changes (bare-layout model. prefix restore, head-free acceptance, extra quantization block) now apply only through a new load_text_backbone entry point. Qwen35Model::load and from_weights keep refusing a checkpoint with no lm_head.weight and tie_word_embeddings=false, so a broken text conversion still fails loudly instead of decoding through the embedding matrix.

The transformer loader checks every projection and norm width the forward pass depends on (quantized widths unpacked from the bits), and the family checks that the conditioner's hidden_size matches text_dim and that the VAE decodes RGB. A mis-shaped checkpoint now returns an error instead of aborting the process inside an MLX op. A zero-step schedule no longer underflows.

Also reuses mage_flow's modulate, drops dead code, restores a doc line the PR removed, fixes two clippy lints the 1.97.1 toolchain reports, unwraps the MOSS docs section and replaces its parity note, which pointed at a test that does not exist.

Validated with clippy -D warnings (lib and tests, metal+accelerate), fmt, and the moss_image, vae, probe, registry, flux2 and qwen3_5 unit tests on Metal.

Refs lablup#3107
@inureyes

Copy link
Copy Markdown
Member

Hardening pass on top of the contributor's commits (no linked issue).

Findings and fixes:

  • rust-toolchain.toml bump to 1.100.0 reverted (7709a92); the pin is shared with the internal repo and changes in its own PR. Two clippy lints in the family that 1.97.1 reports are fixed.
  • Correctness: the conditioner used the model's internal caches, so the negative prompt was prefilled after the positive prompt's tokens and each request continued from the last one's state. forward_prefill_hidden now runs each prompt on fresh caches, with a regression test.
  • Qwen3.5 scope: the model. prefix restore, head-free acceptance and extra quantization block now apply only through Qwen35Model::load_text_backbone. load and from_weights still refuse a checkpoint with no lm_head.weight and tie_word_embeddings=false (test added), so normal text checkpoints behave exactly as on main.
  • Untrusted shapes: the transformer loader checks every projection and norm width the forward pass depends on, and the family checks conditioner hidden_size == text_dim and an RGB VAE, so a mis-shaped checkpoint returns an error instead of aborting inside an MLX op. A zero-step schedule no longer underflows.
  • FLUX.2 VAE: decoder_channels() falls back to block_out_channels, so FLUX.2 decode is unchanged; the full imagegen suite passes.
  • Docs: MOSS section unwrapped; the parity note pointed at a test that does not exist and is replaced with what was actually verified.

Validation (Metal, M3 Ultra): clippy -D warnings on lib and tests with metal+accelerate, cargo fmt --check, and imagegen:: (456 passed), qwen3_5 (43), qwen35 (33) unit tests. No MOSS checkpoint was available on this host, so there is no end-to-end render from this pass.

CI has not run on this PR yet: every run is waiting for first-time-contributor approval.

@inureyes inureyes self-assigned this Nov 19, 2026
…stics

The moss-image-mlx export ships the FLUX.2 VAE decoder alone and stores its batch-norm statistics as top-level `running_mean` / `running_var` (std about 1.77 in VisualInference/MOSS-Image-SFT-MLX-compact). The VAE loader only kept `bn.*`, so they were dropped and the decode skipped the denormalization the reference (`VAEDecoder.decode_packed`) applies, feeding the decoder latents about 1.77x too small.

The loader now reads the bare spelling as `bn.*` when no prefixed copy exists, and MOSS-Image decodes through `decode_packed_latents`, refusing a decoder with no statistics. Also lists the family in docs/supported-models.md.

Refs lablup#3107
…gistry

`imagegen::FAMILIES` gained `moss_image`, but the standalone architecture table did not, so `mlxcel arch` did not list the family and `no_registered_family_claims_image_generation_before_a_model_ports_it` failed (10 advertised vs 11 runnable). Every backend is marked partial: the family was rendered end to end on Metal only, with no numeric parity recorded.

Refs lablup#3107
@inureyes

Copy link
Copy Markdown
Member

Second hardening pass, checked against the reference port (felix-ab/moss-image-mlx) and the published checkpoint.

Findings and fixes:

  • The VAE decode skipped the batch-norm denormalization (648726b). The reference's VAEDecoder.decode_packed multiplies the packed latents by sqrt(running_var + eps) and adds running_mean before unpatchifying. VisualInference/MOSS-Image-SFT-MLX-compact does ship those statistics: besides the decoder.* tensors, vae/decoder.safetensors holds post_quant_conv.{weight,bias} and top-level running_mean / running_var [128] (var 2.91 to 3.47, so std about 1.77). The FLUX.2 VAE loader kept only bn.* and dropped the bare names, so the decoder received latents about 1.77x too small. Text still renders legibly that way, but contrast and color are off. prepare_weights now reads the bare names as bn.* when no prefixed copy exists (other FLUX.2 checkpoints carry bn.* and are unaffected). MOSS-Image decodes through decode_packed_latents, and a decoder with no statistics is refused. Four tests: bare statistics match the upstream packed-decode fixture, the prefixed copy wins when both are present, the MOSS decode equals the denormalized decode, and a stats-free decoder is refused. The first and third fail with the alias removed.
  • The family was missing from the architecture registry (32dc5ac). mlxcel arch did not list it, and no_registered_family_claims_image_generation_before_a_model_ports_it failed (10 advertised vs 11 runnable). Added the row, partial on every backend.
  • Docs: corrected the MOSS VAE bullet and added the family to docs/supported-models.md.

These match the reference and needed no change: the chat template, the 4096-token truncation, the final-norm hidden states, the snapped sigma schedule, and the VAE config's identity scaling and shift.

Validation (ROCm gfx1151, main plus this PR plus #3170): make verify-rocm-held passed versions, kernel checks, overlay, fmt, workspace clippy and the ROCm smoke. The test stage passed 11,878 tests before the host ran low on memory and the run was stopped. Its only failures were the registry test fixed above and profile_rejects_model_kv_substitution_and_read_only_distributed_geometry, which also fails on main on ROCm since #3172 and is unrelated. Focused rerun after the fixes: 807 passed (imagegen::, models::registry, qwen3_5, qwen35, models::sanitize).

Not verified: there is no Metal host or MOSS checkpoint here, so no new render was made. A re-render should show more contrast than the earlier evidence images.

MOSS-Image-SFT-MLX-compact renders end to end on ROCm gfx1151 through mlxcel generate-image (512x512, 12 steps, CFG 3.0). With the same seed, the decode without the batch-norm denormalization gives a washed-out image (pixel std 37.6) and the fixed decode gives full contrast (pixel std 64.4) with the prompt text spelled correctly. The registry comment and the verification section now say so; the backend statuses stay partial since there is still no numeric parity.

Refs lablup#3107
@inureyes

Copy link
Copy Markdown
Member

Follow-up: rendered VisualInference/MOSS-Image-SFT-MLX-compact on ROCm gfx1151 to check the denormalization fix against the real checkpoint.

  • Command: mlxcel generate-image at 512x512, 12 steps, CFG 3.0, seed 42, with a shop-sign prompt. It took about 2 minutes including load, and this is the first end-to-end MOSS-Image run on ROCm.
  • With the fix (648726bc): full contrast, natural lighting, and "MLXCEL BAKERY" spelled correctly. Pixel mean 69.9, std 64.4.
  • With the old decode restored temporarily (unpatchify, then vae.decode with no denormalization): same layout and text, but washed out and low contrast. Pixel mean 83.6, std 37.6.

fe85fcb1 records this in the registry comment and the verification section of docs/image-generation.md. The backend statuses stay partial because there is still no numeric parity against the reference.

georgiedekker and others added 2 commits November 19, 2026 21:34
NOTICE: carry forward the moss-image-mlx NOTICE verbatim, as required by
Apache License 2.0 Section 4(d). It names MOSS-Image (OpenMOSS), Qwen3.5-9B
(Alibaba Cloud), the FLUX.2 VAE (Black Forest Labs), the SFT destripe LoRA
(nynxz) and mlx-lm (Apple).

Tests: the three fixes that had no falsifying test now have one each — the
head-modulation row split, the Flux2Vae::load model-root contract, and the
decoder-width conv-layout probe. Each was checked to fail when its fix is
reverted.

Co-Authored-By: Claude Code <[email protected]>
…ender

- image-generation.md: the module has no config test, so drop "the config"
  from the list of what the unit tests cover.
- supported-models.md: record the ROCm gfx1151 render already documented in
  image-generation.md, instead of saying Metal alone.

Co-Authored-By: Claude Code <[email protected]>
@inureyes
inureyes merged commit 8d267cb into lablup:main Nov 19, 2026
32 checks passed
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:review Under review type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants