Repository navigation
Studio: MOSS-Image (in-tree port, quantised builds, GGUF through stable-diffusion.cpp) - #14552
Conversation
…t8 text encoder Freeze the quant keep-list (text_embedder, time_embedding, modulation) and the ConvRot spec (group 256 over the 252 block Linears) the hosted builds were made with, point SFT and Base at their own unsloth/MOSS-Image-*-FP8 repos, and let the quant tables answer to the Base files' moss-image-base family string. Default on GPU: INT8-ConvRot DiT and the int8 ConvRot Qwen3.5-9B encoder when the hosted files exist, plain INT8 behind the rotated file; fp8 / mxfp8 leave the automatic order (auto_scheme_skip) and stay explicit picks. Base reuses the SFT encoder file through a text-encoder equivalence group. Without the hosted repos a load quantises the released denoiser at runtime with the same spec and keeps the dense bf16 encoder. Also: resolve the in-tree transformer class when seeding a pre-quantized denoiser, give a handed-in encoder the vision drop and gated-delta offload guard, load the tokenizer through the class its config names (offline loads from a repo id failed on the missing root config.json), cast activations to a declared compute_dtype, and hint the refiner input length dynamic so the first render no longer recompiles the text block.
…e compiled blocks ComfyUI's repacked MOSS files fuse proj.q/k/v into one Linear (one GEMM and one activation quant). Do the same at load for int8 weights: codes and per-row scales concatenate, ConvRot parts share one rotation of the shared input, and the parts become views of the fused weight. Every int8 block Linear also runs through int8_linear (probed Triton act quant, torchao's eager math). Exclusive B200, 1024x1024, 30 steps: INT8-ConvRot 0.0769-0.0778 -> 0.0722-0.0726 s/step, plain INT8 0.0700 -> 0.0673-0.0678, peak unchanged, 0 recompiles. bf16 keeps three GEMMs (fused measured 0.0879 vs 0.0881, inside the A/A spread). Kill switch UNSLOTH_DIFFUSION_MOSS_FUSED=0.
…-Image comfy-kitchen's rms_rope_split_half analogue: one Triton kernel reads q, k and v once, applies the q/k RMSNorm and the split-half RoPE with every eager bf16 rounding of the port kept, and writes the [B, H, S, D] layout attention takes. Probed per device against the eager ops. Exclusive B200, 1024x1024, 30 steps: bf16 0.0879-0.0883 -> 0.0871-0.0876 s/step (0.7%), INT8-ConvRot 0.0723-0.0726 -> 0.0722 (no change). LPIPS against the eager port moved 0.025 -> 0.026 (bf16) and 0.049 -> 0.056 (int8), inside the kernel floor but no better, so it stays off: UNSLOTH_DIFFUSION_MOSS_QK_ROPE=1 enables it.
…ment ComfyUI loads as much of the model as fits and streams the rest. Studio has the same partial residency, but without a measured peak MOSS placed from the flat 8 GiB estimate and streamed the 5 GB int8 denoiser on a 16 GB card. Seed the compiled-tier table with the measured worst phase (2905 MiB, the fp32 FLUX.2 VAE decode). B200 capped to 16 GiB (planner and allocator), INT8-ConvRot + int8 encoder, 1024x1024, 30 steps: 0.241 -> 0.0786 s/step, peak 2.9 -> 11.2 GiB, no OOM; 13 GiB 0.0766, 12 GiB 0.0766 (resident: 0.0722).
MOSS-Image GGUFs now load on the native engine with the FLUX.2 small-decoder VAE from the MOSS repo, Qwen3.5-9B Q8_0 as the llm encoder and the MOSS-Image arch marker, so a build older than upstream master-975 is refused with a reason instead of failing mid-load. Diffusers has no single-file loader for the in-tree port, so the router sends these GGUFs native on every backend and the diffusers path refuses them. sd.cpp's MOSS conditioner needs the official tokenizer.json on --tokenizer, so SdCppModelFiles gains an optional tokenizer field that the cli, server and video builders pass through, fetched from the family's sd_cpp_tokenizer.
An unset transformer precision now keeps MOSS-Image's 5.1B bf16 DiT when it fits the card, the same rule FLUX.2-klein, Z-Image and FLUX.3-klein follow. Against the eager bf16 port (14 prompts, 1024x1024, 50 steps) the INT8-ConvRot default scored LPIPS 0.049 and the new default 0.036 with the int8 text encoder. INT8-ConvRot is still picked when bf16 would offload, and an explicit precision is honoured.
[skip ci]
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Adding the |
A dict comprehension's locals() is its own scope before Python 3.12, so the callback mapping raised KeyError on the first step. Build it with a loop as diffusers pipelines do.
supports_lora reports False for the family on every quant, and an active selection is refused before load and at generation time with a clear message.
… FLUX.2 map The FLUX.2 map is token shaped; a 4-D latent carrying the same packed channels is now projected spatially instead of marking the previewer failed. [skip ci]
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…s check A MOSS GGUF or loose transformer file never reaches diffusers, so the transformers >= 5.3 / diffusers remedy cannot help it: report the native sd.cpp requirement first. Tests that import the in-tree pipeline skip without torch and diffusers, and the routing tests no longer assume a transformers new enough to build the pipeline.
Add MOSS-Image-SFT's vae/config.json (pinned revision) to the seam guard fixture, list moss-image among the prompt-tip and cudnn-benchmark opt-out families, gate in-tree pipelines out of the diffusers version-gate check, and read the pipeline source as utf-8. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f73b07b416
ℹ️ 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".
| grid = _time_snr_shift(shift, torch.arange(1, num_train_timesteps + 1, 1) / num_train_timesteps) | ||
| sigma_min, sigma_max = grid[0], grid[-1] | ||
| timesteps = torch.linspace(sigma_max, sigma_min, steps + 1)[:-1] | ||
| return [float(_time_snr_shift(shift, ts)) for ts in timesteps] |
There was a problem hiding this comment.
Avoid shifting the SGM-uniform schedule twice
For every default MOSS render using sgm_uniform, this constructs already-shifted sigma bounds and then feeds the interpolated values through _time_snr_shift again. ComfyUI's normal_scheduler maps the bounds back through ModelSamplingDiscreteFlow.timestep before interpolation, so the interpolation should occur in the unshifted range from 1 to 1 / num_train_timesteps; with shift 5 and 50 steps, the current last nonzero sigma is about 0.1131 rather than 0.0968. This means the advertised ComfyUI baseline and all default generated results use a different denoising schedule.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this one. ComfyUI's ModelSamplingDiscreteFlow.timestep is sigma * self.multiplier (comfy/model_sampling.py), not an inverse shift, so normal_scheduler(sgm=True) interpolates between the already-shifted sigma_max / sigma_min and then runs each point through time_snr_shift again. sgm_uniform_sigmas reproduces exactly that. I executed ComfyUI's own ModelSamplingDiscreteFlow and normal_scheduler (MOSSImage's sampling_settings: multiplier 1.0, shift 5.0, 50 steps) next to this function: both give 50 sigmas, last nonzero 0.11314225941896439, max abs difference 0.0. The 0.0968 schedule would therefore diverge from the ComfyUI baseline.
| bf16Pipeline("OpenMOSS-Team/MOSS-Image-SFT", 25.33, { | ||
| totalParams: 5082308624, | ||
| prequantRepo: "unsloth/MOSS-Image-SFT-FP8", | ||
| prequantSizeGb: { fp8: 5.04, int8: 5.04 }, |
There was a problem hiding this comment.
Account for automatic text-encoder quantization in fit routing
On a 24 GiB GPU with dense quantization enabled, both new MOSS rows are routed to the slow GGUF fallback even though the normal pipeline fits: residentSizeGb derives about 15.86 GiB of dense companions from this row and therefore estimates the quantized load at roughly 20.9 GiB, but the backend automatically loads the hosted INT8 Qwen3.5 encoder (te_quant_auto = "int8"), reducing the actual transformer, encoder, and VAE residency to about 16 GiB, below the 16.8 GiB allowance. Add a way for these artifacts to represent the quantized companion size so common 24 GiB cards select the fast pipeline rather than sd.cpp.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this in this PR. The fit rule sizes companions in bf16 for every family. Ten families on main already set te_quant_auto (FLUX.3 Klein, FLUX.2, Qwen-Image and others), and their rows also count the dense encoder, for example FLUX.3's 8.27 GiB Qwen3-VL-4B. MOSS follows the same contract. Your numbers are right: 25.33 minus the 9.47 GiB bf16 DiT leaves 15.86 GiB of companions, and adding 5.04 gives 20.9 GiB, which is above the 16.8 GiB allowance. But fixing that means giving residentSizeGb a per-row quantized-companion size and re-sizing all of those families together. That is a separate catalog change. Here, a 24 GB card falls back to the GGUF row, which loads and renders.
…the diffusers components the in-tree port reads The manifest names MOSS's own pipeline_moss_image module for both, which the local completeness check passed on any file, so a config-only transformer/ from an interrupted copy was accepted and failed only mid-load. [skip ci]
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
[skip ci]
# Conflicts: # studio/backend/tests/fixtures/diffusion_family_data_freeze.json # studio/backend/tests/test_diffusion_lora.py # studio/frontend/tests/image-generation-defaults.test.ts
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
The two MOSS-Image catalog groups, family label and generation defaults add 1,298 B raw / 181 B transfer to the eager startup JS (6,919,946 -> 6,921,244 B raw, 2,084,333 -> 2,084,514 B transfer against 4e2838e, one machine and build, Node 24, 97 chunks). Raise BUDGET by that growth so main's margin stays where it was. [skip ci]
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
# Conflicts: # studio/backend/tests/test_diffusion_speed.py
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
# Conflicts: # studio/frontend/scripts/check-bundle-budget.ts
…Klein base; layer split prices Z-Image from its measured row (unslothai#14950) ## Problem ComfyUI prices each model's activations with `memory_usage_factor` (comfyanonymous/ComfyUI d07dff4, `comfy/supported_models.py`): Qwen-Image 2.1 `6.0` (2168), MOSS-Image `14.6` (2048), and FLUX.3 (`class Flux3(Flux2)`, 847) inherits the Flux2 formula `factor * 4 * hidden_size / 2604` (820). `model_base.memory_required` (424-442) turns the factor into MiB of activations per latent pixel. Those three numbers are ComfyUI constants, not Studio measurements. Studio's equivalent is the per-phase activation table `_MEASURED_IMAGE_ACTIVATION_MIB` in `diffusion_memory.py` (text encoder, denoise, untiled decode, tiled decode, 2048x2048 worst case, per speed tier). On NVIDIA, `_calibrated_activation` reads it when the load is planned. On main: | family | own row on main | load plan on main | |---|---|---| | `qwen-image-2.1` | yes | measured row | | `flux.3-klein` | yes | measured row | | `flux.3-klein-base` | no | flat 8192 MiB per megapixel | | `moss-image` | no (unslothai#14552 lists it as not added) | flat 8192 MiB per megapixel | So the MOSS-Image and FLUX.3 Klein base load plans reserved 8 GiB of activations at 1024x1024, about 2.2x what they use. ## Fix Two measured rows. B200, bf16 (`transformer_quant=auto` picked bf16 with the hub offline), 1024x1024 and 2048x2048, 4 steps, every tier (off / default / max). Each phase is the peak allocated during that phase minus the resident weights. - `moss-image`: `(1940, 528, 3666, 3662, 3750)` on both tiers. - Denoise: 519-528 eager, 374-462 compiled. - Decode: the fp32 VAE decode is the worst phase, 3666 eager / 2807 compiled. A 512 px tile barely lowers it at 1024x1024 (3662 / 2700). - 2048x2048: max(denoise 2106, tiled decode 3750). - Text encoder: 1940 MiB above the weights when streamed (group offload on a 36 GiB cap), 4-22 MiB when resident. - `flux.3-klein-base`: `(301, 901, 2512, 2512, 3359)` on both tiers. - Measured: denoise 601 / 618 / 652 (off / default / max), untiled decode 2443 / 2512, 2048x2048 max(denoise 2369, tiled decode 2474). - It shares Klein's DiT and VAE (ComfyUI prices both with the one Flux2 formula), so each column takes the larger of the two families. That brings in Klein's 301 MiB text encoder window and its 901 MiB int8 / fp8 denoise, which this bf16 run could not measure. The 1.2 margin applies on top, as for every row. The multi-GPU layer split also reads the measured row now. Before, it took `measured_runtime_headroom_mib`, else `calibrated_headroom_mib`, else the flat `runtime_headroom_mib`. But `calibrated_headroom_mib` is only recorded when the measured row changes the one-card plan, so on a multi-card load the split usually got the flat 8192 MiB per megapixel. The companion split already used the row as its phase headroom. On a multi-card selection, `plan_diffusion_memory` now records `calibrated_split_headroom_mib` (untiled worst phase, since a split keeps the VAE resident on the primary), and `refine_plan_for_multigpu` uses it before the flat figure. One-card plans are unchanged: the key is only written under a multi-card selection. This fixes a Kaggle 2x T4 report: guided Z-Image-Turbo (fp16) declined the layer split, "11931 MiB of denoiser and VAE weights with the text encoders streamed, short by about 1007 MiB after the per-card reserves and 6963 MiB of activations on cuda:0", at both 1024 and 768. Every 2-card arm then streamed one card from host RAM and was SIGKILLed. The load plan always budgets the 1024x1024 default, because the request size is unknown at load. The generate-time guard re-prices the real request, which scales with the pixel count (6963 MiB at 1024, 3916 MiB at 768). Both rows use the eager worst case on every tier, because the table's tiers may only grow with speed. ## Tests - New `tests/test_diffusion_activation_factors.py` (CPU). Each listed family resolves to its measured row, tiers only grow with speed, base >= Klein, and `_calibrated_activation` returns the row on NVIDIA for the real family objects. On main 8 of 13 fail, all MOSS-Image and FLUX.3 base cases. Qwen-Image 2.1 and FLUX.3 Klein already pass on main. - `test_diffusion_auto_placement.py`, using the Kaggle numbers on 2x T4 (Z-Image denoiser 11739 MiB, VAE 211 MiB, encoder 7672 MiB): - the flat 6963 MiB still declines the layer split (the same message); - with Z-Image's measured row the split is accepted across both cards, and each card's requirement fits its limit (fails on main); - the activation estimate scales with resolution (6963 MiB at 1024, 3916 MiB at 768). - `test_diffusion_flux3.py`: the two tests that pinned "base unmeasured, flat estimate" now pin the base row. - Planner, placement and family suites (memory, multigpu, multigpu wiring, auto placement, auto GPU, layer split plan and layer split, ROCm APU reserve, DGX Spark, auto policy, learned peaks, dense tier activation, stream residency, fp8 stored label, measured placement and measured placement dense, MPS / Metal budget, calibrated activation, flux3, MOSS-Image, image decode phase, `test_diffusion_backend.py`): main 1931 passed, 1 failed. This branch has the same single failure (`test_mirrored_base_still_trips_the_flux2_shape_guard`, no `gguf` module in this venv, fails on both) once the two pinned flux3 tests are updated. - Planner prediction vs a real render, MOSS-Image SFT, default tier, bf16, 1024x1024, on a B200 capped to a 42 GiB card (free reading and caching allocator): | tree | plan | predicted activations (MiB above weights) | measured render peak above weights (render 1 / 2) | resident weights | OOM | |---|---|---|---|---|---| | main | `group`, encoder streamed | 8192 (flat) | 2807 / 2700 (encode phase 1940) | 9963 MiB | no | | this branch | `none`, everything resident | 4399 (calibrated row, 1.2 margin) | 2807 / 2700 | 25101 MiB | no | The prediction covers the measured peak with 1.57x headroom, against 2.9x for the flat estimate. The peak, 25101 + 2807 MiB = 27.3 GiB, stays inside the 42 GiB cap. Images are 4-step smoke renders, so the comparison is placement only, not speed. The same capped run at 36 GiB gives `group` on both trees (the full set does not fit there). ## Not covered - int8 / fp8 MOSS-Image and FLUX.3 base denoisers: the prequantised files were not in the local cache, so only bf16 ran. The rows keep the eager worst case, and for the base Klein's measured int8 / fp8 denoise. - NVIDIA B200 only. Like every row in this table, the rows only apply on NVIDIA with a sub-quadratic attention kernel. ROCm, MPS and math-only attention keep the flat estimate. - Qwen-Image 2.1 is unchanged: it already had its own row on main. - The 2x T4 Z-Image split is proven by the unit case only. It was not re-run on Kaggle. The Z-Image row was measured at B200 bf16. On T4 the split takes it only where `_calibrated_activation` already accepts Z-Image (fp16 kept by its guard, sub-quadratic SDPA confirmed). Whether one-card host-RAM streaming still gets SIGKILLed on a 31 GB host is a separate issue.
…nslothai#14929) ## Problem `MOSSImageTransformer._time_modulation` (unslothai#14552) builds the timestep sinusoid in float64 on the model's device: ```python freq = 10000 ** (-torch.arange(half, device = times.device, dtype = torch.float64) / half) phase = times.double()[:, None] * freq ``` MPS has no float64 (https://docs.pytorch.org/docs/main/notes/mps.html, double precision types), and `PYTORCH_ENABLE_MPS_FALLBACK` does not cover dtypes, so on Apple Silicon the first denoise step of a MOSS-Image safetensors render raises. Studio routes MOSS safetensors on MPS to this in-tree pipeline (sd.cpp on MPS is opt-in through `UNSLOTH_DIFFUSION_SD_CPP_MPS`), so every Mac render of it fails. Intel Arc XPUs have no native float64 either. ## Change The sinusoid is built on the model's device on CUDA, CPU and XPUs that report `has_fp64` (Data Center GPU Max), exactly as before (bitwise the reference there), and on the CPU everywhere else (MPS, Arc XPUs), then moved over as float32. The timestep is moved to the CPU before the float64 cast, since a dtype-converting copy out of MPS into a float64 CPU tensor fails or, on torch 2.14, writes nothing (pytorch/pytorch#197715). The value fed to the time MLP is float32 in every case, as in the reference. ## Tests `studio/backend/tests/test_diffusion_moss_image.py`: - new `test_timestep_sinusoid_keeps_float64_off_mps`: MPS and an XPU without float64 map to the CPU; CUDA, CPU and an XPU with float64 stay in place. Fails on main, passes here. - the existing bitwise-parity tests against the reference forward and pipeline still pass. `test_diffusion_moss_image.py` + `test_diffusion_moss_fused.py`: 49 passed, 1 skipped on this branch (CPU). Not covered: a real Apple Silicon render; this host has no Mac. The MPS failure is from the code path and the PyTorch MPS dtype documentation, not a run.
Summary
Adds MOSS-Image (
OpenMOSS-Team/MOSS-Image-SFTandOpenMOSS-Team/MOSS-Image-Base) to Unsloth Studio as an image family.The official repos ship the transformer and scheduler as remote code (
model_index.jsonpoints both at the repo'spipeline_moss_image.py), and diffusers has no MOSS-Image pipeline. Studio never runs repo code, so this PR ports the model in tree (core/inference/diffusion_moss_image.py, from the Apache-2.0 reference) and assembles the pipeline per component from safetensors and JSON only. Notrust_remote_code, nocustom_pipeline.What is supported
begin_load/generate), from a repo id or a local diffusers folder (detected frommodel_index.json_class_name).MOSSImageTransformer(state-dict keys identical to the repo's), the Qwen3.5-9B text encoder (transformers.Qwen3_5Model, vision tower dropped at load), the FLUX.2 small-decoder VAE (diffusers.AutoencoderKLFlux2) and the tokenizer. SFT and Base share every file except the transformer shards (checked by sha256 on the Hub), so one family row serves both.unsloth/*, as for FLUX.3: the upstream diffusers files (model_index.json,pipeline_moss_image.py,scheduler/,text_encoder/,tokenizer/,transformer/,vae/) sit byte for byte inunsloth/MOSS-Image-SFT-FP8andunsloth/MOSS-Image-Base-FP8beside the quantised files (_UNGATED_MIRROR_PAIRS,_ARTIFACT_MIRRORS). TheOpenMOSS-Teamids stay the family's base ids and provenance; a user's complete cached upstream snapshot keeps being used, as for every ungated mirror.in_tree_pipeline_refusal).conv1d.weightstraight into the causal-conv kernel without calling the module, so leaf-level group offload never onloaded it (device mismatch on the first prompt). A pre/post hook on each gated-delta layer now onloads and offloads that conv; leaf-level offload output is bit-identical to resident with and without CUDA streams.Defaults vs ComfyUI
sgm_uniform, shift 5sgm_uniform, shift 5 (default)UNSLOTH_MOSS_SIGMAS=training_grid)randnfrom the seedrandnfrom the seedrandn_tensorwith the caller's generatorfp16_incompatible)Numerics
pipeline_moss_image.py, tiny random model (CPU): sigmas, timesteps, prompt encoding, forward with skip layers, masked batch of 2, full pipeline with CFG + skip 22, no CFG, plain CFG, extra SLG, 2 images per promptSpeed and memory
Exclusive B200, 1024x1024, 30 steps, CFG 3, bf16, transformer quant off, resident placement. Three rounds per arm, each a fresh process, arms interleaved; s/step is the median of warm steps (scheduler-step deltas, synced). Prompt 1 is the first render, prompt 2 a new prompt length, prompt 3 prompt 1 again.
2.26x faster per step at the default tier, 0.83 GiB lower peak. The first render in a fresh process takes 17 to 43 s at the default tier (compile, partly served from the compile cache) against 9 to 17 s eager; later renders take about 2.9 s for 30 steps against 6.2 s.
Compile, graphs and prompt lengths (real weights, 1024x1024, 50 steps, 14 prompts of 8 to 18 words with seeds 1001 to 3002 and CFG 2.5 / 3 / 4.5, then prompt 1 again):
_Block,_TextBlock)The text length is armed dynamic from the first compile (
PROMPT_LENGTH_POLICY/_FAMILY_SOURCES), so a new prompt length never recompiles, and under the existing first-render-only graph policy (#14387) a new length runs compiled without a graph. The two cost the same here (0.0872 to 0.0875 s/step either way), so the policy gives nothing up on MOSS. Same counts under group offload (the denoiser streamed per block, the encoder per leaf).Accuracy against the eager bf16 port (12 prompts: 8 calibration + 4 held out, 1024x1024, 50 steps, same seeds, LPIPS alex):
Swapping only the attention kernel moves a 50-step CFG render further than the compiled blocks do, so the compiled default sits inside the kernel-noise floor of this model.
What each lever is and what it gave:
_repeated_blocks = ["_Block", "_TextBlock"]; 2.26x per step, 0 breaks, 0 recompilesUNSLOTH_MOSS_TEXT_CACHE=0; off under offload hooksencode_prompt(the empty negative is cached too)Quantised builds
Keep-list for every scheme (
_MOSS_IMAGE_QUANT_KEEP): the wholetext_embedder(projection and its 2 refiner blocks),time_embeddingand the AdaLN modulations (shared_block_modulation,video_head_modulation) stay bf16; the 252 block Linears (proj.q/k/v/o/ffn_up_gate/ffn_down) quantise.video_embedderandfinal_linear_videosit under the 512-feature floor and stay bf16 too. int8 rotates those 252 Linears with ConvRot at group 256 (int8_convrot, on by default). These are the settings the hosted files were built with, so a runtime quantise and a hosted file build the same module layout (renders compared below).unsloth/MOSS-Image-SFT-FP8MOSS-Image-SFT-INT8-ConvRot.safetensors,MOSS-Image-SFT-INT8.safetensors,MOSS-Image-SFT-FP8.safetensors,MOSS-Image-SFT-text_encoder-INT8-ConvRot.safetensorsunsloth/MOSS-Image-Base-FP8MOSS-Image-Base-INT8-ConvRot.safetensors,MOSS-Image-Base-INT8.safetensors,MOSS-Image-Base-FP8.safetensorstransformer_quantunset): the bf16 DiT while it fits (auto_bf16_when_resident, the small-DiT rule FLUX.2-klein, Z-Image and FLUX.3-klein follow). When bf16 would offload, auto falls back to INT8-ConvRot, then plain INT8 from the same repo. An explicit precision is honoured.FamilyProfile.auto_scheme_skip) and stay explicit picks. The quant track measured fp8 at LPIPS 0.163 against 0.058 for INT8-ConvRot.text_encoder_quantunset): the int8 ConvRot encoder. ComfyUI's official MOSS-Image templates (SFT and Base) loadqwen3.5_9b_w4a8_gptq(4-bit weights) with anint8_convrotDiT. Their encoder is not bf16 or fp8, and int8 weights are the nearest class at higher precision.text_encoder_quant=nonekeeps the dense bf16 encoder.moss-image-base, which the quant tables now answer to (quant_names). SFT and Base ship identicaltext_encoder/shards, so Base reuses the SFT encoder file through a_TE_EQUIVALENT_BASESgroup.Qwen3_5Model) with the MLP and full-attention projections int8 (128 Linears), 11.49 GB against 16.79 GB dense; budgeted at 0.69 of dense. The vision tower in the file is dropped at load and the gated-delta offload guard is installed on a handed-in encoder as on a dense one.Real weights, hosted files served through
UNSLOTH_DIFFUSION_PREQUANT_MIRROR(measured before the upload), 1024x1024, 50 steps, speed default, 14 prompts (seeds 1001 to 3002, CFG 2.5 to 4.5), B200 shared card:transformer_quant=off(auto), resident) + int8 encoder (128 int8 Linears)Int8TensorLinears, fingerprint 252 of 252, ConvRot on 252) + int8 encoder (128 int8 Linears, vision tower dropped)MOSS-Image-Base-INT8-ConvRot.safetensors+ the SFT encoder file--vram-cap-gib 24, 2 prompts)transformer_quant=int8(auto), 252Int8Tensor), int8 encoder streamed by group offloadtransformer_quant=fp8, hosted file (2 prompts)MOSS-Image-SFT-FP8.safetensors(252Float8TensorLinears) + int8 encoderRuntime against hosted (same tree, encoder bf16 in both): 11 of 14 renders pixel-identical, the other 3 at LPIPS 0.003 mean / 0.028 max. An A/A repeat of the hosted arm is bit-identical (14 of 14), so that small gap is real, not run-to-run noise: the runtime quantise and the builder agree on the spec but not on every rounded code. Both sit at the same distance from the eager bf16 port.
Every quantised arm: 2 dynamo graphs and 2 CUDA graph captures on the first render, then 0 new graphs, 0 graph breaks, 0 recompiles and 0 captures on every later prompt. Before this PR's refiner fix the first render compiled a third graph: the pipeline refines the text once per render outside
forward, where Studio's per-forward prompt-length arming does not reach, so the text block specialised on the cond length and recompiled at the uncond one. The refiner inputs now carry a dynamic-length hint. It moves the compiled kernels for the refiner a little: 8 of 14 renders pixel-identical before and after, the rest LPIPS 0.006 mean / 0.040 max, and the distance to the eager port is unchanged (0.049 both). bf16 keeps its 2 graphs and 0 recompiles.GGUF through stable-diffusion.cpp
MOSS GGUFs go to the native engine. The family row carries the sd.cpp assets:
vae/diffusion_pytorch_model.safetensors, read from its byte-identical copy inunsloth/MOSS-Image-SFT-FP8. It is the FLUX.2 small decoder, not FLUX.2-dev's VAE, and sd.cpp detects its layout itself.unsloth/Qwen3.5-9B-GGUFQwen3.5-9B-Q8_0.ggufon--llm.MOSS-Image.Tokenizer plumbing:
tokenizer.jsonon--tokenizer(taken fromunsloth/MOSS-Image-SFT-FP8, byte-identical to the upstream file).SdCppModelFilesgains an optionaltokenizerfield, and the cli, server and video command builders pass it when it is set.sd_cpp_tokenizer(repo, file) adds it to the fetched assets and to the delete guard's companion files. Every other family leaves itNone, so their commands are unchanged.Routing (new
native_transformer_files_onlyflag in place ofpipeline_only):family_buildable_heregives the picker the same answer.UNSLOTH_DIFFUSION_ENGINE=diffusersorUNSLOTH_DIFFUSION_SD_CPP=0is refused byvalidate_load_requestbefore eviction..safetensorsfiles are not offered as single-file picks.A manual diffusers
GGUFLinearload was not added: the native route covers GGUF more simply.End to end:
SdCppDiffusionBackend(B200, localUD-Q4_K_XLSFT GGUF, master-982 build viaSD_CLI_PATH/SD_SERVER_PATH, 512x512, 20 steps, CFG 3).sd_cppon a CUDA host.MOSS-Image requires the official Qwen3.5 tokenizer.json; pass --tokenizer FILE.ComfyUI and comfy-kitchen levers
Checked against ComfyUI master (fetched read-only; no MOSS changes after b1a247c9:
comfy/ldm/moss_image,model_management,ops,model_prefetch,quant_opsunchanged) and comfy-kitchen 0.2.39 (the latest release). The MOSS defaults Studio uses (shift 5 / multiplier 1, bf16 or fp32 only, FLUX.2 latents, cond and uncond as separate forwards at their own text lengths, uncond skip of block 22, empty negative) are unchanged upstream.All timings: exclusive B200, 1024x1024, 30 steps, CFG 3, speed default (regional compile + CUDA graphs), fresh process per arm, s/step = median warm step over a first prompt, a new prompt length and the first prompt again. Every arm: 0 recompiles, 0 graph breaks and 0 CUDA graph captures on prompts 2 and 3.
proj.qkv, one GEMM + one act quant)_int_mm(torchao's eager math)rms_rope_split_half(q/k RMSNorm + split-half RoPE)UNSLOTH_DIFFUSION_MOSS_QK_ROPE=1rms_adaln(norm weight folded into the scale) + in-placeaddcmul_gated residualffn_downact quant (linear_input_act(..., "situ"))rotq_i8(Studio's own fused rotation + quant,UNSLOTH_DIFFUSION_INT8_ROTQUANT=1on B200)comfy.model_prefetch, lowvram)optimized_attentionpicks PyTorch SDPA there too)concat_condwideningvideo_embedder)Low-VRAM bf16 is unchanged: the dense default tier has no measured-peak table for any family, so bf16 on a 16 GiB card still streams everything (0.410 s/step, peak 2.9 GiB; on 24 GiB the denoiser stays resident with the encoder streamed, 0.0864 s/step, peak 12.5 GiB).
Multi-GPU (Kaggle T4x2, tiny model)
Run on a Kaggle T4x2 kernel (two 15 GB T4s), tiny random MOSS-Image pipeline, 256x256, 4 steps, 4 prompts with different lengths, seeds and CFG; each arm a fresh process through
DiffusionBackend.begin_load/generate. torch 2.11, transformers 5.20.2, diffusers 0.41.0.UNSLOTH_DIFFUSION_MULTIGPU=force(component split)UNSLOTH_DIFFUSION_CFG_PARALLEL=forceDiffusion has no layer split (that lever is llama.cpp only), so it was not run. A real-weight 2xT4 render did not run either: the INT8 / FP8 builds exist but are not uploaded, so a Kaggle kernel cannot fetch them, and bf16 (10.2 GB DiT + 15.9 GB encoder) does not fit two 15 GB T4s without offload.
Tests
tests/test_diffusion_moss_image.py(35 tests, CPU): bitwise parity against the reference file kept as test data (tests/data/moss_image/pipeline_moss_image_reference.py.txt, unmodified Apache-2.0 copy), scheduler parity and ComfyUIsgm_uniformsigmas, seed noise, step callback / interrupt, skip-layer kwargs reaching the transformer as a tuple, the forward taking no host sync without a mask, family detection for both repos and an opaque local folder, defaults, trusted repos, the transformers >= 5.3 gate, prompt-length policy, in-tree class resolution. Skips without diffusers / transformers.tests/test_diffusion_moss_fused.py(8 tests; the kernel test needs CUDA): fused QKV equals the three projections and drops back when a projection is replaced, the int8 runner reaches all six block Linears, bf16 keeps three GEMMs, the RoPE kernel is opt-in and matches the eager ops, kill switch and offload leave the blocks alone, registry entry.tests/test_sd_cpp_moss_image.py(17 tests, CPU):--tokenizerin all three builders, and absent when unset;tests/test_diffusion_moss_image_quant.py(18 tests, CPU): keep-list and ConvRot spec, exclude tables for both recorded family names, hosted file names for SFT and Base (rotated first, plain int8 behind, never the other base's file), fp8 / mxfp8 out of the automatic order on every tier while an explicit fp8 is not denied, the text-encoder file, equivalence and budget, the absent-repo fallback (offline, empty cache: no seed, dense encoder), the in-tree class reaching the denoiser seed, the handed-in encoder's vision drop and offload guard, the tokenizer class lookup, the compute-dtype cast, the measured-peak seed.test_image_fetch_ids_unsloth.py(newtest_moss_image_components_come_from_its_fp8_repos; the MOSS pairs join the in-repo mirror round trip, and the fetch-id guard that failed on MOSS now passes),test_artifact_mirrors.py(both -FP8 repos are artifact mirrors, so a pipeline pick of either id is refused naming its base), the mirror-table counts intest_diffusion_backend.pyandtest_video_unsloth_mirrors.py, and the sd.cpp VAE / tokenizer ids intest_sd_cpp_moss_image.py.test_diffusion_prompt_length_policy.py,test_diffusion_autoopt_parity.py(+ fixture rows for the new family only), the family data freeze fixture,image-generation-defaults.test.ts.test_mirrored_base_still_trips_the_flux2_shape_guard, noggufmodule in that environment) fails the same way on main.Not verified
randn), not by a side-by-side render.low_vramtier did not choose streaming on this host's free memory, so that exact path is unproven end to end._MEASURED_IMAGE_ACTIVATION_MIB) were not added; the planner uses its flat estimate. Measured here: 3.5 GiB above the resident weights at 1024x1024, the fp32 VAE decode being the worst phase.UNSLOTH_DIFFUSION_PREQUANT_MIRROR. Against the hosted repos (checked with a token while they were private; all four now answer a token-less request), the PR's own resolvers, download plan and fetch paths were checked: every quant and mirrored upstream file (42 mirrored files, size and sha256 against the pinned upstream commits), the bf16 download plan of both bases (20 folder files, 27.22 GB, no root quant files), the tokenizer, configs and VAE loaded from the mirrors, and the sd.cpp VAE and tokenizer fetch. A full bf16 load from a fresh cache through the mirrors was not run. If the mirrors are unreachable, the redirect has no fallback to the upstream ids.node_modules); the catalog check script passed.FamilyProfile.auto_bf16_when_residentfield under its own reason string. The small-DiT defaults change (FLUX.2-klein, Z-Image, FLUX.3-klein) edits the sametest_the_bf16_rule_names_only_the_measured_familiesparametrize list and the family freeze fixture, so whichever lands second needs a trivial merge there.