From 44b2ef2006cbd8ea9ca96185caa5bf08ce4019c6 Mon Sep 17 00:00:00 2001 From: Wagner Bruna Date: Fri, 13 Nov 2026 20:49:02 -0300 Subject: [PATCH 1/6] feat: enable prompt weighing for MOSS-Image --- src/conditioning/conditioner.hpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/conditioning/conditioner.hpp b/src/conditioning/conditioner.hpp index eeebb778e1..819da9716c 100644 --- a/src/conditioning/conditioner.hpp +++ b/src/conditioning/conditioner.hpp @@ -3251,8 +3251,11 @@ struct LLMEmbedder : public Conditioner { } else if (version == VERSION_MOSS_IMAGE) { prompt_template_encode_start_idx = 0; max_length = 4096; - prompt = "<|im_start|>user\n" + conditioner_params.text + "<|im_end|>\n<|im_start|>assistant\n\n"; - prompt_attn_range = {0, 0}; + prompt = "<|im_start|>user\n"; + prompt_attn_range.first = static_cast(prompt.size()); + prompt += conditioner_params.text; + prompt_attn_range.second = static_cast(prompt.size()); + prompt += "<|im_end|>\n<|im_start|>assistant\n\n"; } else if (sd_version_is_flux3(version)) { prompt_template_encode_start_idx = 0; max_length = 4096; From a613c58f216a58a66534204174a55c5ac1657557 Mon Sep 17 00:00:00 2001 From: Wagner Bruna Date: Sat, 7 Nov 2026 22:11:00 -0300 Subject: [PATCH 2/6] feat: support for MOSS-Image edit LoRAs --- docs/guides/edit.md | 7 +- src/conditioning/conditioning_cache.h | 2 +- src/model/adapter/lora.hpp | 79 +++++++++++++++++++- src/model/common/rope.hpp | 20 ++++- src/model/diffusion/model.hpp | 36 ++++++--- src/model/diffusion/moss_image.hpp | 103 +++++++++++++++++++++++--- src/model/integrations/moss_image.cpp | 1 + src/name_conversion.cpp | 3 +- src/pipeline/diffusion_engine.cpp | 9 ++- src/pipeline/image.cpp | 31 +++++--- 10 files changed, 254 insertions(+), 37 deletions(-) diff --git a/docs/guides/edit.md b/docs/guides/edit.md index a12cc831fb..d3c590c1e3 100644 --- a/docs/guides/edit.md +++ b/docs/guides/edit.md @@ -21,6 +21,7 @@ Depending on the architecture, different models handle reference images differen | [**LLaDA-Image**](../models/llada_image.md#image-editing) | `llada_image` | | [**Fibo 2.0 Dev / Edit Turbo**](../models/fibo2.md#examples) | `fibo2` | | **Anima (Community Edit LoRAs)** | `cosmos_reference` | +| **MOSS-Image (Community Edit LoRA)** | `moss_edit` | Stable-diffusion.spp also supports basic Unet-based editing models like instruct-pix2pix or CosXL-Edit. This document is not about those. @@ -59,6 +60,7 @@ The `--ref-image-args` argument accepts a comma-separated list of key-value pair | `mage_flow` | Mage-Flow-Edit | | `krea2_edit` | Specifically for [lbouaraba/krea2edit](https://huggingface.co/conradlocke/krea2-identity-edit). (or similar) | | `cosmos_reference` | For Anima | +| `moss_edit` | MOSS-Image Community Edit LoRA (FLUX.2-VAE refs into the DiT at t=0) | | `default` | Uses the automatic detection based on model architecture. | --- @@ -73,13 +75,14 @@ If presets are insufficient, you can manually configure the following parameters | `pass_to_vlm` | bool | Whether reference images are passed to the VLM encoder. | `true`, `false` | | `pass_to_dit` | bool | Whether VAE-encoded references are passed directly to the DiT. | `true`, `false` | | `ref_index_mode` | string | Behavior of the RoPE index. | `fixed`, `increase`, `decrease` | -| `force_ref_timestep_zero` | bool | Forces timestep=0 for reference tokens. | `true`, `false` (Krea2 only) | +| `force_ref_timestep_zero` | bool | Forces timestep=0 for reference tokens. | `true`, `false` (Krea2, MOSS-Image) | | `resize_before_vae` | bool | Whether reference images are resized before VAE encoding. | `true`, `false` | | `resize_vae_to_target` | bool | Use output dimensions for every reference, overriding area-based sizing. | `true`, `false` | | `resize_single_ref_to_target` | bool | Use output dimensions when exactly one reference is supplied. | `true`, `false` | | `vae_size_buckets` | bool | Choose aligned dimensions within ±10% of the requested area, minimizing aspect-ratio cropping. Ignored when using output dimensions. | `true`, `false` | | `vae_center_crop` | bool | Scale to cover the selected dimensions with Lanczos, then center-crop. Otherwise resize directly. | `true`, `false` | | `vae_input_max_pixels` | int | VAE area budget, also capped by output area in ordinary resizing. With size buckets, this is the target area and output area does not cap it. | Integer | +| `vae_input_max_edge` | int | Cap the reference long edge at N px before VAE encoding (aspect ratio preserved, 16-aligned). Overrides the area-based sizing when set. | Integer | | `vlm_use_vae_input` | bool | Reuse the resized/cropped VAE input for the VLM, before the VLM's own resize. Has no effect when `resize_before_vae=false`. | `true`, `false` | | `vlm_resize_mode` | string | How to resize VLM reference inputs. | `longest_side`, `area`, `none` | | `vlm_max_size` | int | Maximum VLM input size; interpreted according to `vlm_resize_mode`. | Integer | @@ -106,6 +109,8 @@ For a technical overview of how each preset is configured, see the table below. | `krea2_ostris_edit`| Yes | `increase` | `area` | `force_ref_timestep_zero = true` | | `krea2_edit` | Yes | `increase` | `longest` | `vlm_size = 768` | | `cosmos_reference` | No | `fixed` | `none` | `resize_before_vae = false` | +| `moss_edit` | No | `increase` | `none` | `force_ref_timestep_zero = true`, `vae_input_max_edge = 1024` | + **Additional Default Notes:** - **VLM Input Sizes:** For most presets, `vlm_max_size` and `vlm_min_size` are set to `-1`, meaning the values are model-dependent and handled automatically. In `area` mode they represent pixel area; in `longest_side` mode they represent a side length in pixels. diff --git a/src/conditioning/conditioning_cache.h b/src/conditioning/conditioning_cache.h index 58f539a388..7f78ca08ce 100644 --- a/src/conditioning/conditioning_cache.h +++ b/src/conditioning/conditioning_cache.h @@ -52,7 +52,7 @@ class ConditioningCache { const auto& r = p.ref_image_params; return std::tie(p.text, p.clip_skip, p.width, p.height, p.zero_out_masked, r.pass_to_vlm, r.pass_to_dit, r.ref_index_mode, - r.force_ref_timestep_zero, r.resize_before_vae, r.vae_input_max_pixels, + r.force_ref_timestep_zero, r.resize_before_vae, r.vae_input_max_pixels, r.vae_input_max_edge, r.vlm_resize_mode, r.vlm_min_size, r.vlm_max_size, r.resize_vae_to_target, r.ref_image_size); }; diff --git a/src/model/adapter/lora.hpp b/src/model/adapter/lora.hpp index 7d71b34f60..5b1f18e68d 100644 --- a/src/model/adapter/lora.hpp +++ b/src/model/adapter/lora.hpp @@ -2,12 +2,14 @@ #define __SD_MODEL_ADAPTER_LORA_HPP__ #include +#include #include #include "core/ggml_extend.h" #include "core/ggml_extend_backend.h" #include "core/ggml_runner.h" #include "core/ggml_tensor_utils.h" #include "core/util.h" +#include "json.hpp" #include "model.h" #include "model/adapter/lora_ops.h" #include "model_loader.h" @@ -20,6 +22,9 @@ struct LoraModel : public GGMLRunner { std::string lora_id; float multiplier = 1.0f; float metadata_alpha = -1.f; + // Per-module alpha from "adapter_config" metadata, keyed by the model tensor base name + // (same name conversion as the lora tensors). Takes precedence over metadata_alpha. + std::map module_alphas; std::unordered_map lora_tensors; std::map original_tensor_to_final_tensor; std::set applied_lora_tensors; @@ -83,6 +88,65 @@ struct LoraModel : public GGMLRunner { } LOG_VERBOSE("LoRA '%s' uses metadata alpha %.6g when tensor alpha/scale is absent", file_path.c_str(), metadata_alpha); } + // MOSS-Image Edit adapters (chinoll/Moss-Image-Edit) carry alpha/rank in an + // "adapter_config" JSON string in the safetensors metadata instead of .alpha tensors. + // Non-matching "adapter_config" keys from other tools are left alone. + const auto adapter_config = metadata.find("adapter_config"); + if (adapter_config != metadata.end() && metadata_alpha < 0.f && metadata.find("baked_scale") == metadata.end()) { + try { + auto cfg = nlohmann::json::parse(adapter_config->second); + if (cfg.value("format", "") == "moss-edit-lora" && cfg.value("format_version", 0) == 1) { + float alpha = -1.f; + int64_t rank = -1; + bool uniform = true; + size_t valid_modules = 0; + if (cfg.contains("modules") && cfg["modules"].is_object()) { + for (const auto& [target, spec] : cfg["modules"].items()) { + auto a_it = spec.find("alpha"); + auto r_it = spec.find("rank"); + if (a_it == spec.end() || !a_it->is_number() || r_it == spec.end() || !r_it->is_number()) { + LOG_WARN("adapter_config module '%s' has a missing or non-numeric alpha/rank; using the default scale for it", target.c_str()); + continue; + } + float a = a_it->get(); + int64_t r = r_it->get(); + if (alpha < 0.f) { + alpha = a; + rank = r; + } else if (a != alpha || r != rank) { + uniform = false; + } + // Convert the module key through the same path as the lora tensors so + // it matches the model tensor base name used by the apply sites below. + std::string name = convert_tensor_name("lora." + target + ".lora_A", source_version); + if (starts_with(name, "lora.") && ends_with(name, ".lora_down")) { + name = name.substr(std::strlen("lora."), name.size() - std::strlen("lora.") - std::strlen(".lora_down")); + module_alphas[name] = a; + } + ++valid_modules; + } + } + if (valid_modules == 0) { + LOG_WARN("adapter_config in '%s' claims format moss-edit-lora but has no modules with a usable alpha/rank; LoRA will use the default scale", file_path.c_str()); + } else if (module_alphas.empty()) { + // all modules parsed, but none matched a known tensor name: the uniform + // alpha below is a guess, not a per-module value + LOG_WARN("adapter_config in '%s' has %zu modules but none converted to known tensor names; falling back to uniform alpha %.6g", file_path.c_str(), valid_modules, alpha); + metadata_alpha = alpha; + } else { + // fallback for any module whose key fails to convert; + metadata_alpha = alpha; + if (uniform) { + LOG_DEBUG("MOSS edit lora: adapter_config alpha=%.6g rank=%lld (%zu modules)", alpha, (long long)rank, valid_modules); + } else { + LOG_DEBUG("MOSS edit lora: adapter_config has non-uniform alpha/rank (%zu modules); using per-module alpha", valid_modules); + } + } + } + } catch (const std::exception& e) { + LOG_WARN("failed to parse adapter_config metadata in '%s': %s", file_path.c_str(), e.what()); + } + } if (sd_version_is_minimax_h3(source_version)) { for (const auto& entry : model_manager->loader().file_tensors(source_file)) { const auto name = convert_tensor_name(entry.first, VERSION_COUNT); @@ -134,6 +198,16 @@ struct LoraModel : public GGMLRunner { return found != scalar_values.end() ? found->second : ggml_ext_backend_tensor_get_f32(tensor); } + // Scale for a module: per-module alpha from "adapter_config" when present, + // else the uniform metadata alpha, else 1. Rank comes from the tensor shape. + float module_alpha_scale(const std::string& base_name, int64_t rank) const { + auto found = module_alphas.find(base_name); + if (found != module_alphas.end() && found->second >= 0.f) { + return found->second / rank; + } + return metadata_alpha >= 0.f ? metadata_alpha / rank : 1.f; + } + void release_loaded_tensors() { runner_end(); if (auto manager = std::dynamic_pointer_cast(residency_manager.lock())) { @@ -150,6 +224,7 @@ struct LoraModel : public GGMLRunner { metadata_alpha = -1.f; skipped_incompatible_lora_tensors.clear(); warned_incompatible_model_tensors.clear(); + module_alphas.clear(); applied = false; tensor_preprocessed = false; } @@ -273,7 +348,7 @@ struct LoraModel : public GGMLRunner { float scale_value = 1.0f; int64_t rank = lora_down->ne[ggml_n_dims(lora_down) - 1]; - scale_value = metadata_alpha >= 0.f ? metadata_alpha / rank : 1.f; + scale_value = module_alpha_scale(key, rank); iter = lora_tensors.find(scale_name); if (iter != lora_tensors.end()) { scale_value = scalar_value(iter->second); @@ -840,7 +915,7 @@ struct LoraModel : public GGMLRunner { std::string scale_tensor_name; int64_t rank = lora_down->ne[ggml_n_dims(lora_down) - 1]; - scale_value = metadata_alpha >= 0.f ? metadata_alpha / rank : 1.f; + scale_value = module_alpha_scale(key, rank); iter = lora_tensors.find(scale_name); if (iter != lora_tensors.end()) { scale_value = scalar_value(iter->second); diff --git a/src/model/common/rope.hpp b/src/model/common/rope.hpp index b6f3111a09..10219c49e8 100644 --- a/src/model/common/rope.hpp +++ b/src/model/common/rope.hpp @@ -1081,7 +1081,8 @@ namespace Rope { ggml_tensor* pe, ggml_tensor* mask, float kv_scale = 1.0f, - bool rope_interleaved = true) { + bool rope_interleaved = true, + int64_t ref_start = -1) { // q,k,v: [N, L, n_head, d_head] // pe: [L, d_head/2, 2, 2] // return: [N, L, n_head*d_head] @@ -1090,6 +1091,23 @@ namespace Rope { q = apply_rope(ctx, q, pe, rope_interleaved); // [N*n_head, L, d_head] k = apply_rope(ctx, k, pe, rope_interleaved); // [N*n_head, L, d_head] + auto c = ctx->ggml_ctx; + if (ref_start >= 0 && mask == nullptr && q->ne[1] > ref_start) { + // q rows [ref_start, L) are reference tokens: they attend ONLY to k/v rows [ref_start, L). + // Body rows [0, ref_start) attend to everything. Refs sit at the END of the sequence. + // Mirrors ComfyUI's MOSS-Image reference_attention; two attention calls instead of a mask. + // q/k are contiguous 3D [d_head, L, n_head*N] after apply_rope (slice along ne[1]); + // v keeps its pre-rope 4D layout [d_head, n_head, L, N] (slice along ne[2]). + auto q_body = ggml_view_3d(c, q, q->ne[0], ref_start, q->ne[2], q->nb[1], q->nb[2], 0); + auto q_ref = ggml_view_3d(c, q, q->ne[0], q->ne[1] - ref_start, q->ne[2], q->nb[1], q->nb[2], ref_start * q->nb[1]); + auto k_ref = ggml_view_3d(c, k, k->ne[0], k->ne[1] - ref_start, k->ne[2], k->nb[1], k->nb[2], ref_start * k->nb[1]); + auto v_ref = ggml_view_4d(c, v, v->ne[0], v->ne[1], v->ne[2] - ref_start, v->ne[3], + v->nb[1], v->nb[2], v->nb[3], ref_start * v->nb[2]); + auto body = ggml_ext_attention_ext(ctx, q_body, k, v, n_head, nullptr, true, ctx->flash_attn_enabled, kv_scale); + auto refs = ggml_ext_attention_ext(ctx, q_ref, k_ref, v_ref, n_head, nullptr, true, ctx->flash_attn_enabled, kv_scale); + return ggml_concat(c, body, refs, 1); + } + auto x = ggml_ext_attention_ext(ctx, q, k, v, n_head, mask, true, ctx->flash_attn_enabled, kv_scale); // [N, L, n_head*d_head] return x; } diff --git a/src/model/diffusion/model.hpp b/src/model/diffusion/model.hpp index ed20c80870..8672c4fbfc 100644 --- a/src/model/diffusion/model.hpp +++ b/src/model/diffusion/model.hpp @@ -28,6 +28,7 @@ struct RefImageParams { bool force_ref_timestep_zero = false; bool resize_before_vae = true; int vae_input_max_pixels = -1; + int vae_input_max_edge = -1; // >0: cap the reference long edge at N px before VAE (16-aligned) RefImageResizeMode vlm_resize_mode = RefImageResizeMode::AREA; int vlm_min_size = -1; int vlm_max_size = -1; @@ -52,19 +53,32 @@ const std::unordered_map REF_IMAGE_PRESETS = { params.vlm_use_vae_input = true; return params; }()}, - {"flux_kontext", {false, true, Rope::RefIndexMode::FIXED, false, true, -1, RefImageResizeMode::NONE, -1, -1}}, - {"longcat", {true, true, Rope::RefIndexMode::FIXED, false, true, -1, RefImageResizeMode::AREA, -1, -1}}, - {"flux2", {false, true, Rope::RefIndexMode::INCREASE, false, true, -1, RefImageResizeMode::NONE, -1, -1}}, - {"qwen", {true, true, Rope::RefIndexMode::INCREASE, false, true, -1, RefImageResizeMode::AREA, -1, -1}}, - {"qwen_layered", {true, true, Rope::RefIndexMode::DECREASE, false, true, -1, RefImageResizeMode::AREA, -1, -1}}, - {"mage_flow", {true, true, Rope::RefIndexMode::INCREASE, false, true, -1, RefImageResizeMode::LONGEST_SIDE, -1, 384, true}}, - {"z_image_omni", {true, true, Rope::RefIndexMode::FIXED, false, true, -1, RefImageResizeMode::AREA, -1, -1}}, - {"krea2_ostris_edit", {true, true, Rope::RefIndexMode::INCREASE, true, true, -1, RefImageResizeMode::AREA, -1, -1}}, - {"krea2_edit", {true, true, Rope::RefIndexMode::INCREASE, false, true, -1, RefImageResizeMode::LONGEST_SIDE, 768, 768}}, + {"flux_kontext", {false, true, Rope::RefIndexMode::FIXED, false, true, -1, -1, RefImageResizeMode::NONE, -1, -1}}, + {"longcat", {true, true, Rope::RefIndexMode::FIXED, false, true, -1, -1, RefImageResizeMode::AREA, -1, -1}}, + {"flux2", {false, true, Rope::RefIndexMode::INCREASE, false, true, -1, -1, RefImageResizeMode::NONE, -1, -1}}, + {"qwen", {true, true, Rope::RefIndexMode::INCREASE, false, true, -1, -1, RefImageResizeMode::AREA, -1, -1}}, + {"qwen_layered", {true, true, Rope::RefIndexMode::DECREASE, false, true, -1, -1, RefImageResizeMode::AREA, -1, -1}}, + {"mage_flow", {true, true, Rope::RefIndexMode::INCREASE, false, true, -1, -1, RefImageResizeMode::LONGEST_SIDE, -1, 384, true}}, + {"z_image_omni", {true, true, Rope::RefIndexMode::FIXED, false, true, -1, -1, RefImageResizeMode::AREA, -1, -1}}, + {"krea2_ostris_edit", {true, true, Rope::RefIndexMode::INCREASE, true, true, -1, -1, RefImageResizeMode::AREA, -1, -1}}, + {"krea2_edit", {true, true, Rope::RefIndexMode::INCREASE, false, true, -1, -1, RefImageResizeMode::LONGEST_SIDE, 768, 768}}, // pass_to_vlm routes the reference image to the conditioner, which is where LLaDA-Image's // SigVQ encoder lives; it does its own half-resolution resize. - {"llada_image", {true, true, Rope::RefIndexMode::FIXED, true, true, -1, RefImageResizeMode::NONE, -1, -1, true}}, - {"cosmos_reference", {false, true, Rope::RefIndexMode::INCREASE, false, false, -1, RefImageResizeMode::NONE, -1, -1}}, + {"llada_image", {true, true, Rope::RefIndexMode::FIXED, true, true, -1, -1, RefImageResizeMode::NONE, -1, -1, true}}, + {"cosmos_reference", {false, true, Rope::RefIndexMode::INCREASE, false, false, -1, -1, RefImageResizeMode::NONE, -1, -1}}, + // MOSS-Image Edit: FLUX.2-VAE latent refs into the DiT at t=0 (chinoll/Moss-Image-Edit adapter). + // pass_to_vlm=false: the ViT is unused; refs never appear in the text prompt. + {"moss_edit", [] { + RefImageParams params; + params.pass_to_vlm = false; + params.pass_to_dit = true; + params.ref_index_mode = Rope::RefIndexMode::INCREASE; // refs numbered 1..N (documentation; MOSS builds its own PE) + params.force_ref_timestep_zero = true; + params.resize_before_vae = true; + params.vlm_resize_mode = RefImageResizeMode::NONE; + params.vae_input_max_edge = 1024; // official adapter default; ComfyUI node ships 512 + return params; + }()}, }; struct UNetDiffusionExtra { diff --git a/src/model/diffusion/moss_image.hpp b/src/model/diffusion/moss_image.hpp index 4bb9077c42..ba84ec41a8 100644 --- a/src/model/diffusion/moss_image.hpp +++ b/src/model/diffusion/moss_image.hpp @@ -109,7 +109,8 @@ namespace MOSSImage { blocks["proj.ffn_down"] = std::make_shared(config.ffn_dim, config.dim, false); } - ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* pe, const std::array& mod) { + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* pe, const std::array& mod, + int64_t ref_start = -1) { auto c = ctx->ggml_ctx; auto linear = [&](const char* name, ggml_tensor* h) { return std::dynamic_pointer_cast(blocks[name])->forward(ctx, h); }; auto norm = [&](const char* name, ggml_tensor* h) { return std::dynamic_pointer_cast(blocks[name])->forward(ctx, h); }; @@ -124,7 +125,7 @@ namespace MOSSImage { auto q = norm("q_norm", split(0)); auto k = norm("k_norm", split(1)); auto v = split(2); - y = Rope::attention(ctx, q, k, v, pe, nullptr, 1.f, false); + y = Rope::attention(ctx, q, k, v, pe, nullptr, 1.f, false, ref_start); y = linear("proj.o", y); y = ggml_mul(c, y, part(2)); x = ggml_add(c, x, y); @@ -159,7 +160,8 @@ namespace MOSSImage { blocks["final_linear_video"] = std::make_shared(config.dim, config.channels, false); } - ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* image, ggml_tensor* time, ggml_tensor* text, ggml_tensor* pe, const std::vector& skip) { + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* image, ggml_tensor* time, ggml_tensor* time_0, ggml_tensor* text, + ggml_tensor* pe, const std::vector& skip, const std::vector& refs) { auto c = ctx->ggml_ctx; auto linear = [&](const char* name, ggml_tensor* h) { return std::dynamic_pointer_cast(blocks[name])->forward(ctx, h); }; int64_t image_len = image->ne[0] * image->ne[1]; @@ -171,19 +173,51 @@ namespace MOSSImage { text = std::dynamic_pointer_cast(blocks["text_embedder.blocks." + std::to_string(i)])->forward(ctx, text, text_pe); } time = linear("time_embedding.2", ggml_silu(c, linear("time_embedding.0", time))); - auto mod = linear("shared_block_modulation", time); auto head = linear("video_head_modulation", time); + x = ggml_concat(c, x, text, 1); + int64_t body_len = x->ne[1]; // image + text; refs are appended after this + + // Per-token modulation: body rows use timestep t, ref rows use the constant t=0 + // embedding (the MOSS-Image edit contract). With no refs, `parts` stays as plain + // [dim] vectors and the graph is bit-identical to the t2i path. + auto mod0 = time_0 != nullptr + ? linear("shared_block_modulation", + linear("time_embedding.2", ggml_silu(c, linear("time_embedding.0", time_0)))) + : nullptr; + auto mod = linear("shared_block_modulation", time); std::array parts; + auto ref_len = [&]() { + int64_t n = 0; + for (ggml_tensor* ref : refs) { + n += ref->ne[0] * ref->ne[1]; + } + return n; + }; for (int i = 0; i < 6; ++i) { parts[i] = ggml_ext_slice(ctx, mod, 0, i * config.dim, (i + 1) * config.dim, false); + if (mod0 != nullptr) { + auto seg = [&](ggml_tensor* vec, int64_t len) { + return ggml_repeat(c, ggml_reshape_3d(c, vec, config.dim, 1, 1), + ggml_new_tensor_3d(c, GGML_TYPE_F32, config.dim, len, 1)); + }; + auto refp = ggml_ext_slice(ctx, mod0, 0, i * config.dim, (i + 1) * config.dim); + parts[i] = ggml_concat(c, seg(parts[i], body_len), seg(refp, ref_len()), 1); // [dim, L_total, 1] + } if (ctx->graph != nullptr) { ggml_build_forward_expand(ctx->graph, parts[i]); } } - x = ggml_concat(c, x, text, 1); + + for (ggml_tensor* ref : refs) { // refs appended at the END of the sequence + auto pixels_ref = ggml_reshape_3d(c, ref, ref->ne[0] * ref->ne[1], ref->ne[2], ref->ne[3]); + pixels_ref = ggml_cont(c, ggml_transpose(c, pixels_ref)); + x = ggml_concat(c, x, linear("video_embedder", pixels_ref), 1); + } + int64_t ref_start = ref_len() > 0 ? body_len : -1; + for (int64_t i = 0; i < config.depth; ++i) { if (std::find(skip.begin(), skip.end(), i) == skip.end()) { - x = std::dynamic_pointer_cast(blocks["layers." + std::to_string(i)])->forward(ctx, x, pe, parts); + x = std::dynamic_pointer_cast(blocks["layers." + std::to_string(i)])->forward(ctx, x, pe, parts, ref_start); sd::ggml_graph_cut::mark_graph_cut(x, "moss_image.layers." + std::to_string(i), "x"); } } @@ -202,6 +236,7 @@ namespace MOSSImage { MOSSImageConfig config; Model model; std::vector time_data; + std::vector time0_data; MOSSImageRunner(ggml_backend_t backend, const String2TensorStorage& weights, const std::string& prefix, std::shared_ptr weight_manager = nullptr) : DiffusionModelRunner(backend, prefix, weight_manager), config(MOSSImageConfig::detect_from_weights(weights, prefix)), model(config) { @@ -224,21 +259,50 @@ namespace MOSSImage { skip = *extra->skip_layers; } } + // edit refs: FLUX.2-VAE latents consumed by the DiT (moss_edit preset) + // validation only: the graph inputs are made inside the lambda, because make_input + // allocates in compute_ctx which exists only after new_graph_custom + const bool use_edit_refs = inputs.ref_latents != nullptr && inputs.ref_image_params.pass_to_dit && + !inputs.ref_latents->empty(); + if (use_edit_refs && !inputs.ref_image_params.force_ref_timestep_zero) { + LOG_WARN("MOSS-Image edit requires force_ref_timestep_zero; using t=0 for refs anyway"); + } auto graph = [&]() { auto gf = new_graph_custom(65536); auto x = make_input(*inputs.x); auto text = make_input(*inputs.context); GGML_ASSERT(x->ne[3] == 1 && x->ne[2] == config.channels && text->ne[0] == config.text_dim); int64_t h = x->ne[1], w = x->ne[0], nt = text->ne[1]; + // edit refs: VAE latents with the same layout as x (ne[0]=W_lat, ne[1]=H_lat, ne[2]=128, ne[3]=1). + std::vector refs; + if (use_edit_refs) { + for (const auto& ref : *inputs.ref_latents) { + GGML_ASSERT(ref.shape()[2] == config.channels && ref.shape()[3] == 1); + refs.push_back(make_input(ref)); + } + } + int64_t ref_tokens = 0; + for (const auto& ref : refs) { + ref_tokens += ref->ne[1] * ref->ne[0]; + } sd::PECacheKey pe_key("moss_image.pe"); pe_key.add(h).add(w).add(nt).add(config.head_dim).add(circular_x_enabled).add(circular_y_enabled); + for (const auto& ref : refs) { + pe_key.add(ref->ne[1]).add(ref->ne[0]); + } auto pe = make_input(pe_cache_.get_or_create(pe_key, [&]() { Rope::Embedding embedding; embedding.positions.append_image(static_cast(h), static_cast(w)); embedding.positions.images.back().height_axis = 2; embedding.positions.images.back().width_axis = 3; embedding.positions.append_tokens(nt); - for (int64_t token = 0; token < h * w + nt; ++token) { + for (const auto& ref : refs) { + embedding.positions.append_image(static_cast(ref->ne[1]), static_cast(ref->ne[0])); + embedding.positions.images.back().height_axis = 2; + embedding.positions.images.back().width_axis = 3; + } + int64_t body = h * w + nt; + for (int64_t token = 0; token < body; ++token) { float pos[4] = {0.f, float(token - h * w), 0.f, 0.f}; if (token < h * w) { pos[1] = float(nt); @@ -247,9 +311,21 @@ namespace MOSSImage { } embedding.ids.push_back({pos[0], pos[1], pos[2], pos[3]}); } + // ref i owns r-index i+1 with f=0, centered in h/w, on its own PE rows so a + // later Scale-ROPE on the generated image cannot corrupt the ref frequencies. + for (int64_t ri = 0; ri < (int64_t)refs.size(); ++ri) { + const int64_t rh = refs[ri]->ne[1], rw = refs[ri]->ne[0]; + for (int64_t t = 0; t < rh * rw; ++t) { + float pos[4] = {float(ri + 1), 0.f, + float(t / rw) - float(rh - 1) / 2.f, + float(t % rw) - float(rw - 1) / 2.f}; + embedding.ids.push_back({pos[0], pos[1], pos[2], pos[3]}); + } + } + GGML_ASSERT((int64_t)embedding.ids.size() == body + ref_tokens); embedding.values = Rope::embed_nd(embedding.ids, 1, 10000.f, std::vector(4, static_cast(config.head_dim / 4)), embedding.layout, &embedding.frequencies); auto values = finish_rope_pe(std::move(embedding)); - return sd::Tensor({2, 2, config.head_dim / 2, h * w + nt}, std::move(values)); + return sd::Tensor({2, 2, config.head_dim / 2, body + ref_tokens}, std::move(values)); })); time_data.resize(config.freq_dim); for (int64_t i = 0; i < config.freq_dim / 2; ++i) { @@ -259,8 +335,17 @@ namespace MOSSImage { } auto time = ggml_new_tensor_3d(compute_ctx, GGML_TYPE_F32, config.freq_dim, 1, 1); set_backend_tensor_data(time, time_data.data()); + // timestep_embedding(0) = [1 x freq_dim/2, 0 x freq_dim/2] (cos(0)=1, sin(0)=0). + // Not built as ggml_scale(time, 0) — that would zero the cos half as well. + ggml_tensor* time_0 = nullptr; + if (!refs.empty()) { + time0_data.assign(config.freq_dim / 2, 1.f); + time0_data.resize(config.freq_dim, 0.f); + time_0 = ggml_new_tensor_3d(compute_ctx, GGML_TYPE_F32, config.freq_dim, 1, 1); + set_backend_tensor_data(time_0, time0_data.data()); + } auto ctx = get_context(gf); - ggml_build_forward_expand(gf, model.forward(&ctx, x, time, text, pe, skip)); + ggml_build_forward_expand(gf, model.forward(&ctx, x, time, time_0, text, pe, skip, refs)); return gf; }; return restore_trailing_singleton_dims(GGMLRunner::compute(graph, n_threads, false), inputs.x->dim()); diff --git a/src/model/integrations/moss_image.cpp b/src/model/integrations/moss_image.cpp index 6a2114da2c..33d778e2a5 100644 --- a/src/model/integrations/moss_image.cpp +++ b/src/model/integrations/moss_image.cpp @@ -20,6 +20,7 @@ const std::vector& moss_image_definitions() { ModelDefinition definition; definition.version = VERSION_MOSS_IMAGE; definition.geometry = {1, 128, 3}; + definition.ref_image_preset = "moss_edit"; definition.name = "MOSS-Image"; definition.traits.is_dit = true; definition.traits.vae_kind = ModelVAEKind::FLUX2; diff --git a/src/name_conversion.cpp b/src/name_conversion.cpp index bd232319c6..212b3b4e3e 100644 --- a/src/name_conversion.cpp +++ b/src/name_conversion.cpp @@ -1828,7 +1828,8 @@ std::string convert_tensor_name(std::string name, SDVersion version) { if (starts_with(name, "down_blocks.") || starts_with(name, "up_blocks.") || starts_with(name, "mid_block.") || starts_with(name, "conv_in.") || starts_with(name, "conv_out.") || starts_with(name, "time_embedding.") || - starts_with(name, "conv_norm_out.")) { + starts_with(name, "conv_norm_out.") || + (version == VERSION_MOSS_IMAGE && starts_with(name, "layers."))) { const std::string& canonical_prefix = diffuison_model_prefix_vec.front(); name = convert_diffusion_model_name(name, canonical_prefix, version); name = canonical_prefix + name; diff --git a/src/pipeline/diffusion_engine.cpp b/src/pipeline/diffusion_engine.cpp index 745c8ba467..07d48bfd13 100644 --- a/src/pipeline/diffusion_engine.cpp +++ b/src/pipeline/diffusion_engine.cpp @@ -3241,6 +3241,11 @@ RefImageParams StableDiffusionGGML::resolve_ref_image_params(const char* ref_ima LOG_WARN("ignoring invalid reference image arg '%s=%s'", key.c_str(), value.c_str()); rejected_keys.insert(key); } + } else if (key == "vae_input_max_edge") { + if (!parse_strict_int(value, params.vae_input_max_edge)) { + LOG_WARN("ignoring invalid reference image arg '%s=%s'", key.c_str(), value.c_str()); + rejected_keys.insert(key); + } } else if (key == "vlm_resize_mode") { if (value == "longest_side") { params.vlm_resize_mode = RefImageResizeMode::LONGEST_SIDE; @@ -3294,8 +3299,8 @@ RefImageParams StableDiffusionGGML::resolve_ref_image_params(const char* ref_ima break; } } - if (params.force_ref_timestep_zero && !sd_version_is_krea2(version)) { - LOG_WARN("force_ref_timestep_zero is only supported by Krea2 architecture for now"); + if (params.force_ref_timestep_zero && !sd_version_is_krea2(version) && version != VERSION_MOSS_IMAGE) { + LOG_WARN("force_ref_timestep_zero is only supported by Krea2 and MOSS-Image for now"); } if (version == VERSION_MINIMAX_H3) { // H3 consumes references as VAE latents in its own packed sequence rather than diff --git a/src/pipeline/image.cpp b/src/pipeline/image.cpp index 5e7a349583..21adba2dbb 100644 --- a/src/pipeline/image.cpp +++ b/src/pipeline/image.cpp @@ -390,21 +390,34 @@ namespace sd::pipeline { vae_width = request->width; vae_height = request->height; } else { - int default_pixels = sd->version == VERSION_QWEN_IMAGE_2_1 ? request->width * request->height : 1024 * 1024; - int target_pixels = ref_image_params.vae_input_max_pixels > 0 ? ref_image_params.vae_input_max_pixels : default_pixels; - if (ref_image_params.vae_size_buckets) { - auto size = sd::select_image_size_bucket(static_cast(ref_images[i].shape()[0]), static_cast(ref_images[i].shape()[1]), target_pixels, factor, request->width, request->height); - vae_width = size.first; - vae_height = size.second; + if (ref_image_params.vae_input_max_edge > 0) { + // Long-edge cap (ComfyUI MOSS-Image-Edit parity): scale down so the + // longest edge is at most vae_input_max_edge px, preserving aspect ratio. + double edge_scale = std::min(1.0, + double(ref_image_params.vae_input_max_edge) / + double(std::max(ref_images[i].shape()[0], ref_images[i].shape()[1]))); + vae_width = double(ref_images[i].shape()[0]) * edge_scale; + vae_height = double(ref_images[i].shape()[1]) * edge_scale; } else { - int vae_image_size = std::min(target_pixels, request->width * request->height); - vae_width = sqrt(vae_image_size * ref_images[i].shape()[0] / ref_images[i].shape()[1]); - vae_height = vae_width * ref_images[i].shape()[1] / ref_images[i].shape()[0]; + int default_pixels = sd->version == VERSION_QWEN_IMAGE_2_1 ? request->width * request->height : 1024 * 1024; + int target_pixels = ref_image_params.vae_input_max_pixels > 0 ? ref_image_params.vae_input_max_pixels : default_pixels; + if (ref_image_params.vae_size_buckets) { + auto size = sd::select_image_size_bucket(static_cast(ref_images[i].shape()[0]), static_cast(ref_images[i].shape()[1]), target_pixels, factor, request->width, request->height); + vae_width = size.first; + vae_height = size.second; + } else { + int vae_image_size = std::min(target_pixels, request->width * request->height); + vae_width = sqrt(vae_image_size * ref_images[i].shape()[0] / ref_images[i].shape()[1]); + vae_height = vae_width * ref_images[i].shape()[1] / ref_images[i].shape()[0]; + } } } vae_height = round(vae_height / factor) * factor; vae_width = round(vae_width / factor) * factor; + // Never produce a sub-16px axis (ComfyUI's max(16, ...) floor). + vae_height = std::max(double(factor), vae_height); + vae_width = std::max(double(factor), vae_width); auto resized_ref_img = ref_image_params.vae_center_crop ? sd::resize_and_center_crop(ref_images[i], static_cast(vae_width), static_cast(vae_height)) From 074370a7e51becbe531be7c3dbd16bac8b70a987 Mon Sep 17 00:00:00 2001 From: leejet Date: Mon, 23 Nov 2026 00:23:17 +0800 Subject: [PATCH 3/6] fix: use full CFG for MOSS-Image editing --- docs/dgl/moss_image/moss-image-edit.dgl | 20 ++++---- docs/models/moss_image.md | 62 +++++++++++++++++++++---- src/api/generation_image.cpp | 2 +- 3 files changed, 64 insertions(+), 20 deletions(-) diff --git a/docs/dgl/moss_image/moss-image-edit.dgl b/docs/dgl/moss_image/moss-image-edit.dgl index 155bcadbee..4c7cd820b8 100644 --- a/docs/dgl/moss_image/moss-image-edit.dgl +++ b/docs/dgl/moss_image/moss-image-edit.dgl @@ -6,18 +6,18 @@ var { text_path = "../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf" tokenizer_path = "../models/tokenizers/tokenizer_qwen3.5.json" vae_path = "../models/vae/flux2_ae.safetensors" - lora_path = "../models/loras/adapter_model.safetensors" + lora_path = "../models/loras/moss/moss-edit-lora.safetensors" lora_weight = 1.0 - reference_paths = ["reference.png"] + reference_paths = ["../assets/flux/flux1-dev-q8_0.png"] output_path = "output.png" - prompt = "Change the jacket to (dark blue:1.2)." + prompt = "change 'flux.cpp' to 'moss.cpp'" negative_prompt = "" seed = 42 rng_type = "cuda" - width = 1024 - height = 1024 + width = 512 + height = 512 steps = 20 cfg_scale = 3.0 method = "euler" @@ -36,10 +36,10 @@ fn encode_reference(path, vae, rng) { } fn main() { - base_model = load_dit(model_path, family = "moss_image", params_backend = "cpu") - model = apply_lora(base_model, load_lora(lora_path), weight = lora_weight, mode = "at_runtime") - text = load_text_encoder(text_path, family = "moss_image", params_backend = "cpu", tokenizer = tokenizer_path) - vae = load_vae(vae_path, family = "moss_image", params_backend = "cpu") + base_model = load_dit(model_path, family = "moss_image") + model = apply_lora(base_model, load_lora(lora_path), weight = lora_weight, mode = "auto") + text = load_text_encoder(text_path, family = "moss_image", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "moss_image") encode_rng = make_rng(rng_type, seed = seed) references = map(reference_paths, process = encode_reference, vae = vae, rng = encode_rng) @@ -47,7 +47,7 @@ fn main() { positive = encode_prompt(text, prompt, width = width, height = height) negative = encode_prompt(text, negative_prompt, width = width, height = height) pos = predictor(model, positive, ref_latents = references, ref_index_mode = "increase", force_ref_timestep_zero = true) - neg = predictor(model, negative, ref_latents = references, ref_index_mode = "increase", force_ref_timestep_zero = true, skip_layers = [22]) + neg = predictor(model, negative, ref_latents = references, ref_index_mode = "increase", force_ref_timestep_zero = true) guided = cfg(pos, neg, scale = cfg_scale) sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) rng = make_rng(rng_type, seed = seed) diff --git a/docs/models/moss_image.md b/docs/models/moss_image.md index 23860a54f7..ce331300d5 100644 --- a/docs/models/moss_image.md +++ b/docs/models/moss_image.md @@ -10,7 +10,7 @@ MOSS-Image uses a 5B diffusion transformer, the FLUX.2 VAE, and Qwen3.5 9B as th | vae | [Safetensors](https://huggingface.co/Comfy-Org/MOSS-Image/tree/main/vae) | `--vae` | Use matching VAE | | Qwen3.5 9B | [GGUF](https://huggingface.co/unsloth/Qwen3.5-9B-GGUF/tree/main) | `--llm` | Use matching text encoder | | `tokenizer.json` | [Download](https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base/tree/main/tokenizer) | `--tokenizer` | Required; match text encoder | -| MOSS-Image Edit LoRA | [`adapter_model.safetensors`](https://huggingface.co/chinoll/Moss-Image-Edit/tree/main) | `--lora-model-dir` and `` in the prompt | Required for editing | +| MOSS-Image Edit LoRA | [`adapter_model.safetensors`](https://huggingface.co/chinoll/Moss-Image-Edit/tree/main) | `--lora-model-dir` and `` in the prompt | Required for editing | Pass the external `tokenizer.json` with `--tokenizer`; Qwen3.5 uses a different vocabulary from the embedded Qwen tokenizer. @@ -46,13 +46,12 @@ Select optional components when required by your checkpoint or task. | [Inline images](../dgl/moss_image/moss-image-sft-inline-images.dgl) | Insert named images into the prompt. | | [Reference-guided editing](../dgl/moss_image/moss-image-edit.dgl) | Edit with Base or SFT and the community editing LoRA. | -Set `lora_path` and list the input images in `reference_paths`. The example -caps the long edge at 1024 pixels and aligns both dimensions to 16 before -encoding with the FLUX.2 VAE. References enter the diffusion model at timestep -zero. Describe the desired change in `prompt`, using `(phrase:1.2)` to weight -a phrase. The CLI and C API use the same reference defaults. Pass `-r` once -per reference in the CLI, or supply `ref_images` in the C API, and select the -editing LoRA explicitly. +The editing script uses the same input and settings as the [CLI edit example](#moss-image-edit). +Change `lora_path` or list different inputs in `reference_paths` as needed. +The script caps the reference long edge at 1024 pixels and aligns both dimensions +to 16 before encoding with the FLUX.2 VAE. Both predictor branches receive the +same reference latents at timestep zero. Use `(phrase:1.2)` to weight a phrase +in the prompt. #### Run a script @@ -150,4 +149,49 @@ CLI examples use the [shared path and shell conventions](README.md#example-conve -Use dimensions divisible by 16. The default discrete scheduler uses the upstream time shift of 5. Use `--flow-shift` to override it. The CLI and C API set `skip_layers = [22]` on the negative predictor when translating requests to DGL, matching the upstream pipeline. Handwritten DGL scripts specify this zero-based layer index explicitly, as shown in the examples. +#### MOSS-Image Edit + +Save the edit LoRA as `models/loras/moss/moss-edit-lora.safetensors` in the +repository, or adjust the LoRA path in the [DGL example](../dgl/moss_image/moss-image-edit.dgl) +or the LoRA tag below. Pass `-r` once per reference in the CLI, or supply +`ref_images` in the C API. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe ` + --diffusion-model ..\models\diffusion_models\moss_image_sft_int8_convrot_attn.safetensors ` + --llm ..\models\text_encoders\Qwen3.5-9B-Q4_K_M.gguf ` + --vae ..\models\vae\flux2_ae.safetensors ` + --tokenizer ..\models\tokenizers\tokenizer_qwen3.5.json ` + --lora-model-dir ..\models\loras ` + -r ..\assets\flux\flux1-dev-q8_0.png ` + -p "change 'flux.cpp' to 'moss.cpp'" ` + --cfg-scale 3.0 ` + -v +``` + +**Linux/macOS** + +```sh +./bin/sd-cli \ + --diffusion-model ../models/diffusion_models/moss_image_sft_int8_convrot_attn.safetensors \ + --llm ../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf \ + --vae ../models/vae/flux2_ae.safetensors \ + --tokenizer ../models/tokenizers/tokenizer_qwen3.5.json \ + --lora-model-dir ../models/loras \ + -r ../assets/flux/flux1-dev-q8_0.png \ + -p "change 'flux.cpp' to 'moss.cpp'" \ + --cfg-scale 3.0 \ + -v +``` + +## Notes and limitations + +Use output dimensions divisible by 16. The default discrete scheduler uses a +flow shift of 5. Use `--flow-shift` to override it. + +Text-to-image requests skip layer 22 in the negative predictor. Reference-guided +editing uses all layers in both CFG branches, as in the edit LoRA's reference +sampler. [MOSS-Image SFT pipeline](https://huggingface.co/OpenMOSS-Team/MOSS-Image-SFT/blob/main/pipeline_moss_image.py) · +[MOSS-Image Edit sampler](https://github.com/Chenkin-x/Moss-Image-Edit/blob/main/moss_edit/sampling.py) diff --git a/src/api/generation_image.cpp b/src/api/generation_image.cpp index 4fa6d80b9f..d1a5456802 100644 --- a/src/api/generation_image.cpp +++ b/src/api/generation_image.cpp @@ -191,7 +191,7 @@ namespace sd::api { request.flags["reference_image_guidance"] = reference_guidance && image_guidance; request.flags["hidream_o1"] = version == VERSION_HIDREAM_O1; request.flags["control_image_guidance"] = image_guidance && version == VERSION_FLUX_CONTROLS; - if (version == VERSION_MOSS_IMAGE) + if (version == VERSION_MOSS_IMAGE && !refs) request.fields["negative_predictor_options"] += ", skip_layers = [22]"; if (sd_version_is_sensenova_u1(version)) { request.fields["negative_prompt_input"] = "negative_prompt_raw"; From 691d2a13e0b0e211b7957e159c8de31ad88de1c9 Mon Sep 17 00:00:00 2001 From: leejet Date: Mon, 23 Nov 2026 00:49:25 +0800 Subject: [PATCH 4/6] clean code --- docs/models/moss_image.md | 6 + src/model/adapter/lora.hpp | 116 ++++++----------- src/model/common/rope.hpp | 20 +-- src/model/diffusion/moss_image.hpp | 196 ++++++++++++++--------------- 4 files changed, 140 insertions(+), 198 deletions(-) diff --git a/docs/models/moss_image.md b/docs/models/moss_image.md index ce331300d5..cb471cbd58 100644 --- a/docs/models/moss_image.md +++ b/docs/models/moss_image.md @@ -53,6 +53,12 @@ to 16 before encoding with the FLUX.2 VAE. Both predictor branches receive the same reference latents at timestep zero. Use `(phrase:1.2)` to weight a phrase in the prompt. +The editing examples use the `moss-edit-lora` format. MOSS-Image-Edit-HQ publishes +an `armV5-moss-edit-lora.safetensors` export for this workflow with MOSS-Image SFT. +Its native `weights/armV5/armV5.safetensors` file uses the ai-toolkit workflow, +which also sends reference images to the vision encoder and uses different +diffusion position indices. [MOSS-Image-Edit-HQ model card](https://huggingface.co/akhaliq/MOSS-Image-Edit-HQ#use-in-comfyui) + #### Run a script Edit paths, prompts and settings in the script's `var` block, then run from diff --git a/src/model/adapter/lora.hpp b/src/model/adapter/lora.hpp index 2cb67a26a7..ddb2f24af2 100644 --- a/src/model/adapter/lora.hpp +++ b/src/model/adapter/lora.hpp @@ -2,7 +2,6 @@ #define __SD_MODEL_ADAPTER_LORA_HPP__ #include -#include #include #include "core/ggml_extend.h" #include "core/ggml_extend_backend.h" @@ -22,9 +21,6 @@ struct LoraModel : public GGMLRunner { std::string lora_id; float multiplier = 1.0f; float metadata_alpha = -1.f; - // Per-module alpha from "adapter_config" metadata, keyed by the model tensor base name - // (same name conversion as the lora tensors). Takes precedence over metadata_alpha. - std::map module_alphas; std::unordered_map lora_tensors; std::map original_tensor_to_final_tensor; std::set applied_lora_tensors; @@ -71,6 +67,38 @@ struct LoraModel : public GGMLRunner { ggml_backend_t backend() const { return runtime_backend; } + void load_moss_edit_scales(const std::string& adapter_config) { + try { + const auto config = nlohmann::json::parse(adapter_config); + if (config.value("format", "") != "moss-edit-lora" || config.value("format_version", 0) != 1) + return; + const auto modules = config.find("modules"); + if (modules == config.end() || !modules->is_object()) + return; + for (const auto& [target, spec] : modules->items()) { + const auto alpha = spec.find("alpha"); + if (alpha == spec.end() || !alpha->is_number()) + continue; + const float value = alpha->get(); + if (!std::isfinite(value) || value < 0.f) + continue; + + auto name = convert_tensor_name("lora." + target + ".scale", source_version); + const auto base = name.substr(0, name.size() - (sizeof(".scale") - 1)); + const auto down = lora_tensors.find(base + ".lora_down"); + if (down == lora_tensors.end() || lora_tensors.count(name) || lora_tensors.count(base + ".alpha")) + continue; + + // Use the loaded linear tensor's rank and the same scale path as file-backed scalars. + auto* scale = ggml_new_tensor_1d(params_ctx, GGML_TYPE_F32, 1); + scale->data = &scalar_values.emplace(scale, value / down->second->ne[1]).first->second; + lora_tensors.emplace(std::move(name), scale); + } + } catch (const nlohmann::json::exception& e) { + LOG_WARN("invalid MOSS-Image Edit adapter_config in '%s': %s", file_path.c_str(), e.what()); + } + } + bool init_params(int n_threads, filter_t filter = nullptr) { if (!weights) return false; @@ -81,7 +109,8 @@ struct LoraModel : public GGMLRunner { const auto metadata = weights->loader().file_metadata(source_file); const auto alpha = metadata.find("alpha"); // Converters that write "baked_scale" have already folded alpha / rank into lora_up. - if (alpha != metadata.end() && metadata.find("baked_scale") == metadata.end()) { + const bool baked_scale = metadata.count("baked_scale") != 0; + if (alpha != metadata.end() && !baked_scale) { try { size_t parsed = 0; metadata_alpha = std::stof(alpha->second, &parsed); @@ -94,65 +123,6 @@ struct LoraModel : public GGMLRunner { } LOG_VERBOSE("LoRA '%s' uses metadata alpha %.6g when tensor alpha/scale is absent", file_path.c_str(), metadata_alpha); } - // MOSS-Image Edit adapters (chinoll/Moss-Image-Edit) carry alpha/rank in an - // "adapter_config" JSON string in the safetensors metadata instead of .alpha tensors. - // Non-matching "adapter_config" keys from other tools are left alone. - const auto adapter_config = metadata.find("adapter_config"); - if (adapter_config != metadata.end() && metadata_alpha < 0.f && metadata.find("baked_scale") == metadata.end()) { - try { - auto cfg = nlohmann::json::parse(adapter_config->second); - if (cfg.value("format", "") == "moss-edit-lora" && cfg.value("format_version", 0) == 1) { - float alpha = -1.f; - int64_t rank = -1; - bool uniform = true; - size_t valid_modules = 0; - if (cfg.contains("modules") && cfg["modules"].is_object()) { - for (const auto& [target, spec] : cfg["modules"].items()) { - auto a_it = spec.find("alpha"); - auto r_it = spec.find("rank"); - if (a_it == spec.end() || !a_it->is_number() || r_it == spec.end() || !r_it->is_number()) { - LOG_WARN("adapter_config module '%s' has a missing or non-numeric alpha/rank; using the default scale for it", target.c_str()); - continue; - } - float a = a_it->get(); - int64_t r = r_it->get(); - if (alpha < 0.f) { - alpha = a; - rank = r; - } else if (a != alpha || r != rank) { - uniform = false; - } - // Convert the module key through the same path as the lora tensors so - // it matches the model tensor base name used by the apply sites below. - std::string name = convert_tensor_name("lora." + target + ".lora_A", source_version); - if (starts_with(name, "lora.") && ends_with(name, ".lora_down")) { - name = name.substr(std::strlen("lora."), name.size() - std::strlen("lora.") - std::strlen(".lora_down")); - module_alphas[name] = a; - } - ++valid_modules; - } - } - if (valid_modules == 0) { - LOG_WARN("adapter_config in '%s' claims format moss-edit-lora but has no modules with a usable alpha/rank; LoRA will use the default scale", file_path.c_str()); - } else if (module_alphas.empty()) { - // all modules parsed, but none matched a known tensor name: the uniform - // alpha below is a guess, not a per-module value - LOG_WARN("adapter_config in '%s' has %zu modules but none converted to known tensor names; falling back to uniform alpha %.6g", file_path.c_str(), valid_modules, alpha); - metadata_alpha = alpha; - } else { - // fallback for any module whose key fails to convert; - metadata_alpha = alpha; - if (uniform) { - LOG_DEBUG("MOSS edit lora: adapter_config alpha=%.6g rank=%lld (%zu modules)", alpha, (long long)rank, valid_modules); - } else { - LOG_DEBUG("MOSS edit lora: adapter_config has non-uniform alpha/rank (%zu modules); using per-module alpha", valid_modules); - } - } - } - } catch (const std::exception& e) { - LOG_WARN("failed to parse adapter_config metadata in '%s': %s", file_path.c_str(), e.what()); - } - } if (sd_version_is_minimax_h3(source_version)) { for (const auto& entry : weights->loader().file_tensors(source_file)) { const auto name = convert_tensor_name(entry.first, VERSION_COUNT); @@ -190,6 +160,9 @@ struct LoraModel : public GGMLRunner { if (!weights->loader().load_file_tensors(source_file, source_version, callback, scalar_names)) return false; } + const auto adapter_config = metadata.find("adapter_config"); + if (source_version == VERSION_MOSS_IMAGE && !baked_scale && metadata_alpha < 0.f && adapter_config != metadata.end()) + load_moss_edit_scales(adapter_config->second); if (!weights->register_param_tensors(ModelComponent::LoRA, tensors, residency_mode, runtime_backend, params_backend, nullptr, false, params_follow_compute, nullptr, source_file, source_version)) @@ -204,16 +177,6 @@ struct LoraModel : public GGMLRunner { return found != scalar_values.end() ? found->second : ggml_ext_backend_tensor_get_f32(tensor); } - // Scale for a module: per-module alpha from "adapter_config" when present, - // else the uniform metadata alpha, else 1. Rank comes from the tensor shape. - float module_alpha_scale(const std::string& base_name, int64_t rank) const { - auto found = module_alphas.find(base_name); - if (found != module_alphas.end() && found->second >= 0.f) { - return found->second / rank; - } - return metadata_alpha >= 0.f ? metadata_alpha / rank : 1.f; - } - void release_loaded_tensors() { runner_end(); if (weights) { @@ -230,7 +193,6 @@ struct LoraModel : public GGMLRunner { metadata_alpha = -1.f; skipped_incompatible_lora_tensors.clear(); warned_incompatible_model_tensors.clear(); - module_alphas.clear(); applied = false; tensor_preprocessed = false; } @@ -354,7 +316,7 @@ struct LoraModel : public GGMLRunner { float scale_value = 1.0f; int64_t rank = lora_down->ne[ggml_n_dims(lora_down) - 1]; - scale_value = module_alpha_scale(key, rank); + scale_value = metadata_alpha >= 0.f ? metadata_alpha / rank : 1.f; iter = lora_tensors.find(scale_name); if (iter != lora_tensors.end()) { scale_value = scalar_value(iter->second); @@ -921,7 +883,7 @@ struct LoraModel : public GGMLRunner { std::string scale_tensor_name; int64_t rank = lora_down->ne[ggml_n_dims(lora_down) - 1]; - scale_value = module_alpha_scale(key, rank); + scale_value = metadata_alpha >= 0.f ? metadata_alpha / rank : 1.f; iter = lora_tensors.find(scale_name); if (iter != lora_tensors.end()) { scale_value = scalar_value(iter->second); diff --git a/src/model/common/rope.hpp b/src/model/common/rope.hpp index 10219c49e8..b6f3111a09 100644 --- a/src/model/common/rope.hpp +++ b/src/model/common/rope.hpp @@ -1081,8 +1081,7 @@ namespace Rope { ggml_tensor* pe, ggml_tensor* mask, float kv_scale = 1.0f, - bool rope_interleaved = true, - int64_t ref_start = -1) { + bool rope_interleaved = true) { // q,k,v: [N, L, n_head, d_head] // pe: [L, d_head/2, 2, 2] // return: [N, L, n_head*d_head] @@ -1091,23 +1090,6 @@ namespace Rope { q = apply_rope(ctx, q, pe, rope_interleaved); // [N*n_head, L, d_head] k = apply_rope(ctx, k, pe, rope_interleaved); // [N*n_head, L, d_head] - auto c = ctx->ggml_ctx; - if (ref_start >= 0 && mask == nullptr && q->ne[1] > ref_start) { - // q rows [ref_start, L) are reference tokens: they attend ONLY to k/v rows [ref_start, L). - // Body rows [0, ref_start) attend to everything. Refs sit at the END of the sequence. - // Mirrors ComfyUI's MOSS-Image reference_attention; two attention calls instead of a mask. - // q/k are contiguous 3D [d_head, L, n_head*N] after apply_rope (slice along ne[1]); - // v keeps its pre-rope 4D layout [d_head, n_head, L, N] (slice along ne[2]). - auto q_body = ggml_view_3d(c, q, q->ne[0], ref_start, q->ne[2], q->nb[1], q->nb[2], 0); - auto q_ref = ggml_view_3d(c, q, q->ne[0], q->ne[1] - ref_start, q->ne[2], q->nb[1], q->nb[2], ref_start * q->nb[1]); - auto k_ref = ggml_view_3d(c, k, k->ne[0], k->ne[1] - ref_start, k->ne[2], k->nb[1], k->nb[2], ref_start * k->nb[1]); - auto v_ref = ggml_view_4d(c, v, v->ne[0], v->ne[1], v->ne[2] - ref_start, v->ne[3], - v->nb[1], v->nb[2], v->nb[3], ref_start * v->nb[2]); - auto body = ggml_ext_attention_ext(ctx, q_body, k, v, n_head, nullptr, true, ctx->flash_attn_enabled, kv_scale); - auto refs = ggml_ext_attention_ext(ctx, q_ref, k_ref, v_ref, n_head, nullptr, true, ctx->flash_attn_enabled, kv_scale); - return ggml_concat(c, body, refs, 1); - } - auto x = ggml_ext_attention_ext(ctx, q, k, v, n_head, mask, true, ctx->flash_attn_enabled, kv_scale); // [N, L, n_head*d_head] return x; } diff --git a/src/model/diffusion/moss_image.hpp b/src/model/diffusion/moss_image.hpp index 38372cb4b7..5da85af2a4 100644 --- a/src/model/diffusion/moss_image.hpp +++ b/src/model/diffusion/moss_image.hpp @@ -2,7 +2,6 @@ #define __SD_MODEL_DIFFUSION_MOSS_IMAGE_HPP__ #include -#include #include #include @@ -95,6 +94,26 @@ namespace MOSSImage { } }; + static ggml_tensor* attend(GGMLRunnerContext* ctx, ggml_tensor* q, ggml_tensor* k, ggml_tensor* v, ggml_tensor* pe, int64_t ref_start) { + const int64_t tokens = q->ne[2]; + if (ref_start == tokens) { + return Rope::attention(ctx, q, k, v, pe, nullptr, 1.f, false); + } + + const int64_t heads = q->ne[1]; + q = Rope::apply_rope(ctx, q, pe, false); + k = Rope::apply_rope(ctx, k, pe, false); + // Image and text queries see the whole sequence. Reference queries see only references. + auto attention = [&](ggml_tensor* query, ggml_tensor* key, ggml_tensor* value) { + return ggml_ext_attention_ext(ctx, query, key, value, heads, nullptr, true, ctx->flash_attn_enabled); + }; + auto body = attention(ggml_ext_slice(ctx, q, 1, 0, ref_start, false), k, v); + auto refs = attention(ggml_ext_slice(ctx, q, 1, ref_start, tokens, false), + ggml_ext_slice(ctx, k, 1, ref_start, tokens, false), + ggml_ext_slice(ctx, v, 2, ref_start, tokens, false)); + return ggml_concat(ctx->ggml_ctx, body, refs, 1); + } + struct Block : public GGMLBlock { MOSSImageConfig config; @@ -110,13 +129,12 @@ namespace MOSSImage { blocks["proj.ffn_down"] = std::make_shared(config.ffn_dim, config.dim, false); } - ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* pe, const std::array& mod, int64_t ref_start = -1) { + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* pe, const std::vector& mod, int64_t ref_start) { auto c = ctx->ggml_ctx; auto linear = [&](const char* name, ggml_tensor* h) { return std::dynamic_pointer_cast(blocks[name])->forward(ctx, h); }; auto norm = [&](const char* name, ggml_tensor* h) { return std::dynamic_pointer_cast(blocks[name])->forward(ctx, h); }; - auto part = [&](int i) { return mod[i]; }; auto y = norm("norm1", x); - y = ggml_ext_modulate(ctx, y, part(0), part(1)); + y = ggml_ext_modulate(ctx, y, mod[0], mod[1]); auto qkv = linear("proj.qkv", y); auto split = [&](int i) { return ggml_view_4d(c, qkv, config.head_dim, config.dim / config.head_dim, x->ne[1], x->ne[2], @@ -125,16 +143,16 @@ namespace MOSSImage { auto q = norm("q_norm", split(0)); auto k = norm("k_norm", split(1)); auto v = split(2); - y = Rope::attention(ctx, q, k, v, pe, nullptr, 1.f, false, ref_start); + y = attend(ctx, q, k, v, pe, ref_start); y = linear("proj.o", y); - y = ggml_mul(c, y, part(2)); + y = ggml_mul(c, y, mod[2]); x = ggml_add(c, x, y); y = norm("norm2", x); - y = ggml_ext_modulate(ctx, y, part(3), part(4)); + y = ggml_ext_modulate(ctx, y, mod[3], mod[4]); auto up_gate = linear("proj.ffn_up_gate", y); y = ggml_ext_situ(ctx, up_gate); y = linear("proj.ffn_down", y); - y = ggml_mul(c, y, part(5)); + y = ggml_mul(c, y, mod[5]); return ggml_add(c, x, y); } }; @@ -160,51 +178,38 @@ namespace MOSSImage { blocks["final_linear_video"] = std::make_shared(config.dim, config.channels, false); } - ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* image, ggml_tensor* time, ggml_tensor* time_0, ggml_tensor* text, ggml_tensor* pe, const std::vector& skip, const std::vector& refs) { - auto c = ctx->ggml_ctx; - auto linear = [&](const char* name, ggml_tensor* h) { return std::dynamic_pointer_cast(blocks[name])->forward(ctx, h); }; - int64_t image_len = image->ne[0] * image->ne[1]; - auto pixels = ggml_reshape_3d(c, image, image_len, image->ne[2], image->ne[3]); - auto x = linear("video_embedder", ggml_cont(c, ggml_transpose(c, pixels))); - text = linear("text_embedder.proj", text); - auto text_pe = ggml_ext_slice(ctx, pe, 3, image_len, image_len + text->ne[1], false); + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* image, ggml_tensor* time, ggml_tensor* text, ggml_tensor* pe, const std::vector& skip, const std::vector& refs, ggml_tensor* modulation_rows) { + auto c = ctx->ggml_ctx; + auto linear = [&](const char* name, ggml_tensor* h) { return std::dynamic_pointer_cast(blocks[name])->forward(ctx, h); }; + auto embed_image = [&](ggml_tensor* latent) { + auto pixels = ggml_reshape_3d(c, latent, latent->ne[0] * latent->ne[1], latent->ne[2], latent->ne[3]); + return linear("video_embedder", ggml_cont(c, ggml_transpose(c, pixels))); + }; + auto x = embed_image(image); + const int64_t image_len = x->ne[1]; + text = linear("text_embedder.proj", text); + auto text_pe = ggml_ext_slice(ctx, pe, 3, image_len, image_len + text->ne[1], false); for (int i = 0; i < 2; ++i) { text = std::dynamic_pointer_cast(blocks["text_embedder.blocks." + std::to_string(i)])->forward(ctx, text, text_pe); } - time = linear("time_embedding.2", ggml_silu(c, linear("time_embedding.0", time))); - auto head = linear("video_head_modulation", time); - x = ggml_concat(c, x, text, 1); - const int64_t body_len = x->ne[1]; + x = ggml_concat(c, x, text, 1); + const int64_t ref_start = x->ne[1]; for (auto* ref : refs) { - auto pixels_ref = ggml_reshape_3d(c, ref, ref->ne[0] * ref->ne[1], ref->ne[2], ref->ne[3]); - pixels_ref = ggml_cont(c, ggml_transpose(c, pixels_ref)); - x = ggml_concat(c, x, linear("video_embedder", pixels_ref), 1); + x = ggml_concat(c, x, embed_image(ref), 1); } - const int64_t ref_len = x->ne[1] - body_len; - // Reference tokens use the clean-image timestep while image and text use the sampling timestep. - auto mod0 = time_0 != nullptr - ? linear("shared_block_modulation", - linear("time_embedding.2", ggml_silu(c, linear("time_embedding.0", time_0)))) - : nullptr; - auto mod = linear("shared_block_modulation", time); - std::array parts; - for (int i = 0; i < 6; ++i) { - parts[i] = ggml_ext_slice(ctx, mod, 0, i * config.dim, (i + 1) * config.dim, false); - if (mod0 != nullptr) { - auto seg = [&](ggml_tensor* vec, int64_t len) { - return ggml_repeat(c, ggml_reshape_3d(c, vec, config.dim, 1, 1), - ggml_new_tensor_3d(c, GGML_TYPE_F32, config.dim, len, 1)); - }; - auto refp = ggml_ext_slice(ctx, mod0, 0, i * config.dim, (i + 1) * config.dim, false); - parts[i] = ggml_concat(c, seg(parts[i], body_len), seg(refp, ref_len), 1); + time = linear("time_embedding.2", ggml_silu(c, linear("time_embedding.0", time))); + auto head = linear("video_head_modulation", ggml_ext_slice(ctx, time, 1, 0, 1, false)); + auto parts = ggml_ext_chunk(ctx, linear("shared_block_modulation", time), 6, 0, false); + for (auto*& part : parts) { + if (modulation_rows) { + part = ggml_get_rows(c, part, modulation_rows); } if (ctx->graph != nullptr) { - ggml_build_forward_expand(ctx->graph, parts[i]); + ggml_build_forward_expand(ctx->graph, part); } } - const int64_t ref_start = refs.empty() ? -1 : body_len; for (int64_t i = 0; i < config.depth; ++i) { if (std::find(skip.begin(), skip.end(), i) == skip.end()) { x = std::dynamic_pointer_cast(blocks["layers." + std::to_string(i)])->forward(ctx, x, pe, parts, ref_start); @@ -226,7 +231,6 @@ namespace MOSSImage { MOSSImageConfig config; Model model; std::vector time_data; - std::vector time0_data; MOSSImageRunner(ggml_backend_t backend, const String2TensorStorage& weights, const std::string& prefix, std::shared_ptr weight_manager = nullptr) : DiffusionModelRunner(backend, prefix, weight_manager), config(MOSSImageConfig::detect_from_weights(weights, prefix)), model(config) { @@ -249,90 +253,78 @@ namespace MOSSImage { skip = *extra->skip_layers; } } - if (inputs.ref_latents != nullptr) { - for (const auto& ref : *inputs.ref_latents) { + const auto* references = inputs.ref_latents; + if (references) { + for (const auto& ref : *references) { if (ref.empty() || ref.dim() != 4 || ref.shape()[2] != config.channels || ref.shape()[3] != 1) { throw std::runtime_error("MOSS-Image reference latents must have shape [width, height, channels, 1] with the model's latent channel count"); } } } + sd::Tensor modulation_rows; auto graph = [&]() { auto gf = new_graph_custom(65536); auto x = make_input(*inputs.x); auto text = make_input(*inputs.context); GGML_ASSERT(x->ne[3] == 1 && x->ne[2] == config.channels && text->ne[0] == config.text_dim); - int64_t h = x->ne[1], w = x->ne[0], nt = text->ne[1]; + const auto h = x->ne[1], w = x->ne[0], nt = text->ne[1]; + const auto ref_start = h * w + nt; + auto tokens = ref_start; + sd::PECacheKey pe_key("moss_image.pe"); + pe_key.add(h).add(w).add(nt).add(config.head_dim).add(circular_x_enabled).add(circular_y_enabled); std::vector refs; - if (inputs.ref_latents != nullptr) { - for (const auto& ref : *inputs.ref_latents) { + if (references) { + for (const auto& ref : *references) { refs.push_back(make_input(ref)); + pe_key.add(ref.shape()[1]).add(ref.shape()[0]); + tokens += ref.shape()[1] * ref.shape()[0]; } } - int64_t ref_tokens = 0; - for (const auto& ref : refs) { - ref_tokens += ref->ne[1] * ref->ne[0]; - } - sd::PECacheKey pe_key("moss_image.pe"); - pe_key.add(h).add(w).add(nt).add(config.head_dim).add(circular_x_enabled).add(circular_y_enabled); - for (const auto& ref : refs) { - pe_key.add(ref->ne[1]).add(ref->ne[0]); - } auto pe = make_input(pe_cache_.get_or_create(pe_key, [&]() { Rope::Embedding embedding; - embedding.positions.append_image(static_cast(h), static_cast(w)); - embedding.positions.images.back().height_axis = 2; - embedding.positions.images.back().width_axis = 3; - embedding.positions.append_tokens(nt); - for (const auto& ref : refs) { - embedding.positions.append_image(static_cast(ref->ne[1]), static_cast(ref->ne[0])); - embedding.positions.images.back().height_axis = 2; - embedding.positions.images.back().width_axis = 3; - } - int64_t body = h * w + nt; - for (int64_t token = 0; token < body; ++token) { - float pos[4] = {0.f, float(token - h * w), 0.f, 0.f}; - if (token < h * w) { - pos[1] = float(nt); - pos[2] = float(token / w) - float(h - 1) / 2.f; - pos[3] = float(token % w) - float(w - 1) / 2.f; + embedding.ids.reserve(tokens); + auto append_image = [&](int64_t height, int64_t width, float ref_index, float text_position) { + embedding.positions.append_image(static_cast(height), static_cast(width)); + auto& region = embedding.positions.images.back(); + region.height_axis = 2; + region.width_axis = 3; + for (int64_t i = 0; i < height * width; ++i) { + embedding.ids.push_back({ref_index, text_position, + float(i / width) - float(height - 1) / 2.f, + float(i % width) - float(width - 1) / 2.f}); } - embedding.ids.push_back({pos[0], pos[1], pos[2], pos[3]}); + }; + append_image(h, w, 0.f, float(nt)); + embedding.positions.append_tokens(nt); + for (int64_t i = 0; i < nt; ++i) { + embedding.ids.push_back({0.f, float(i), 0.f, 0.f}); } - // ref i owns r-index i+1 with f=0, centered in h/w, on its own PE rows so a - // later Scale-ROPE on the generated image cannot corrupt the ref frequencies. - for (int64_t ri = 0; ri < (int64_t)refs.size(); ++ri) { - const int64_t rh = refs[ri]->ne[1], rw = refs[ri]->ne[0]; - for (int64_t t = 0; t < rh * rw; ++t) { - float pos[4] = {float(ri + 1), 0.f, - float(t / rw) - float(rh - 1) / 2.f, - float(t % rw) - float(rw - 1) / 2.f}; - embedding.ids.push_back({pos[0], pos[1], pos[2], pos[3]}); - } + for (size_t i = 0; i < refs.size(); ++i) { + append_image(refs[i]->ne[1], refs[i]->ne[0], float(i + 1), 0.f); } - GGML_ASSERT((int64_t)embedding.ids.size() == body + ref_tokens); embedding.values = Rope::embed_nd(embedding.ids, 1, 10000.f, std::vector(4, static_cast(config.head_dim / 4)), embedding.layout, &embedding.frequencies); - auto values = finish_rope_pe(std::move(embedding)); - return sd::Tensor({2, 2, config.head_dim / 2, body + ref_tokens}, std::move(values)); + return sd::Tensor({2, 2, config.head_dim / 2, tokens}, finish_rope_pe(std::move(embedding))); })); - time_data.resize(config.freq_dim); - for (int64_t i = 0; i < config.freq_dim / 2; ++i) { - double angle = inputs.timesteps->values()[0] * std::pow(10000.0, -double(i) / double(config.freq_dim / 2)); - time_data[i] = float(std::cos(angle)); - time_data[i + config.freq_dim / 2] = float(std::sin(angle)); + const auto half = config.freq_dim / 2; + const int time_count = refs.empty() ? 1 : 2; + time_data.assign(time_count * config.freq_dim, 0.f); + for (int64_t i = 0; i < half; ++i) { + const double angle = inputs.timesteps->values()[0] * std::pow(10000.0, -double(i) / double(half)); + time_data[i] = float(std::cos(angle)); + time_data[i + half] = float(std::sin(angle)); } - auto time = ggml_new_tensor_3d(compute_ctx, GGML_TYPE_F32, config.freq_dim, 1, 1); - set_backend_tensor_data(time, time_data.data()); - // timestep_embedding(0) = [1 x freq_dim/2, 0 x freq_dim/2] (cos(0)=1, sin(0)=0). - // Not built as ggml_scale(time, 0) — that would zero the cos half as well. - ggml_tensor* time_0 = nullptr; + ggml_tensor* rows = nullptr; if (!refs.empty()) { - time0_data.assign(config.freq_dim / 2, 1.f); - time0_data.resize(config.freq_dim, 0.f); - time_0 = ggml_new_tensor_3d(compute_ctx, GGML_TYPE_F32, config.freq_dim, 1, 1); - set_backend_tensor_data(time_0, time0_data.data()); + // The second row is the timestep-zero embedding for reference tokens. + std::fill_n(time_data.begin() + config.freq_dim, half, 1.f); + modulation_rows = sd::Tensor::zeros({tokens}); + std::fill_n(modulation_rows.data() + ref_start, tokens - ref_start, 1); + rows = make_input(modulation_rows); } + auto time = ggml_new_tensor_2d(compute_ctx, GGML_TYPE_F32, config.freq_dim, time_count); + set_backend_tensor_data(time, time_data.data()); auto ctx = get_context(gf); - ggml_build_forward_expand(gf, model.forward(&ctx, x, time, time_0, text, pe, skip, refs)); + ggml_build_forward_expand(gf, model.forward(&ctx, x, time, text, pe, skip, refs, rows)); return gf; }; return restore_trailing_singleton_dims(GGMLRunner::compute(graph, n_threads, false), inputs.x->dim()); From 072c1a164f3a435b076efa4c472d868aaa2c5690 Mon Sep 17 00:00:00 2001 From: leejet Date: Mon, 23 Nov 2026 00:53:32 +0800 Subject: [PATCH 5/6] feat: use the HQ workflow by default for MOSS-Image editing --- docs/dgl-builtins.md | 2 +- docs/dgl.md | 4 ++ docs/dgl/README.md | 2 +- .../moss_image/moss-image-edit-chinoll.dgl | 59 +++++++++++++++++++ docs/dgl/moss_image/moss-image-edit.dgl | 25 ++++---- docs/guides/edit.md | 2 +- docs/models/moss_image.md | 49 ++++++++------- src/api/generation_image.cpp | 16 +++-- src/conditioning/conditioner.hpp | 30 ++++++++-- src/dgl/bindings/predictor.cpp | 6 ++ src/dgl/bindings/registration.cpp | 1 + src/dgl/models/diffusion_prediction.h | 1 + src/dgl/models/dit.cpp | 1 + src/model/common/rope.hpp | 6 ++ src/model/diffusion/model.hpp | 1 + src/model/diffusion/moss_image.hpp | 17 +++--- src/name_conversion.cpp | 2 + 17 files changed, 167 insertions(+), 57 deletions(-) create mode 100644 docs/dgl/moss_image/moss-image-edit-chinoll.dgl diff --git a/docs/dgl-builtins.md b/docs/dgl-builtins.md index 4905a7fa15..073fbe73a9 100644 --- a/docs/dgl-builtins.md +++ b/docs/dgl-builtins.md @@ -70,7 +70,7 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn | `photomaker::encode_images` | `photomaker: photomaker`, `images: list`, `id_embedding?: tensor` | `tensor` | | `photomaker::encode_prompt` | `encoder: text_encoder`, `text: string`, `tokens: tensor`, `width?: int = 1024`, `height?: int = 1024`, `clip_skip?: int = -1` | `dict`
`condition: dict`
`condition.concat: tensor`
`condition.crossattn: tensor`
`condition.extra_crossattn: list`
`condition.image_embed_indices: list`
`condition.image_embeds: list`
`condition.input_ids: tensor`
`condition.position_ids: tensor`
`condition.ref_audios: list`
`condition.ref_images: list`
`condition.reference_blocks: list`
`condition.reference_blocks.audio: int`
`condition.reference_blocks.kind: string`
`condition.reference_blocks.video: int`
`condition.t5_ids: tensor`
`condition.t5_weights: tensor`
`condition.token_types: tensor`
`condition.vector: tensor`
`condition.vinput_mask: tensor`
`mask: tensor`
`plain: dict`
`plain.concat: tensor`
`plain.crossattn: tensor`
`plain.extra_crossattn: list`
`plain.image_embed_indices: list`
`plain.image_embeds: list`
`plain.input_ids: tensor`
`plain.position_ids: tensor`
`plain.ref_audios: list`
`plain.ref_images: list`
`plain.reference_blocks: list`
`plain.reference_blocks.audio: int`
`plain.reference_blocks.kind: string`
`plain.reference_blocks.video: int`
`plain.t5_ids: tensor`
`plain.t5_weights: tensor`
`plain.token_types: tensor`
`plain.vector: tensor`
`plain.vinput_mask: tensor` | | `photomaker::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false` | `photomaker` | -| `predictor` | `model: denoiser`, `condition: dict`, `prediction?: string = "auto"`, `concat?: tensor`, `ref_latents?: list`, `ref_audios?: list`, `reference_blocks?: list`, `keyframe_indices?: list`, `ref_index_mode?: string = "fixed"`, `force_ref_timestep_zero?: bool = false`, `guidance?: number = 3.5`, `skip_layers?: list`, `vace_context?: tensor`, `vace_strength?: number = 1`, `audio_embedding?: tensor`, `video_positions?: tensor`, `audio_length?: int = 0`, `fps?: number = 24`, `video_sigma_shift?: number = 12`, `audio_sigma_shift?: number = 3`, `circular_x?: bool = false`, `circular_y?: bool = false`, `transform?: fn`, `transform_args?: dict` | `predictor` | +| `predictor` | `model: denoiser`, `condition: dict`, `prediction?: string = "auto"`, `concat?: tensor`, `ref_latents?: list`, `ref_audios?: list`, `reference_blocks?: list`, `keyframe_indices?: list`, `ref_index_mode?: string = "fixed"`, `force_ref_timestep_zero?: bool = false`, `ref_rope_anchor?: string = "default"`, `guidance?: number = 3.5`, `skip_layers?: list`, `vace_context?: tensor`, `vace_strength?: number = 1`, `audio_embedding?: tensor`, `video_positions?: tensor`, `audio_length?: int = 0`, `fps?: number = 24`, `video_sigma_shift?: number = 12`, `audio_sigma_shift?: number = 3`, `circular_x?: bool = false`, `circular_y?: bool = false`, `transform?: fn`, `transform_args?: dict` | `predictor` | | `preview` | `decoder?: vae`, `circular_x?: bool = false`, `circular_y?: bool = false` | `sampling_observer` | | `pulid::apply` | `condition: dict`, `pulid: pulid`, `embedding: tensor`, `strength?: number = 1`, `start_sigma?: number`, `end_sigma?: number` | same type as `condition`
`pulid: pulid_bindings` | | `pulid::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false` | `pulid` | diff --git a/docs/dgl.md b/docs/dgl.md index 1adb6249e2..2f98af6a74 100644 --- a/docs/dgl.md +++ b/docs/dgl.md @@ -780,6 +780,10 @@ pixels to `encode_prompt` and prepared latents to `predictor` explicitly. `predictor(ref_index_mode="increase")` selects reference position indexing; the default is `"fixed"`. Use `"decrease"` for layered references and set `force_ref_timestep_zero=true` when required by the checkpoint. +`ref_rope_anchor` selects which position reference tokens share along the RoPE +sequence axis. MOSS-Image uses `"image_start"` for HQ and `"text_start"` for the +chinoll LoRA. `"default"` uses the model's alignment. See the +[MOSS-Image editing examples](models/moss_image.md#dgl). `prediction` belongs to `predictor`, for example `pos = predictor(dit, condition, prediction="eps")`. `load_dit` and its diff --git a/docs/dgl/README.md b/docs/dgl/README.md index 669476a32e..0cbc3ce2aa 100644 --- a/docs/dgl/README.md +++ b/docs/dgl/README.md @@ -65,7 +65,7 @@ and [NumPy tensor files](../dgl.md#tensor-files). | [Ming-Image](../models/ming_image.md) | [0.1 Design text to image](ming_image/ming-image-0-1-design-txt2img.dgl) | | [MiniMax-H3-Image](../models/minimax_h3_image.md) | [Text to image](minimax_h3_image/minimax-h3-image-txt2img.dgl) · [Image editing](minimax_h3_image/minimax-h3-image-edit.dgl) | | [MiniT2I](../models/minit2i.md) | [CUDA](minit2i/minit2i-cuda-txt2img.dgl) · [Metal](minit2i/minit2i-metal-txt2img.dgl) (`--threads 8`) | -| [MOSS-Image](../models/moss_image.md) | [Base: text to image](moss_image/moss-image-base-txt2img.dgl) · [SFT: text to image](moss_image/moss-image-sft-txt2img.dgl) · [Inline images](moss_image/moss-image-sft-inline-images.dgl) · [Reference-guided editing](moss_image/moss-image-edit.dgl) | +| [MOSS-Image](../models/moss_image.md) | [Base: text to image](moss_image/moss-image-base-txt2img.dgl) · [SFT: text to image](moss_image/moss-image-sft-txt2img.dgl) · [Inline images](moss_image/moss-image-sft-inline-images.dgl) · [HQ editing](moss_image/moss-image-edit.dgl) · [chinoll editing](moss_image/moss-image-edit-chinoll.dgl) | | [Ovis-Image](../models/ovis_image.md) | [Text to image](ovis_image/ovis-image-txt2img.dgl) | | [P-H3-Image](../models/p_h3_image.md) | [Text to image](p_h3_image/p-h3-image-txt2img.dgl) · [Image editing](p_h3_image/p-h3-image-edit.dgl) | | [PiD](../models/pid.md) | [512 to 2048 pixels](pid/pid-flux1-512-to-2048-txt2img.dgl) | diff --git a/docs/dgl/moss_image/moss-image-edit-chinoll.dgl b/docs/dgl/moss_image/moss-image-edit-chinoll.dgl new file mode 100644 index 0000000000..b6199a7711 --- /dev/null +++ b/docs/dgl/moss_image/moss-image-edit-chinoll.dgl @@ -0,0 +1,59 @@ +# version: 0.0.0 +# docs/models/moss_image.md — chinoll/Moss-Image-Edit + +var { + model_path = "../models/diffusion_models/moss_image_sft_int8_convrot_attn.safetensors" + text_path = "../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf" + tokenizer_path = "../models/tokenizers/tokenizer_qwen3.5.json" + vae_path = "../models/vae/flux2_ae.safetensors" + lora_path = "../models/loras/moss/moss-edit-lora.safetensors" + lora_weight = 1.0 + + reference_paths = ["../assets/flux/flux1-dev-q8_0.png"] + output_path = "output.png" + prompt = "change 'flux.cpp' to 'moss.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "discrete" +} + +fn encode_reference(path, vae, rng) { + image = image::to_f32(image::load(path), channels = 3) + shape = tensor::shape(image) + long_edge = shape[0] + shape[1] - math::min(shape[0], shape[1]) + scale = math::min(1024, long_edge) / long_edge + rounded = [math::round(shape[0] * scale / 16) * 16, math::round(shape[1] * scale / 16) * 16] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], 16, dtype = "i64")) + pixels = tensor::interpolate(image, size = size, mode = "bilinear") + return vae_to_dit_latents(vae, vae_encode(vae, pixels, rng = rng)) +} + +fn main() { + base_model = load_dit(model_path, family = "moss_image") + model = apply_lora(base_model, load_lora(lora_path), weight = lora_weight, mode = "auto") + text = load_text_encoder(text_path, family = "moss_image", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "moss_image") + + encode_rng = make_rng(rng_type, seed = seed) + references = map(reference_paths, process = encode_reference, vae = vae, rng = encode_rng) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, ref_latents = references, ref_index_mode = "increase", ref_rope_anchor = "text_start", force_ref_timestep_zero = true) + neg = predictor(model, negative, ref_latents = references, ref_index_mode = "increase", ref_rope_anchor = "text_start", force_ref_timestep_zero = true) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/moss_image/moss-image-edit.dgl b/docs/dgl/moss_image/moss-image-edit.dgl index 4c7cd820b8..40bc4b7771 100644 --- a/docs/dgl/moss_image/moss-image-edit.dgl +++ b/docs/dgl/moss_image/moss-image-edit.dgl @@ -1,12 +1,13 @@ # version: 0.0.0 -# docs/models/moss_image.md +# docs/models/moss_image.md — MOSS-Image-Edit-HQ var { model_path = "../models/diffusion_models/moss_image_sft_int8_convrot_attn.safetensors" text_path = "../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf" + vision_path = "../models/text_encoders/Qwen3.5-9B-mmproj-BF16.gguf" tokenizer_path = "../models/tokenizers/tokenizer_qwen3.5.json" vae_path = "../models/vae/flux2_ae.safetensors" - lora_path = "../models/loras/moss/moss-edit-lora.safetensors" + lora_path = "../models/loras/moss/armV5-moss-edit-lora.safetensors" lora_weight = 1.0 reference_paths = ["../assets/flux/flux1-dev-q8_0.png"] @@ -24,8 +25,11 @@ var { scheduler = "discrete" } -fn encode_reference(path, vae, rng) { - image = image::to_f32(image::load(path), channels = 3) +fn load_reference(path) { + return image::to_f32(image::load(path), channels = 3) +} + +fn encode_reference(image, vae, rng) { shape = tensor::shape(image) long_edge = shape[0] + shape[1] - math::min(shape[0], shape[1]) scale = math::min(1024, long_edge) / long_edge @@ -38,16 +42,17 @@ fn encode_reference(path, vae, rng) { fn main() { base_model = load_dit(model_path, family = "moss_image") model = apply_lora(base_model, load_lora(lora_path), weight = lora_weight, mode = "auto") - text = load_text_encoder(text_path, family = "moss_image", tokenizer = tokenizer_path) + text = load_text_encoder(text_path, family = "moss_image", tokenizer = tokenizer_path, vision_path = vision_path) vae = load_vae(vae_path, family = "moss_image") encode_rng = make_rng(rng_type, seed = seed) - references = map(reference_paths, process = encode_reference, vae = vae, rng = encode_rng) + images = map(reference_paths, process = load_reference) + references = map(images, process = encode_reference, vae = vae, rng = encode_rng) base = tensor::zeros(latent_shape(vae, width = width, height = height)) - positive = encode_prompt(text, prompt, width = width, height = height) - negative = encode_prompt(text, negative_prompt, width = width, height = height) - pos = predictor(model, positive, ref_latents = references, ref_index_mode = "increase", force_ref_timestep_zero = true) - neg = predictor(model, negative, ref_latents = references, ref_index_mode = "increase", force_ref_timestep_zero = true) + positive = encode_prompt(text, prompt, width = width, height = height, media = images) + negative = encode_prompt(text, negative_prompt, width = width, height = height, media = images) + pos = predictor(model, positive, ref_latents = references, ref_index_mode = "increase", ref_rope_anchor = "image_start", force_ref_timestep_zero = true) + neg = predictor(model, negative, ref_latents = references, ref_index_mode = "increase", ref_rope_anchor = "image_start", force_ref_timestep_zero = true, skip_layers = [22]) guided = cfg(pos, neg, scale = cfg_scale) sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) rng = make_rng(rng_type, seed = seed) diff --git a/docs/guides/edit.md b/docs/guides/edit.md index 48bc9ba86f..4a6fe1d69f 100644 --- a/docs/guides/edit.md +++ b/docs/guides/edit.md @@ -23,7 +23,7 @@ that do not support image guidance report an error. | Fibo 2.0 | Shared center crops for VAE and vision encoding; multiple references use aspect-ratio buckets | | [Anima Edit](../models/anima.md) | Matching community editing LoRA; VAE reference latents | | [Krea2 Edit](../models/krea2.md) | Matching community editing LoRA; vision inputs and VAE reference latents | -| [MOSS-Image Edit](../models/moss_image.md#dgl) | Community editing LoRA; FLUX.2 VAE reference latents at timestep zero, with a 1024-pixel long-edge cap | +| [MOSS-Image-Edit-HQ](../models/moss_image.md#dgl) | FLUX.2 VAE reference latents at timestep zero and Qwen3.5 vision conditioning when vision weights are available | | LLaDA-Image | Reference pixels go to the text encoder's native image components and reference latents to the diffusion model | | MiniMax-H3 | Aspect-preserving references aligned to the model grid | diff --git a/docs/models/moss_image.md b/docs/models/moss_image.md index cb471cbd58..6300b2215d 100644 --- a/docs/models/moss_image.md +++ b/docs/models/moss_image.md @@ -1,6 +1,6 @@ # MOSS-Image -MOSS-Image uses a 5B diffusion transformer, the FLUX.2 VAE, and Qwen3.5 9B as the LLM text encoder. Base and SFT support text-to-image generation and reference-guided editing with the MOSS-Image Edit LoRA. +MOSS-Image uses a 5B diffusion transformer, the FLUX.2 VAE, and Qwen3.5 9B as the LLM text encoder. Base and SFT support text-to-image generation. The default reference-guided workflow uses MOSS-Image-Edit-HQ with SFT. The chinoll LoRA has a dedicated DGL example for Base or SFT. ## Model files @@ -10,7 +10,9 @@ MOSS-Image uses a 5B diffusion transformer, the FLUX.2 VAE, and Qwen3.5 9B as th | vae | [Safetensors](https://huggingface.co/Comfy-Org/MOSS-Image/tree/main/vae) | `--vae` | Use matching VAE | | Qwen3.5 9B | [GGUF](https://huggingface.co/unsloth/Qwen3.5-9B-GGUF/tree/main) | `--llm` | Use matching text encoder | | `tokenizer.json` | [Download](https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base/tree/main/tokenizer) | `--tokenizer` | Required; match text encoder | -| MOSS-Image Edit LoRA | [`adapter_model.safetensors`](https://huggingface.co/chinoll/Moss-Image-Edit/tree/main) | `--lora-model-dir` and `` in the prompt | Required for editing | +| Qwen3.5 9B vision projector | Matching Qwen3.5 9B `mmproj` or an encoder with embedded vision weights | `--llm_vision` | Required for HQ visual prompt conditioning and inline prompt images | +| MOSS-Image-Edit-HQ LoRA | [`armV5-moss-edit-lora.safetensors`](https://huggingface.co/akhaliq/MOSS-Image-Edit-HQ/tree/main) | `--lora-model-dir` and `` in the prompt | Required for the default editing example | +| chinoll Moss-Image-Edit LoRA | [`adapter_model.safetensors`](https://huggingface.co/chinoll/Moss-Image-Edit/tree/main) | `lora_path` in the chinoll DGL script | Required for the chinoll workflow | Pass the external `tokenizer.json` with `--tokenizer`; Qwen3.5 uses a different vocabulary from the embedded Qwen tokenizer. @@ -44,20 +46,15 @@ Select optional components when required by your checkpoint or task. | [Base: text to image](../dgl/moss_image/moss-image-base-txt2img.dgl) | MOSS-Image Base. | | [SFT: text to image](../dgl/moss_image/moss-image-sft-txt2img.dgl) | MOSS-Image SFT. | | [Inline images](../dgl/moss_image/moss-image-sft-inline-images.dgl) | Insert named images into the prompt. | -| [Reference-guided editing](../dgl/moss_image/moss-image-edit.dgl) | Edit with Base or SFT and the community editing LoRA. | +| [MOSS-Image-Edit-HQ](../dgl/moss_image/moss-image-edit.dgl) | Edit with SFT and the HQ LoRA. | +| [chinoll Moss-Image-Edit](../dgl/moss_image/moss-image-edit-chinoll.dgl) | Edit with Base or SFT and the chinoll LoRA. | -The editing script uses the same input and settings as the [CLI edit example](#moss-image-edit). -Change `lora_path` or list different inputs in `reference_paths` as needed. -The script caps the reference long edge at 1024 pixels and aligns both dimensions -to 16 before encoding with the FLUX.2 VAE. Both predictor branches receive the -same reference latents at timestep zero. Use `(phrase:1.2)` to weight a phrase -in the prompt. - -The editing examples use the `moss-edit-lora` format. MOSS-Image-Edit-HQ publishes -an `armV5-moss-edit-lora.safetensors` export for this workflow with MOSS-Image SFT. -Its native `weights/armV5/armV5.safetensors` file uses the ai-toolkit workflow, -which also sends reference images to the vision encoder and uses different -diffusion position indices. [MOSS-Image-Edit-HQ model card](https://huggingface.co/akhaliq/MOSS-Image-Edit-HQ#use-in-comfyui) +The HQ script uses the same input and settings as the [CLI edit example](#moss-image-edit). +It passes the references to both the FLUX.2 VAE and Qwen3.5 vision encoder. The +chinoll script passes them to the VAE and uses `ref_rope_anchor = "text_start"`. +Both scripts cap the reference long edge at 1024 pixels and align both dimensions +to 16 for VAE encoding. Change `lora_path` and `reference_paths` to use your +files. Use `(phrase:1.2)` to weight a phrase in the prompt. #### Run a script @@ -157,10 +154,11 @@ CLI examples use the [shared path and shell conventions](README.md#example-conve #### MOSS-Image Edit -Save the edit LoRA as `models/loras/moss/moss-edit-lora.safetensors` in the -repository, or adjust the LoRA path in the [DGL example](../dgl/moss_image/moss-image-edit.dgl) -or the LoRA tag below. Pass `-r` once per reference in the CLI, or supply -`ref_images` in the C API. +Save the HQ LoRA as `models/loras/moss/armV5-moss-edit-lora.safetensors`, or +adjust the LoRA tag below. The CLI and C API use the HQ layout by default. +Pass `-r` once per reference in the CLI, or set `ref_images` in the C API. +Set `llm_vision_path` in the C API for a separate vision projector. A text-only +encoder still supplies the text condition and the VAE supplies reference latents. **Windows (PowerShell)** @@ -168,11 +166,12 @@ or the LoRA tag below. Pass `-r` once per reference in the CLI, or supply .\bin\Release\sd-cli.exe ` --diffusion-model ..\models\diffusion_models\moss_image_sft_int8_convrot_attn.safetensors ` --llm ..\models\text_encoders\Qwen3.5-9B-Q4_K_M.gguf ` + --llm_vision ..\models\text_encoders\Qwen3.5-9B-mmproj-BF16.gguf ` --vae ..\models\vae\flux2_ae.safetensors ` --tokenizer ..\models\tokenizers\tokenizer_qwen3.5.json ` --lora-model-dir ..\models\loras ` -r ..\assets\flux\flux1-dev-q8_0.png ` - -p "change 'flux.cpp' to 'moss.cpp'" ` + -p "change 'flux.cpp' to 'moss.cpp'" ` --cfg-scale 3.0 ` -v ``` @@ -183,11 +182,12 @@ or the LoRA tag below. Pass `-r` once per reference in the CLI, or supply ./bin/sd-cli \ --diffusion-model ../models/diffusion_models/moss_image_sft_int8_convrot_attn.safetensors \ --llm ../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf \ + --llm_vision ../models/text_encoders/Qwen3.5-9B-mmproj-BF16.gguf \ --vae ../models/vae/flux2_ae.safetensors \ --tokenizer ../models/tokenizers/tokenizer_qwen3.5.json \ --lora-model-dir ../models/loras \ -r ../assets/flux/flux1-dev-q8_0.png \ - -p "change 'flux.cpp' to 'moss.cpp'" \ + -p "change 'flux.cpp' to 'moss.cpp'" \ --cfg-scale 3.0 \ -v ``` @@ -197,7 +197,6 @@ or the LoRA tag below. Pass `-r` once per reference in the CLI, or supply Use output dimensions divisible by 16. The default discrete scheduler uses a flow shift of 5. Use `--flow-shift` to override it. -Text-to-image requests skip layer 22 in the negative predictor. Reference-guided -editing uses all layers in both CFG branches, as in the edit LoRA's reference -sampler. [MOSS-Image SFT pipeline](https://huggingface.co/OpenMOSS-Team/MOSS-Image-SFT/blob/main/pipeline_moss_image.py) · -[MOSS-Image Edit sampler](https://github.com/Chenkin-x/Moss-Image-Edit/blob/main/moss_edit/sampling.py) +Text-to-image and HQ editing skip layer 22 in the negative predictor. The +chinoll workflow uses all layers in both CFG branches. [HQ demo](https://huggingface.co/spaces/akhaliq/moss-image-edit-hq-demo/blob/main/app.py) · +[chinoll sampler](https://github.com/Chenkin-x/Moss-Image-Edit/blob/main/moss_edit/sampling.py) diff --git a/src/api/generation_image.cpp b/src/api/generation_image.cpp index d1a5456802..a5168ba8b4 100644 --- a/src/api/generation_image.cpp +++ b/src/api/generation_image.cpp @@ -54,9 +54,7 @@ namespace sd::api { return pixels; } - static bool qwen_prompt_has_vision(const GenerationTemplate& request) { - if (request.definition.version == VERSION_QWEN_IMAGE_LAYERED) - return false; + static bool prompt_has_vision(const GenerationTemplate& request) { const auto* vision_path = request.context.config.context.llm_vision_path; if (vision_path && *vision_path) return true; @@ -76,6 +74,11 @@ namespace sd::api { const auto refs = bound_tensors(request.options, "ref_images"); if (refs.empty() && !sd_version_is_unet_edit(version)) return; + const bool moss_edit = version == VERSION_MOSS_IMAGE; + const bool qwen_edit = sd_version_is_qwen_image(version) && version != VERSION_QWEN_IMAGE_LAYERED; + const bool has_vision = (moss_edit || qwen_edit) && prompt_has_vision(request); + if (moss_edit && !has_vision) + LOG_INFO("MOSS-Image HQ edit is using text-only prompt conditioning; set llm_vision_path (--llm_vision) to add reference images to Qwen3.5"); std::string pixels, latents; const bool encode = version != VERSION_HIDREAM_O1; for (size_t i = 0; i < refs.size(); ++i) { @@ -94,7 +97,7 @@ namespace sd::api { request.fields["negative_predictor_options"] += ", reference_blocks = " + literal(blocks); request.fields["reference_predictor_options"] += ", reference_blocks = " + literal(blocks); } - if ((sd_version_is_qwen_image(version) && qwen_prompt_has_vision(request)) || sd_version_is_minimax_h3_image(version) || + if (has_vision || sd_version_is_minimax_h3_image(version) || version == VERSION_FIBO2 || sd_version_is_llada_image(version) || sd_version_is_krea2(version) || sd_version_is_mage_flow(version) || sd_version_is_longcat(version) || sd_version_is_boogu_image(version)) { request.fields["prompt_options"] += ", media = [" + pixels + "]"; @@ -102,7 +105,6 @@ namespace sd::api { request.fields["negative_prompt_options"] += ", media = [" + pixels + "]"; } if (encode && !sd_version_is_unet_edit(version)) { - const bool moss_edit = version == VERSION_MOSS_IMAGE; const bool increase = sd_version_is_flux2(version) || sd_version_is_flux3(version) || sd_version_is_qwen_image(version) || sd_version_is_minimax_h3_image(version) || version == VERSION_FIBO2 || sd_version_is_krea2(version) || @@ -111,6 +113,8 @@ namespace sd::api { literal(version == VERSION_QWEN_IMAGE_LAYERED ? "decrease" : increase ? "increase" : "fixed") + ", force_ref_timestep_zero = " + literal(sd_version_is_llada_image(version) || sd_version_is_krea2(version) || moss_edit); + if (moss_edit) + options += ", ref_rope_anchor = \"image_start\""; request.fields["predictor_options"] += options; request.fields["negative_predictor_options"] += options; request.fields["reference_predictor_options"] += options; @@ -191,7 +195,7 @@ namespace sd::api { request.flags["reference_image_guidance"] = reference_guidance && image_guidance; request.flags["hidream_o1"] = version == VERSION_HIDREAM_O1; request.flags["control_image_guidance"] = image_guidance && version == VERSION_FLUX_CONTROLS; - if (version == VERSION_MOSS_IMAGE && !refs) + if (version == VERSION_MOSS_IMAGE) request.fields["negative_predictor_options"] += ", skip_layers = [22]"; if (sd_version_is_sensenova_u1(version)) { request.fields["negative_prompt_input"] = "negative_prompt_raw"; diff --git a/src/conditioning/conditioner.hpp b/src/conditioning/conditioner.hpp index 57aa8a693e..64f8007743 100644 --- a/src/conditioning/conditioner.hpp +++ b/src/conditioning/conditioner.hpp @@ -14,6 +14,7 @@ #include "conditioning/textual_inversion.h" #include "core/ggml_tensor_utils.h" #include "core/image_geometry.h" +#include "core/image_tensor.h" #include "core/tensor_ggml.hpp" #include "core/util.h" @@ -1993,7 +1994,8 @@ struct LLMEmbedder : public Conditioner { return 0; return sd_version_is_minimax_h3(version) || sd_version_is_lingbot_video(version) || sd_version_is_qwen_image(version) || sd_version_is_mage_flow(version) || - sd_version_is_boogu_image(version) || sd_version_is_krea2(version) || sd_version_is_longcat(version) + sd_version_is_boogu_image(version) || sd_version_is_krea2(version) || sd_version_is_longcat(version) || + version == VERSION_MOSS_IMAGE ? std::numeric_limits::max() : 0; } @@ -2560,8 +2562,28 @@ struct LLMEmbedder : public Conditioner { SDCondition get_learned_condition(int n_threads, const ConditionerParams& params) override { ConditionerParams conditioner_params = params; - sd::PromptInputTemplate input_template(params.prompt_input); - if (params.prompt_input != nullptr) { + sd::PromptInput prompt_with_references; + if (version == VERSION_MOSS_IMAGE && params.ref_images && !params.ref_images->empty()) { + for (size_t i = 0; i < params.ref_images->size(); ++i) { + const auto& source = (*params.ref_images)[i]; + const auto width = source.shape()[0], height = source.shape()[1]; + const double scale = std::min(1.0, std::sqrt(384.0 * 384.0 / (double(width) * height))); + const auto w = std::max(32, std::llround(width * scale)); + const auto h = std::max(32, std::llround(height * scale)); + auto rgb = sd::ensure_image_tensor_channels(source, 3); + if (w != width || h != height) + rgb = sd::ops::interpolate(rgb, {w, h, 3, 1}, sd::ops::InterpolateMode::Bicubic, false, true); + prompt_with_references.push_back({sd::PromptPart::Type::TEXT, "Picture " + std::to_string(i + 1) + ": "}); + prompt_with_references.push_back({sd::PromptPart::Type::IMAGE, {}, std::make_shared>(std::move(rgb))}); + } + if (params.prompt_input) + prompt_with_references.insert(prompt_with_references.end(), params.prompt_input->begin(), params.prompt_input->end()); + else + prompt_with_references.push_back({sd::PromptPart::Type::TEXT, params.text}); + conditioner_params.prompt_input = &prompt_with_references; + } + sd::PromptInputTemplate input_template(conditioner_params.prompt_input); + if (conditioner_params.prompt_input != nullptr) { if (!supports_prompt_images()) { LOG_ERROR("This conditioner does not support inline prompt images"); return {}; @@ -3332,7 +3354,7 @@ struct LLMEmbedder : public Conditioner { image_grids, prompt_suffix, version == VERSION_IRIS ? &text_mask : nullptr, - params.prompt_input == nullptr ? nullptr : &input_template, + conditioner_params.prompt_input == nullptr ? nullptr : &input_template, &prompt_tokens); if (hidden_states.empty()) { return {}; diff --git a/src/dgl/bindings/predictor.cpp b/src/dgl/bindings/predictor.cpp index 562b44949f..5e20df0852 100644 --- a/src/dgl/bindings/predictor.cpp +++ b/src/dgl/bindings/predictor.cpp @@ -136,6 +136,12 @@ namespace sd::dgl { : ref_index_mode == "decrease" ? Rope::RefIndexMode::DECREASE : Rope::RefIndexMode::FIXED; output.options.force_ref_timestep_zero = get_bool(args, "force_ref_timestep_zero"); + const auto ref_rope_anchor = get_string(args, "ref_rope_anchor"); + if (ref_rope_anchor != "default" && engine.version() != VERSION_MOSS_IMAGE) + throw std::runtime_error("reference RoPE anchoring is not configurable for this model"); + output.options.ref_rope_anchor = ref_rope_anchor == "image_start" ? Rope::RefRoPEAnchor::IMAGE_START + : ref_rope_anchor == "text_start" ? Rope::RefRoPEAnchor::TEXT_START + : Rope::RefRoPEAnchor::MODEL_DEFAULT; output.options.guidance = float(get_number(args, "guidance")); bind_predictor_options(output, args); const auto& condition = args.at("condition").fields; diff --git a/src/dgl/bindings/registration.cpp b/src/dgl/bindings/registration.cpp index f06ebb201e..6a066ef1c2 100644 --- a/src/dgl/bindings/registration.cpp +++ b/src/dgl/bindings/registration.cpp @@ -578,6 +578,7 @@ namespace sd::dgl { optional_list("ref_latents", Kind::Tensor), optional_list("ref_audios", Kind::Tensor), optional_list("reference_blocks", Kind::Dict), optional_list("keyframe_indices", Kind::Integer), choice("ref_index_mode", {"fixed", "increase", "decrease"}, "fixed"), optional("force_ref_timestep_zero", Kind::Boolean, false), + choice("ref_rope_anchor", {"default", "image_start", "text_start"}, "default"), number("guidance", 0, 1000, 3.5), optional_list("skip_layers", Kind::Integer), optional("vace_context", Kind::Tensor), number("vace_strength", 0, 100, 1), optional("audio_embedding", Kind::Tensor), optional("video_positions", Kind::Tensor), diff --git a/src/dgl/models/diffusion_prediction.h b/src/dgl/models/diffusion_prediction.h index 4a7cb78a2c..94bc6d1e64 100644 --- a/src/dgl/models/diffusion_prediction.h +++ b/src/dgl/models/diffusion_prediction.h @@ -41,6 +41,7 @@ namespace sd::dgl::models { float audio_sigma_shift = 3.f; int audio_length = 0; Rope::RefIndexMode ref_index_mode = Rope::RefIndexMode::FIXED; + Rope::RefRoPEAnchor ref_rope_anchor = Rope::RefRoPEAnchor::MODEL_DEFAULT; bool force_ref_timestep_zero = false; std::function transform; }; diff --git a/src/dgl/models/dit.cpp b/src/dgl/models/dit.cpp index 9999f4629c..73e7bbaf54 100644 --- a/src/dgl/models/dit.cpp +++ b/src/dgl/models/dit.cpp @@ -359,6 +359,7 @@ namespace sd::dgl::models { params.c_concat = present(condition.c_concat); params.ref_latents = references.empty() ? &condition.c_ref_images : &references; params.ref_index_mode = options.ref_index_mode; + params.ref_rope_anchor = options.ref_rope_anchor; params.force_ref_timestep_zero = options.force_ref_timestep_zero; UNetControls unet_controls; std::vector z_image_controls; diff --git a/src/model/common/rope.hpp b/src/model/common/rope.hpp index b6f3111a09..c3d638b1a7 100644 --- a/src/model/common/rope.hpp +++ b/src/model/common/rope.hpp @@ -62,6 +62,12 @@ namespace Rope { DECREASE, }; + enum class RefRoPEAnchor { + MODEL_DEFAULT, + IMAGE_START, + TEXT_START, + }; + template __STATIC_INLINE__ std::vector linspace(T start, T end, int num) { std::vector result(num); diff --git a/src/model/diffusion/model.hpp b/src/model/diffusion/model.hpp index b717192702..993624b526 100644 --- a/src/model/diffusion/model.hpp +++ b/src/model/diffusion/model.hpp @@ -178,6 +178,7 @@ struct DiffusionParams { const sd::Tensor* y = nullptr; const std::vector>* ref_latents = nullptr; Rope::RefIndexMode ref_index_mode = Rope::RefIndexMode::FIXED; + Rope::RefRoPEAnchor ref_rope_anchor = Rope::RefRoPEAnchor::MODEL_DEFAULT; bool force_ref_timestep_zero = false; DiffusionExtraParams extra = std::monostate{}; }; diff --git a/src/model/diffusion/moss_image.hpp b/src/model/diffusion/moss_image.hpp index 5da85af2a4..3e87433394 100644 --- a/src/model/diffusion/moss_image.hpp +++ b/src/model/diffusion/moss_image.hpp @@ -247,12 +247,9 @@ namespace MOSSImage { LOG_ERROR("MOSS-Image requires latents, timesteps and text features"); return {}; } - std::vector skip; - if (auto extra = std::get_if(&inputs.extra)) { - if (extra->skip_layers) { - skip = *extra->skip_layers; - } - } + const auto* extra = std::get_if(&inputs.extra); + const std::vector no_skips; + const auto& skip = extra && extra->skip_layers ? *extra->skip_layers : no_skips; const auto* references = inputs.ref_latents; if (references) { for (const auto& ref : *references) { @@ -270,8 +267,10 @@ namespace MOSSImage { const auto h = x->ne[1], w = x->ne[0], nt = text->ne[1]; const auto ref_start = h * w + nt; auto tokens = ref_start; + // ai-toolkit aligns references with image positions. Chinoll aligns them with the start of the text. + const auto text_offset = references && !references->empty() && inputs.ref_rope_anchor != Rope::RefRoPEAnchor::TEXT_START ? -nt : 0; sd::PECacheKey pe_key("moss_image.pe"); - pe_key.add(h).add(w).add(nt).add(config.head_dim).add(circular_x_enabled).add(circular_y_enabled); + pe_key.add(h).add(w).add(nt).add(text_offset).add(config.head_dim).add(circular_x_enabled).add(circular_y_enabled); std::vector refs; if (references) { for (const auto& ref : *references) { @@ -294,10 +293,10 @@ namespace MOSSImage { float(i % width) - float(width - 1) / 2.f}); } }; - append_image(h, w, 0.f, float(nt)); + append_image(h, w, 0.f, float(nt + text_offset)); embedding.positions.append_tokens(nt); for (int64_t i = 0; i < nt; ++i) { - embedding.ids.push_back({0.f, float(i), 0.f, 0.f}); + embedding.ids.push_back({0.f, float(i + text_offset), 0.f, 0.f}); } for (size_t i = 0; i < refs.size(); ++i) { append_image(refs[i]->ne[1], refs[i]->ne[0], float(i + 1), 0.f); diff --git a/src/name_conversion.cpp b/src/name_conversion.cpp index 5216d3d39c..3032597422 100644 --- a/src/name_conversion.cpp +++ b/src/name_conversion.cpp @@ -1076,6 +1076,8 @@ static std::string convert_diffusers_dit_to_original_pixart(std::string name) { } static std::string convert_moss_image_dit_name(std::string name) { + if (starts_with(name, "transformer.layers.")) + name.erase(0, sizeof("transformer.") - 1); static const std::vector> name_map = { {".proj.q.weight", ".proj.qkv.weight"}, {".proj.k.weight", ".proj.qkv.weight.1"}, From 499f60fd44d14e6d9c734cbd3be2a89c7e47df7a Mon Sep 17 00:00:00 2001 From: leejet Date: Mon, 23 Nov 2026 01:03:29 +0800 Subject: [PATCH 6/6] clean doc --- README.md | 3 +- docs/dgl.md | 6 +-- docs/dgl/README.md | 2 +- .../moss_image/moss-image-edit-chinoll.dgl | 8 +++- docs/dgl/moss_image/moss-image-edit.dgl | 11 +++-- docs/guides/edit.md | 2 +- docs/models/moss_image.md | 46 ++++++++----------- 7 files changed, 40 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index b8c2a8186d..b5ddd2a03f 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ API and command-line option may change frequently.*** - [FLUX.1-dev/FLUX.1-schnell](./docs/models/flux.md) - [FLUX.2-dev/FLUX.2-klein](./docs/models/flux2.md) - [FLUX.3 Image Klein / Klein Base](./docs/models/flux3.md) - - [MOSS-Image-Base / MOSS-Image-SFT](./docs/models/moss_image.md), including editing with the community LoRA + - [MOSS-Image-Base / MOSS-Image-SFT](./docs/models/moss_image.md) - [Fibo 2.0 Dev](./docs/models/fibo2.md) - [Lens](./docs/models/lens.md) - [Chroma](./docs/models/chroma.md) @@ -85,6 +85,7 @@ API and command-line option may change frequently.*** - [Mage-Flow-Edit](./docs/models/mage_flow.md#image-editing) - [LLaDA-Image Edit](./docs/models/llada_image.md#image-editing) - [Fibo 2.0 Dev / Edit Turbo](./docs/models/fibo2.md#fibo-20-edit-turbo) + - [MOSS-Image Edit](./docs/models/moss_image.md#moss-image-edit) - Video Models - [Wan2.1/Wan2.2](./docs/models/wan.md) - [MiniMax-H3](./docs/models/minimax_h3.md) diff --git a/docs/dgl.md b/docs/dgl.md index 2f98af6a74..17072e01e4 100644 --- a/docs/dgl.md +++ b/docs/dgl.md @@ -780,9 +780,9 @@ pixels to `encode_prompt` and prepared latents to `predictor` explicitly. `predictor(ref_index_mode="increase")` selects reference position indexing; the default is `"fixed"`. Use `"decrease"` for layered references and set `force_ref_timestep_zero=true` when required by the checkpoint. -`ref_rope_anchor` selects which position reference tokens share along the RoPE -sequence axis. MOSS-Image uses `"image_start"` for HQ and `"text_start"` for the -chinoll LoRA. `"default"` uses the model's alignment. See the +For MOSS-Image, `ref_rope_anchor` aligns reference tokens with the start of the +image (`"image_start"`) or text (`"text_start"`) along the RoPE sequence axis. +`"default"` uses the model's alignment. See the [MOSS-Image editing examples](models/moss_image.md#dgl). `prediction` belongs to `predictor`, for example diff --git a/docs/dgl/README.md b/docs/dgl/README.md index 0cbc3ce2aa..df8958cc69 100644 --- a/docs/dgl/README.md +++ b/docs/dgl/README.md @@ -65,7 +65,7 @@ and [NumPy tensor files](../dgl.md#tensor-files). | [Ming-Image](../models/ming_image.md) | [0.1 Design text to image](ming_image/ming-image-0-1-design-txt2img.dgl) | | [MiniMax-H3-Image](../models/minimax_h3_image.md) | [Text to image](minimax_h3_image/minimax-h3-image-txt2img.dgl) · [Image editing](minimax_h3_image/minimax-h3-image-edit.dgl) | | [MiniT2I](../models/minit2i.md) | [CUDA](minit2i/minit2i-cuda-txt2img.dgl) · [Metal](minit2i/minit2i-metal-txt2img.dgl) (`--threads 8`) | -| [MOSS-Image](../models/moss_image.md) | [Base: text to image](moss_image/moss-image-base-txt2img.dgl) · [SFT: text to image](moss_image/moss-image-sft-txt2img.dgl) · [Inline images](moss_image/moss-image-sft-inline-images.dgl) · [HQ editing](moss_image/moss-image-edit.dgl) · [chinoll editing](moss_image/moss-image-edit-chinoll.dgl) | +| [MOSS-Image](../models/moss_image.md) | [Base: text to image](moss_image/moss-image-base-txt2img.dgl) · [SFT: text to image](moss_image/moss-image-sft-txt2img.dgl) · [Inline images](moss_image/moss-image-sft-inline-images.dgl) · [Image editing (HQ)](moss_image/moss-image-edit.dgl) · [Image editing (chinoll)](moss_image/moss-image-edit-chinoll.dgl) | | [Ovis-Image](../models/ovis_image.md) | [Text to image](ovis_image/ovis-image-txt2img.dgl) | | [P-H3-Image](../models/p_h3_image.md) | [Text to image](p_h3_image/p-h3-image-txt2img.dgl) · [Image editing](p_h3_image/p-h3-image-edit.dgl) | | [PiD](../models/pid.md) | [512 to 2048 pixels](pid/pid-flux1-512-to-2048-txt2img.dgl) | diff --git a/docs/dgl/moss_image/moss-image-edit-chinoll.dgl b/docs/dgl/moss_image/moss-image-edit-chinoll.dgl index b6199a7711..d03021fe84 100644 --- a/docs/dgl/moss_image/moss-image-edit-chinoll.dgl +++ b/docs/dgl/moss_image/moss-image-edit-chinoll.dgl @@ -11,6 +11,7 @@ var { reference_paths = ["../assets/flux/flux1-dev-q8_0.png"] output_path = "output.png" + prompt = "change 'flux.cpp' to 'moss.cpp'" negative_prompt = "" @@ -18,6 +19,7 @@ var { rng_type = "cuda" width = 512 height = 512 + steps = 20 cfg_scale = 3.0 method = "euler" @@ -46,8 +48,10 @@ fn main() { base = tensor::zeros(latent_shape(vae, width = width, height = height)) positive = encode_prompt(text, prompt, width = width, height = height) negative = encode_prompt(text, negative_prompt, width = width, height = height) - pos = predictor(model, positive, ref_latents = references, ref_index_mode = "increase", ref_rope_anchor = "text_start", force_ref_timestep_zero = true) - neg = predictor(model, negative, ref_latents = references, ref_index_mode = "increase", ref_rope_anchor = "text_start", force_ref_timestep_zero = true) + pos = predictor(model, positive, ref_latents = references, + ref_index_mode = "increase", ref_rope_anchor = "text_start", force_ref_timestep_zero = true) + neg = predictor(model, negative, ref_latents = references, + ref_index_mode = "increase", ref_rope_anchor = "text_start", force_ref_timestep_zero = true) guided = cfg(pos, neg, scale = cfg_scale) sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) rng = make_rng(rng_type, seed = seed) diff --git a/docs/dgl/moss_image/moss-image-edit.dgl b/docs/dgl/moss_image/moss-image-edit.dgl index 40bc4b7771..2417f494c2 100644 --- a/docs/dgl/moss_image/moss-image-edit.dgl +++ b/docs/dgl/moss_image/moss-image-edit.dgl @@ -12,6 +12,7 @@ var { reference_paths = ["../assets/flux/flux1-dev-q8_0.png"] output_path = "output.png" + prompt = "change 'flux.cpp' to 'moss.cpp'" negative_prompt = "" @@ -19,6 +20,7 @@ var { rng_type = "cuda" width = 512 height = 512 + steps = 20 cfg_scale = 3.0 method = "euler" @@ -42,7 +44,8 @@ fn encode_reference(image, vae, rng) { fn main() { base_model = load_dit(model_path, family = "moss_image") model = apply_lora(base_model, load_lora(lora_path), weight = lora_weight, mode = "auto") - text = load_text_encoder(text_path, family = "moss_image", tokenizer = tokenizer_path, vision_path = vision_path) + text = load_text_encoder(text_path, family = "moss_image", + tokenizer = tokenizer_path, vision_path = vision_path) vae = load_vae(vae_path, family = "moss_image") encode_rng = make_rng(rng_type, seed = seed) @@ -51,8 +54,10 @@ fn main() { base = tensor::zeros(latent_shape(vae, width = width, height = height)) positive = encode_prompt(text, prompt, width = width, height = height, media = images) negative = encode_prompt(text, negative_prompt, width = width, height = height, media = images) - pos = predictor(model, positive, ref_latents = references, ref_index_mode = "increase", ref_rope_anchor = "image_start", force_ref_timestep_zero = true) - neg = predictor(model, negative, ref_latents = references, ref_index_mode = "increase", ref_rope_anchor = "image_start", force_ref_timestep_zero = true, skip_layers = [22]) + pos = predictor(model, positive, ref_latents = references, + ref_index_mode = "increase", ref_rope_anchor = "image_start", force_ref_timestep_zero = true) + neg = predictor(model, negative, ref_latents = references, + ref_index_mode = "increase", ref_rope_anchor = "image_start", force_ref_timestep_zero = true, skip_layers = [22]) guided = cfg(pos, neg, scale = cfg_scale) sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) rng = make_rng(rng_type, seed = seed) diff --git a/docs/guides/edit.md b/docs/guides/edit.md index 4a6fe1d69f..ac7ef2031a 100644 --- a/docs/guides/edit.md +++ b/docs/guides/edit.md @@ -23,7 +23,7 @@ that do not support image guidance report an error. | Fibo 2.0 | Shared center crops for VAE and vision encoding; multiple references use aspect-ratio buckets | | [Anima Edit](../models/anima.md) | Matching community editing LoRA; VAE reference latents | | [Krea2 Edit](../models/krea2.md) | Matching community editing LoRA; vision inputs and VAE reference latents | -| [MOSS-Image-Edit-HQ](../models/moss_image.md#dgl) | FLUX.2 VAE reference latents at timestep zero and Qwen3.5 vision conditioning when vision weights are available | +| [MOSS-Image Edit](../models/moss_image.md#moss-image-edit) | HQ LoRA with VAE reference latents and optional vision conditioning | | LLaDA-Image | Reference pixels go to the text encoder's native image components and reference latents to the diffusion model | | MiniMax-H3 | Aspect-preserving references aligned to the model grid | diff --git a/docs/models/moss_image.md b/docs/models/moss_image.md index 6300b2215d..f56442a3f4 100644 --- a/docs/models/moss_image.md +++ b/docs/models/moss_image.md @@ -1,6 +1,7 @@ # MOSS-Image -MOSS-Image uses a 5B diffusion transformer, the FLUX.2 VAE, and Qwen3.5 9B as the LLM text encoder. Base and SFT support text-to-image generation. The default reference-guided workflow uses MOSS-Image-Edit-HQ with SFT. The chinoll LoRA has a dedicated DGL example for Base or SFT. +MOSS-Image uses a 5B diffusion transformer, the FLUX.2 VAE, and Qwen3.5 9B as the LLM text encoder. Both Base and SFT are supported. Prompt enhancement is not included. +Image editing requires a matching LoRA. ## Model files @@ -10,16 +11,15 @@ MOSS-Image uses a 5B diffusion transformer, the FLUX.2 VAE, and Qwen3.5 9B as th | vae | [Safetensors](https://huggingface.co/Comfy-Org/MOSS-Image/tree/main/vae) | `--vae` | Use matching VAE | | Qwen3.5 9B | [GGUF](https://huggingface.co/unsloth/Qwen3.5-9B-GGUF/tree/main) | `--llm` | Use matching text encoder | | `tokenizer.json` | [Download](https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base/tree/main/tokenizer) | `--tokenizer` | Required; match text encoder | -| Qwen3.5 9B vision projector | Matching Qwen3.5 9B `mmproj` or an encoder with embedded vision weights | `--llm_vision` | Required for HQ visual prompt conditioning and inline prompt images | -| MOSS-Image-Edit-HQ LoRA | [`armV5-moss-edit-lora.safetensors`](https://huggingface.co/akhaliq/MOSS-Image-Edit-HQ/tree/main) | `--lora-model-dir` and `` in the prompt | Required for the default editing example | -| chinoll Moss-Image-Edit LoRA | [`adapter_model.safetensors`](https://huggingface.co/chinoll/Moss-Image-Edit/tree/main) | `lora_path` in the chinoll DGL script | Required for the chinoll workflow | +| Qwen3.5 9B vision projector | [GGUF](https://huggingface.co/unsloth/Qwen3.5-9B-GGUF/blob/main/mmproj-BF16.gguf) | `--llm_vision` | Required for vision inputs when the encoder uses separate vision weights | +| MOSS-Image-Edit-HQ LoRA | [`armV5-moss-edit-lora.safetensors`](https://huggingface.co/akhaliq/MOSS-Image-Edit-HQ/blob/main/armV5-moss-edit-lora.safetensors) | `--lora-model-dir` | HQ editing with SFT | +| chinoll Moss-Image-Edit LoRA | [`adapter_model.safetensors`](https://huggingface.co/chinoll/Moss-Image-Edit/blob/main/adapter_model.safetensors) | — | Editing with Base or SFT in DGL | Pass the external `tokenizer.json` with `--tokenizer`; Qwen3.5 uses a different vocabulary from the embedded Qwen tokenizer. -For [inline prompt images](../guides/prompt_images.md), use a matching Qwen3.5 -vision projector. Pass it with `--llm_vision` in the CLI or `vision_path` on -`load_text_encoder` in DGL. See the -[DGL example](../dgl/moss_image/moss-image-sft-inline-images.dgl). +[Inline prompt images](../guides/prompt_images.md) require Qwen3.5 vision +weights. HQ editing also uses them when available. Pass a separate projector +with `--llm_vision` in the CLI or `vision_path` on `load_text_encoder` in DGL. ## Usage @@ -46,15 +46,8 @@ Select optional components when required by your checkpoint or task. | [Base: text to image](../dgl/moss_image/moss-image-base-txt2img.dgl) | MOSS-Image Base. | | [SFT: text to image](../dgl/moss_image/moss-image-sft-txt2img.dgl) | MOSS-Image SFT. | | [Inline images](../dgl/moss_image/moss-image-sft-inline-images.dgl) | Insert named images into the prompt. | -| [MOSS-Image-Edit-HQ](../dgl/moss_image/moss-image-edit.dgl) | Edit with SFT and the HQ LoRA. | -| [chinoll Moss-Image-Edit](../dgl/moss_image/moss-image-edit-chinoll.dgl) | Edit with Base or SFT and the chinoll LoRA. | - -The HQ script uses the same input and settings as the [CLI edit example](#moss-image-edit). -It passes the references to both the FLUX.2 VAE and Qwen3.5 vision encoder. The -chinoll script passes them to the VAE and uses `ref_rope_anchor = "text_start"`. -Both scripts cap the reference long edge at 1024 pixels and align both dimensions -to 16 for VAE encoding. Change `lora_path` and `reference_paths` to use your -files. Use `(phrase:1.2)` to weight a phrase in the prompt. +| [Image editing (HQ)](../dgl/moss_image/moss-image-edit.dgl) | SFT with the armV5 LoRA and a Qwen3.5 vision projector. | +| [Image editing (chinoll)](../dgl/moss_image/moss-image-edit-chinoll.dgl) | Base or SFT with the chinoll LoRA. | #### Run a script @@ -154,11 +147,9 @@ CLI examples use the [shared path and shell conventions](README.md#example-conve #### MOSS-Image Edit -Save the HQ LoRA as `models/loras/moss/armV5-moss-edit-lora.safetensors`, or -adjust the LoRA tag below. The CLI and C API use the HQ layout by default. -Pass `-r` once per reference in the CLI, or set `ref_images` in the C API. -Set `llm_vision_path` in the C API for a separate vision projector. A text-only -encoder still supplies the text condition and the VAE supplies reference latents. +The CLI uses the HQ workflow with SFT. Save the LoRA as +`models/loras/moss/armV5-moss-edit-lora.safetensors` or adjust the LoRA tag below. +Pass `-r` for each reference image. **Windows (PowerShell)** @@ -194,9 +185,10 @@ encoder still supplies the text condition and the VAE supplies reference latents ## Notes and limitations -Use output dimensions divisible by 16. The default discrete scheduler uses a -flow shift of 5. Use `--flow-shift` to override it. +Use output dimensions divisible by 16. The editing examples cap the reference +long edge at 1024 pixels. The discrete scheduler defaults to a flow shift of 5. +Use `--flow-shift` to override it. Prompt weights use `(phrase:1.2)` syntax. -Text-to-image and HQ editing skip layer 22 in the negative predictor. The -chinoll workflow uses all layers in both CFG branches. [HQ demo](https://huggingface.co/spaces/akhaliq/moss-image-edit-hq-demo/blob/main/app.py) · -[chinoll sampler](https://github.com/Chenkin-x/Moss-Image-Edit/blob/main/moss_edit/sampling.py) +For text-to-image and HQ editing, the CLI and C API set `skip_layers = [22]` on +the negative predictor. The corresponding DGL examples set the same zero-based +layer index.