diff --git a/README.md b/README.md index 40f09e4ca7..fcd7580d78 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ API and command-line option may change frequently.*** - [Ming-Image Design](./docs/models/ming_image.md) - [PixArt](./docs/models/pixart.md) - [Iris-3B](./docs/models/iris.md) + - [Nucleus-Image](./docs/models/nucleus_image.md) - [Image Edit Models](./docs/guides/edit.md) - [FLUX.1-Kontext-dev](./docs/models/kontext.md) - [Qwen Image Edit series](./docs/models/qwen_image_edit.md) diff --git a/docs/dgl-builtins.md b/docs/dgl-builtins.md index 4c367a6cda..cdebc7d19c 100644 --- a/docs/dgl-builtins.md +++ b/docs/dgl-builtins.md @@ -220,3 +220,4 @@ Pass the ID as the component loader's `family` argument. The default is `"auto"` | `relayvsr` | RelayVSR | | `seedvr2` | SeedVR2 | | `kandinsky_imagesr` | Kandinsky ImageSR 2.0 | +| `nucleus_image` | Nucleus-Image | diff --git a/docs/dgl/README.md b/docs/dgl/README.md index 31cd367b56..39c595aca7 100644 --- a/docs/dgl/README.md +++ b/docs/dgl/README.md @@ -66,6 +66,7 @@ and [NumPy tensor files](../dgl.md#tensor-files). | [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) · [Image editing (HQ)](moss_image/moss-image-edit.dgl) · [Image editing (chinoll)](moss_image/moss-image-edit-chinoll.dgl) | +| [Nucleus-Image](../models/nucleus_image.md) | [Text to image](nucleus_image/nucleus-image-txt2img.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/nucleus_image/nucleus-image-txt2img.dgl b/docs/dgl/nucleus_image/nucleus-image-txt2img.dgl new file mode 100644 index 0000000000..0529f93ebc --- /dev/null +++ b/docs/dgl/nucleus_image/nucleus-image-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/nucleus_image.md — Nucleus-Image + +var { + model_path = "../models/diffusion_models/Nucleus-Image-Q8_0.safetensors" + text_path = "../models/text_encoders/Qwen3VL-8B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/qwen_image_vae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'nucleus.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 768 + height = 768 + + steps = 24 + cfg_scale = 4.5 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "nucleus_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "nucleus_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "nucleus_image", params_backend = "cpu") + + 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) + neg = predictor(model, negative) + 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/models/README.md b/docs/models/README.md index 16ac26df95..b197e83764 100644 --- a/docs/models/README.md +++ b/docs/models/README.md @@ -69,6 +69,7 @@ variant; a VAE or TAE selection must match that model. - [MiniMax-H3-Image](minimax_h3_image.md) - [MiniT2I](minit2i.md) - [MOSS-Image](moss_image.md) +- [Nucleus-Image](nucleus_image.md) - [Ovis-Image](ovis_image.md) - [P-H3-Image](p_h3_image.md) - [PiD](pid.md) diff --git a/docs/models/nucleus_image.md b/docs/models/nucleus_image.md new file mode 100644 index 0000000000..3b668ad970 --- /dev/null +++ b/docs/models/nucleus_image.md @@ -0,0 +1,106 @@ +# Nucleus-Image + +Nucleus-Image is a text-to-image diffusion transformer with sparse mixture-of-experts +layers: 17B total parameters, about 2B active per step. It uses Qwen3-VL-8B-Instruct as +the LLM text encoder and the Qwen-Image VAE. + +## Model files + +| Component | Weights and downloads | CLI option | Requirement | +| --- | --- | --- | --- | +| Nucleus-Image | [Safetensors](https://huggingface.co/stduhpf/Nucleus-Image-sdcpp/tree/main): `Nucleus-Image-Q8_0.safetensors` (18 GB) or `Nucleus-Image-Q5_1.safetensors` (12.7 GB) | `--diffusion-model` | Required | +| Qwen3-VL-8B-Instruct | [GGUF](https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct-GGUF/tree/main): `Qwen3VL-8B-Instruct-Q4_K_M.gguf` | `--llm` | Required | +| vae | [Safetensors](https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/tree/main/split_files/vae): `qwen_image_vae.safetensors` | `--vae` | Required | + +No separate tokenizer file is needed. + +## Usage + +### Web UI + +Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the +server, then select the recipe matching your weights. Fill the component slots +below and click **Load models**. +Use the files and compatibility requirements in [Model files](#model-files). + +| Recipe | Component slots | +| --- | --- | +| Nucleus Image (`nucleus-image`) | `diffusion_model`, `llm`, `vae` | + +Slot IDs correspond to CLI component options: `diffusion_model` uses +`--diffusion-model` and `llm` uses `--llm`. + +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/nucleus_image/nucleus-image-txt2img.dgl) | Nucleus-Image Q8_0. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\nucleus_image\nucleus-image-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/nucleus_image/nucleus-image-txt2img.dgl +``` + +Add `--check` to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe ` + --diffusion-model ..\models\diffusion_models\Nucleus-Image-Q8_0.safetensors ` + --llm ..\models\text_encoders\Qwen3VL-8B-Instruct-Q4_K_M.gguf ` + --vae ..\models\vae\qwen_image_vae.safetensors ` + -p "a lovely cat holding a sign says 'nucleus.cpp'" ` + --cfg-scale 4.5 ` + --steps 24 ` + --sampling-method euler ` + -H 768 ` + -W 768 ` + --seed 42 ` + -v +``` + +**Linux/macOS** + +```sh +./bin/sd-cli \ + --diffusion-model ../models/diffusion_models/Nucleus-Image-Q8_0.safetensors \ + --llm ../models/text_encoders/Qwen3VL-8B-Instruct-Q4_K_M.gguf \ + --vae ../models/vae/qwen_image_vae.safetensors \ + -p "a lovely cat holding a sign says 'nucleus.cpp'" \ + --cfg-scale 4.5 \ + --steps 24 \ + --sampling-method euler \ + -H 768 \ + -W 768 \ + --seed 42 \ + -v +``` + +## Notes and limitations + +- Text-to-image only. Reference-image editing is not supported. +- The default flow shift is 1.0, matching the authors' scheduler configuration. +- The model card reports benchmark settings of 1024×1024, 50 steps and CFG 8.0 with + renormalized guidance in diffusers. This integration applies standard classifier-free + guidance. +- The checkpoints are 12.7 GB (Q5_1) and 18 GB (Q8_0) before the text encoder and VAE. + On GPUs that cannot hold them, add `--offload-to-cpu`. diff --git a/examples/server/recipes/nucleus-image.json b/examples/server/recipes/nucleus-image.json new file mode 100644 index 0000000000..f64df8209c --- /dev/null +++ b/examples/server/recipes/nucleus-image.json @@ -0,0 +1,33 @@ +{ + "schema_version": 1, + "id": "nucleus-image", + "name": "Nucleus Image (Sparse MoE)", + "description": "Nucleus-Image text-to-image with the Qwen3-VL-8B-Instruct text encoder and the Qwen-Image VAE.", + "model_url": "https://huggingface.co/NucleusAI/Nucleus-Image", + "slots": [ + { + "id": "diffusion_model", + "required": true + }, + { + "id": "llm", + "required": true, + "label": "Qwen 3 VL 8B Text Encoder" + }, + { + "id": "vae", + "required": true, + "label": "Qwen Image VAE" + } + ], + "defaults": { + "sampling_method": "euler", + "cfg_scale": 4.5, + "steps": 24, + "width": 768, + "height": 768 + }, + "features": [ + "flow_shift" + ] +} diff --git a/src/conditioning/llm_conditioner.cpp b/src/conditioning/llm_conditioner.cpp index a822d355b6..01380a1d7e 100644 --- a/src/conditioning/llm_conditioner.cpp +++ b/src/conditioning/llm_conditioner.cpp @@ -86,6 +86,7 @@ struct LLMEmbedder : public Conditioner { arch = LLM::LLMArch::GEMMA2_2B; } else if (version == VERSION_FIBO2 || version == VERSION_QWEN_IMAGE_2_1 || + version == VERSION_NUCLEUS_IMAGE || sd_version_is_flux3(version) || sd_version_is_lingbot_video(version) || sd_version_is_ideogram4(version) || @@ -1290,6 +1291,17 @@ struct LLMEmbedder : public Conditioner { prompt += conditioner_params.text; prompt_attn_range.second = static_cast(prompt.size()); prompt += "<|im_end|>\n<|im_start|>assistant\n\n"; + } else if (version == VERSION_NUCLEUS_IMAGE) { + prompt_template_encode_start_idx = 0; + out_layers = {static_cast(llm->config.num_layers) - 7}; // -8 + + prompt = system_prefix("<|im_start|>system\nYou are an image generation assistant. Follow the user's prompt literally. Pay careful attention to spatial layout: objects described as on the left must appear on the left, on the right on the right. Match exact object counts and assign colors to the correct objects.<|im_end|>\n<|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"; } else if (sd_version_is_flux3(version)) { prompt_template_encode_start_idx = 0; max_length = 4096; diff --git a/src/model.h b/src/model.h index fb411349b8..d2f5101f3d 100644 --- a/src/model.h +++ b/src/model.h @@ -75,6 +75,7 @@ enum SDVersion { VERSION_RELAY_VSR, VERSION_SEEDVR2, VERSION_KANDINSKY_IMAGESR, + VERSION_NUCLEUS_IMAGE, VERSION_COUNT, }; diff --git a/src/model/diffusion/nucleus_image.hpp b/src/model/diffusion/nucleus_image.hpp new file mode 100644 index 0000000000..22f6fb87b1 --- /dev/null +++ b/src/model/diffusion/nucleus_image.hpp @@ -0,0 +1,496 @@ +#ifndef __SD_MODEL_DIFFUSION_NUCLEUS_IMAGE_HPP__ +#define __SD_MODEL_DIFFUSION_NUCLEUS_IMAGE_HPP__ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "core/ggml_graph_cut.h" +#include "core/util.h" +#include "model/common/ggml_block.hpp" +#include "model/common/rope.hpp" +#include "model/diffusion/dit.hpp" +#include "model/diffusion/model.hpp" +#include "model_loader.h" + +namespace NucleusImage { + + // The checkpoint carries no metadata, so the config is derived from weight shapes where + // possible and hardcoded otherwise. + struct NucleusImageConfig { + int patch_size = 2; + int64_t in_channels = 64; // patchified input dim = patch_size^2 * 16 + int64_t out_channels = 16; // Qwen-Image VAE latent channels + int64_t hidden_size = 2048; + int64_t num_attention_heads = 16; + int64_t num_kv_heads = 4; // GQA + int64_t head_dim = 128; + int64_t depth = 32; + int64_t joint_attention_dim = 4096; // Qwen3-VL-8B hidden size + int64_t dense_inner_dim = 5376; + int64_t moe_inner_dim = 1344; + int64_t num_experts = 64; + float capacity_factor_first = 4.f; // MoE layers 3-4 + float capacity_factor_rest = 2.f; // MoE layers 5+ + float route_scale = 2.5f; + int theta = 10000; + std::vector axes_dim = {16, 56, 56}; + int axes_dim_sum = 128; + float norm_eps = 1e-6f; + std::vector moe_layers; + + static NucleusImageConfig detect_from_weights(const String2TensorStorage& weights, const std::string& prefix) { + NucleusImageConfig config; + config.depth = 0; + config.moe_layers.clear(); + const std::string p = prefix + "."; + for (const auto& [name, tensor] : weights) { + if (!starts_with(name, p)) { + continue; + } + auto key = name.substr(p.size()); + if (key == "img_in.weight" && tensor.n_dims == 2) { + config.in_channels = tensor.logical_ne0(); + config.hidden_size = tensor.ne[1]; + } else if (key == "txt_norm.weight") { + config.joint_attention_dim = tensor.ne[0]; + } else if (key == "proj_out.weight" && tensor.n_dims == 2) { + config.out_channels = tensor.ne[1] / (2 * 2); // patch_size * patch_size + } else if (key == "transformer_blocks.0.img_mlp.net.0.proj.weight" && tensor.n_dims == 2) { + config.dense_inner_dim = tensor.ne[1] / 2; // fused gate+up + } else if (key == "transformer_blocks.0.attn.norm_q.weight") { + config.head_dim = tensor.ne[0]; + } else if (key == "transformer_blocks.0.img_mlp.experts.gate_up_proj" && tensor.n_dims == 3) { + config.num_experts = tensor.ne[2]; + config.moe_inner_dim = tensor.logical_ne0() / 2; + } + if (starts_with(key, "transformer_blocks.")) { + auto items = split_string(key, '.'); + if (items.size() > 1) { + int block_index = atoi(items[1].c_str()); + config.depth = std::max(config.depth, block_index + 1); + if (key == "transformer_blocks." + std::to_string(block_index) + ".img_mlp.experts.gate_up_proj") { + config.moe_layers.push_back(block_index); + } + } + } + } + std::sort(config.moe_layers.begin(), config.moe_layers.end()); + config.num_attention_heads = config.hidden_size / config.head_dim; + config.axes_dim_sum = 0; + for (int axis_dim : config.axes_dim) { + config.axes_dim_sum += axis_dim; + } + GGML_ASSERT(config.head_dim * config.num_attention_heads == config.hidden_size); + GGML_ASSERT(config.hidden_size == 2048 && config.depth == 32 && config.num_experts == 64 && + config.moe_inner_dim == 1344); + LOG_VERBOSE("nucleus_image: hidden = %" PRId64 ", depth = %" PRId64 ", heads = %" PRId64 ", text_dim = %" PRId64 + ", experts = %" PRId64 ", moe_inner = %" PRId64 ", moe_layers = %zu", + config.hidden_size, config.depth, config.num_attention_heads, config.joint_attention_dim, + config.num_experts, config.moe_inner_dim, config.moe_layers.size()); + return config; + } + + bool is_moe_layer(int layer) const { + return std::find(moe_layers.begin(), moe_layers.end(), layer) != moe_layers.end(); + } + + float capacity_factor_for(int layer) const { + return layer <= 4 ? capacity_factor_first : capacity_factor_rest; + } + }; + + struct NucleusFeedForward : public UnaryBlock { + NucleusFeedForward(int64_t dim, int64_t inner_dim) { + blocks["net.0.proj"] = std::make_shared(dim, inner_dim * 2, false); + blocks["net.2"] = std::make_shared(inner_dim, dim, false); + } + + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) override { + auto c = ctx->ggml_ctx; + auto net2 = std::dynamic_pointer_cast(blocks["net.2"]); + net2->set_precision_flags(GGML_PRECISION_F32_VULKAN | GGML_PRECISION_F32_ROCM); + // Nucleus activations overflow the F16 accumulators of the quantized matmul kernels, + // so large inputs are wrapped in exact power-of-two down/up-scale pairs. + auto net0 = std::dynamic_pointer_cast(blocks["net.0.proj"]); + x = net0->forward(ctx, ggml_scale(c, x, 1.f / 64.f)); + x = ggml_scale(c, x, 64.f); + // silu applies to the second half here; the routed experts below use the opposite order. + auto up = ggml_ext_slice(ctx, x, 0, 0, x->ne[0] / 2); + auto gate = ggml_ext_slice(ctx, x, 0, x->ne[0] / 2, x->ne[0]); + gate = ggml_silu(c, gate); + x = ggml_mul(c, gate, up); + x = net2->forward(ctx, ggml_scale(c, x, 1.f / 4096.f)); + return ggml_scale(c, x, 4096.f); + } + }; + + // diffusers NucleusMoELayer: each expert takes its top-C tokens by router probability, and + // a token selected by several experts receives all of their contributions. + struct NucleusMoELayer : public GGMLBlock { + NucleusImageConfig config; + float capacity_factor; + int64_t hidden_size; + int64_t inner_dim; + int64_t num_experts; + + NucleusMoELayer(const NucleusImageConfig& config_, float capacity_factor_) + : config(config_), + capacity_factor(capacity_factor_), + hidden_size(config_.hidden_size), + inner_dim(config_.moe_inner_dim), + num_experts(config_.num_experts) { + blocks["gate"] = std::make_shared(hidden_size * 2, num_experts, false); + blocks["shared_expert"] = std::make_shared(hidden_size, inner_dim); + } + + void init_params(ggml_context* ctx, const String2TensorStorage& tensor_storage_map = {}, const std::string prefix = "") override { + // Declared in the checkpoint's [out, in, E] layout so they load as-is; + // expert_weight() transposes them in the graph. + ggml_type gate_up_type = get_type(prefix + "experts.gate_up_proj", tensor_storage_map, GGML_TYPE_F32); + if (inner_dim * 2 % ggml_blck_size(gate_up_type) != 0) { + gate_up_type = GGML_TYPE_F32; + } + params["experts.gate_up_proj"] = ggml_new_tensor_3d(ctx, gate_up_type, inner_dim * 2, hidden_size, num_experts); + ggml_type down_type = get_type(prefix + "experts.down_proj", tensor_storage_map, GGML_TYPE_F32); + if (hidden_size % ggml_blck_size(down_type) != 0) { + down_type = GGML_TYPE_F32; + } + params["experts.down_proj"] = ggml_new_tensor_3d(ctx, down_type, hidden_size, inner_dim, num_experts); + } + + // Expert e's weights in the [in, out] layout ggml_mul_mat expects. + ggml_tensor* expert_weight(GGMLRunnerContext* ctx, const char* param, int64_t e, int64_t in, int64_t out) { + auto c = ctx->ggml_ctx; + auto w = params[param]; // [out, in, E] + auto w_e = ggml_view_2d(c, w, out, in, w->nb[1], e * w->nb[2]); // [out, in] + w_e = ggml_cast(c, w_e, GGML_TYPE_F32); + return ggml_ext_cont(ctx, ggml_permute(c, w_e, 1, 0, 2, 3)); // [in, out] + } + + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x_mod, ggml_tensor* x_unmodulated, ggml_tensor* temb) { + auto c = ctx->ggml_ctx; + auto gate = std::dynamic_pointer_cast(blocks["gate"]); + auto shared_expert = std::dynamic_pointer_cast(blocks["shared_expert"]); + + const int64_t H = hidden_size; + const int64_t E = num_experts; + const int64_t S = x_mod->ne[1]; + const int64_t B = x_mod->ne[2]; + const int64_t C = std::max(1, (int64_t)std::ceil(capacity_factor * S / (double)E)); + + auto temb_expanded = ggml_repeat(c, ggml_reshape_3d(c, temb, H, 1, B), x_unmodulated); // [H, S, B] + auto router_in = ggml_concat(c, temb_expanded, x_unmodulated, 0); // [2H, S, B] + auto probs = ggml_soft_max(c, gate->forward(ctx, router_in)); // [E, S, B] + + auto affinity = ggml_cont(c, ggml_permute(c, probs, 1, 0, 2, 3)); // [S, E, B] + auto top_idx = ggml_cont(c, ggml_argsort_top_k(c, affinity, (int)C)); // I32 [C, E, B], descending + + auto affinity_rows = ggml_reshape_4d(c, affinity, 1, S, E, B); // [1, S, E, B] + auto gating_sel = ggml_get_rows(c, affinity_rows, top_idx); // [1, C, E, B] + auto zeros = ggml_ext_zeros(ctx, 1, S, E, B); + auto m = ggml_set_rows(c, zeros, gating_sel, top_idx); // view of `zeros` [1, S, E, B] + + // ggml_sum_rows needs contiguous rows. + auto expert_major = ggml_cont(c, ggml_permute(c, m, 2, 1, 0, 3)); // [E, S, 1, B] + auto denom = ggml_sum_rows(c, expert_major); // [1, S, 1, B] + denom = ggml_clamp(c, denom, 1e-12f, INFINITY); + auto g = ggml_div(c, m, denom); // broadcast over E + if (config.route_scale != 1.f) { + g = ggml_scale(c, g, config.route_scale); + } + + auto x_rows = ggml_reshape_4d(c, x_mod, H, S, B, 1); // row source for batched ggml_get_rows + ggml_tensor* routed = nullptr; + for (int64_t e = 0; e < E; ++e) { + auto ids = ggml_view_3d(c, top_idx, C, B, 1, top_idx->nb[2], top_idx->nb[3], e * top_idx->nb[1]); + auto xs = ggml_get_rows(c, x_rows, ids); // [H, C, B, 1] selected tokens + auto g_e = ggml_view_4d(c, g, 1, S, B, 1, g->nb[1], g->nb[3], g->nb[3], e * g->nb[2]); + auto w = ggml_get_rows(c, g_e, ids); // [1, C, B, 1] + // gate first, unlike the shared expert + auto gate_up = ggml_mul_mat(c, expert_weight(ctx, "experts.gate_up_proj", e, H, inner_dim * 2), xs); + auto h = ggml_mul(c, + ggml_silu(c, ggml_ext_slice(ctx, gate_up, 0, 0, inner_dim)), + ggml_ext_slice(ctx, gate_up, 0, inner_dim, inner_dim * 2)); // [I, C, B, 1] + auto out = ggml_mul(c, ggml_mul_mat(c, expert_weight(ctx, "experts.down_proj", e, inner_dim, H), h), w); + auto z = ggml_set_rows(c, ggml_ext_zeros(ctx, H, S, B, 1), out, ids); // [H, S, B, 1] + routed = routed == nullptr ? z : ggml_add(c, routed, z); + } + + auto routed_sum = ggml_reshape_3d(c, routed, H, S, B); + return ggml_add(c, routed_sum, shared_expert->forward(ctx, x_mod)); + } + }; + + // Image queries attend to concatenated text+image K/V (diffusers NucleusMoEAttnProcessor2_0). + struct NucleusAttention : public GGMLBlock { + int64_t num_heads; + int64_t kv_heads; + int64_t head_dim; + + NucleusAttention(const NucleusImageConfig& config) + : num_heads(config.num_attention_heads), + kv_heads(config.num_kv_heads), + head_dim(config.head_dim) { + const int64_t inner = num_heads * head_dim; + const int64_t inner_kv = kv_heads * head_dim; + blocks["to_q"] = std::make_shared(config.hidden_size, inner, false); + blocks["to_k"] = std::make_shared(config.hidden_size, inner_kv, false); + blocks["to_v"] = std::make_shared(config.hidden_size, inner_kv, false); + blocks["add_k_proj"] = std::make_shared(config.hidden_size, inner_kv, false); + blocks["add_v_proj"] = std::make_shared(config.hidden_size, inner_kv, false); + blocks["norm_q"] = std::make_shared(head_dim, config.norm_eps); + blocks["norm_k"] = std::make_shared(head_dim, config.norm_eps); + // norm_added_q is in the checkpoint but unused: text tokens are keys/values only. + blocks["norm_added_q"] = std::make_shared(head_dim, config.norm_eps); + blocks["norm_added_k"] = std::make_shared(head_dim, config.norm_eps); + blocks["to_out.0"] = std::make_shared(inner, config.hidden_size, false); + } + + // pe_full: [2, 2, d/2, Lt + S] with txt tokens first (Rope::gen_qwen_image_pe order); + // img_pe: [2, 2, d/2, S] slice for the image-only queries. + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* y, ggml_tensor* pe_full, ggml_tensor* img_pe) { + auto c = ctx->ggml_ctx; + const int64_t S = x->ne[1]; + const int64_t Lt = y->ne[1]; + const int64_t N = x->ne[2]; + + auto to_q = std::dynamic_pointer_cast(blocks["to_q"]); + auto to_k = std::dynamic_pointer_cast(blocks["to_k"]); + auto to_v = std::dynamic_pointer_cast(blocks["to_v"]); + auto add_k_proj = std::dynamic_pointer_cast(blocks["add_k_proj"]); + auto add_v_proj = std::dynamic_pointer_cast(blocks["add_v_proj"]); + auto norm_q = std::dynamic_pointer_cast(blocks["norm_q"]); + auto norm_k = std::dynamic_pointer_cast(blocks["norm_k"]); + auto norm_added_k = std::dynamic_pointer_cast(blocks["norm_added_k"]); + auto to_out = std::dynamic_pointer_cast(blocks["to_out.0"]); + to_out->set_precision_flags(GGML_PRECISION_F32_VULKAN | GGML_PRECISION_F32_ROCM); + + // RMSNorm absorbs the input scale for q/k, so only v is scaled back. + auto x_scaled = ggml_scale(c, x, 1.f / 64.f); + auto q = norm_q->forward(ctx, ggml_reshape_4d(c, to_q->forward(ctx, x_scaled), head_dim, num_heads, S, N)); + auto v = ggml_reshape_4d(c, to_v->forward(ctx, x_scaled), head_dim, kv_heads, S, N); + v = ggml_scale(c, v, 64.f); + + // K/V are concatenated before rope: apply_rope returns 3D and pe covers txt+img. + auto k_img = norm_k->forward(ctx, ggml_reshape_4d(c, to_k->forward(ctx, x_scaled), head_dim, kv_heads, S, N)); + auto k_txt = norm_added_k->forward(ctx, ggml_reshape_4d(c, add_k_proj->forward(ctx, y), head_dim, kv_heads, Lt, N)); + auto k = ggml_concat(c, k_txt, k_img, 2); // [d, kv_heads, Lt + S, N] + auto v_txt = ggml_reshape_4d(c, add_v_proj->forward(ctx, y), head_dim, kv_heads, Lt, N); + v = ggml_concat(c, v_txt, v, 2); // [d, kv_heads, Lt + S, N] + + q = Rope::apply_rope(ctx, q, img_pe); // image queries: img positions only + k = Rope::apply_rope(ctx, k, pe_full); // txt-first pe order matches the concat order + + // The attention op casts v to F16. + v = ggml_scale(c, v, 1.f / 1024.f); + auto attn = ggml_ext_attention_ext(ctx, q, k, v, num_heads, nullptr, true, ctx->flash_attn_enabled, 1.f); + auto out = to_out->forward(ctx, ggml_scale(c, attn, 1.f / 8.f)); + return ggml_scale(c, out, 8.f * 1024.f); + } + }; + + struct NucleusBlock : public GGMLBlock { + NucleusImageConfig config; + bool moe; + float capacity_factor; + + NucleusBlock(const NucleusImageConfig& config_, bool moe_, float capacity_factor_) + : config(config_), + moe(moe_), + capacity_factor(capacity_factor_) { + blocks["img_mod.1"] = std::make_shared(config.hidden_size, config.hidden_size * 4, true); + blocks["encoder_proj"] = std::make_shared(config.joint_attention_dim, config.hidden_size, true); + blocks["attn"] = std::make_shared(config); + if (moe) { + blocks["img_mlp"] = std::make_shared(config, capacity_factor); + } else { + blocks["img_mlp"] = std::make_shared(config.hidden_size, config.dense_inner_dim); + } + } + + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* txt, ggml_tensor* temb, ggml_tensor* pe_full, ggml_tensor* img_pe) { + auto c = ctx->ggml_ctx; + auto img_mod = std::dynamic_pointer_cast(blocks["img_mod.1"]); + auto attn = std::dynamic_pointer_cast(blocks["attn"]); + auto encoder_proj = std::dynamic_pointer_cast(blocks["encoder_proj"]); + + auto mod_params = img_mod->forward(ctx, ggml_silu(c, temb)); // [4H, 1, B] + auto mods = ggml_ext_chunk(ctx, mod_params, 4, 0, false); + auto scale1 = mods[0]; + auto gate1 = ggml_clamp(c, mods[1], -2.f, 2.f); + auto scale2 = mods[2]; + auto gate2 = ggml_clamp(c, mods[3], -2.f, 2.f); + + auto context = encoder_proj->forward(ctx, txt); // [H, Lt, B] + + auto normed = ggml_norm(c, x, config.norm_eps); // affine-free LayerNorm + auto modulated = ggml_add(c, normed, ggml_mul(c, normed, scale1)); + auto attn_out = attn->forward(ctx, modulated, context, pe_full, img_pe); + x = ggml_add(c, x, ggml_mul(c, attn_out, ggml_tanh(c, gate1))); + + auto normed2 = ggml_norm(c, x, config.norm_eps); + auto modulated2 = ggml_add(c, normed2, ggml_mul(c, normed2, scale2)); + ggml_tensor* mlp_out; + if (moe) { + mlp_out = std::dynamic_pointer_cast(blocks["img_mlp"])->forward(ctx, modulated2, normed2, temb); + } else { + mlp_out = std::dynamic_pointer_cast(blocks["img_mlp"])->forward(ctx, modulated2); + } + return ggml_add(c, x, ggml_mul(c, mlp_out, ggml_tanh(c, gate2))); + } + }; + + struct NucleusTimeTextEmbed : public GGMLBlock { + int64_t freq_dim; + + NucleusTimeTextEmbed(int64_t embedding_dim, int64_t out_dim) + : freq_dim(embedding_dim) { + blocks["timestep_embedder.linear_1"] = std::make_shared(embedding_dim, embedding_dim * 4, true); + blocks["timestep_embedder.linear_2"] = std::make_shared(embedding_dim * 4, out_dim, true); + blocks["norm"] = std::make_shared(out_dim, 1e-6f); + } + + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* timestep) { + auto c = ctx->ggml_ctx; + // Timesteps already carry the scheduler's x1000 scale. + auto t = ggml_ext_timestep_embedding(ctx, timestep, (int)freq_dim, 10000, 1.f); + auto l1 = std::dynamic_pointer_cast(blocks["timestep_embedder.linear_1"]); + auto l2 = std::dynamic_pointer_cast(blocks["timestep_embedder.linear_2"]); + auto n = std::dynamic_pointer_cast(blocks["norm"]); + t = l1->forward(ctx, t); + t = ggml_silu(c, t); + t = l2->forward(ctx, t); + return n->forward(ctx, t); + } + }; + + struct NucleusImageModel : public GGMLBlock { + NucleusImageConfig config; + + NucleusImageModel(const NucleusImageConfig& config_) + : config(config_) { + const int64_t H = config.hidden_size; + blocks["txt_norm"] = std::make_shared(config.joint_attention_dim, 1e-6f); + blocks["time_text_embed"] = std::make_shared(H, H); + blocks["img_in"] = std::make_shared(config.in_channels, H, true); + for (int64_t i = 0; i < config.depth; ++i) { + const bool moe = config.is_moe_layer((int)i); + blocks["transformer_blocks." + std::to_string(i)] = + std::make_shared(config, moe, config.capacity_factor_for((int)i)); + } + blocks["norm_out.linear"] = std::make_shared(H, H * 2, true); + blocks["proj_out"] = std::make_shared(H, config.out_channels * config.patch_size * config.patch_size, false); + } + + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* context, ggml_tensor* timestep, ggml_tensor* pe) { + auto c = ctx->ggml_ctx; + const int64_t H = config.hidden_size; + // x is the raw latent [W, H, C, N]; token counts must round like Rope::gen_qwen_image_ids. + const int64_t patch = config.patch_size; + const int64_t h_len = (x->ne[1] + (patch / 2)) / patch; + const int64_t w_len = (x->ne[0] + (patch / 2)) / patch; + const int64_t S = h_len * w_len; // img tokens + const int64_t Lt = pe->ne[3] - S; // txt tokens (pe covers txt + img, txt first) + + // patch_last: diffusers _pack_latents is channel-major. + auto img = std::dynamic_pointer_cast(blocks["img_in"])->forward(ctx, DiT::pad_and_patchify(ctx, x, config.patch_size, config.patch_size, true)); // [H, S, N] + + auto txt = std::dynamic_pointer_cast(blocks["txt_norm"])->forward(ctx, context); // [4096, Lt, N] + + auto temb = std::dynamic_pointer_cast(blocks["time_text_embed"])->forward(ctx, timestep); + temb = ggml_reshape_3d(c, temb, H, 1, temb->ne[1]); // [H, 1, N] + + auto img_pe = ggml_ext_slice(ctx, pe, 3, Lt, Lt + S); + + for (int64_t i = 0; i < config.depth; ++i) { + img = std::dynamic_pointer_cast(blocks["transformer_blocks." + std::to_string(i)]) + ->forward(ctx, img, txt, temb, pe, img_pe); + sd::ggml_graph_cut::mark_graph_cut(img, "nucleus_image.transformer_blocks." + std::to_string(i), "img"); + } + + auto emb = std::dynamic_pointer_cast(blocks["norm_out.linear"])->forward(ctx, ggml_silu(c, temb)); + auto mods = ggml_ext_chunk(ctx, emb, 2, 0, false); + auto scale = ggml_reshape_3d(c, mods[0], H, 1, emb->ne[2]); + auto shift = ggml_reshape_3d(c, mods[1], H, 1, emb->ne[2]); + img = ggml_norm(c, img, config.norm_eps); + img = ggml_add(c, ggml_add(c, ggml_mul(c, img, scale), img), shift); + + img = std::dynamic_pointer_cast(blocks["proj_out"])->forward(ctx, img); // [4*out_ch, S, N] + + // The diffusers pipeline negates the model output before the scheduler step. + auto out = DiT::unpatchify_and_crop(ctx, img, x->ne[1], x->ne[0], config.patch_size, config.patch_size, true); + return ggml_scale(c, out, -1.f); + } + }; + + struct NucleusImageRunner : public DiffusionModelRunner { + NucleusImageConfig config; + NucleusImageModel model; + std::vector pe_vec; + + NucleusImageRunner(ggml_backend_t backend, + const String2TensorStorage& weights, + const std::string& prefix, + std::shared_ptr weight_manager = nullptr) + : DiffusionModelRunner(backend, prefix, weight_manager), + config(NucleusImageConfig::detect_from_weights(weights, prefix)), + model(config) { + model.init(params_ctx, weights, prefix); + } + + std::string get_desc() override { return "Nucleus-Image"; } + + void get_param_tensors(std::map& tensors, const std::string& prefix) override { + model.get_param_tensors(tensors, prefix); + } + + sd::Tensor compute(int n_threads, const DiffusionParams& inputs_) override { + DiffusionParams inputs = inputs_; + if (!inputs.x || !inputs.timesteps || !inputs.context || inputs.context->empty()) { + LOG_ERROR("Nucleus-Image requires latents, timesteps and text features"); + return {}; + } + auto graph = [&]() { + auto gf = new_graph_custom(131072); + auto x = make_input(*inputs.x); + auto text = make_input(*inputs.context); + int64_t h = x->ne[1], w = x->ne[0]; + int64_t nt = text->ne[1]; + + // pe is built for batch 1: positions are identical across the batch and rope + // broadcasts pe over heads and batch. + auto embedding = Rope::gen_qwen_image_pe(1, (int)h, (int)w, config.patch_size, + 1, (int)nt, {}, + Rope::RefIndexMode::FIXED, config.theta, config.axes_dim); + pe_vec = finish_rope_pe(std::move(embedding)); + int pos_len = static_cast(pe_vec.size() / config.axes_dim_sum / 2); + auto pe = ggml_new_tensor_4d(compute_ctx, GGML_TYPE_F32, 2, 2, config.axes_dim_sum / 2, pos_len); + set_backend_tensor_data(pe, pe_vec.data()); + + auto timesteps = make_input(*inputs.timesteps); + auto ctx2 = get_context(); + ggml_tensor* out = model.forward(&ctx2, x, text, timesteps, pe); + ggml_build_forward_expand(gf, out); + // F16 accumulation overflows on this model's activation magnitudes. + for (int ni = 0; ni < ggml_graph_n_nodes(gf); ++ni) { + ggml_tensor* node = ggml_graph_node(gf, ni); + if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) { + ggml_prec_set_acc(node, GGML_PREC_F32); + } + } + return gf; + }; + return restore_trailing_singleton_dims(GGMLRunner::compute(graph, n_threads, false, false), + inputs.x->dim()); + } + }; + +} // namespace NucleusImage + +#endif // __SD_MODEL_DIFFUSION_NUCLEUS_IMAGE_HPP__ diff --git a/src/model/integrations/nucleus_image.cpp b/src/model/integrations/nucleus_image.cpp new file mode 100644 index 0000000000..0d4a9fcb21 --- /dev/null +++ b/src/model/integrations/nucleus_image.cpp @@ -0,0 +1,39 @@ +#include "model_definition.h" + +#include "conditioning/llm_conditioner.h" +#include "model/diffusion/nucleus_image.hpp" +#include "model_build_context.h" + +static bool build_nucleus_image(const sd::model_builders::Context& ctx, + const TokenizerConfig& tokenizers, + sd::model_builders::CoreRunners& runners) { + if (ctx.build_conditioner) { + runners.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE), + ctx.tensor_storage_map, ctx.version, false, + ctx.weight_manager, tokenizers); + } + if (ctx.build_diffusion) { + runners.diffusion = std::make_shared(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION), + ctx.tensor_storage_map, "model.diffusion_model", ctx.weight_manager); + } + return true; +} + +const std::vector& nucleus_image_definitions() { + static const std::vector definitions = [] { + ModelDefinition definition; + definition.version = VERSION_NUCLEUS_IMAGE; + definition.geometry = {1, 16, 3}; + definition.name = "Nucleus-Image"; + definition.id = "nucleus_image"; + definition.traits.is_dit = true; + definition.traits.vae_kind = ModelVAEKind::WAN; + definition.traits.video_tae = true; + definition.sampling = {FLOW_PRED, 1.f}; + definition.sampling.default_sample_method = EULER_SAMPLE_METHOD; + definition.sampling.default_scheduler = DISCRETE_SCHEDULER; + definition.build = build_nucleus_image; + return std::vector{std::move(definition)}; + }(); + return definitions; +} diff --git a/src/model_loader.cpp b/src/model_loader.cpp index 8606fceeec..c7636e952d 100644 --- a/src/model_loader.cpp +++ b/src/model_loader.cpp @@ -477,6 +477,12 @@ SDVersion ModelLoader::get_sd_version() const { return VERSION_MOSS_IMAGE; } + if (tensor_storage_map.count("model.diffusion_model.transformer_blocks.3.img_mlp.experts.gate_up_proj") && + tensor_storage_map.count("model.diffusion_model.img_in.weight") && + tensor_storage_map.count("model.diffusion_model.time_text_embed.timestep_embedder.linear_1.weight")) { + return VERSION_NUCLEUS_IMAGE; + } + bool has_multiple_encoders = false; bool is_unet = false; diff --git a/src/model_registry.cpp b/src/model_registry.cpp index e8496c0a23..25759025b8 100644 --- a/src/model_registry.cpp +++ b/src/model_registry.cpp @@ -36,6 +36,7 @@ const std::vector& sd_definitions(); const std::vector& moss_image_definitions(); const std::vector& seedvr2_definitions(); const std::vector& kandinsky_imagesr_definitions(); +const std::vector& nucleus_image_definitions(); static bool valid_model_id(std::string_view id) { if (id.empty() || id == "auto" || id.front() < 'a' || id.front() > 'z') @@ -101,6 +102,7 @@ static const std::array& model_definition append(moss_image_definitions()); append(seedvr2_definitions()); append(kandinsky_imagesr_definitions()); + append(nucleus_image_definitions()); for (const auto* definition : result) { if (!definition) throw std::logic_error("missing model registration");