Skip to content

Studio: Qwen-Image-Layered on the native sd.cpp engine - #12777

Merged
danielhanchen merged 39 commits into
mainfrom
studio/sdcpp-qwen-layered
Oct 6, 2026
Merged

danielhanchen merged 39 commits into
mainfrom
studio/sdcpp-qwen-layered

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Stacked on #12775 (Qwen-Image-Layered on the diffusers engine) and #12776 (sd.cpp edit routes, itself on #12755). Merge those first; this PR adds one commit on top of their merge.

Problem

The native sd.cpp engine cannot run Qwen-Image-Layered, although the pinned sd.cpp build (master-813-bfbef5b-u1d02858) decomposes it from a reference image:

  • On main the model has no Studio family at all, so the native load fails at family detection: 'unsloth/Qwen-Image-Layered-GGUF' is not a supported diffusion image model.
  • With the diffusers Layered route alone the family exists but has no single-file assets, so begin_load refuses it: Family 'qwen-image-layered' has no native sd.cpp asset mapping.
  • The engine also had nothing to drive it with. There was no layer count on either transport. sd.cpp decodes layers + 1 images per generation; the server path's all-or-nothing count check refused that, and the one-shot path read only --output, while sd-cli writes <stem>_0.png ... <stem>_N.png for a multi-image result.

Change

Asset mapping (diffusion_families.py, qwen-image-layered)

  • The model's own 4-channel VAE: Qwen/Qwen-Image-Layered vae/diffusion_pytorch_model.safetensors.
    • This is the vendor base's single file, the one the diffusers route already downloads. sd-cli reads its tensor names as is.
    • With it, the layers are byte-identical to a run with the ComfyUI repack (Comfy-Org/Qwen-Image-Layered_ComfyUI, qwen_image_layered_vae.safetensors), so no community repack is needed.
  • The Qwen2.5-VL-7B Q4_K_M encoder qwen-image uses. No vision projector: sd.cpp never runs the vision tower for this model (enable_vision = version != VERSION_QWEN_IMAGE_LAYERED).
  • euler with flow shift 1.0: the diffusers route's ComfyUI AuraFlow shift, the same schedule formula.

Layer count on both transports (sd_cpp_args.py)

  • SdCppGenParams.qwen_image_layers puts --qwen-image-layers N on the one-shot argv. build_img_gen_request(qwen_image_layers=N) puts the top-level qwen_image_layers field in the sd-server body.
  • New sd_cli_output_paths() gives sd-cli's file naming for a multi-image run (examples/cli/main.cpp save_results). SdCppEngine.generate checks the first numbered file instead of --output, which a layered run never writes.

Engine (sd_cpp_backend.py)

  • The family's layer_count (2) is sent as the layer count.
  • sd.cpp's first image, its reconstruction of the input, is dropped. The diffusers pipeline drops that frame too ("remove the first frame as it is the origin input"), so both engines return the same 2 RGBA layers, each with the generation's seed.
  • The server's count check expects batch x (layers + 1) images. The one-shot path collects every numbered file.
  • The input is resized to the family's 640 canvas at its aspect ratio (rounded to 32), the same canvas the diffusers engine decomposes at. The helper is duplicated because this module never imports the torch engine; a test pins the two equal.
  • Workflows, readiness and refusals come from the edit-only handling of the edit routes PR: edit only, an input image is required.

Results

B200, Studio's own SdCppDiffusionBackend in process, on the pinned sd.cpp build.

  • Inputs: the public unsloth qwen-image-layered-BF16.gguf and qwen-image-layered-Q4_K_M.gguf, with the same input as the diffusers route's proof (object.png, 768x768). Prompt "A product photo of an object on a plain studio background", seed 42, 20 steps, cfg 2.5.
  • Mode: server mode, plus one-shot (sd-server hidden) for Q4_K_M.
tree BF16 Q4_K_M
main (f865421355) refused: not a supported diffusion image model refused, same
sd.cpp edit routes only (2f35d5e728) refused, same refused, same
diffusers Layered route only (c2a0d16d5f) refused: has no native sd.cpp asset mapping refused, same
this PR 2 RGBA layers, 640x640 2 RGBA layers, 640x640

What this PR sends. Server body qwen_image_layers: 2, width/height 640, one 640x640 ref_images entry, txt_cfg 2.5, sample_method euler, flow_shift 1.0. The server returned 3 images and Studio kept the last 2. The one-shot argv carries --ref-image, --qwen-image-layers 2, --width 640 --height 640, --cfg-scale 2.5, --sampling-method euler, --flow-shift 1.0.

LPIPS, vgg / alex, each layer composited over gray:

pair layer 1 layer 2 layers composited
this PR, Q4_K_M vs BF16 0.003 / 0.000 0.011 / 0.005 0.014 / 0.008
this PR BF16 vs the diffusers Layered route's BF16 render (same input, prompt, seed) 0.006 / 0.001 0.058 / 0.060 0.058 / 0.035
one-shot vs server, Q4_K_M 0.000 0.000 0.000
  • Both engines split the input the same way: layer 1 is the opaque white background (alpha mean 1.000), layer 2 is the apple with its transparency. Layer 2 alpha mean is 0.867 here (BF16) and 0.881 on the diffusers route.
  • One-shot and server layers are byte-identical (same md5). This branch's runs with the vendor VAE are md5-identical to an earlier run of the same code pointed at the ComfyUI VAE file, and a direct sd-cli run with the vendor VAE matches them pixel for pixel.
  • The loadability campaign's own sd-cli Layered render is not used as a reference: it ran text-to-image with a different prompt (no input image), so it is not a decomposition.
  • Render time for one decomposition (server): BF16 149 s, Q4_K_M 175 s. The GPUs were shared, so treat these as indicative only.

Qwen-Image-Layered on sd.cpp

Columns: input, layer 1 and layer 2 over gray, the layers composited. Rows: the diffusers Layered route BF16, this PR BF16, this PR Q4_K_M.

Tests

  • New test_sd_cpp_qwen_layered.py, 8 cases:
    • the asset mapping: the vendor VAE equal to the family base, no projector, the shift equal to the diffusers route's;
    • both builders carry the layer count only when set;
    • sd_cli_output_paths naming;
    • the canvas equals the diffusers engine's _layered_canvas on four sizes;
    • edit-only workflows;
    • the server body plus dropping the reconstruction, RGBA layers and per-layer seeds;
    • a short server result is refused;
    • the one-shot argv collects the numbered files.
  • test_sd_cpp_edit_families.py: the layered-refusal case now expects Qwen-Image-Layered to resolve to its family, and still refuses a FLUX layered or inpaint variant.
  • Test set run on both arms: test_sd_cpp_*.py, test_h3_native_server.py, test_diffusion_backend.py, test_diffusion_engine_router.py, test_cached_gguf_routes.py, test_diffusion_more_families.py, test_diffusion_gated_base.py, test_diffusion_gguf_compile.py, test_diffusion_gguf_offload_route.py, test_native_gguf_companion.py, test_diffusion_unified_edit.py, test_diffusion_qwen_layered.py.
    • This branch: 2179 passed, 1 failed, 1 skipped.
    • main: 2141 passed, 27 failed, 4 errors. All of those are in the stack's new files, apart from the shared failure below.
    • The new test_sd_cpp_qwen_layered.py cannot import on main (sd_cli_output_paths).
    • The one failure on both, test_generate_guard_uses_the_hint_the_load_planned_with, reads live free VRAM on a shared GPU.

Not covered

  • One input, prompt and seed. There is no noise floor.
  • The layer count (2) and the 640 canvas are fixed by the family on both engines; requests cannot change them.
  • The pinned build reads reference images as RGB. An input with transparency is flattened over white before it is sent (the existing native behaviour for every edit family), while the diffusers route hands the alpha to the 4-channel VAE. Not compared on a transparent input.
  • CUDA only. The CPU, Metal and Vulkan hosts were not run.

_map_guidance returned no cfg for flux.1, flux.2-klein and flux.2-dev, so
the one-shot argv had no --cfg-scale and the server request had no
guidance.txt_cfg. sd.cpp then applied its own default cfg of 7.0, which
renders FLUX.1-dev and schnell dark or burnt and oversaturates FLUX.2.

Guidance-distilled FLUX (FLUX.1 dev / schnell / Kontext, FLUX.2-dev) now
runs one pass at cfg 1.0 with the embedded guidance. FLUX.2-klein has no
guidance embedder, so it takes the real-CFG mapping: the 4-step models
default to 1.0, the undistilled klein-base to its real CFG of 5.0.
…sd.cpp engine

The native engine refused every edit-only family at load ("has no native
sd.cpp asset mapping"), because qwen-image-edit and flux.1-kontext declared
no single-file VAE or text encoders, although the pinned sd.cpp build runs
all of them with the source image as a reference image.

- Asset mapping: Qwen-Image-Edit (original, 2509, 2511) takes Qwen-Image's
  VAE, the Qwen2.5-VL Q4_K_M encoder and its mmproj vision projector, euler,
  flow shift 3. 2511's zero-timestep conditioning is detected by sd.cpp
  from the __index_timestep_zero__ tensor the GGUF carries. Kontext takes
  the FLUX.1 VAE and CLIP-L + T5-XXL.
- Guidance: Kontext runs cfg 1.0 with the embedded guidance; the Qwen edit
  checkpoints keep real CFG, the value the diffusers path passes as
  true_cfg_scale.
- Edit-only workflow on both transports: an input image is an edit, the
  source is sent as the one --ref-image / ref_images entry, the output takes
  the source size snapped to the grid as on the diffusers engine, and
  status() advertises only "edit". Qwen edit needs its projector loaded.
- Same refusals as the diffusers engine for text-to-image, the reference
  workflow, reference images and masks on these families.
Qwen-Image-Layered had no family, and the layered keyword guard routed
every layered id away from qwen-image, so the public GGUFs were refused
as unsupported. Add a qwen-image-layered family on
QwenImageLayeredPipeline with the ComfyUI Image to Layers defaults
(20 steps, cfg 2.5, shift 1, 2 layers at 640), an RGBA input, and each
decomposed RGBA layer returned as its own output image.

The public GGUFs store time_text_embed.addition_t_embedding (an
nn.Embedding) in BF16, which diffusers keeps packed outside its
GGUFLinear layers, so the first step read raw bytes. Dequantise packed
parameters that sit outside the quantizer's linears after a GGUF
transformer load; no other shipped family has any.

A local pipeline whose model_index declares a family that its folder
name rules out stays refused in both the listing and the loader.
Qwen-Image-Layered now has a Studio family (the diffusers route), but the
native engine still refused it: the family had no single-file assets, and
the engine had no way to ask for a layer count or to collect the layers.
The pinned sd.cpp build decomposes it from a reference image with
--qwen-image-layers / "qwen_image_layers".

- Assets: the layered model's own 4-channel VAE, taken from the vendor
  base's vae/diffusion_pytorch_model.safetensors (the file the diffusers
  route fetches; sd-cli reads it as is and its layers are pixel-identical
  to the ComfyUI repack's), and the Qwen2.5-VL Q4_K_M encoder. No
  projector: sd.cpp never runs the vision tower for this model. euler,
  flow shift 1.0, the diffusers route's ComfyUI shift.
- The layer count goes out on both transports: --qwen-image-layers on the
  one-shot argv, qwen_image_layers in the sd-server body.
- sd.cpp decodes layers + 1 images, the first being its reconstruction of
  the input. That frame is dropped, as the diffusers pipeline drops it, so
  both engines return the same layers; every layer carries its seed. The
  server's all-or-nothing count check expects the extra images, and the
  one-shot path collects sd-cli's numbered output files.
- The input is resized to the family's 640 canvas at its aspect ratio,
  the same canvas the diffusers engine decomposes at.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-06T05:24:25.586169Z 5aa580c New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 5, 2026
@danielhanchen danielhanchen self-assigned this Oct 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d5767beb15

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# ``use_layer3d_rope`` in the base's transformer config, which a GGUF pick reads through ``config=``), and its
# own RGBA VAE. Its own entry, so the name outranks "qwen-image" in detect_family and the layered keyword
# guard no longer refuses it.
name = "qwen-image-layered",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Gate Layered on an sd.cpp architecture marker

On hosts with an existing runnable pre-Layered sd.cpp installation, or a custom older SD_CLI_PATH, this family leaves sd_cpp_arch_marker unset. Consequently, sd_cpp_binary_runs_family treats every binary as capable, the router can select the native backend, and an old one-shot binary may be committed as ready before rejecting the architecture or --qwen-image-layers at generation time. Runnable same-accelerator installations are deliberately reused rather than upgraded, so this newly added architecture needs a binary marker like the Qwen-Image-2.1 family to trigger fallback instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8bdac33: the family now sets sd_cpp_arch_marker = "qwen_image_layers". Layered landed upstream in master-744 (556f04b); the pinned sd-cli and sd-server both carry the literal, so an older reused build falls back instead of failing at generation.

Comment on lines +1884 to +1889
if source_sized and _layer_count(fam):
# A layered family decomposes at its own canvas, whatever the source's size: resize the source to it, as the
# layered pipeline does before encoding.
width, height = _layered_canvas_size(fam, images[0].size)
if images[0].size != (width, height):
images[0] = images[0].resize((width, height), Image.LANCZOS)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the same source aspect ratio on both engines

For source images whose dimensions are not multiples of 16, this computes the native canvas from the original size, while the diffusers path first applies _snap_to_multiple(init_pil, 16) and then calls _layered_canvas. The rounding can materially change the result—for example, a 500×521 input becomes a 608×672 canvas under diffusers but 640×640 here—so selecting a different engine changes the output dimensions and distorts the source differently. Apply the same pre-snap on this path, or exempt Layered from the generic diffusers snap so both use the original ratio.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8bdac33: the native canvas is now picked from the 16 px snapped source, as the diffusers engine does (500x521 -> 608x672 on both), with a test against _layered_canvas(_snap_to_multiple(...)).

Comment on lines +33 to +34
{ match: "qwen-image-layered", steps: 20, guidance: 2.5 },
{ match: "qwen_image_layered", steps: 20, guidance: 2.5 },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cover the compact Layered alias in generation defaults

When an automatically detected repository or local path uses the supported qwenimagelayered alias declared by this family, neither of these new matches applies, and the generic qwen-image key does not match either. defaultsFor therefore selects the fallback 9 steps and guidance 0 instead of the intended 20/2.5; for a page-initiated load, lastLoad.current prevents the resident-model effect from reseeding those controls afterward. Add the compact alias here, and to the mirrored backend defaults table, so every accepted family spelling receives the same recipe.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 542a09e (#12775, merged here): qwenimagelayered added to both defaults tables.

Comment on lines +2687 to +2689
// Editing families the backend now SUPPORTS: not hidden despite the edit keyword. Mirrors the
// backend's qwen-image-edit family.
const SUPPORTED_EDIT_KEYWORDS = ["qwen-image-edit", "kontext"] as const;
// backend's qwen-image-edit, flux.1-kontext and qwen-image-layered families.
const SUPPORTED_EDIT_KEYWORDS = ["qwen-image-edit", "kontext", "qwen-image-layered"] as const;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep the underscore Layered alias visible in the image picker

For a supported repository or local filename using the backend's qwen_image_layered alias, idHasSegment(id, "qwen-image-layered") does not match because the separators inside the keyword differ, while the later standalone layered check does match. isImageEditModel therefore treats this supported family as an unsupported edit model and filters it out of the task-scoped image picker. Include the underscore spelling in the supported set or normalize separators before comparing.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 542a09e (#12775, merged here): the supported list carries every accepted spelling.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: e6671222ce

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Base automatically changed from studio/sdcpp-edit-routes to main October 6, 2026 05:23
@danielhanchen
danielhanchen merged commit 55c79f1 into main Oct 6, 2026
@danielhanchen
danielhanchen deleted the studio/sdcpp-qwen-layered branch October 6, 2026 05:47
danielhanchen added a commit that referenced this pull request Oct 6, 2026
…erage in Backend CI (#12843)

#12766 added the VAE seam guard and #12775 / #12777 added the
qwen-image-layered family right after it, with no entry in
vae_tile_configs.json. The seam guard fails on main:
test_every_family_has_a_vae_config, then a KeyError in the geometry check.

Add Qwen/Qwen-Image-Layered's vae/config.json at revision 8f0ca708df (the
4-channel RGBA AutoencoderKLQwenImage). With it the full seam guard passes:
27 passed.

The coverage check lives in a module that importorskips torch and diffusers,
so it only ran in the path-filtered seam-guard job. A dependency-free copy
now runs in Backend CI, plus a shape check on each entry.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant