Skip to content

Studio: MOSS-Image (in-tree port, quantised builds, GGUF through stable-diffusion.cpp) - #14552

Merged
danielhanchen merged 39 commits into
mainfrom
studio-moss-image
Oct 23, 2026
Merged

danielhanchen merged 39 commits into
mainfrom
studio-moss-image

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds MOSS-Image (OpenMOSS-Team/MOSS-Image-SFT and OpenMOSS-Team/MOSS-Image-Base) to Unsloth Studio as an image family.

The official repos ship the transformer and scheduler as remote code (model_index.json points both at the repo's pipeline_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. No trust_remote_code, no custom_pipeline.

What is supported

  • Text to image on both repos, through the normal Images load path (begin_load / generate), from a repo id or a local diffusers folder (detected from model_index.json _class_name).
  • Components: the in-tree 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.
  • Every component is fetched from 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 in unsloth/MOSS-Image-SFT-FP8 and unsloth/MOSS-Image-Base-FP8 beside the quantised files (_UNGATED_MIRROR_PAIRS, _ARTIFACT_MIRRORS). The OpenMOSS-Team ids stay the family's base ids and provenance; a user's complete cached upstream snapshot keeps being used, as for every ungated mirror.
  • Needs transformers >= 5.3 for the text encoder. Older transformers hides the family from the picker and a load is refused with a clear message (in_tree_pipeline_refusal).
  • Memory modes: resident, model offload and group offload (block-level denoiser, leaf-level encoder streaming). Qwen3.5's gated-delta layers read conv1d.weight straight 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.
  • Quantised builds: INT8-ConvRot, INT8 and FP8 denoisers for SFT and Base and an int8 ConvRot text encoder shared by both, seeded into the per-component assembly (section below). When the hosted repos cannot be reached, a load quantises at runtime with the same spec.
  • GGUF on the native stable-diffusion.cpp engine (section below). A MOSS GGUF loads only there, on every backend, from a build that has MOSS (upstream master-975 or newer).
  • Not in this PR: single-file safetensors transformer picks and GGUF through diffusers (see the GGUF section), LoRA, image conditioning (the released pipeline is text to image only).

Defaults vs ComfyUI

knob ComfyUI (MOSS workflow / native support) Studio reference pipeline
size 1024x1024 1024x1024 1024x1024
steps / CFG 50 / 3.0 50 / 3.0 50 / 3.0
sampler euler Euler (flow matching) Euler
sigmas sgm_uniform, shift 5 sgm_uniform, shift 5 (default) shift 5 snapped to the 1000-point training grid (UNSLOTH_MOSS_SIGMAS=training_grid)
guidance trick SkipLayerGuidanceDiTSimple, block 22, uncond only, 0..1 uncond skips block 22 uncond skips block 22
negative prompt empty empty empty
seed noise CPU fp32 randn from the seed CPU fp32 randn from the seed fp32 randn_tensor with the caller's generator
DiT / text encoder dtype bf16 (fp16 not supported) bf16, fp16 promoted (fp16_incompatible) bf16
VAE decode fp32 fp32 fp32

Numerics

check result
port vs the repo's 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 prompt bit-identical in every case
port vs the official pipeline, real SFT weights, 1024x1024, 50 steps, 4 prompts, same noise (B200) bit-identical, 4 of 4
Studio speed off vs the plain eager port, real weights, 12 prompts bit-identical, 12 of 12
eager port A/A (same prompt twice in one process) bit-identical

Speed 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.

arm s/step, prompt 1 (3 rounds) s/step, new length s/step, repeat peak allocated
speed off (the eager port) 0.1966 / 0.1974 / 0.1973 0.1981 / 0.1973 / 0.2039 0.1966 / 0.1974 / 0.1968 28.09 GiB
speed default (regional compile + CUDA graphs + cuDNN attention) 0.0874 / 0.0874 / 0.0871 0.0875 / 0.0872 / 0.0873 0.0875 / 0.0870 / 0.0874 27.26 GiB

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):

prompt 1 prompts 2 to 14 prompt 1 again
dynamo graphs compiled 2 (_Block, _TextBlock) 0 0
graph breaks 0 0 0
recompiles 0 0 0
CUDA graph captures 2 (cond and uncond lengths) 0 0

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):

arm LPIPS mean LPIPS max
speed off 0 (12 of 12 pixel-identical) 0
speed default (compile + graphs + cuDNN attention) 0.020 0.052
speed default with native SDPA, group offload 0.026 0.098
speed eager (cuDNN attention, no compile), for scale 0.032 0.157

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:

lever status
regional compile _repeated_blocks = ["_Block", "_TextBlock"]; 2.26x per step, 0 breaks, 0 recompiles
dynamic text length on from day one; 0 recompiles across 14 prompt lengths
CUDA graphs whole step, cond and uncond; skip layers passed as a tuple so the uncond call is capturable; the forward takes no host sync without a mask
attention backend attention goes through diffusers' dispatcher, so Studio's backend pick (cuDNN on NVIDIA) reaches it
text refiner cache the 2-block text refiner runs once per prompt per render, not per step and branch; bit-identical (tiny model), kill switch UNSLOTH_MOSS_TEXT_CACHE=0; off under offload hooks
RoPE tables built once per (size, prompt length) instead of per forward; bit-identical. Inside the compiled block inductor fuses the q/k RMSNorm and the split-half rotation
prompt-embedding cache Studio's prompt cache wraps encode_prompt (the empty negative is cached too)
cudnn.benchmark off for this family: on the fp32 VAE decode its plan search took 254 s and a 73 GiB transient workspace on the first 1024x1024 decode, then picked a 4x slower plan (0.34 vs 0.08 s warm)
offload resident, group and model offload render pixel-identical to resident in eager mode (tiny model)
CFG batching not done: cond and uncond run at different text lengths with different RoPE positions (the image sits after the text on the f axis), so batching needs padding plus masks in both the refiner and the joint blocks and cannot be bit-identical; ComfyUI also runs the branches separately. A hand-written fused RoPE kernel was not added either, since the compiled path already fuses it

Quantised builds

Keep-list for every scheme (_MOSS_IMAGE_QUANT_KEEP): the whole text_embedder (projection and its 2 refiner blocks), time_embedding and 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_embedder and final_linear_video sit 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).

repo files
unsloth/MOSS-Image-SFT-FP8 MOSS-Image-SFT-INT8-ConvRot.safetensors, MOSS-Image-SFT-INT8.safetensors, MOSS-Image-SFT-FP8.safetensors, MOSS-Image-SFT-text_encoder-INT8-ConvRot.safetensors
unsloth/MOSS-Image-Base-FP8 MOSS-Image-Base-INT8-ConvRot.safetensors, MOSS-Image-Base-INT8.safetensors, MOSS-Image-Base-FP8.safetensors
  • Default denoiser (GPU, transformer_quant unset): 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.
  • fp8 and mxfp8 are removed from the family's automatic order (new FamilyProfile.auto_scheme_skip) and stay explicit picks. The quant track measured fp8 at LPIPS 0.163 against 0.058 for INT8-ConvRot.
  • Default text encoder (text_encoder_quant unset): the int8 ConvRot encoder. ComfyUI's official MOSS-Image templates (SFT and Base) load qwen3.5_9b_w4a8_gptq (4-bit weights) with an int8_convrot DiT. Their encoder is not bf16 or fp8, and int8 weights are the nearest class at higher precision. text_encoder_quant=none keeps the dense bf16 encoder.
  • Base: its own denoiser builds (variant repo rows; any other scheme on Base quantises Base's weights, never SFT's file). The Base files record family moss-image-base, which the quant tables now answer to (quant_names). SFT and Base ship identical text_encoder/ shards, so Base reuses the SFT encoder file through a _TE_EQUIVALENT_BASES group.
  • Text encoder: Qwen3.5-9B (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.
  • Hosted repos absent or unreachable: the seed finds nothing, the released denoiser is loaded and quantised at runtime (INT8-ConvRot, same spec), and the automatic text-encoder pick keeps the dense bf16 encoder; an explicit request is reported as falling back. Covered by tests with an empty offline cache.

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:

arm what loaded LPIPS vs eager bf16 port, mean / max peak allocated
bf16 (transformer quant off) dense 0.025 / 0.156 27.26 GiB
SFT default (new): bf16 DiT kept by auto, hosted int8 encoder dense DiT (269 bf16 Linears, transformer_quant=off(auto), resident) + int8 encoder (128 int8 Linears) 0.036 / 0.164 22.33 GiB
SFT INT8-ConvRot (previous default; now the offload fallback), hosted files INT8-ConvRot DiT (252 Int8Tensor Linears, fingerprint 252 of 252, ConvRot on 252) + int8 encoder (128 int8 Linears, vision tower dropped) 0.049 / 0.136 17.90 GiB
SFT, hosted DiT, encoder pinned bf16 INT8-ConvRot DiT 0.049 / 0.137 22.83 GiB
SFT, no hosted files, encoder pinned bf16 runtime INT8-ConvRot ("ConvRot group 256 on 252 int8 linears") 0.049 / 0.137 22.83 GiB
Base INT8-ConvRot (the previous default), hosted files (2 prompts) MOSS-Image-Base-INT8-ConvRot.safetensors + the SFT encoder file not scored (no Base eager reference) 17.90 GiB
SFT default on a simulated 24 GiB card (--vram-cap-gib 24, 2 prompts) bf16 would offload, so auto picks INT8-ConvRot (transformer_quant=int8(auto), 252 Int8Tensor), int8 encoder streamed by group offload not scored (load-and-render check) 17.90 GiB
SFT, explicit transformer_quant=fp8, hosted file (2 prompts) MOSS-Image-SFT-FP8.safetensors (252 Float8Tensor Linears) + int8 encoder not scored (load-and-render check) 17.90 GiB

Runtime 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: the MOSS repo's own vae/diffusion_pytorch_model.safetensors, read from its byte-identical copy in unsloth/MOSS-Image-SFT-FP8. It is the FLUX.2 small decoder, not FLUX.2-dev's VAE, and sd.cpp detects its layout itself.
  • Text encoder: unsloth/Qwen3.5-9B-GGUF Qwen3.5-9B-Q8_0.gguf on --llm.
  • Arch marker: MOSS-Image.
  • No flow-shift override: sd.cpp's MOSS default of 5 is the reference recipe.

Tokenizer plumbing:

  • sd.cpp's MOSS conditioner refuses to run without the official Qwen3.5 tokenizer.json on --tokenizer (taken from unsloth/MOSS-Image-SFT-FP8, byte-identical to the upstream file).
  • SdCppModelFiles gains an optional tokenizer field, and the cli, server and video command builders pass it when it is set.
  • The family's new sd_cpp_tokenizer (repo, file) adds it to the fetched assets and to the delete guard's companion files. Every other family leaves it None, so their commands are unchanged.

Routing (new native_transformer_files_only flag in place of pipeline_only):

  • Diffusers has no single-file loader for the in-tree port, so the router sends a MOSS GGUF native on GPU hosts too.
  • The architecture marker gates the native route. A build older than master-975 is refused with a reason before anything unloads, rather than handed to diffusers.
  • family_buildable_here gives the picker the same answer.
  • An explicit diffusers pick, UNSLOTH_DIFFUSION_ENGINE=diffusers or UNSLOTH_DIFFUSION_SD_CPP=0 is refused by validate_load_request before eviction.
  • Loose MOSS .safetensors files are not offered as single-file picks.

A manual diffusers GGUFLinear load was not added: the native route covers GGUF more simply.

End to end:

  • Setup: Studio's own SdCppDiffusionBackend (B200, local UD-Q4_K_XL SFT GGUF, master-982 build via SD_CLI_PATH / SD_SERVER_PATH, 512x512, 20 steps, CFG 3).
  • Routing: predicted sd_cpp on a CUDA host.
  • Load: in server mode.
  • Render: a coherent image with the prompted sign text (peak 12 GB).
  • Base arm (same run, tokenizer asset stripped): sd-server fails, and the sd-cli fallback exits 1 with 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_ops unchanged) 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.

lever (ComfyUI / kitchen) Studio s/step before -> after peak accuracy (LPIPS vs eager port, 14 prompts, 50 steps)
fused QKV (repacked proj.qkv, one GEMM + one act quant) on for int8: codes and per-row scales concatenate, ConvRot parts share one rotation; parts become views (no extra memory) INT8-ConvRot 0.0769-0.0778 -> 0.0721-0.0727; plain INT8 0.0700 -> 0.0673-0.0678 unchanged int8: 0.049 before and after (base vs fused A/A is bit-identical run to run)
same, bf16 off: one fused GEMM measured 0.0876-0.0880 vs 0.0881-0.0886 (inside the A/A spread) - - 13 of 14 pixel-identical to three GEMMs
int8 act quant (kitchen int8 kernels) on: every int8 block Linear runs Studio's probed Triton act quant and _int_mm (torchao's eager math) included above (runner alone: 0.0752) unchanged as above
rms_rope_split_half (q/k RMSNorm + split-half RoPE) new one-pass Triton kernel (q, k, v read once, written in the attention layout), every eager bf16 rounding kept, probed per device; opt-in UNSLOTH_DIFFUSION_MOSS_QK_ROPE=1 bf16 0.0879-0.0883 -> 0.0871-0.0876 (0.7%); INT8-ConvRot 0.0723-0.0726 -> 0.0722 unchanged bf16 0.025 -> 0.026, int8 0.049 -> 0.056: inside the kernel floor, no better, so off
rms_adaln (norm weight folded into the scale) + in-place addcmul_ gated residual not added: the compiled block already emits one fused reduction kernel per norm + modulation site (both sites together ~1.4 ms of a ~40 ms forward in the profile), and Studio measured in-place addcmul neutral before; the fold also changes the reference's rounding - - -
SiTU folded into the int8 ffn_down act quant (linear_input_act(..., "situ")) not added: plain INT8 already compiles SiTU + act quant into one kernel; INT8-ConvRot (the quantised default) must rotate the SiTU output before quantising, so nothing can fold. A cheaper SiTU formulation (sigmoid form) was 16% faster on the kernel alone, about 1% of a step, and changes bits, so not taken - - -
rotq_i8 (Studio's own fused rotation + quant, UNSLOTH_DIFFUSION_INT8_ROTQUANT=1 on B200) stays off on sm100 (its existing arch gate) 0.0721-0.0727 -> 0.0818-0.0830 (slower) - -
offload prefetch / partial load (comfy.model_prefetch, lowvram) Studio's group offload already prefetches blocks on a side stream and keeps whole groups resident within the room; what was missing was MOSS's measured activation peak, so the flat 8 GiB estimate streamed the 5 GB int8 denoiser on a 16 GB card. Seeded (2905 MiB worst phase) card capped to 16 GiB (planner + allocator), INT8-ConvRot + int8 encoder: 0.241 -> 0.0786; 13 GiB 0.0766; 12 GiB 0.0766 (resident 0.0722) 2.9 -> 11.2 GiB (16 GiB cap), no OOM placement only
attention backend already the same choice: SDPA routed to cuDNN on B200 (optimized_attention picks PyTorch SDPA there too) - - -
fp64 RoPE omegas not adopted: ComfyUI builds the omegas in fp64; Studio keeps the reference's CPU fp32 bands (the training construction), which is what the parity tests pin - - -
SLG under compile already: the uncond skip of block 22 is a tuple kwarg, the compiled blocks are simply not called, 0 recompiles - - -
control adapters (concat_cond widening video_embedder) later item: no control checkpoint is released - - -

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.

arm placement images vs one card
two cards selected, automatic CFG-parallel armed: uncond branch on a replica on cuda:1, 12 of 12 multi-branch steps in parallel, replica built in 0.07 s pixel-identical, 4 of 4
UNSLOTH_DIFFUSION_MULTIGPU=force (component split) text encoder and VAE on cuda:1, DiT on cuda:0 pixel-identical, 4 of 4
component split + UNSLOTH_DIFFUSION_CFG_PARALLEL=force split as above; CFG-parallel declined (cuda:1 holds the split's components) pixel-identical, 4 of 4
component split, speed default (compile + CUDA graphs) split as above; CFG-parallel declined (the graphed forward is an instance override) pixel-identical to one-card speed default, 5 of 5; 0 recompiles, 0 graph breaks, 0 captures on prompts 2 to 4

Diffusion 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 ComfyUI sgm_uniform sigmas, 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):
    • the family row's sd.cpp assets, and that only MOSS sets a tokenizer or native-only files;
    • asset specs and the companion delete guard include the tokenizer;
    • --tokenizer in all three builders, and absent when unset;
    • the marker gate against fake binaries;
    • native routing on CUDA and CPU;
    • refusal (not a diffusers fallback) for a pre-975 build;
    • refusal of an explicit diffusers pick and of the two env disables;
    • route validation passing a GGUF native can take and refusing one it cannot;
    • single-file refusal and the loose-file listing.
  • 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.
  • Mirror guards: test_image_fetch_ids_unsloth.py (new test_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 in test_diffusion_backend.py and test_video_unsloth_mirrors.py, and the sd.cpp VAE / tokenizer ids in test_sd_cpp_moss_image.py.
  • Updated: 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.
  • Ran: the new file plus prompt-length policy, autoopt parity, family freeze, more families, flow shift, auto policy, dynamic text, hub metadata, backend and diffusers repair suites. The only failure (test_mirrored_base_still_trips_the_flux2_shape_guard, no gguf module in that environment) fails the same way on main.

Not verified

  • ComfyUI itself was not run (no Comfy-Org files); the defaults come from the MOSS ComfyUI workflow and ComfyUI's native MOSS support code, and the seed noise matches ComfyUI's draw by construction (CPU fp32 randn), not by a side-by-side render.
  • Base ran only with its hosted INT8-ConvRot file and the SFT encoder file (2 prompts, load-and-render, not scored); Base in bf16 was not rendered. It differs from SFT only in the transformer shards (sha256 on the Hub).
  • Timing is B200 only. Consumer cards, ROCm, Apple and CPU did not run. The eager speed tier measured 0.49 s/step on a shared card (not exclusive), slower than speed off there; it was not timed on an exclusive card.
  • Low-VRAM streaming of the encoder was checked on the tiny model with diffusers' leaf-level group offload directly (bit-identical with and without CUDA streams) and on real weights through Studio's group offload; Studio's low_vram tier did not choose streaming on this host's free memory, so that exact path is unproven end to end.
  • Under model offload (tiny model) the second prompt recorded one new CUDA graph, which is the existing offloaded-key behaviour of the graph layer, not specific to this family.
  • Measured activation rows (_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.
  • The hosted-file arms above read the built files through 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.
  • Quantised speed is not a timing claim: the s/step numbers in those arms come from a shared card. The GGUF route was rendered with a locally built master-982 sd-cli / sd-server; the Studio prebuilt pin moves on a separate branch, so a managed install from this branch alone was not exercised (a build without MOSS is refused by the marker gate, covered by tests). No LoRA, no single-file transformer pick.
  • Under the seeded 16 / 13 GiB placements the denoiser runs resident behind group-offload hooks, where the fused levers do not install (0.0786 against 0.0722 fully resident); at 12 GiB the second prompt re-captured its CUDA graphs once (the graph layer's existing behaviour for offloaded keys).
  • No side-by-side ComfyUI render or timing: running ComfyUI needs Comfy-Org's MOSS files, which this work does not download.
  • The int8 encoder keeps the gated-delta projections, embeddings and vision tower dense (as built); a text-only, fully int8 encoder needs a builder and loader change and was not done.
  • CFG-parallel together with CUDA graphs (speed default) was not armed on the T4x2 run (the graphed forward is an instance override the router declines); whether that pair should combine is a question for the CFG-parallel layer, not this family.
  • The frontend tests could not run here (no node_modules); the catalog check script passed.
  • The MOSS bf16-while-it-fits rule uses the existing FamilyProfile.auto_bf16_when_resident field under its own reason string. The small-DiT defaults change (FLUX.2-klein, Z-Image, FLUX.3-klein) edits the same test_the_bf16_rule_names_only_the_measured_families parametrize list and the family freeze fixture, so whichever lands second needs a trivial merge there.
  • The int8 encoder adds LPIPS 0.011 mean over the bf16 encoder with the bf16 DiT (0.036 vs 0.025) and saves about 5 GiB of peak. ComfyUI's W4A8 encoder was not scored (no Comfy-Org files).

…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.
@danielhanchen danielhanchen self-assigned this Oct 21, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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 ✅ Completed 2026-10-23T02:35:22.916039Z 749e729 Manual request
ℹ️ 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

seam-guard fails on this PR (job 119436758475) because the new family has no VAE tile config:

AssertionError: families without a VAE config in vae_tile_configs.json: ['moss-image']. Add each one's vae/config.json (base repo, pinned revision) so the seam guard checks the tile geometry Studio decodes it with.
KeyError: 'moss-image'

Adding the moss-image entry (its base repo's vae/config.json at a pinned revision) to vae_tile_configs.json should clear it. moss-image is new in this PR, so this is specific to it rather than a repo-wide failure.

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]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 39ccf6bb74

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 867f6306d0

ℹ️ 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".

…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]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@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: 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".

Comment on lines +521 to +524
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]

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 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 👍 / 👎.

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.

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.

Comment on lines +302 to +305
bf16Pipeline("OpenMOSS-Team/MOSS-Image-SFT", 25.33, {
totalParams: 5082308624,
prequantRepo: "unsloth/MOSS-Image-SFT-FP8",
prequantSizeGb: { fp8: 5.04, int8: 5.04 },

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 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 👍 / 👎.

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.

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]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 8ef45a093b

ℹ️ 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".

# 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
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review October 22, 2026 22:59
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 56ab3b0679

ℹ️ 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".

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
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]
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 23, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: ef8aa9485e

ℹ️ 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".

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 23, 2026
@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: 749e729f8b

ℹ️ 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".

# Conflicts:
#	studio/frontend/scripts/check-bundle-budget.ts
@danielhanchen
danielhanchen merged commit 9778ef7 into main Oct 23, 2026
3 of 46 checks passed
@danielhanchen
danielhanchen deleted the studio-moss-image branch October 23, 2026 04:23
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 23, 2026
…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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 24, 2026
…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.
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