Commit a5b83a9 for stable-diffusion.cpp
commit a5b83a9be2c160807ed812b96329d028bfa8f4bc
Author: leejet <leejet714@gmail.com>
Date: Mon Nov 30 23:54:00 2026 +0800
perf: reduce build time (#2471)
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 67b6f63..34bed64 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 3.12)
+cmake_minimum_required(VERSION 3.16)
project("stable-diffusion")
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
@@ -91,6 +91,7 @@ endif()
# general
#option(SD_BUILD_TESTS "sd: build tests" ${SD_STANDALONE})
option(SD_BUILD_EXAMPLES "sd: build examples" ${SD_STANDALONE})
+option(SD_BUILD_PCH "sd: use a C++ precompiled header for the library" ON)
option(SD_WEBP "sd: enable WebP image I/O support" ${SD_WEBP_DEFAULT})
option(SD_USE_SYSTEM_WEBP "sd: link against system libwebp" OFF)
option(SD_WEBM "sd: enable WebM video I/O support" ${SD_WEBM_DEFAULT})
@@ -122,9 +123,6 @@ endif()
if(SD_METAL)
if(NOT SD_USE_UPSTREAM_GGML)
- if(CMAKE_VERSION VERSION_LESS 3.16)
- message(FATAL_ERROR "SD_METAL with SD_USE_UPSTREAM_GGML=OFF requires CMake 3.16 or later for OBJC and OBJCXX support")
- endif()
enable_language(OBJC OBJCXX)
endif()
message("-- Use Metal as backend stable-diffusion")
@@ -295,6 +293,14 @@ file(GLOB SD_LIB_SOURCES CONFIGURE_DEPENDS
"src/weights/*.cpp"
)
+if(CMAKE_GENERATOR MATCHES "^Ninja")
+ # Compile the vocabulary data alongside PCH generation to shorten the build tail.
+ set(SD_VOCAB_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/src/tokenizers/vocab/vocab.cpp")
+ list(REMOVE_ITEM SD_LIB_SOURCES "${SD_VOCAB_SOURCE}")
+ list(PREPEND SD_LIB_SOURCES "${SD_VOCAB_SOURCE}")
+ set_source_files_properties("${SD_VOCAB_SOURCE}" PROPERTIES SKIP_PRECOMPILE_HEADERS ON)
+endif()
+
find_program(GIT_EXE NAMES git git.exe NO_CMAKE_FIND_ROOT_PATH)
if(GIT_EXE)
execute_process(COMMAND ${GIT_EXE} describe --tags --abbrev=7 --dirty=+
@@ -465,6 +471,16 @@ target_include_directories(${SD_LIB} PUBLIC include)
target_include_directories(${SD_LIB} PRIVATE src src/core "${CMAKE_CURRENT_BINARY_DIR}/generated")
target_include_directories(${SD_LIB} PUBLIC thirdparty)
target_compile_features(${SD_LIB} PUBLIC c_std_11 cxx_std_17)
+if(SD_BUILD_PCH)
+ set(SD_PCH_HEADERS ${SD_LIB_SOURCES})
+ list(FILTER SD_PCH_HEADERS INCLUDE REGEX "[.]hpp$")
+ list(FILTER SD_PCH_HEADERS EXCLUDE REGEX "/tokenizers/vocab/")
+ list(TRANSFORM SD_PCH_HEADERS PREPEND "$<$<COMPILE_LANGUAGE:CXX>:")
+ list(TRANSFORM SD_PCH_HEADERS APPEND ">")
+ target_precompile_headers(${SD_LIB} PRIVATE
+ "$<$<COMPILE_LANGUAGE:CXX>:<json.hpp$<ANGLE-R>>"
+ ${SD_PCH_HEADERS})
+endif()
set_target_properties(${SD_LIB} PROPERTIES
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN ON)
diff --git a/docs/build.md b/docs/build.md
index 484eede..3cb50cd 100644
--- a/docs/build.md
+++ b/docs/build.md
@@ -1,5 +1,7 @@
# Build from scratch
+CMake 3.16 or later is required.
+
## Get the Code
```shell
@@ -417,6 +419,23 @@ ccache --show-stats
Look for cache hits in the statistics. A normal incremental build with no
changed files skips compilation and does not produce new cache hits.
+If ccache reports `Could not use precompiled header` for C++ compilations,
+add `-DSD_BUILD_PCH=OFF` to your configure command and check the cache again.
+
+### Precompiled header
+
+By default, the stable-diffusion C++ library precompiles the JSON header
+and the project `.hpp` headers in the library source list to speed up
+clean builds. Editing a header used by the PCH rebuilds the PCH and the
+C++ files that use it. To disable it, add `-DSD_BUILD_PCH=OFF` to your
+configure command.
+
+To compare uncached clean builds, pass `-DGGML_CCACHE=OFF`,
+`-DCMAKE_C_COMPILER_LAUNCHER=`, and `-DCMAKE_CXX_COMPILER_LAUNCHER=` in both
+configure commands. For CUDA builds, also pass `-DCMAKE_CUDA_COMPILER_LAUNCHER=`.
+The empty values override any compiler launchers saved in a reused build
+directory.
+
### MSVC compilation parallelism
MSVC builds limit parallel C/C++ compilation within each project by default.
diff --git a/src/conditioning/conditioner.cpp b/src/conditioning/conditioner.cpp
new file mode 100644
index 0000000..f683550
--- /dev/null
+++ b/src/conditioning/conditioner.cpp
@@ -0,0 +1,48 @@
+#include "conditioning/conditioner.h"
+
+#include <cmath>
+
+#include "core/ggml_runner.h"
+
+sd::Tensor<float> sd::apply_token_weights(sd::Tensor<float> hidden_states,
+ const std::vector<float>& weights) {
+ if (hidden_states.empty()) {
+ return hidden_states;
+ }
+
+ bool all_one = true;
+ for (float weight : weights) {
+ if (weight != 1.0f) {
+ all_one = false;
+ break;
+ }
+ }
+ if (all_one) {
+ return hidden_states;
+ }
+
+ if (hidden_states.dim() == 1) {
+ hidden_states.unsqueeze_(1);
+ }
+
+ GGML_ASSERT(static_cast<size_t>(hidden_states.shape()[1]) == weights.size());
+
+ float original_mean = hidden_states.mean();
+ auto chunk_weights = sd::Tensor<float>::from_vector(weights);
+ chunk_weights.reshape_({1, static_cast<int64_t>(weights.size())});
+ hidden_states *= chunk_weights;
+ float new_mean = hidden_states.mean();
+ if (std::isfinite(original_mean) && std::isfinite(new_mean) && new_mean != 0.0f) {
+ hidden_states *= (original_mean / new_mean);
+ }
+
+ return hidden_states;
+}
+
+void Conditioner::set_flash_attention_enabled(bool enabled) {
+ for_each_runner([enabled](GGMLRunner& runner) { runner.set_flash_attention_enabled(enabled); });
+}
+
+void Conditioner::set_linear_i8_enabled(bool enabled) {
+ for_each_runner([enabled](GGMLRunner& runner) { runner.set_linear_i8_enabled(enabled); });
+}
diff --git a/src/conditioning/conditioner.h b/src/conditioning/conditioner.h
new file mode 100644
index 0000000..450914d
--- /dev/null
+++ b/src/conditioning/conditioner.h
@@ -0,0 +1,139 @@
+#ifndef __SD_CONDITIONING_CONDITIONER_H__
+#define __SD_CONDITIONING_CONDITIONER_H__
+
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "conditioning/prompt_input.h"
+#include "core/tensor.hpp"
+#include "ggml-backend.h"
+#include "model/diffusion/minimax_h3_reference.hpp"
+
+struct GGMLRunner;
+struct WeightAdapter;
+
+namespace sd {
+ struct TextualInversion;
+ Tensor<float> apply_token_weights(Tensor<float> hidden_states, const std::vector<float>& weights);
+}
+
+struct SDCondition {
+ sd::Tensor<float> c_crossattn;
+ sd::Tensor<float> c_vector;
+ sd::Tensor<float> c_concat;
+ sd::Tensor<int32_t> c_t5_ids;
+ sd::Tensor<float> c_t5_weights;
+ sd::Tensor<int32_t> c_input_ids;
+ sd::Tensor<int32_t> c_position_ids;
+ sd::Tensor<int32_t> c_token_types;
+ sd::Tensor<int32_t> c_vinput_mask;
+ std::vector<std::pair<int, sd::Tensor<float>>> c_image_embeds;
+ std::vector<sd::Tensor<float>> c_ref_images;
+ std::vector<sd::Tensor<float>> c_ref_audios;
+ std::vector<MiniMaxH3ReferenceBlock> c_reference_blocks;
+
+ std::vector<sd::Tensor<float>> extra_c_crossattns;
+
+ SDCondition() = default;
+
+ SDCondition(sd::Tensor<float> c_crossattn,
+ sd::Tensor<float> c_vector,
+ sd::Tensor<float> c_concat)
+ : c_crossattn(std::move(c_crossattn)), c_vector(std::move(c_vector)), c_concat(std::move(c_concat)) {}
+
+ bool empty() const {
+ if (!c_crossattn.empty() || !c_vector.empty() || !c_concat.empty() ||
+ !c_t5_ids.empty() || !c_t5_weights.empty() ||
+ !c_input_ids.empty() || !c_position_ids.empty() ||
+ !c_token_types.empty() || !c_vinput_mask.empty()) {
+ return false;
+ }
+
+ for (const auto& image_embed : c_image_embeds) {
+ if (!image_embed.second.empty()) {
+ return false;
+ }
+ }
+
+ for (const auto& tensor : c_ref_images) {
+ if (!tensor.empty()) {
+ return false;
+ }
+ }
+
+ for (const auto& tensor : c_ref_audios) {
+ if (!tensor.empty()) {
+ return false;
+ }
+ }
+
+ for (const auto& tensor : extra_c_crossattns) {
+ if (!tensor.empty()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+};
+
+enum class MiniMaxH3PresentationKind {
+ IMAGE,
+ VIDEO,
+ AUDIO,
+};
+
+struct MiniMaxH3PresentationItem {
+ MiniMaxH3PresentationKind kind = MiniMaxH3PresentationKind::IMAGE;
+ std::vector<sd::Tensor<float>> frames;
+ std::vector<float> timestamps;
+};
+
+struct ConditionerParams {
+ std::string text;
+ const sd::PromptInput* prompt_input = nullptr;
+ int clip_skip = -1;
+ int width = -1;
+ int height = -1;
+ bool zero_out_masked = false;
+ const std::vector<sd::Tensor<float>>* ref_images = nullptr; // for qwen image edit
+ const std::vector<MiniMaxH3PresentationItem>* minimax_h3_references = nullptr;
+ std::optional<std::string> system_prompt;
+ bool raw = false;
+ std::shared_ptr<sd::TextualInversion> textual_inversion;
+};
+
+struct Conditioner {
+ virtual int resolve_clip_skip(int) const { return 0; }
+ virtual bool supports_prompt_images() const { return false; }
+ virtual size_t max_reference_images() const { return 0; }
+ virtual bool supports_multimodal_prompt() const { return false; }
+ virtual bool supports_prompt_formatting() const { return false; }
+ virtual ~Conditioner() = default;
+
+public:
+ virtual SDCondition get_learned_condition(int n_threads,
+ const ConditionerParams& conditioner_params) = 0;
+ virtual void get_param_tensors(std::map<std::string, ggml_tensor*>& tensors) = 0;
+ virtual void get_param_tensor_ops(std::map<ggml_tensor*, enum ggml_op>& tensor_ops) {}
+ virtual void set_max_graph_vram_bytes(size_t max_vram_bytes) {}
+ virtual void set_runtime_backends(const std::vector<ggml_backend_t>& backends) {}
+ virtual void set_graph_cut_layer_split_enabled(bool enabled) {}
+ virtual void set_graph_cut_layer_split_backend_vram_limits(const std::vector<size_t>& limits) {}
+ virtual void get_layer_split_param_tensors(std::map<std::string, ggml_tensor*>& tensors) {}
+ virtual void for_each_runner(const std::function<void(GGMLRunner&)>& visit) = 0;
+ void set_flash_attention_enabled(bool enabled);
+ void set_linear_i8_enabled(bool enabled);
+ virtual void set_scale_overrides(float linear_scale, float attn_scale) {}
+ virtual void set_weight_adapter(const std::shared_ptr<WeightAdapter>& adapter) {}
+ virtual void runner_end() {}
+};
+
+#endif // __SD_CONDITIONING_CONDITIONER_H__
diff --git a/src/conditioning/conditioner.hpp b/src/conditioning/conditioner.hpp
index a5dd10c..3808459 100644
--- a/src/conditioning/conditioner.hpp
+++ b/src/conditioning/conditioner.hpp
@@ -10,6 +10,7 @@
#include <optional>
#include <sstream>
#include <stdexcept>
+#include "conditioning/conditioner.h"
#include "conditioning/prompt_input.h"
#include "conditioning/prompt_templates.h"
#include "conditioning/textual_inversion.h"
@@ -21,168 +22,15 @@
#include "core/util.h"
#include "model/diffusion/model.hpp"
#include "model/te/clip.hpp"
-#include "model/te/clipproj_connector.hpp"
#include "model/te/llada_image_te.hpp"
#include "model/te/llm.hpp"
#include "model/te/ltx_connector.hpp"
#include "model/te/ming_image_te.hpp"
-#include "model/te/ph3_image_connector.hpp"
#include "model/te/t5.hpp"
#include "model_loader.h"
#include "tokenizers/sensenova_u1_tokenizer.h"
#include "tokenizers/tokenizer_config.h"
-struct SDCondition {
- sd::Tensor<float> c_crossattn;
- sd::Tensor<float> c_vector;
- sd::Tensor<float> c_concat;
- sd::Tensor<int32_t> c_t5_ids;
- sd::Tensor<float> c_t5_weights;
- sd::Tensor<int32_t> c_input_ids;
- sd::Tensor<int32_t> c_position_ids;
- sd::Tensor<int32_t> c_token_types;
- sd::Tensor<int32_t> c_vinput_mask;
- std::vector<std::pair<int, sd::Tensor<float>>> c_image_embeds;
- std::vector<sd::Tensor<float>> c_ref_images;
- std::vector<sd::Tensor<float>> c_ref_audios;
- std::vector<MiniMaxH3ReferenceBlock> c_reference_blocks;
-
- std::vector<sd::Tensor<float>> extra_c_crossattns;
-
- SDCondition() = default;
-
- SDCondition(sd::Tensor<float> c_crossattn,
- sd::Tensor<float> c_vector,
- sd::Tensor<float> c_concat)
- : c_crossattn(std::move(c_crossattn)), c_vector(std::move(c_vector)), c_concat(std::move(c_concat)) {}
-
- bool empty() const {
- if (!c_crossattn.empty() || !c_vector.empty() || !c_concat.empty() ||
- !c_t5_ids.empty() || !c_t5_weights.empty() ||
- !c_input_ids.empty() || !c_position_ids.empty() ||
- !c_token_types.empty() || !c_vinput_mask.empty()) {
- return false;
- }
-
- for (const auto& image_embed : c_image_embeds) {
- if (!image_embed.second.empty()) {
- return false;
- }
- }
-
- for (const auto& tensor : c_ref_images) {
- if (!tensor.empty()) {
- return false;
- }
- }
-
- for (const auto& tensor : c_ref_audios) {
- if (!tensor.empty()) {
- return false;
- }
- }
-
- for (const auto& tensor : extra_c_crossattns) {
- if (!tensor.empty()) {
- return false;
- }
- }
-
- return true;
- }
-};
-
-enum class MiniMaxH3PresentationKind {
- IMAGE,
- VIDEO,
- AUDIO,
-};
-
-struct MiniMaxH3PresentationItem {
- MiniMaxH3PresentationKind kind = MiniMaxH3PresentationKind::IMAGE;
- std::vector<sd::Tensor<float>> frames;
- std::vector<float> timestamps;
-};
-
-static inline sd::Tensor<float> apply_token_weights(sd::Tensor<float> hidden_states,
- const std::vector<float>& weights) {
- if (hidden_states.empty()) {
- return hidden_states;
- }
-
- bool all_one = true;
- for (float weight : weights) {
- if (weight != 1.0f) {
- all_one = false;
- break;
- }
- }
- if (all_one) {
- return hidden_states;
- }
-
- if (hidden_states.dim() == 1) {
- hidden_states.unsqueeze_(1);
- }
-
- GGML_ASSERT(static_cast<size_t>(hidden_states.shape()[1]) == weights.size());
-
- float original_mean = hidden_states.mean();
- auto chunk_weights = sd::Tensor<float>::from_vector(weights);
- chunk_weights.reshape_({1, static_cast<int64_t>(weights.size())});
- hidden_states *= chunk_weights;
- float new_mean = hidden_states.mean();
- if (std::isfinite(original_mean) && std::isfinite(new_mean) && new_mean != 0.0f) {
- hidden_states *= (original_mean / new_mean);
- }
-
- return hidden_states;
-}
-
-struct ConditionerParams {
- std::string text;
- const sd::PromptInput* prompt_input = nullptr;
- int clip_skip = -1;
- int width = -1;
- int height = -1;
- bool zero_out_masked = false;
- const std::vector<sd::Tensor<float>>* ref_images = nullptr; // for qwen image edit
- const std::vector<MiniMaxH3PresentationItem>* minimax_h3_references = nullptr;
- std::optional<std::string> system_prompt;
- bool raw = false;
- std::shared_ptr<sd::TextualInversion> textual_inversion;
-};
-
-struct Conditioner {
- virtual int resolve_clip_skip(int) const { return 0; }
- virtual bool supports_prompt_images() const { return false; }
- virtual size_t max_reference_images() const { return 0; }
- virtual bool supports_multimodal_prompt() const { return false; }
- virtual bool supports_prompt_formatting() const { return false; }
- virtual ~Conditioner() = default;
-
-public:
- virtual SDCondition get_learned_condition(int n_threads,
- const ConditionerParams& conditioner_params) = 0;
- virtual void get_param_tensors(std::map<std::string, ggml_tensor*>& tensors) = 0;
- virtual void get_param_tensor_ops(std::map<ggml_tensor*, enum ggml_op>& tensor_ops) {}
- virtual void set_max_graph_vram_bytes(size_t max_vram_bytes) {}
- virtual void set_runtime_backends(const std::vector<ggml_backend_t>& backends) {}
- virtual void set_graph_cut_layer_split_enabled(bool enabled) {}
- virtual void set_graph_cut_layer_split_backend_vram_limits(const std::vector<size_t>& limits) {}
- virtual void get_layer_split_param_tensors(std::map<std::string, ggml_tensor*>& tensors) {}
- virtual void for_each_runner(const std::function<void(GGMLRunner&)>& visit) = 0;
- void set_flash_attention_enabled(bool enabled) {
- for_each_runner([enabled](GGMLRunner& runner) { runner.set_flash_attention_enabled(enabled); });
- }
- void set_linear_i8_enabled(bool enabled) {
- for_each_runner([enabled](GGMLRunner& runner) { runner.set_linear_i8_enabled(enabled); });
- }
- virtual void set_scale_overrides(float linear_scale, float attn_scale) {}
- virtual void set_weight_adapter(const std::shared_ptr<WeightAdapter>& adapter) {}
- virtual void runner_end() {}
-};
-
// ldm.modules.encoders.modules.FrozenCLIPEmbedder
// Ref: https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/cad87bf4e3e0b0a759afa94e933527c3123d59bc/modules/sd_hijack_clip.py#L283
struct FrozenCLIPEmbedderWithCustomWords : public Conditioner {
@@ -554,7 +402,7 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner {
int64_t t1 = ggml_time_ms();
LOG_VERBOSE("computing condition graph completed, taking %" PRId64 " ms", t1 - t0);
- chunk_hidden_states = apply_token_weights(std::move(chunk_hidden_states), chunk_weights);
+ chunk_hidden_states = sd::apply_token_weights(std::move(chunk_hidden_states), chunk_weights);
if (zero_out_masked) {
chunk_hidden_states.fill_(0.0f);
@@ -989,7 +837,7 @@ struct SD3CLIPEmbedder : public Conditioner {
false);
if (chunk_hidden_states_l.empty())
return {};
- chunk_hidden_states_l = ::apply_token_weights(std::move(chunk_hidden_states_l), chunk_weights);
+ chunk_hidden_states_l = sd::apply_token_weights(std::move(chunk_hidden_states_l), chunk_weights);
if (chunk_idx == 0) {
auto it = std::find(chunk_tokens.begin(), chunk_tokens.end(), clip_l_tokenizer->EOS_TOKEN_ID);
@@ -1034,7 +882,7 @@ struct SD3CLIPEmbedder : public Conditioner {
false);
if (chunk_hidden_states_g.empty())
return {};
- chunk_hidden_states_g = ::apply_token_weights(std::move(chunk_hidden_states_g), chunk_weights);
+ chunk_hidden_states_g = sd::apply_token_weights(std::move(chunk_hidden_states_g), chunk_weights);
if (chunk_idx == 0) {
auto it = std::find(chunk_tokens.begin(), chunk_tokens.end(), clip_g_tokenizer->EOS_TOKEN_ID);
@@ -1073,7 +921,7 @@ struct SD3CLIPEmbedder : public Conditioner {
false);
if (chunk_hidden_states_t5.empty())
return {};
- chunk_hidden_states_t5 = ::apply_token_weights(std::move(chunk_hidden_states_t5), chunk_weights);
+ chunk_hidden_states_t5 = sd::apply_token_weights(std::move(chunk_hidden_states_t5), chunk_weights);
} else {
chunk_hidden_states_t5 = sd::Tensor<float>::zeros({4096, static_cast<int64_t>(chunk_len), 1});
}
@@ -1387,7 +1235,7 @@ struct FluxCLIPEmbedder : public Conditioner {
LOG_ERROR("Flux T5 encoding failed at chunk %d/%zu", chunk_idx + 1, chunk_count);
return {};
}
- chunk_hidden_states = ::apply_token_weights(std::move(chunk_hidden_states), chunk_weights);
+ chunk_hidden_states = sd::apply_token_weights(std::move(chunk_hidden_states), chunk_weights);
if (zero_out_masked) {
chunk_hidden_states.fill_(0.0f);
}
@@ -1632,7 +1480,7 @@ struct T5CLIPEmbedder : public Conditioner {
false);
if (chunk_hidden_states.empty())
return {};
- chunk_hidden_states = apply_token_weights(std::move(chunk_hidden_states), chunk_weights);
+ chunk_hidden_states = sd::apply_token_weights(std::move(chunk_hidden_states), chunk_weights);
if (zero_out_masked) {
auto chunk_mask_tensor = sd::Tensor<float>::from_vector(chunk_mask)
@@ -1967,7 +1815,7 @@ struct AnimaConditioner : public Conditioner {
false);
if (hidden_states.empty())
return {};
- hidden_states = apply_token_weights(std::move(hidden_states), qwen_weights);
+ hidden_states = sd::apply_token_weights(std::move(hidden_states), qwen_weights);
auto t5_ids_tensor = sd::Tensor<int32_t>::from_vector(t5_tokens);
auto t5_weight_tensor = sd::Tensor<float>::from_vector(t5_weights);
@@ -1982,1528 +1830,6 @@ struct AnimaConditioner : public Conditioner {
}
};
-struct LLMEmbedder : public Conditioner {
- bool supports_prompt_formatting() const override { return true; }
-
- SDVersion version;
- std::shared_ptr<Tokenizer> tokenizer;
- std::shared_ptr<LLM::LLMRunner> llm;
- std::shared_ptr<T5Runner> byt5;
- std::shared_ptr<PH3ImageTextConnectorRunner> ph3_connector;
- std::shared_ptr<ClipProjConnectorRunner> clipproj_connector;
-
- bool supports_prompt_images() const override {
- return llm->supports_prompt_images();
- }
-
- size_t max_reference_images() const override {
- if (!llm->enable_vision)
- 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) ||
- version == VERSION_MOSS_IMAGE
- ? std::numeric_limits<size_t>::max()
- : 0;
- }
-
- bool supports_multimodal_prompt() const override {
- return llm->enable_vision && sd_version_is_minimax_h3(version) &&
- version != VERSION_MINIMAX_H3_IMAGE && version != VERSION_P_H3_IMAGE;
- }
-
- LLMEmbedder(ggml_backend_t backend,
- const String2TensorStorage& tensor_storage_map = {},
- SDVersion version = VERSION_QWEN_IMAGE,
- const std::string prefix = "",
- bool enable_vision = false,
- std::shared_ptr<RunnerWeightManager> weight_manager = nullptr,
- const TokenizerConfig& tokenizers = {})
- : version(version) {
- if (!tokenizers.has(TokenizerConfig::MAIN)) {
- if (sd_version_is_lens(version)) {
- throw std::runtime_error("Lens requires an external GPT-OSS tokenizer.json; pass --tokenizer FILE or set the tokenizer context option");
- }
- if (sd_version_is_pid(version)) {
- throw std::runtime_error("PiD requires an external Gemma 2 tokenizer.json; pass --tokenizer FILE or set the tokenizer context option");
- }
- if (version == VERSION_MOSS_IMAGE) {
- throw std::runtime_error("MOSS-Image requires the official Qwen3.5 tokenizer.json; pass --tokenizer FILE or set the tokenizer context option");
- }
- }
- LLM::LLMArch arch = LLM::LLMArch::QWEN2_5_VL;
- if (version == VERSION_FLUX2) {
- arch = LLM::LLMArch::MISTRAL_SMALL_3_2;
- } else if (sd_version_is_ernie_image(version)) {
- arch = LLM::LLMArch::MINISTRAL_3_3B;
- } else if (sd_version_is_lens(version)) {
- arch = LLM::LLMArch::GPT_OSS_20B;
- } else if (sd_version_is_pid(version)) {
- arch = LLM::LLMArch::GEMMA2_2B;
- } else if (version == VERSION_FIBO2 ||
- version == VERSION_QWEN_IMAGE_2_1 ||
- sd_version_is_flux3(version) ||
- sd_version_is_lingbot_video(version) ||
- sd_version_is_ideogram4(version) ||
- sd_version_is_boogu_image(version) ||
- sd_version_is_sefi_image(version) ||
- sd_version_is_krea2(version) ||
- sd_version_is_minimax_h3(version) ||
- sd_version_is_mage_flow(version) ||
- version == VERSION_IRIS) {
- arch = LLM::LLMArch::QWEN3_VL;
- } else if (sd_version_is_z_image(version) || sd_version_is_z_image_l2p(version) || version == VERSION_OVIS_IMAGE || version == VERSION_FLUX2_KLEIN) {
- arch = LLM::LLMArch::QWEN3;
- } else if (version == VERSION_MOSS_IMAGE) {
- arch = LLM::LLMArch::QWEN3_5;
- }
- if (arch == LLM::LLMArch::QWEN2_5_VL || arch == LLM::LLMArch::QWEN3_VL || arch == LLM::LLMArch::QWEN3_5) {
- for (const auto& entry : tensor_storage_map) {
- if (starts_with(entry.first, "text_encoders.llm.visual.")) {
- enable_vision = true;
- break;
- }
- }
- }
- llm = std::make_shared<LLM::LLMRunner>(arch,
- backend,
- tensor_storage_map,
- "text_encoders.llm",
- enable_vision,
- weight_manager);
- if (sd_version_is_minimax_h3(version)) {
- const bool has_ph3_connector = tensor_storage_map.count(std::string(PH3ImageTextConnectorRunner::prefix) + ".proj.weight") != 0;
- const bool has_clipproj_connector = tensor_storage_map.count(std::string(ClipProjConnectorRunner::prefix) + ".mean_in") != 0;
- if (has_ph3_connector) {
- if (llm->config.num_layers != 36 || llm->config.hidden_size != 2560) {
- throw std::runtime_error("The P-H3-Image text connector requires the Qwen3-VL-4B text encoder");
- }
- ph3_connector = std::make_shared<PH3ImageTextConnectorRunner>(backend, tensor_storage_map, weight_manager);
- } else if (has_clipproj_connector) {
- clipproj_connector = std::make_shared<ClipProjConnectorRunner>(backend, llm->config.hidden_size, 5120, tensor_storage_map, weight_manager);
- } else if (llm->config.hidden_size == 2560) {
- throw std::runtime_error(
- sd_format("%s with Qwen3-VL-4B requires a text connector; pass the P-H3-Image text connector "
- "or a ClipProj projection with --embeddings-connectors, or use the MiniMax-H3 Qwen3-VL-32B text encoder",
- sd_version_name(version)));
- } else if (llm->config.hidden_size == 4096) {
- throw std::runtime_error(
- sd_format("%s with Qwen3-VL-8B requires a ClipProj text connector; "
- "pass it with --embeddings-connectors or use the MiniMax-H3 Qwen3-VL-32B text encoder",
- sd_version_name(version)));
- } else if (llm->config.hidden_size != 5120 || (llm->config.num_layers != 50 && llm->config.num_layers != 64)) {
- throw std::runtime_error(
- sd_format("%s requires the MiniMax-H3 Qwen3-VL-32B text encoder or Qwen3-VL-4B with the P-H3-Image (or a ClipProj) text connector, or Qwen3-VL-8B with a ClipProj projection",
- sd_version_name(version)));
- }
- }
- int pad_id = 151643;
- if (arch == LLM::LLMArch::MISTRAL_SMALL_3_2 || arch == LLM::LLMArch::MINISTRAL_3_3B) {
- pad_id = 11;
- } else if (arch == LLM::LLMArch::GPT_OSS_20B) {
- pad_id = 199999;
- } else if (arch == LLM::LLMArch::GEMMA2_2B) {
- pad_id = 0;
- } else if (arch == LLM::LLMArch::QWEN3_5) {
- pad_id = 248044;
- }
- tokenizer = tokenizers.create(TokenizerConfig::MAIN, llm->config.vocab_size, pad_id);
- if (!tokenizer) {
- if (arch == LLM::LLMArch::MISTRAL_SMALL_3_2 || arch == LLM::LLMArch::MINISTRAL_3_3B) {
- tokenizer = std::make_shared<MistralTokenizer>();
- } else {
- tokenizer = std::make_shared<Qwen2Tokenizer>();
- }
- }
- if (sd_version_is_hunyuan_video(version)) {
- const std::string byt5_prefix = "text_encoders.t5xxl.transformer";
- for (const auto& [name, _] : tensor_storage_map) {
- if (starts_with(name, byt5_prefix + ".")) {
- byt5 = std::make_shared<T5Runner>(backend,
- tensor_storage_map,
- byt5_prefix,
- false,
- weight_manager);
- break;
- }
- }
- }
- }
-
- void get_param_tensors(std::map<std::string, ggml_tensor*>& tensors) override {
- llm->get_param_tensors(tensors, "text_encoders.llm");
- if (ph3_connector) {
- ph3_connector->get_param_tensors(tensors);
- }
- if (clipproj_connector) {
- clipproj_connector->get_param_tensors(tensors);
- }
- if (byt5) {
- byt5->get_param_tensors(tensors, "text_encoders.t5xxl.transformer");
- }
- }
-
- void get_param_tensor_ops(std::map<ggml_tensor*, enum ggml_op>& tensor_ops) override {
- llm->get_param_tensor_ops(tensor_ops);
- }
-
- void set_max_graph_vram_bytes(size_t max_vram_bytes) override {
- llm->set_max_graph_vram_bytes(max_vram_bytes);
- if (ph3_connector) {
- ph3_connector->set_max_graph_vram_bytes(max_vram_bytes);
- }
- if (clipproj_connector) {
- clipproj_connector->set_max_graph_vram_bytes(max_vram_bytes);
- }
- if (byt5) {
- byt5->set_max_graph_vram_bytes(max_vram_bytes);
- }
- }
-
- void set_runtime_backends(const std::vector<ggml_backend_t>& backends) override {
- llm->set_runtime_backends(backends);
- if (ph3_connector) {
- ph3_connector->set_runtime_backends(backends);
- }
- if (clipproj_connector) {
- clipproj_connector->set_runtime_backends(backends);
- }
- if (byt5) {
- byt5->set_runtime_backends(backends);
- }
- }
-
- void set_graph_cut_layer_split_enabled(bool enabled) override {
- if (llm) {
- llm->set_graph_cut_layer_split_enabled(enabled);
- }
- if (byt5) {
- byt5->set_graph_cut_layer_split_enabled(enabled);
- }
- }
-
- void set_graph_cut_layer_split_backend_vram_limits(const std::vector<size_t>& limits) override {
- if (llm) {
- llm->set_graph_cut_layer_split_backend_vram_limits(limits);
- }
- if (byt5) {
- byt5->set_graph_cut_layer_split_backend_vram_limits(limits);
- }
- }
-
- void get_layer_split_param_tensors(std::map<std::string, ggml_tensor*>& tensors) override {
- llm->get_param_tensors(tensors, "text_encoders.llm");
- if (byt5) {
- byt5->get_param_tensors(tensors, "text_encoders.t5xxl.transformer");
- }
- }
-
- void for_each_runner(const std::function<void(GGMLRunner&)>& visit) override {
- visit(*llm);
- if (ph3_connector) {
- visit(*ph3_connector);
- }
- if (clipproj_connector) {
- visit(*clipproj_connector);
- }
- if (byt5) {
- visit(*byt5);
- }
- }
-
- void set_scale_overrides(float linear_scale, float attn_scale) override {
- llm->set_scale_overrides(linear_scale, attn_scale);
- if (ph3_connector) {
- ph3_connector->set_scale_overrides(linear_scale, attn_scale);
- }
- if (clipproj_connector) {
- clipproj_connector->set_scale_overrides(linear_scale, attn_scale);
- }
- if (byt5) {
- byt5->set_scale_overrides(linear_scale, attn_scale);
- }
- }
-
- void set_weight_adapter(const std::shared_ptr<WeightAdapter>& adapter) override {
- if (ph3_connector) {
- ph3_connector->set_weight_adapter(adapter);
- }
- if (clipproj_connector) {
- clipproj_connector->set_weight_adapter(adapter);
- }
- if (llm) {
- llm->set_weight_adapter(adapter);
- }
- if (byt5) {
- byt5->set_weight_adapter(adapter);
- }
- }
-
- void runner_end() override {
- if (ph3_connector) {
- ph3_connector->runner_end();
- }
- if (clipproj_connector) {
- clipproj_connector->runner_end();
- }
- if (llm) {
- llm->runner_end();
- }
- if (byt5) {
- byt5->runner_end();
- }
- }
-
- static std::vector<std::pair<std::string, float>> parse_text_attention(const std::string& text,
- const std::pair<int, int>& attn_range,
- bool spell_quotes) {
- std::vector<std::pair<std::string, float>> parsed_attention;
- if (attn_range.first >= 0 && attn_range.second > 0) {
- if (attn_range.first > 0) {
- parsed_attention.emplace_back(text.substr(0, attn_range.first), 1.f);
- }
- if (attn_range.second - attn_range.first > 0) {
- auto new_parsed_attention = parse_prompt_attention(text.substr(attn_range.first, attn_range.second - attn_range.first));
- if (spell_quotes) {
- new_parsed_attention = split_quotation_attention(new_parsed_attention);
- }
- parsed_attention.insert(parsed_attention.end(),
- new_parsed_attention.begin(),
- new_parsed_attention.end());
- }
- if (attn_range.second < text.size()) {
- parsed_attention.emplace_back(text.substr(attn_range.second), 1.f);
- }
- } else {
- parsed_attention.emplace_back(text, 1.f);
- }
-
- return parsed_attention;
- }
-
- std::tuple<std::vector<int>, std::vector<float>, std::vector<float>> tokenize(std::string text,
- const std::pair<int, int>& attn_range,
- size_t min_length = 0,
- size_t max_length = 100000000,
- bool spell_quotes = false,
- const std::string& suffix = "",
- const std::vector<std::pair<int, sd::Tensor<float>>>& image_embeds = {}) {
- auto parsed_attention = parse_text_attention(text, attn_range, spell_quotes);
-
- {
- std::stringstream ss;
- ss << "[";
- for (const auto& item : parsed_attention) {
- ss << "['" << item.first << "', " << item.second << "], ";
- }
- ss << "]";
- LOG_VERBOSE("parse '%s' to %s", escape_newlines(text).c_str(), escape_newlines(ss.str()).c_str());
- }
-
- std::vector<int> tokens;
- std::vector<float> weights;
- for (const auto& item : parsed_attention) {
- const std::string& curr_text = item.first;
- float curr_weight = item.second;
- std::vector<int> curr_tokens;
- if (!tokenizer->encode(curr_text, curr_tokens, nullptr)) {
- return {};
- }
- tokens.insert(tokens.end(), curr_tokens.begin(), curr_tokens.end());
- weights.insert(weights.end(), curr_tokens.size(), curr_weight);
- }
-
- for (const auto& image_embed : image_embeds) {
- const int index = image_embed.first;
- const int64_t count = image_embed.second.shape()[1];
- if (index < 0 || static_cast<size_t>(index) >= tokens.size() || count < 1) {
- LOG_ERROR("Invalid reference image token range");
- return {};
- }
- const int token = tokens[index];
- const float weight = weights[index];
- tokens.insert(tokens.begin() + index, count - 1, token);
- weights.insert(weights.begin() + index, count - 1, weight);
- }
-
- if (!suffix.empty()) {
- std::vector<int> suffix_tokens;
- if (!tokenizer->encode(suffix, suffix_tokens) || suffix_tokens.size() >= max_length) {
- return {};
- }
- // Reserve the assistant-turn marker before truncating the caption.
- if (tokens.size() > max_length - suffix_tokens.size()) {
- tokens.resize(max_length - suffix_tokens.size());
- weights.resize(tokens.size());
- }
- tokens.insert(tokens.end(), suffix_tokens.begin(), suffix_tokens.end());
- weights.insert(weights.end(), suffix_tokens.size(), 1.f);
- }
-
- if (sd_version_is_flux3(version)) {
- min_length = std::min(max_length, ((tokens.size() + 79) / 80) * 80);
- }
- std::vector<float> mask;
- tokenizer->pad_tokens(tokens, &weights, &mask, min_length, max_length);
-
- // Keep masks and weights in expanded coordinates, but only look up one token per image.
- for (auto it = image_embeds.rbegin(); it != image_embeds.rend(); ++it) {
- const int64_t begin = it->first;
- const int64_t end = begin + it->second.shape()[1];
- if (begin < 0 || end > static_cast<int64_t>(tokens.size())) {
- LOG_ERROR("Reference image exceeds the tokenized context");
- return {};
- }
- tokens.erase(tokens.begin() + begin + 1, tokens.begin() + end);
- }
-
- // for (int i = 0; i < tokens.size(); i++) {
- // std::cout << tokens[i] << ":" << weights[i] << ", " << i << std::endl;
- // }
- // std::cout << std::endl;
-
- return {tokens, weights, mask};
- }
-
- bool prepare_prompt_tokens(int n_threads,
- const sd::PromptInputTemplate& input_template,
- const std::string& prompt,
- const std::pair<int, int>& attn_range,
- int min_length,
- int max_length,
- bool spell_quotes,
- const std::string& suffix,
- const LLM::ImageEmbeds& images,
- const LLM::DeepStackImageEmbeds& deepstack,
- const std::vector<LLM::ImageGrid>& grids,
- LLM::PromptTokens& result) {
- sd::PromptInput input;
- auto text = parse_text_attention(prompt, attn_range, spell_quotes);
- text.emplace_back(suffix, 1.f);
- for (const auto& span : text) {
- auto parts = input_template.expand(span.first, span.second);
- input.insert(input.end(), std::make_move_iterator(parts.begin()), std::make_move_iterator(parts.end()));
- }
- max_length = std::min(max_length, static_cast<int>(llm->config.max_position_embeddings));
- if (!llm->prepare_prompt(n_threads, *tokenizer, input, max_length, result, images, deepstack, grids)) {
- return false;
- }
- auto expanded = result.tokens;
- for (const auto& image : result.image_embeds) {
- expanded.insert(expanded.begin() + image.first, image.second.shape()[1] - 1, expanded[image.first]);
- }
- if (sd_version_is_flux3(version)) {
- min_length = std::min(max_length, ((result.expanded_length + 79) / 80) * 80);
- }
- tokenizer->pad_tokens(expanded, &result.weights, &result.mask, min_length, max_length);
- const int leading_padding = static_cast<int>(std::find(result.mask.begin(), result.mask.end(), 1.f) - result.mask.begin());
- for (auto& image : result.image_embeds) {
- image.first += leading_padding;
- }
- for (auto& layer : result.deepstack_image_embeds) {
- for (auto& image : layer) {
- image.first += leading_padding;
- }
- }
- for (auto& grid : result.image_grids) {
- grid.index += leading_padding;
- }
- for (auto it = result.image_embeds.rbegin(); it != result.image_embeds.rend(); ++it) {
- expanded.erase(expanded.begin() + it->first + 1, expanded.begin() + it->first + it->second.shape()[1]);
- }
- result.tokens = std::move(expanded);
- result.expanded_length = static_cast<int>(result.weights.size());
- return true;
- }
-
- sd::Tensor<float> encode_prompt(int n_threads,
- const std::string prompt,
- const std::pair<int, int>& prompt_attn_range,
- int min_length,
- int hidden_states_min_length,
- const std::vector<std::pair<int, sd::Tensor<float>>>& image_embeds,
- const std::set<int>& out_layers,
- int prompt_template_encode_start_idx,
- bool spell_quotes = false,
- int max_length = 100000000,
- const LLM::DeepStackImageEmbeds& deepstack_image_embeds = {},
- const std::vector<LLM::ImageGrid>& image_grids = {},
- const std::string& prompt_suffix = "",
- sd::Tensor<float>* output_mask = nullptr,
- const sd::PromptInputTemplate* input_template = nullptr,
- LLM::PromptTokens* output_prompt_tokens = nullptr) {
- LLM::PromptTokens prepared;
- if (input_template != nullptr &&
- !prepare_prompt_tokens(n_threads, *input_template, prompt, prompt_attn_range, min_length, max_length,
- spell_quotes, prompt_suffix, image_embeds, deepstack_image_embeds, image_grids, prepared)) {
- return {};
- }
- auto tokens_weights_mask = input_template == nullptr
- ? tokenize(prompt, prompt_attn_range, min_length, max_length, spell_quotes, prompt_suffix, image_embeds)
- : std::make_tuple(prepared.tokens, prepared.weights, prepared.mask);
- auto& tokens = std::get<0>(tokens_weights_mask);
- auto& weights = std::get<1>(tokens_weights_mask);
- auto& mask = std::get<2>(tokens_weights_mask);
-
- if (tokens.empty()) {
- return {};
- }
- if (prompt_template_encode_start_idx < 0 || static_cast<size_t>(prompt_template_encode_start_idx) >= weights.size()) {
- LOG_ERROR("Prompt template exceeds the text encoder context; shorten system or prompt");
- return {};
- }
-
- sd::Tensor<int32_t> input_ids({static_cast<int64_t>(tokens.size())}, tokens);
- sd::Tensor<float> attention_mask;
- if (!mask.empty()) {
- attention_mask = sd::Tensor<float>({static_cast<int64_t>(mask.size()), static_cast<int64_t>(mask.size())});
- const float masked_attention_value = -std::numeric_limits<float>::max() / 4.0f;
- for (size_t i1 = 0; i1 < mask.size(); ++i1) {
- for (size_t i0 = 0; i0 < mask.size(); ++i0) {
- float value = 0.0f;
- if (mask[i0] == 0.0f) {
- value += masked_attention_value;
- }
- if (i0 > i1) {
- value += masked_attention_value;
- }
- attention_mask[static_cast<int64_t>(i0 + mask.size() * i1)] = value;
- }
- }
- }
-
- sd::Tensor<int32_t> position_ids;
- if (sd_version_is_flux3(version)) {
- position_ids = sd::Tensor<int32_t>::zeros({static_cast<int64_t>(weights.size() * 4)});
- if (input_template != nullptr) {
- position_ids.values() = LLM::LLMRunner::build_position_ids(llm->config, weights.size(), prepared.image_grids);
- }
- for (size_t axis = 0; axis < 4; ++axis) {
- for (size_t i = 0; i < weights.size(); ++i) {
- position_ids[axis * weights.size() + i] = mask[i] == 0.f ? 1 : (input_template == nullptr ? static_cast<int32_t>(i) : position_ids[axis * weights.size() + i]);
- }
- }
- }
- auto hidden_states = llm->compute(n_threads,
- input_ids,
- attention_mask,
- input_template == nullptr ? image_embeds : prepared.image_embeds,
- out_layers,
- false,
- false,
- input_template == nullptr ? deepstack_image_embeds : prepared.deepstack_image_embeds,
- input_template == nullptr ? image_grids : prepared.image_grids,
- position_ids);
- if (hidden_states.empty()) {
- LOG_ERROR("LLM prompt encoding failed");
- return {};
- }
- if (ph3_connector) {
- hidden_states = ph3_connector->compute(n_threads, hidden_states);
- if (hidden_states.empty()) {
- return {};
- }
- } else if (clipproj_connector) {
- hidden_states = clipproj_connector->compute(n_threads, hidden_states);
- if (hidden_states.empty()) {
- return {};
- }
- }
- hidden_states = apply_token_weights(std::move(hidden_states), weights);
- GGML_ASSERT(hidden_states.shape()[1] > prompt_template_encode_start_idx);
-
- int64_t zero_pad_len = 0;
- if (hidden_states_min_length > 0) {
- if (hidden_states.shape()[1] - prompt_template_encode_start_idx < hidden_states_min_length) {
- zero_pad_len = hidden_states_min_length - hidden_states.shape()[1] + prompt_template_encode_start_idx;
- }
- }
-
- sd::Tensor<float> new_hidden_states = sd::ops::slice(hidden_states,
- 1,
- prompt_template_encode_start_idx,
- hidden_states.shape()[1]);
- if (zero_pad_len > 0) {
- auto pad_shape = new_hidden_states.shape();
- pad_shape[1] = zero_pad_len;
- new_hidden_states = sd::ops::concat(new_hidden_states,
- sd::Tensor<float>::zeros(std::move(pad_shape)),
- 1);
- }
-
- if (output_mask != nullptr) {
- *output_mask = sd::Tensor<float>::zeros({new_hidden_states.shape()[1]});
- for (size_t i = prompt_template_encode_start_idx; i < mask.size(); ++i) {
- output_mask->data()[i - prompt_template_encode_start_idx] = mask[i];
- }
- }
- if (output_prompt_tokens != nullptr && input_template != nullptr) {
- *output_prompt_tokens = std::move(prepared);
- }
- return new_hidden_states;
- }
-
- static void fit_h3_vision_dims(int height, int width, int& h_bar, int& w_bar, int factor) {
- const double area = static_cast<double>(h_bar) * w_bar;
- if (area > 12845056) {
- const double beta = std::sqrt(static_cast<double>(height) * width / 12845056);
- h_bar = std::max(factor, static_cast<int>(std::floor(height / beta / factor)) * factor);
- w_bar = std::max(factor, static_cast<int>(std::floor(width / beta / factor)) * factor);
- } else if (area < 3136) {
- const double beta = std::sqrt(3136.0 / (static_cast<double>(height) * width));
- h_bar = static_cast<int>(std::ceil(height * beta / factor)) * factor;
- w_bar = static_cast<int>(std::ceil(width * beta / factor)) * factor;
- }
- }
-
- bool expand_vision_marker(const std::string& prompt,
- size_t& marker_start,
- std::vector<sd::Tensor<float>> outputs,
- int grid_h,
- int grid_w,
- std::vector<std::pair<int, sd::Tensor<float>>>& image_embeds,
- LLM::DeepStackImageEmbeds& deepstack_image_embeds,
- std::vector<LLM::ImageGrid>& image_grids,
- int max_length = std::numeric_limits<int>::max()) {
- if (outputs.empty()) {
- return false;
- }
- const std::string placeholder = "<|image_pad|>";
- size_t position = prompt.find(placeholder, marker_start);
- if (position == std::string::npos) {
- LOG_ERROR("Reference image marker is missing");
- return false;
- }
- std::vector<int> prefix_tokens;
- if (!tokenizer->encode(prompt.substr(0, position), prefix_tokens, nullptr)) {
- return false;
- }
- int index = static_cast<int>(prefix_tokens.size());
- for (const auto& image_embed : image_embeds) {
- index += static_cast<int>(image_embed.second.shape()[1]) - 1;
- }
- int count = static_cast<int>(outputs[0].shape()[1]);
- if (index > max_length || count > max_length - index) {
- LOG_ERROR("Reference images exceed the %d-token context", max_length);
- return false;
- }
- if (deepstack_image_embeds.empty()) {
- deepstack_image_embeds.resize(outputs.size() - 1);
- }
- GGML_ASSERT(deepstack_image_embeds.size() == outputs.size() - 1);
- image_embeds.emplace_back(index, std::move(outputs[0]));
- for (size_t layer = 1; layer < outputs.size(); ++layer) {
- deepstack_image_embeds[layer - 1].emplace_back(index, std::move(outputs[layer]));
- }
- image_grids.push_back({index, count, grid_h, grid_w});
- marker_start = position + placeholder.size();
- return true;
- }
-
- SDCondition get_learned_condition(int n_threads,
- const ConditionerParams& params) override {
- ConditionerParams conditioner_params = params;
- 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<int64_t>(32, std::llround(width * scale));
- const auto h = std::max<int64_t>(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<sd::Tensor<float>>(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 {};
- }
- conditioner_params.text = input_template.text;
- }
- std::string prompt;
- std::pair<int, int> prompt_attn_range;
- std::vector<std::string> extra_prompts;
- std::vector<std::pair<int, int>> extra_prompts_attn_range;
- std::vector<std::pair<int, sd::Tensor<float>>> image_embeds;
- LLM::DeepStackImageEmbeds deepstack_image_embeds;
- std::vector<LLM::ImageGrid> image_grids;
- int prompt_template_encode_start_idx = 34;
- int min_length = 0; // pad tokens
- int max_length = 100000000;
- int hidden_states_min_length = 0; // zero pad hidden_states
- bool spell_quotes = false;
- std::set<int> out_layers;
- std::string prompt_suffix;
- sd::Tensor<float> text_mask;
-
- int template_token_delta = 0;
- bool dynamic_template_crop = false;
- bool max_length_includes_template = false;
- auto system_prefix = [&](const std::string& prefix) {
- auto format = version == VERSION_FLUX2 ? sd::prompt_templates::RoleFormat::Mistral
- : sd_version_is_lens(version) ? sd::prompt_templates::RoleFormat::GPTOSS
- : sd_version_is_pid(version) ? sd::prompt_templates::RoleFormat::Gemma
- : sd::prompt_templates::RoleFormat::ChatML;
- auto result = sd::prompt_templates::with_system(prefix, conditioner_params.system_prompt, format);
- if (result != prefix && !dynamic_template_crop) {
- std::vector<int> before, after;
- if ((!prefix.empty() && !tokenizer->encode(prefix, before)) ||
- (!result.empty() && !tokenizer->encode(result, after)))
- throw std::runtime_error("cannot tokenize prompt template");
- template_token_delta += static_cast<int>(after.size()) - static_cast<int>(before.size());
- }
- return result;
- };
-
- int64_t t0 = ggml_time_ms();
-
- if (sd_version_is_minimax_h3(version)) {
- prompt = system_prefix("");
- prompt_template_encode_start_idx = 0;
- // The final tap is normalized; LLMRunner exposes it at num_layers + 1.
- // clipproj taps out at layer 24 in all versions so far, so it should be fine to hardcode it there
- out_layers = ph3_connector ? std::set<int>{13, 19, 25, 31, 37} : std::set<int>{clipproj_connector ? 24 : 50};
- prompt_attn_range = {0, 0};
-
- if (llm->enable_vision) {
- const int patch_size = llm->config.vision.patch_size;
- const int factor = patch_size * llm->config.vision.spatial_merge_size;
-
- auto resize_for_vision = [&](const sd::Tensor<float>& image) {
- int height = static_cast<int>(image.shape()[1]);
- int width = static_cast<int>(image.shape()[0]);
- int h_bar = std::max(factor, static_cast<int>(std::round(static_cast<double>(height) / factor)) * factor);
- int w_bar = std::max(factor, static_cast<int>(std::round(static_cast<double>(width) / factor)) * factor);
- fit_h3_vision_dims(height, width, h_bar, w_bar, factor);
- auto resized = sd::ops::interpolate(
- image,
- std::vector<int64_t>{w_bar, h_bar, image.shape()[2], image.shape()[3]});
- for (int64_t i = 0; i < resized.numel(); ++i) {
- resized[i] = std::clamp(resized[i], 0.f, 1.f) * 2.f - 1.f;
- }
- return resized;
- };
-
- auto add_vision_outputs = [&](std::vector<sd::Tensor<float>> image_outputs,
- int grid_h,
- int grid_w) {
- GGML_ASSERT(image_outputs.size() == 4);
- prompt += "<|vision_start|>";
- size_t marker_start = prompt.size();
- prompt += "<|image_pad|><|vision_end|>";
- return expand_vision_marker(prompt, marker_start, std::move(image_outputs), grid_h, grid_w,
- image_embeds, deepstack_image_embeds, image_grids);
- };
-
- const auto* references = conditioner_params.minimax_h3_references;
- if (references != nullptr && !references->empty()) {
- int picture_index = 0;
- int video_index = 0;
- int audio_index = 0;
- for (const auto& item : *references) {
- if (item.kind == MiniMaxH3PresentationKind::AUDIO) {
- prompt += "<Audio " + std::to_string(++audio_index) + ">: ";
- continue;
- }
- if (item.kind == MiniMaxH3PresentationKind::IMAGE) {
- GGML_ASSERT(item.frames.size() == 1);
- auto resized = resize_for_vision(item.frames[0]);
- prompt += "<Picture " + std::to_string(++picture_index) + ">: ";
- if (!add_vision_outputs(llm->encode_image_outputs(n_threads,
- resized,
- false),
- static_cast<int>(resized.shape()[1]) / patch_size,
- static_cast<int>(resized.shape()[0]) / patch_size)) {
- return {};
- }
- continue;
- }
-
- GGML_ASSERT(!item.frames.empty());
- prompt += "<Video " + std::to_string(++video_index) + ">: ";
- for (size_t frame = 0; frame < item.frames.size(); frame += 2) {
- size_t next = std::min(frame + 1, item.frames.size() - 1);
- float t0 = frame < item.timestamps.size() ? item.timestamps[frame] : frame / 2.f;
- float t1 = next < item.timestamps.size() ? item.timestamps[next] : next / 2.f;
- std::ostringstream timestamp;
- timestamp << '<' << std::fixed << std::setprecision(1) << (t0 + t1) * 0.5f << " seconds>";
- prompt += timestamp.str();
-
- auto first = resize_for_vision(item.frames[frame]);
- auto second = resize_for_vision(item.frames[next]);
- if (first.shape()[0] != second.shape()[0] || first.shape()[1] != second.shape()[1]) {
- second = sd::ops::interpolate(second,
- std::vector<int64_t>{first.shape()[0],
- first.shape()[1],
- second.shape()[2],
- second.shape()[3]});
- }
- auto pair = sd::ops::concat(first.unsqueeze(2), second.unsqueeze(2), 2);
- if (!add_vision_outputs(llm->encode_video_block_outputs(n_threads,
- pair,
- false),
- static_cast<int>(first.shape()[1]) / patch_size,
- static_cast<int>(first.shape()[0]) / patch_size)) {
- return {};
- }
- }
- }
- } else if (conditioner_params.ref_images != nullptr) {
- for (size_t i = 0; i < conditioner_params.ref_images->size(); ++i) {
- auto resized = resize_for_vision((*conditioner_params.ref_images)[i]);
- prompt += version == VERSION_MINIMAX_H3_IMAGE
- ? "Picture " + std::to_string(i + 1) + ": "
- : "<Picture " + std::to_string(i + 1) + ">: ";
- if (!add_vision_outputs(llm->encode_image_outputs(n_threads,
- resized,
- false),
- static_cast<int>(resized.shape()[1]) / patch_size,
- static_cast<int>(resized.shape()[0]) / patch_size)) {
- return {};
- }
- }
- }
- }
- auto text = conditioner_params.text;
- if (version == VERSION_P_H3_IMAGE && !image_embeds.empty()) {
- // Preserve explicit picture targets and structured briefs from the upstream upsampler.
- static const std::regex verbatim(R"(^\s*(Edit <Picture \d+>|subject_definitions:))");
- if (!std::regex_search(text, verbatim)) {
- text = "Edit <Picture 1>. " + text;
- } else {
- text = trim(text);
- }
- }
- prompt += text;
- } else if (sd_version_is_hunyuan_video(version)) {
- prompt_template_encode_start_idx = 98;
- out_layers = {26};
-
- prompt =
- system_prefix(
- "<|im_start|>system\nYou are a helpful assistant. Describe the video by detailing the following aspects:\n"
- "1. The main content and theme of the video.\n"
- "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects.\n"
- "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects.\n"
- "4. background environment, light, style and atmosphere.\n"
- "5. camera angles, movements, and transitions used in the video.<|im_end|>\n"
- "<|im_start|>user\n");
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- } else if (sd_version_is_lingbot_video(version)) {
- dynamic_template_crop = true;
- const int pad_token = 151643;
- const std::string prompt_prefix =
- system_prefix(
- "<|im_start|>system\nGiven a user input that may include a text prompt alone, "
- "a text prompt with an image reference, or a text prompt with a video reference "
- "or a video reference alone, generate an \"Enhanced prompt\" that provides detailed "
- "visual descriptions suitable for video generation. Evaluate the level of detail "
- "in the user's input: if it is simple, enrich it by adding specifics about colors, "
- "shapes, sizes, textures, lighting, motion dynamics, camera movement, temporal "
- "progression, and spatial relationships to create vivid, concrete, and temporally "
- "coherent scenes to create vivid and concrete scenes. Please generate only the "
- "enhanced description for the prompt below and avoid including any additional "
- "commentary or evaluations:<|im_end|>\n<|im_start|>user\n");
-
- std::vector<int> prefix_tokens;
- if (!conditioner_params.raw && !tokenizer->encode(prompt_prefix, prefix_tokens, nullptr)) {
- return {};
- }
- prompt_template_encode_start_idx = 0;
- for (int token : prefix_tokens) {
- if (token != pad_token) {
- prompt_template_encode_start_idx++;
- }
- }
- LOG_VERBOSE("prompt_template_encode_start_idx %d", prompt_template_encode_start_idx);
-
- prompt = prompt_prefix;
- if (llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
- LOG_INFO("LingBotVideoI2VPipeline");
- const std::string placeholder = "<|image_pad|>";
- std::string img_prompt;
-
- for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
- const auto& image = (*conditioner_params.ref_images)[i];
- const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
- int height = static_cast<int>(image.shape()[1]);
- int width = static_cast<int>(image.shape()[0]);
-
- int h_bar = std::max(factor, static_cast<int>(std::round(static_cast<double>(height) / factor) * factor));
- int w_bar = std::max(factor, static_cast<int>(std::round(static_cast<double>(width) / factor) * factor));
-
- if (std::max(height, width) > 200 * std::min(height, width)) {
- LOG_WARN("LingBotVideo image aspect ratio is very large: %dx%d", width, height);
- }
-
- LOG_VERBOSE("resize LingBotVideo ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
- auto resized_image = clip_preprocess(image, w_bar, h_bar);
- auto image_embed = llm->encode_image(n_threads, resized_image, false);
- if (image_embed.empty())
- return {};
-
- std::string image_prefix = prompt + img_prompt + "<|vision_start|>";
- std::vector<int> prefix_tokens;
- if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
- return {};
- }
- int image_embed_idx = static_cast<int>(prefix_tokens.size());
- for (const auto& previous_image : image_embeds) {
- image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
- }
- image_embeds.emplace_back(image_embed_idx, image_embed);
-
- img_prompt += "<|vision_start|>";
- img_prompt += placeholder;
- img_prompt += "<|vision_end|>";
- }
- prompt += img_prompt;
- }
-
- prompt += conditioner_params.text;
- prompt_attn_range = {0, 0};
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- } else if (version == VERSION_QWEN_IMAGE_2_1) {
- if (!llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
- LOG_ERROR("Qwen Image 2.1 editing requires Qwen3-VL vision weights; provide --llm_vision or a combined encoder");
- return {};
- }
- prompt = sd::prompt_templates::system_message(conditioner_params.system_prompt, "Comprehend and analyze the provided prompt.");
- std::vector<int> system_tokens;
- if (!conditioner_params.raw && !prompt.empty() && !tokenizer->encode(prompt, system_tokens, nullptr)) {
- return {};
- }
- prompt_template_encode_start_idx = static_cast<int>(system_tokens.size());
- out_layers = {static_cast<int>(llm->config.num_layers)};
- prompt += "<|im_start|>user\n";
- if (llm->enable_vision && conditioner_params.ref_images != nullptr) {
- for (size_t i = 0; i < conditioner_params.ref_images->size(); ++i) {
- const auto& source = (*conditioner_params.ref_images)[i];
- const auto resized = sd::fit_image_tensor(source, 32, "Qwen Image 2.1 reference encoding");
- const auto& image = resized.empty() ? source : resized;
- int64_t width = image.shape()[0];
- int64_t height = image.shape()[1];
- int64_t pixels = width * height;
- auto rgb = sd::Tensor<float>({width, height, 3, 1});
- for (int64_t p = 0; p < pixels; ++p) {
- float alpha = image.shape()[2] == 4 ? image[p + 3 * pixels] : 1.f;
- for (int c = 0; c < 3; ++c) {
- rgb[p + c * pixels] = 2.f * (image[p + c * pixels] * alpha + 1.f - alpha) - 1.f;
- }
- }
- auto outputs = llm->encode_image_outputs(n_threads, rgb, false);
- if (outputs.empty()) {
- return {};
- }
- prompt += (i == 0 ? "" : " ") + std::string("<image") + std::to_string(i + 1) + "><|vision_start|>";
- size_t marker_start = prompt.size();
- prompt += "<|image_pad|><|vision_end|>";
- if (!expand_vision_marker(prompt, marker_start, std::move(outputs),
- static_cast<int>(height) / llm->config.vision.patch_size,
- static_cast<int>(width) / llm->config.vision.patch_size,
- image_embeds, deepstack_image_embeds, image_grids)) {
- return {};
- }
- }
- }
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text.empty() ? " " : conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- } else if (sd_version_is_qwen_image(version) || sd_version_is_mage_flow(version)) {
- if (llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
- LOG_INFO("%s", sd_version_is_mage_flow(version) ? "MageFlowEditPipeline" : "QwenImageEditPlusPipeline");
- prompt_template_encode_start_idx = 64;
-
- prompt = system_prefix("<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n");
- std::string placeholder = "<|image_pad|>";
- std::string img_prompt;
-
- for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
- const auto& image = (*conditioner_params.ref_images)[i];
- const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
- int height = static_cast<int>(image.shape()[1]);
- int width = static_cast<int>(image.shape()[0]);
- int h_bar = static_cast<int>(std::round(static_cast<double>(height) / factor) * factor);
- int w_bar = static_cast<int>(std::round(static_cast<double>(width) / factor) * factor);
-
- if (version == VERSION_QWEN_IMAGE) {
- constexpr double target_area = 384.0 * 384.0;
- const double scale = std::sqrt(target_area / (static_cast<double>(width) * height));
- h_bar = std::max(factor, static_cast<int>(std::round(height * scale / factor)) * factor);
- w_bar = std::max(factor, static_cast<int>(std::round(width * scale / factor)) * factor);
- }
-
- LOG_VERBOSE("resize conditioner ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
-
- auto resized_image = clip_preprocess(image, w_bar, h_bar);
-
- auto image_embed = llm->encode_image(n_threads, resized_image, false);
- if (image_embed.empty())
- return {};
- std::string image_prefix = prompt + img_prompt + (sd_version_is_mage_flow(version) ? "Image " : "Picture ") + std::to_string(i + 1) + ": <|vision_start|>";
- std::vector<int> prefix_tokens;
- if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
- return {};
- }
- int image_embed_idx = static_cast<int>(prefix_tokens.size());
- for (const auto& previous_image : image_embeds) {
- image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
- }
- image_embeds.emplace_back(image_embed_idx, image_embed);
-
- img_prompt += (sd_version_is_mage_flow(version) ? "Image " : "Picture ") + std::to_string(i + 1) + ": <|vision_start|>";
- img_prompt += placeholder;
- img_prompt += "<|vision_end|>";
- }
-
- prompt += img_prompt;
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- } else {
- prompt_template_encode_start_idx = 34;
-
- prompt = system_prefix("<|im_start|>system\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>\n<|im_start|>user\n");
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- }
- if (sd_version_is_mage_flow(version)) {
- max_length = 2048 + prompt_template_encode_start_idx;
- max_length_includes_template = true;
- }
- } else if (sd_version_is_boogu_image(version)) {
- prompt_template_encode_start_idx = 0;
-
- const std::string t2i_system_prompt =
- "You are a helpful assistant that generates high-quality images based on user instructions. The instructions are as follows.";
- const std::string edit_system_prompt =
- "Describe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.";
- const bool has_ref_images = llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty();
- const bool text_empty = conditioner_params.text.find_first_not_of(" \t\r\n") == std::string::npos;
-
- if (has_ref_images) {
- LOG_INFO("BooguImageEditPipeline");
- const std::string prompt_prefix = system_prefix("<|im_start|>system\n" + edit_system_prompt + "<|im_end|>\n<|im_start|>user\n");
- std::string img_prompt;
- const std::string placeholder = "<|image_pad|>";
-
- for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
- const auto& image = (*conditioner_params.ref_images)[i];
- const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
- int height = static_cast<int>(image.shape()[1]);
- int width = static_cast<int>(image.shape()[0]);
-
- int h_bar = std::max(factor,
- static_cast<int>(std::round(static_cast<double>(height) / factor)) * factor);
- int w_bar = std::max(factor,
- static_cast<int>(std::round(static_cast<double>(width) / factor)) * factor);
-
- LOG_VERBOSE("resize conditioner ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
-
- auto resized_image = clip_preprocess(image, w_bar, h_bar);
- auto image_embed = llm->encode_image(n_threads, resized_image, false);
- if (image_embed.empty())
- return {};
-
- std::string image_prefix = prompt_prefix + img_prompt + "<|vision_start|>";
- std::vector<int> prefix_tokens;
- if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
- return {};
- }
- int image_embed_idx = static_cast<int>(prefix_tokens.size());
- for (const auto& previous_image : image_embeds) {
- image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
- }
- image_embeds.emplace_back(image_embed_idx, image_embed);
-
- img_prompt += "<|vision_start|>";
- img_prompt += placeholder;
- img_prompt += "<|vision_end|>";
- }
-
- prompt = prompt_prefix + img_prompt;
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
- prompt += "<|im_end|>\n";
- } else {
- const std::string& system_prompt = text_empty ? edit_system_prompt : t2i_system_prompt;
- prompt = system_prefix("<|im_start|>system\n" + system_prompt + "<|im_end|>\n<|im_start|>user\n");
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
- prompt += "<|im_end|>\n";
- }
- } else if (sd_version_is_krea2(version)) {
- prompt_template_encode_start_idx = 34;
- out_layers = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35};
-
- prompt = system_prefix("<|im_start|>system\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>\n<|im_start|>user\n");
- if (llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
- std::string img_prompt = "";
- const std::string placeholder = "<|image_pad|>";
- for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
- const auto& image = (*conditioner_params.ref_images)[i];
- const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
- int height = static_cast<int>(image.shape()[1]);
- int width = static_cast<int>(image.shape()[0]);
-
- int h_bar = std::max(factor,
- static_cast<int>(std::round(static_cast<double>(height) / factor)) * factor);
- int w_bar = std::max(factor,
- static_cast<int>(std::round(static_cast<double>(width) / factor)) * factor);
-
- LOG_VERBOSE("resize conditioner ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
-
- auto resized_image = clip_preprocess(image, w_bar, h_bar);
- auto image_embed = llm->encode_image(n_threads, resized_image, false);
- if (image_embed.empty())
- return {};
-
- std::string image_prefix = prompt + img_prompt + "Picture " + std::to_string(i + 1) + ": <|vision_start|>";
- std::vector<int> prefix_tokens;
- if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
- return {};
- }
- int image_embed_idx = static_cast<int>(prefix_tokens.size());
- for (const auto& previous_image : image_embeds) {
- image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
- }
- image_embeds.emplace_back(image_embed_idx, image_embed);
-
- img_prompt += "Picture " + std::to_string(i + 1) + ": <|vision_start|>";
- img_prompt += placeholder;
- img_prompt += "<|vision_end|>";
- }
- prompt += img_prompt;
- }
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- } else if (sd_version_is_longcat(version)) {
- spell_quotes = true;
-
- if (llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
- LOG_INFO("LongCatEditPipeline");
- prompt_template_encode_start_idx = 67;
- min_length = 512 + prompt_template_encode_start_idx;
-
- prompt = system_prefix("<|im_start|>system\nAs an image editing expert, first analyze the content and attributes of the input image(s). Then, based on the user's editing instructions, clearly and precisely determine how to modify the given image(s), ensuring that only the specified parts are altered and all other aspects remain consistent with the original(s).<|im_end|>\n<|im_start|>user\n");
- std::string placeholder = "<|image_pad|>";
- std::string img_prompt;
-
- for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
- const auto& image = (*conditioner_params.ref_images)[i];
- const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
- int height = static_cast<int>(image.shape()[1]);
- int width = static_cast<int>(image.shape()[0]);
- int h_bar = static_cast<int>(std::round(static_cast<double>(height) / factor) * factor);
- int w_bar = static_cast<int>(std::round(static_cast<double>(width) / factor) * factor);
-
- LOG_VERBOSE("resize conditioner ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
-
- auto resized_image = clip_preprocess(image, w_bar, h_bar);
- auto image_embed = llm->encode_image(n_threads, resized_image, false);
- if (image_embed.empty())
- return {};
- std::string image_prefix = prompt + img_prompt + "<|vision_start|>";
- std::vector<int> prefix_tokens;
- if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
- return {};
- }
- int image_embed_idx = static_cast<int>(prefix_tokens.size());
- for (const auto& previous_image : image_embeds) {
- image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
- }
- image_embeds.emplace_back(image_embed_idx, image_embed);
-
- img_prompt += "<|vision_start|>";
- img_prompt += placeholder;
- img_prompt += "<|vision_end|>";
- }
-
- prompt += img_prompt;
- } else {
- prompt_template_encode_start_idx = 36;
- min_length = 512 + prompt_template_encode_start_idx;
-
- prompt = system_prefix("<|im_start|>system\nAs an image captioning expert, generate a descriptive text prompt based on an image content, suitable for input to a text-to-image model.<|im_end|>\n<|im_start|>user\n");
- }
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- } else if (version == VERSION_FLUX2) {
- prompt_template_encode_start_idx = 0;
- hidden_states_min_length = 512;
- out_layers = {10, 20, 30};
-
- prompt = system_prefix("[SYSTEM_PROMPT]You are an AI that reasons about image descriptions. You give structured responses focusing on object relationships, object\nattribution and actions without speculation.[/SYSTEM_PROMPT][INST]");
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "[/INST]";
- } else if (sd_version_is_ideogram4(version)) {
- prompt_template_encode_start_idx = 0;
- out_layers = {1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 36};
-
- prompt = system_prefix("<|im_start|>user\n");
- prompt += conditioner_params.text;
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- prompt_attn_range = {0, 0};
- } else if (sd_version_is_ernie_image(version)) {
- prompt = system_prefix("");
- prompt_template_encode_start_idx = 0;
- out_layers = {25}; // -2
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
- } else if (sd_version_is_lens(version)) {
- prompt_template_encode_start_idx = 97;
- min_length = 0;
- max_length = 512;
- out_layers = {6, 12, 18, 24};
-
- prompt =
- system_prefix(
- "<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.\n"
- "Knowledge cutoff: 2024-06\n"
- "Current date: 2026-05-26\n" // fix for current date
- "\n"
- "Reasoning: medium\n"
- "\n"
- "# Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions\n"
- "\n"
- "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background.\n"
- "\n"
- "<|end|><|start|>user<|message|>");
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "<|end|><|start|>assistant<|channel|>analysis<|message|>Need to generate one image according to the description.<|end|><|start|>assistant<|channel|>final<|message|>";
- } else if (sd_version_is_z_image(version) || sd_version_is_z_image_l2p(version)) {
- prompt_template_encode_start_idx = 0;
- out_layers = {35}; // -2
- if (conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
- LOG_ERROR("Z-Image currently does not support reference-image conditioning");
- return {};
- }
- if (conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
- LOG_INFO("ZImageOmniPipeline");
- prompt = system_prefix("<|im_start|>user\n<|vision_start|>");
- for (int i = 0; i < conditioner_params.ref_images->size() - 1; i++) {
- extra_prompts.push_back("<|vision_end|><|vision_start|>");
- }
- extra_prompts.push_back("<|vision_end|>" + conditioner_params.text + "<|im_end|>\n<|im_start|>assistant\n<|vision_start|>");
- extra_prompts.push_back("<|vision_end|><|im_end|>");
- } else {
- prompt = system_prefix("<|im_start|>user\n");
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- }
- } else if (version == VERSION_MOSS_IMAGE) {
- prompt_template_encode_start_idx = 0;
- max_length = 4096;
- prompt = system_prefix("<|im_start|>user\n");
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
- prompt += "<|im_end|>\n<|im_start|>assistant\n<think>\n";
- } else if (sd_version_is_flux3(version)) {
- prompt_template_encode_start_idx = 0;
- max_length = 4096;
- out_layers = {4, 8, 12, 16, 20, 24, 28, 32};
- prompt = system_prefix("<|im_start|>user\n");
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- } else if (version == VERSION_FLUX2_KLEIN) {
- prompt_template_encode_start_idx = 0;
- min_length = 512;
- out_layers = {9, 18, 27};
-
- prompt = system_prefix("<|im_start|>user\n");
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n";
- } else if (sd_version_is_sefi_image(version)) {
- prompt_template_encode_start_idx = 0;
- min_length = 1024;
- out_layers = {9, 18, 27};
-
- prompt = system_prefix("<|im_start|>user\n");
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "<|im_end|>\n<|im_start|>assistant\n";
- } else if (version == VERSION_OVIS_IMAGE) {
- prompt_template_encode_start_idx = 28;
- min_length = prompt_template_encode_start_idx + 256;
-
- prompt = system_prefix("<|im_start|>user\nDescribe the image by detailing the color, quantity, text, shape, size, texture, spatial relationships of the objects and background:");
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += " " + conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
-
- prompt += "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n";
- } else if (sd_version_is_pid(version)) {
- prompt = system_prefix("");
- constexpr int pixeldit_max_length = 300;
- const std::string chi_prompt =
- "Given a user prompt, generate an \"Enhanced prompt\" that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:\n"
- "- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.\n"
- "- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.\n"
- "Here are examples of how to transform or refine prompts:\n"
- "- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.\n"
- "- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.\n"
- "Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:\n"
- "User Prompt: ";
- auto chi_tokens = conditioner_params.raw ? std::vector<int>{} : std::get<0>(tokenize(chi_prompt, {0, 0}));
- if (!conditioner_params.raw && chi_tokens.empty()) {
- return {};
- }
- size_t num_chi_tokens = chi_tokens.size();
- max_length = conditioner_params.raw ? pixeldit_max_length : (int)num_chi_tokens + pixeldit_max_length - 2;
- min_length = max_length;
-
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += " " + conditioner_params.text;
- if (conditioner_params.raw)
- prompt = conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
- if (conditioner_params.raw)
- prompt_attn_range = {0, 0};
-
- auto hidden_states = encode_prompt(n_threads,
- prompt,
- prompt_attn_range,
- min_length,
- 0,
- image_embeds,
- out_layers,
- 0,
- false,
- max_length);
- if (hidden_states.empty()) {
- return {};
- }
-
- if (hidden_states.shape()[1] > pixeldit_max_length) {
- auto bos = sd::ops::slice(hidden_states, 1, 0, 1);
- auto tail = sd::ops::slice(hidden_states,
- 1,
- hidden_states.shape()[1] - (pixeldit_max_length - 1),
- hidden_states.shape()[1]);
- hidden_states = sd::ops::concat(bos, tail, 1);
- }
-
- int64_t t1 = ggml_time_ms();
- LOG_INFO("computing condition graph completed, taking %" PRId64 " ms", t1 - t0);
-
- SDCondition result;
- result.c_crossattn = std::move(hidden_states);
- return result;
- } else if (version == VERSION_IRIS) {
- dynamic_template_crop = true;
- prompt =
- system_prefix(
- "<|im_start|>system\n"
- "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial "
- "relationships of the objects and background:<|im_end|>\n<|im_start|>user\n");
- auto prefix_tokens = conditioner_params.raw ? std::vector<int>{} : std::get<0>(tokenize(prompt, {0, 0}));
- if (!conditioner_params.raw && prefix_tokens.empty()) {
- return {};
- }
- prompt_template_encode_start_idx = static_cast<int>(prefix_tokens.size());
- hidden_states_min_length = 300;
- max_length = prompt_template_encode_start_idx + hidden_states_min_length;
- out_layers = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35};
- prompt_attn_range.first = static_cast<int>(prompt.size());
- prompt += conditioner_params.text;
- prompt_attn_range.second = static_cast<int>(prompt.size());
- prompt_suffix = "<|im_end|>\n<|im_start|>assistant\n";
- } else {
- GGML_ABORT("unknown version %d", version);
- }
-
- if (conditioner_params.raw) {
- prompt = conditioner_params.text;
- prompt_suffix.clear();
- prompt_attn_range = {0, 0};
- spell_quotes = false;
- if (min_length > 0)
- min_length = std::max(0, min_length - prompt_template_encode_start_idx);
- if (max_length_includes_template)
- max_length -= prompt_template_encode_start_idx;
- prompt_template_encode_start_idx = 0;
- } else if (conditioner_params.system_prompt && !dynamic_template_crop && prompt_template_encode_start_idx > 0) {
- prompt_template_encode_start_idx += template_token_delta;
- if (min_length > 0)
- min_length += template_token_delta;
- if (max_length_includes_template)
- max_length += template_token_delta;
- }
-
- LLM::PromptTokens prompt_tokens;
- auto hidden_states = encode_prompt(n_threads,
- prompt,
- prompt_attn_range,
- min_length,
- hidden_states_min_length,
- image_embeds,
- out_layers,
- prompt_template_encode_start_idx,
- spell_quotes,
- max_length,
- deepstack_image_embeds,
- image_grids,
- prompt_suffix,
- version == VERSION_IRIS ? &text_mask : nullptr,
- conditioner_params.prompt_input == nullptr ? nullptr : &input_template,
- &prompt_tokens);
- if (hidden_states.empty()) {
- return {};
- }
- std::vector<sd::Tensor<float>> extra_hidden_states_vec;
- if (sd_version_is_hunyuan_video(version) && byt5) {
- std::vector<std::string> quoted_texts;
- auto collect_quoted = [&](const std::string& open, const std::string& close) {
- size_t begin = 0;
- while ((begin = conditioner_params.text.find(open, begin)) != std::string::npos) {
- size_t content_begin = begin + open.size();
- size_t end = conditioner_params.text.find(close, content_begin);
- if (end == std::string::npos) {
- break;
- }
- quoted_texts.push_back(conditioner_params.text.substr(content_begin, end - content_begin));
- begin = end + close.size();
- }
- };
- collect_quoted("\"", "\"");
- collect_quoted("\xE2\x80\x98", "\xE2\x80\x99");
- collect_quoted("\xE2\x80\x9C", "\xE2\x80\x9D");
-
- if (!quoted_texts.empty()) {
- std::string byt5_text;
- for (const auto& text : quoted_texts) {
- byt5_text += "Text \"" + text + "\". ";
- }
- std::vector<int> tokens;
- tokens.reserve(byt5_text.size() + 1);
- for (unsigned char byte : byt5_text) {
- tokens.push_back(static_cast<int>(byte) + 3);
- }
- tokens.push_back(1);
- sd::Tensor<int32_t> input_ids({static_cast<int64_t>(tokens.size())}, tokens);
- auto byt5_hidden_states = byt5->compute(n_threads,
- input_ids,
- sd::Tensor<float>(),
- false);
- if (byt5_hidden_states.empty())
- return {};
- extra_hidden_states_vec.push_back(std::move(byt5_hidden_states));
- }
- }
- for (int i = 0; i < extra_prompts.size(); i++) {
- auto extra_hidden_states = encode_prompt(n_threads,
- extra_prompts[i],
- extra_prompts_attn_range[i],
- min_length,
- hidden_states_min_length,
- image_embeds,
- out_layers,
- prompt_template_encode_start_idx,
- spell_quotes,
- max_length);
- if (extra_hidden_states.empty()) {
- return {};
- }
- extra_hidden_states_vec.push_back(std::move(extra_hidden_states));
- }
-
- int64_t t1 = ggml_time_ms();
- LOG_INFO("computing condition graph completed, taking %" PRId64 " ms", t1 - t0);
- SDCondition result;
- result.c_crossattn = std::move(hidden_states);
- result.extra_c_crossattns = std::move(extra_hidden_states_vec);
- result.c_vector = std::move(text_mask);
- if (version == VERSION_QWEN_IMAGE_2_1) {
- auto slots = sd::Tensor<int32_t>::zeros({result.c_crossattn.shape()[1]});
- const auto& references = params.prompt_input == nullptr ? image_embeds : prompt_tokens.image_embeds;
- for (size_t i = 0; i < references.size(); ++i) {
- int64_t begin = references[i].first - prompt_template_encode_start_idx;
- int64_t end = begin + references[i].second.shape()[1];
- if (begin < 0 || end > slots.numel()) {
- LOG_ERROR("Qwen Image 2.1 image slots exceed the encoded prompt");
- return {};
- }
- for (int64_t j = begin; j < end; ++j) {
- slots[j] = static_cast<int32_t>(i + 1);
- }
- }
- result.c_token_types = std::move(slots);
- }
- if (sd_version_is_minimax_h3(version)) {
- std::vector<int32_t> tags(static_cast<size_t>(result.c_crossattn.shape()[1]), 1);
- const auto& images = params.prompt_input == nullptr ? image_embeds : prompt_tokens.image_embeds;
- for (const auto& [index, image_embed] : images) {
- int64_t begin = std::max<int64_t>(0, index - 1);
- int64_t end = std::min<int64_t>(static_cast<int64_t>(tags.size()),
- index + image_embed.shape()[1] + 1);
- std::fill(tags.begin() + begin, tags.begin() + end, 0);
- }
- int64_t tag_count = static_cast<int64_t>(tags.size());
- result.c_token_types = sd::Tensor<int32_t>({tag_count}, std::move(tags));
- }
-
- return result;
- }
-};
-
struct MingImageEmbedder : public Conditioner {
bool supports_prompt_formatting() const override { return true; }
@@ -4029,7 +2355,7 @@ struct LTXAVEmbedder : public Conditioner {
false);
if (hidden_states.empty())
return {};
- hidden_states = apply_token_weights(std::move(hidden_states), weights);
+ hidden_states = sd::apply_token_weights(std::move(hidden_states), weights);
int64_t valid_tokens = 0;
for (float value : mask) {
diff --git a/src/conditioning/conditioning_cache.h b/src/conditioning/conditioning_cache.h
index b07e768..5345877 100644
--- a/src/conditioning/conditioning_cache.h
+++ b/src/conditioning/conditioning_cache.h
@@ -5,7 +5,9 @@
#include <list>
#include <tuple>
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
+#include "conditioning/textual_inversion.h"
+#include "core/util.h"
class ConditioningCache {
struct Entry {
diff --git a/src/conditioning/fibo2.hpp b/src/conditioning/fibo2.hpp
deleted file mode 100644
index 1c73008..0000000
--- a/src/conditioning/fibo2.hpp
+++ /dev/null
@@ -1,185 +0,0 @@
-#ifndef __SD_CONDITIONING_FIBO2_HPP__
-#define __SD_CONDITIONING_FIBO2_HPP__
-
-#include "conditioning/conditioner.hpp"
-
-struct Fibo2Conditioner : public LLMEmbedder {
- size_t max_reference_images() const override { return std::numeric_limits<size_t>::max(); }
- using JSON = nlohmann::ordered_json;
-
- Fibo2Conditioner(ggml_backend_t backend, const String2TensorStorage& weights, std::shared_ptr<RunnerWeightManager> weight_manager, const TokenizerConfig& tokenizers)
- : LLMEmbedder(backend, weights, VERSION_FIBO2, "", true, weight_manager, tokenizers) {
- if (llm->config.hidden_size != 2560 || llm->config.num_layers != 36) {
- throw std::runtime_error("Fibo 2.0 requires its Qwen3-VL-4B text encoder");
- }
- }
-
- static bool empty_value(const JSON& value) {
- return value.is_null() ||
- (value.is_string() && value.get_ref<const std::string&>().empty()) ||
- ((value.is_array() || value.is_object()) && value.empty());
- }
-
- static JSON clean_caption(const JSON& value) {
- if (value.is_object()) {
- auto result = JSON::object();
- for (auto it = value.begin(); it != value.end(); ++it) {
- auto cleaned = clean_caption(it.value());
- if (!empty_value(cleaned)) {
- result[it.key()] = std::move(cleaned);
- }
- }
- return result;
- }
- if (value.is_array()) {
- auto result = JSON::array();
- for (const auto& item : value) {
- auto cleaned = clean_caption(item);
- if (!empty_value(cleaned)) {
- result.push_back(std::move(cleaned));
- }
- }
- return result;
- }
- return value;
- }
-
- static std::pair<JSON, JSON> parse_prompt(const std::string& prompt) {
- auto caption = JSON::parse(prompt, nullptr, false);
- if (!caption.is_object()) {
- return {prompt, nullptr};
- }
- JSON instruction;
- if (caption.contains("edit_instruction")) {
- instruction = caption["edit_instruction"];
- caption.erase("edit_instruction");
- }
- if (caption.contains("structured_caption")) {
- caption = JSON(caption["structured_caption"]);
- if (!caption.is_object()) {
- return {caption, instruction};
- }
- }
- bool short_form = caption.size() == 2 && caption.contains("short_description") && caption.contains("text_render");
- caption = clean_caption(caption);
- for (const char* score : {"aesthetic_score", "preference_score"}) {
- caption.erase(score);
- for (auto& value : caption) {
- if (value.is_object()) {
- value.erase(score);
- }
- }
- }
- caption = clean_caption(caption);
- if (short_form) {
- caption = JSON{{"short_description", caption.value("short_description", JSON(""))},
- {"text_render", caption.value("text_render", JSON::array())}};
- }
- return {caption, instruction};
- }
-
- static std::string format_prompt(const std::string& text, int num_images) {
- auto [caption, instruction] = parse_prompt(text);
- if (num_images > 0) {
- if (instruction.is_null()) {
- caption = nullptr;
- instruction = text;
- }
- auto edit = JSON::object();
- for (int i = 0; i < num_images; ++i) {
- edit[num_images == 1 ? "image" : "image_" + std::to_string(i + 1)] = "<|vision_start|><|image_pad|><|vision_end|>";
- }
- if (!empty_value(caption)) {
- edit["structured_caption"] = caption;
- }
- edit["edit_instruction"] = instruction;
- return edit.dump();
- }
- if (text.empty()) {
- return R"({"short_description":"","objects":[],"background_setting":"","lighting":{},"aesthetics":{},"photographic_characteristics":{},"style_medium":"","context":"","artistic_style":""})";
- }
- if (caption.is_string()) {
- return caption.get<std::string>();
- }
- return empty_value(caption) ? "{}" : caption.dump();
- }
-
- static sd::Tensor<float> make_bundles(sd::Tensor<float> states, const std::set<int>& layers) {
- constexpr int width = 2560;
- constexpr int bundles[6][3] = {{9, 20, 31}, {5, 16, 27}, {7, 18, 29}, {9, 20, 31}, {11, 22, 33}, {13, 24, 35}};
- for (int64_t token = 0; token < states.shape()[1]; ++token) {
- for (size_t layer = 0; layer < layers.size(); ++layer) {
- float sum = 0.f;
- int64_t offset = token * states.shape()[0] + layer * width;
- for (int i = 0; i < width; ++i) {
- sum += states[offset + i] * states[offset + i];
- }
- float scale = 1.f / std::sqrt(sum / width + 1e-6f);
- for (int i = 0; i < width; ++i) {
- states[offset + i] *= scale;
- }
- }
- }
- sd::Tensor<float> result({6 * 3 * width, states.shape()[1]});
- for (int b = 0; b < 6; ++b) {
- for (int j = 0; j < 3; ++j) {
- int index = static_cast<int>(std::distance(layers.begin(), layers.find(bundles[b][j])));
- for (int64_t token = 0; token < states.shape()[1]; ++token) {
- std::copy_n(states.data() + token * states.shape()[0] + index * width, width,
- result.data() + token * result.shape()[0] + (b * 3 + j) * width);
- }
- }
- }
- return result;
- }
-
- SDCondition get_learned_condition(int n_threads, const ConditionerParams& params) override {
- auto p = params;
- sd::PromptInputTemplate input_template(p.prompt_input);
- if (p.prompt_input != nullptr) {
- p.text = input_template.text;
- }
- int image_count = p.ref_images ? static_cast<int>(p.ref_images->size()) : 0;
- if (image_count && !llm->enable_vision) {
- LOG_ERROR("Fibo 2.0 editing requires vision weights");
- return {};
- }
- std::string prompt = p.raw ? p.text : sd::prompt_templates::with_system("<|im_start|>user\n", p.system_prompt) + format_prompt(p.text, image_count) + "<|im_end|>\n<|im_start|>assistant\n";
- std::vector<std::pair<int, sd::Tensor<float>>> images;
- LLM::DeepStackImageEmbeds deepstack;
- std::vector<LLM::ImageGrid> grids;
- size_t marker_start = 0;
- for (int i = 0; i < image_count; ++i) {
- const auto& image = (*p.ref_images)[i];
- int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
- int height = static_cast<int>(image.shape()[1]), width = static_cast<int>(image.shape()[0]);
- int h = std::max(factor, static_cast<int>(std::round(static_cast<double>(height) / factor)) * factor);
- int w = std::max(factor, static_cast<int>(std::round(static_cast<double>(width) / factor)) * factor);
- auto pixels = sd::ops::interpolate(image, {w, h, image.shape()[2], image.shape()[3]}, sd::ops::InterpolateMode::Bicubic, false, true);
- auto rgb = sd::Tensor<float>({w, h, 3, 1});
- for (int64_t pixel = 0; pixel < int64_t(w) * h; ++pixel) {
- float alpha = pixels.shape()[2] == 4 ? pixels[pixel + 3 * w * h] : 1.f;
- for (int channel = 0; channel < 3; ++channel) {
- rgb[pixel + channel * w * h] = 2.f * std::clamp(pixels[pixel + channel * w * h] * alpha + 1.f - alpha, 0.f, 1.f) - 1.f;
- }
- }
- auto outputs = llm->encode_image_outputs(n_threads, rgb, false);
- if (!expand_vision_marker(prompt, marker_start, std::move(outputs),
- h / llm->config.vision.patch_size, w / llm->config.vision.patch_size,
- images, deepstack, grids, 4096)) {
- return {};
- }
- }
- const std::set<int> layers = {5, 7, 9, 11, 13, 16, 18, 20, 22, 24, 27, 29, 31, 33, 35};
- auto states = encode_prompt(n_threads, prompt, {0, 0}, 0, 0, images, layers, 0, false, 4096, deepstack, grids,
- "", nullptr, p.prompt_input == nullptr ? nullptr : &input_template);
- if (states.empty()) {
- return {};
- }
- SDCondition result;
- result.c_crossattn = make_bundles(std::move(states), layers);
- return result;
- }
-};
-
-#endif // __SD_CONDITIONING_FIBO2_HPP__
diff --git a/src/conditioning/llm_conditioner.cpp b/src/conditioning/llm_conditioner.cpp
new file mode 100644
index 0000000..a822d35
--- /dev/null
+++ b/src/conditioning/llm_conditioner.cpp
@@ -0,0 +1,1748 @@
+#include "conditioning/llm_conditioner.h"
+
+#include <algorithm>
+#include <cinttypes>
+#include <cmath>
+#include <iomanip>
+#include <iterator>
+#include <limits>
+#include <regex>
+#include <set>
+#include <sstream>
+#include <stdexcept>
+#include <tuple>
+#include <utility>
+
+#include "conditioning/conditioner.h"
+#include "conditioning/prompt_templates.h"
+#include "core/image_geometry.h"
+#include "core/image_tensor.h"
+#include "core/util.h"
+#include "json.hpp"
+#include "model/te/clipproj_connector.hpp"
+#include "model/te/llm.hpp"
+#include "model/te/ph3_image_connector.hpp"
+#include "model/te/t5.hpp"
+#include "tokenizers/mistral_tokenizer.h"
+#include "tokenizers/qwen2_tokenizer.h"
+#include "tokenizers/tokenizer_config.h"
+
+struct LLMEmbedder : public Conditioner {
+ bool supports_prompt_formatting() const override { return true; }
+
+ SDVersion version;
+ std::shared_ptr<Tokenizer> tokenizer;
+ std::shared_ptr<LLM::LLMRunner> llm;
+ std::shared_ptr<T5Runner> byt5;
+ std::shared_ptr<PH3ImageTextConnectorRunner> ph3_connector;
+ std::shared_ptr<ClipProjConnectorRunner> clipproj_connector;
+
+ bool supports_prompt_images() const override {
+ return llm->supports_prompt_images();
+ }
+
+ size_t max_reference_images() const override {
+ if (!llm->enable_vision)
+ 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) ||
+ version == VERSION_MOSS_IMAGE
+ ? std::numeric_limits<size_t>::max()
+ : 0;
+ }
+
+ bool supports_multimodal_prompt() const override {
+ return llm->enable_vision && sd_version_is_minimax_h3(version) &&
+ version != VERSION_MINIMAX_H3_IMAGE && version != VERSION_P_H3_IMAGE;
+ }
+
+ LLMEmbedder(ggml_backend_t backend,
+ const String2TensorStorage& tensor_storage_map,
+ SDVersion version,
+ bool enable_vision,
+ std::shared_ptr<RunnerWeightManager> weight_manager,
+ const TokenizerConfig& tokenizers)
+ : version(version) {
+ if (!tokenizers.has(TokenizerConfig::MAIN)) {
+ if (sd_version_is_lens(version)) {
+ throw std::runtime_error("Lens requires an external GPT-OSS tokenizer.json; pass --tokenizer FILE or set the tokenizer context option");
+ }
+ if (sd_version_is_pid(version)) {
+ throw std::runtime_error("PiD requires an external Gemma 2 tokenizer.json; pass --tokenizer FILE or set the tokenizer context option");
+ }
+ if (version == VERSION_MOSS_IMAGE) {
+ throw std::runtime_error("MOSS-Image requires the official Qwen3.5 tokenizer.json; pass --tokenizer FILE or set the tokenizer context option");
+ }
+ }
+ LLM::LLMArch arch = LLM::LLMArch::QWEN2_5_VL;
+ if (version == VERSION_FLUX2) {
+ arch = LLM::LLMArch::MISTRAL_SMALL_3_2;
+ } else if (sd_version_is_ernie_image(version)) {
+ arch = LLM::LLMArch::MINISTRAL_3_3B;
+ } else if (sd_version_is_lens(version)) {
+ arch = LLM::LLMArch::GPT_OSS_20B;
+ } else if (sd_version_is_pid(version)) {
+ arch = LLM::LLMArch::GEMMA2_2B;
+ } else if (version == VERSION_FIBO2 ||
+ version == VERSION_QWEN_IMAGE_2_1 ||
+ sd_version_is_flux3(version) ||
+ sd_version_is_lingbot_video(version) ||
+ sd_version_is_ideogram4(version) ||
+ sd_version_is_boogu_image(version) ||
+ sd_version_is_sefi_image(version) ||
+ sd_version_is_krea2(version) ||
+ sd_version_is_minimax_h3(version) ||
+ sd_version_is_mage_flow(version) ||
+ version == VERSION_IRIS) {
+ arch = LLM::LLMArch::QWEN3_VL;
+ } else if (sd_version_is_z_image(version) || sd_version_is_z_image_l2p(version) || version == VERSION_OVIS_IMAGE || version == VERSION_FLUX2_KLEIN) {
+ arch = LLM::LLMArch::QWEN3;
+ } else if (version == VERSION_MOSS_IMAGE) {
+ arch = LLM::LLMArch::QWEN3_5;
+ }
+ if (arch == LLM::LLMArch::QWEN2_5_VL || arch == LLM::LLMArch::QWEN3_VL || arch == LLM::LLMArch::QWEN3_5) {
+ for (const auto& entry : tensor_storage_map) {
+ if (starts_with(entry.first, "text_encoders.llm.visual.")) {
+ enable_vision = true;
+ break;
+ }
+ }
+ }
+ llm = std::make_shared<LLM::LLMRunner>(arch,
+ backend,
+ tensor_storage_map,
+ "text_encoders.llm",
+ enable_vision,
+ weight_manager);
+ if (sd_version_is_minimax_h3(version)) {
+ const bool has_ph3_connector = tensor_storage_map.count(std::string(PH3ImageTextConnectorRunner::prefix) + ".proj.weight") != 0;
+ const bool has_clipproj_connector = tensor_storage_map.count(std::string(ClipProjConnectorRunner::prefix) + ".mean_in") != 0;
+ if (has_ph3_connector) {
+ if (llm->config.num_layers != 36 || llm->config.hidden_size != 2560) {
+ throw std::runtime_error("The P-H3-Image text connector requires the Qwen3-VL-4B text encoder");
+ }
+ ph3_connector = std::make_shared<PH3ImageTextConnectorRunner>(backend, tensor_storage_map, weight_manager);
+ } else if (has_clipproj_connector) {
+ clipproj_connector = std::make_shared<ClipProjConnectorRunner>(backend, llm->config.hidden_size, 5120, tensor_storage_map, weight_manager);
+ } else if (llm->config.hidden_size == 2560) {
+ throw std::runtime_error(
+ sd_format("%s with Qwen3-VL-4B requires a text connector; pass the P-H3-Image text connector "
+ "or a ClipProj projection with --embeddings-connectors, or use the MiniMax-H3 Qwen3-VL-32B text encoder",
+ sd_version_name(version)));
+ } else if (llm->config.hidden_size == 4096) {
+ throw std::runtime_error(
+ sd_format("%s with Qwen3-VL-8B requires a ClipProj text connector; "
+ "pass it with --embeddings-connectors or use the MiniMax-H3 Qwen3-VL-32B text encoder",
+ sd_version_name(version)));
+ } else if (llm->config.hidden_size != 5120 || (llm->config.num_layers != 50 && llm->config.num_layers != 64)) {
+ throw std::runtime_error(
+ sd_format("%s requires the MiniMax-H3 Qwen3-VL-32B text encoder or Qwen3-VL-4B with the P-H3-Image (or a ClipProj) text connector, or Qwen3-VL-8B with a ClipProj projection",
+ sd_version_name(version)));
+ }
+ }
+ int pad_id = 151643;
+ if (arch == LLM::LLMArch::MISTRAL_SMALL_3_2 || arch == LLM::LLMArch::MINISTRAL_3_3B) {
+ pad_id = 11;
+ } else if (arch == LLM::LLMArch::GPT_OSS_20B) {
+ pad_id = 199999;
+ } else if (arch == LLM::LLMArch::GEMMA2_2B) {
+ pad_id = 0;
+ } else if (arch == LLM::LLMArch::QWEN3_5) {
+ pad_id = 248044;
+ }
+ tokenizer = tokenizers.create(TokenizerConfig::MAIN, llm->config.vocab_size, pad_id);
+ if (!tokenizer) {
+ if (arch == LLM::LLMArch::MISTRAL_SMALL_3_2 || arch == LLM::LLMArch::MINISTRAL_3_3B) {
+ tokenizer = std::make_shared<MistralTokenizer>();
+ } else {
+ tokenizer = std::make_shared<Qwen2Tokenizer>();
+ }
+ }
+ if (sd_version_is_hunyuan_video(version)) {
+ const std::string byt5_prefix = "text_encoders.t5xxl.transformer";
+ for (const auto& [name, _] : tensor_storage_map) {
+ if (starts_with(name, byt5_prefix + ".")) {
+ byt5 = std::make_shared<T5Runner>(backend,
+ tensor_storage_map,
+ byt5_prefix,
+ false,
+ weight_manager);
+ break;
+ }
+ }
+ }
+ }
+
+ void get_param_tensors(std::map<std::string, ggml_tensor*>& tensors) override {
+ llm->get_param_tensors(tensors, "text_encoders.llm");
+ if (ph3_connector) {
+ ph3_connector->get_param_tensors(tensors);
+ }
+ if (clipproj_connector) {
+ clipproj_connector->get_param_tensors(tensors);
+ }
+ if (byt5) {
+ byt5->get_param_tensors(tensors, "text_encoders.t5xxl.transformer");
+ }
+ }
+
+ void get_param_tensor_ops(std::map<ggml_tensor*, enum ggml_op>& tensor_ops) override {
+ llm->get_param_tensor_ops(tensor_ops);
+ }
+
+ void set_max_graph_vram_bytes(size_t max_vram_bytes) override {
+ llm->set_max_graph_vram_bytes(max_vram_bytes);
+ if (ph3_connector) {
+ ph3_connector->set_max_graph_vram_bytes(max_vram_bytes);
+ }
+ if (clipproj_connector) {
+ clipproj_connector->set_max_graph_vram_bytes(max_vram_bytes);
+ }
+ if (byt5) {
+ byt5->set_max_graph_vram_bytes(max_vram_bytes);
+ }
+ }
+
+ void set_runtime_backends(const std::vector<ggml_backend_t>& backends) override {
+ llm->set_runtime_backends(backends);
+ if (ph3_connector) {
+ ph3_connector->set_runtime_backends(backends);
+ }
+ if (clipproj_connector) {
+ clipproj_connector->set_runtime_backends(backends);
+ }
+ if (byt5) {
+ byt5->set_runtime_backends(backends);
+ }
+ }
+
+ void set_graph_cut_layer_split_enabled(bool enabled) override {
+ if (llm) {
+ llm->set_graph_cut_layer_split_enabled(enabled);
+ }
+ if (byt5) {
+ byt5->set_graph_cut_layer_split_enabled(enabled);
+ }
+ }
+
+ void set_graph_cut_layer_split_backend_vram_limits(const std::vector<size_t>& limits) override {
+ if (llm) {
+ llm->set_graph_cut_layer_split_backend_vram_limits(limits);
+ }
+ if (byt5) {
+ byt5->set_graph_cut_layer_split_backend_vram_limits(limits);
+ }
+ }
+
+ void get_layer_split_param_tensors(std::map<std::string, ggml_tensor*>& tensors) override {
+ llm->get_param_tensors(tensors, "text_encoders.llm");
+ if (byt5) {
+ byt5->get_param_tensors(tensors, "text_encoders.t5xxl.transformer");
+ }
+ }
+
+ void for_each_runner(const std::function<void(GGMLRunner&)>& visit) override {
+ visit(*llm);
+ if (ph3_connector) {
+ visit(*ph3_connector);
+ }
+ if (clipproj_connector) {
+ visit(*clipproj_connector);
+ }
+ if (byt5) {
+ visit(*byt5);
+ }
+ }
+
+ void set_scale_overrides(float linear_scale, float attn_scale) override {
+ llm->set_scale_overrides(linear_scale, attn_scale);
+ if (ph3_connector) {
+ ph3_connector->set_scale_overrides(linear_scale, attn_scale);
+ }
+ if (clipproj_connector) {
+ clipproj_connector->set_scale_overrides(linear_scale, attn_scale);
+ }
+ if (byt5) {
+ byt5->set_scale_overrides(linear_scale, attn_scale);
+ }
+ }
+
+ void set_weight_adapter(const std::shared_ptr<WeightAdapter>& adapter) override {
+ if (ph3_connector) {
+ ph3_connector->set_weight_adapter(adapter);
+ }
+ if (clipproj_connector) {
+ clipproj_connector->set_weight_adapter(adapter);
+ }
+ if (llm) {
+ llm->set_weight_adapter(adapter);
+ }
+ if (byt5) {
+ byt5->set_weight_adapter(adapter);
+ }
+ }
+
+ void runner_end() override {
+ if (ph3_connector) {
+ ph3_connector->runner_end();
+ }
+ if (clipproj_connector) {
+ clipproj_connector->runner_end();
+ }
+ if (llm) {
+ llm->runner_end();
+ }
+ if (byt5) {
+ byt5->runner_end();
+ }
+ }
+
+ static std::vector<std::pair<std::string, float>> parse_text_attention(const std::string& text,
+ const std::pair<int, int>& attn_range,
+ bool spell_quotes) {
+ std::vector<std::pair<std::string, float>> parsed_attention;
+ if (attn_range.first >= 0 && attn_range.second > 0) {
+ if (attn_range.first > 0) {
+ parsed_attention.emplace_back(text.substr(0, attn_range.first), 1.f);
+ }
+ if (attn_range.second - attn_range.first > 0) {
+ auto new_parsed_attention = parse_prompt_attention(text.substr(attn_range.first, attn_range.second - attn_range.first));
+ if (spell_quotes) {
+ new_parsed_attention = split_quotation_attention(new_parsed_attention);
+ }
+ parsed_attention.insert(parsed_attention.end(),
+ new_parsed_attention.begin(),
+ new_parsed_attention.end());
+ }
+ if (attn_range.second < text.size()) {
+ parsed_attention.emplace_back(text.substr(attn_range.second), 1.f);
+ }
+ } else {
+ parsed_attention.emplace_back(text, 1.f);
+ }
+
+ return parsed_attention;
+ }
+
+ std::tuple<std::vector<int>, std::vector<float>, std::vector<float>> tokenize(std::string text,
+ const std::pair<int, int>& attn_range,
+ size_t min_length = 0,
+ size_t max_length = 100000000,
+ bool spell_quotes = false,
+ const std::string& suffix = "",
+ const std::vector<std::pair<int, sd::Tensor<float>>>& image_embeds = {}) {
+ auto parsed_attention = parse_text_attention(text, attn_range, spell_quotes);
+
+ {
+ std::stringstream ss;
+ ss << "[";
+ for (const auto& item : parsed_attention) {
+ ss << "['" << item.first << "', " << item.second << "], ";
+ }
+ ss << "]";
+ LOG_VERBOSE("parse '%s' to %s", escape_newlines(text).c_str(), escape_newlines(ss.str()).c_str());
+ }
+
+ std::vector<int> tokens;
+ std::vector<float> weights;
+ for (const auto& item : parsed_attention) {
+ const std::string& curr_text = item.first;
+ float curr_weight = item.second;
+ std::vector<int> curr_tokens;
+ if (!tokenizer->encode(curr_text, curr_tokens, nullptr)) {
+ return {};
+ }
+ tokens.insert(tokens.end(), curr_tokens.begin(), curr_tokens.end());
+ weights.insert(weights.end(), curr_tokens.size(), curr_weight);
+ }
+
+ for (const auto& image_embed : image_embeds) {
+ const int index = image_embed.first;
+ const int64_t count = image_embed.second.shape()[1];
+ if (index < 0 || static_cast<size_t>(index) >= tokens.size() || count < 1) {
+ LOG_ERROR("Invalid reference image token range");
+ return {};
+ }
+ const int token = tokens[index];
+ const float weight = weights[index];
+ tokens.insert(tokens.begin() + index, count - 1, token);
+ weights.insert(weights.begin() + index, count - 1, weight);
+ }
+
+ if (!suffix.empty()) {
+ std::vector<int> suffix_tokens;
+ if (!tokenizer->encode(suffix, suffix_tokens) || suffix_tokens.size() >= max_length) {
+ return {};
+ }
+ // Reserve the assistant-turn marker before truncating the caption.
+ if (tokens.size() > max_length - suffix_tokens.size()) {
+ tokens.resize(max_length - suffix_tokens.size());
+ weights.resize(tokens.size());
+ }
+ tokens.insert(tokens.end(), suffix_tokens.begin(), suffix_tokens.end());
+ weights.insert(weights.end(), suffix_tokens.size(), 1.f);
+ }
+
+ if (sd_version_is_flux3(version)) {
+ min_length = std::min(max_length, ((tokens.size() + 79) / 80) * 80);
+ }
+ std::vector<float> mask;
+ tokenizer->pad_tokens(tokens, &weights, &mask, min_length, max_length);
+
+ // Keep masks and weights in expanded coordinates, but only look up one token per image.
+ for (auto it = image_embeds.rbegin(); it != image_embeds.rend(); ++it) {
+ const int64_t begin = it->first;
+ const int64_t end = begin + it->second.shape()[1];
+ if (begin < 0 || end > static_cast<int64_t>(tokens.size())) {
+ LOG_ERROR("Reference image exceeds the tokenized context");
+ return {};
+ }
+ tokens.erase(tokens.begin() + begin + 1, tokens.begin() + end);
+ }
+
+ // for (int i = 0; i < tokens.size(); i++) {
+ // std::cout << tokens[i] << ":" << weights[i] << ", " << i << std::endl;
+ // }
+ // std::cout << std::endl;
+
+ return {tokens, weights, mask};
+ }
+
+ bool prepare_prompt_tokens(int n_threads,
+ const sd::PromptInputTemplate& input_template,
+ const std::string& prompt,
+ const std::pair<int, int>& attn_range,
+ int min_length,
+ int max_length,
+ bool spell_quotes,
+ const std::string& suffix,
+ const LLM::ImageEmbeds& images,
+ const LLM::DeepStackImageEmbeds& deepstack,
+ const std::vector<LLM::ImageGrid>& grids,
+ LLM::PromptTokens& result) {
+ sd::PromptInput input;
+ auto text = parse_text_attention(prompt, attn_range, spell_quotes);
+ text.emplace_back(suffix, 1.f);
+ for (const auto& span : text) {
+ auto parts = input_template.expand(span.first, span.second);
+ input.insert(input.end(), std::make_move_iterator(parts.begin()), std::make_move_iterator(parts.end()));
+ }
+ max_length = std::min(max_length, static_cast<int>(llm->config.max_position_embeddings));
+ if (!llm->prepare_prompt(n_threads, *tokenizer, input, max_length, result, images, deepstack, grids)) {
+ return false;
+ }
+ auto expanded = result.tokens;
+ for (const auto& image : result.image_embeds) {
+ expanded.insert(expanded.begin() + image.first, image.second.shape()[1] - 1, expanded[image.first]);
+ }
+ if (sd_version_is_flux3(version)) {
+ min_length = std::min(max_length, ((result.expanded_length + 79) / 80) * 80);
+ }
+ tokenizer->pad_tokens(expanded, &result.weights, &result.mask, min_length, max_length);
+ const int leading_padding = static_cast<int>(std::find(result.mask.begin(), result.mask.end(), 1.f) - result.mask.begin());
+ for (auto& image : result.image_embeds) {
+ image.first += leading_padding;
+ }
+ for (auto& layer : result.deepstack_image_embeds) {
+ for (auto& image : layer) {
+ image.first += leading_padding;
+ }
+ }
+ for (auto& grid : result.image_grids) {
+ grid.index += leading_padding;
+ }
+ for (auto it = result.image_embeds.rbegin(); it != result.image_embeds.rend(); ++it) {
+ expanded.erase(expanded.begin() + it->first + 1, expanded.begin() + it->first + it->second.shape()[1]);
+ }
+ result.tokens = std::move(expanded);
+ result.expanded_length = static_cast<int>(result.weights.size());
+ return true;
+ }
+
+ sd::Tensor<float> encode_prompt(int n_threads,
+ const std::string prompt,
+ const std::pair<int, int>& prompt_attn_range,
+ int min_length,
+ int hidden_states_min_length,
+ const std::vector<std::pair<int, sd::Tensor<float>>>& image_embeds,
+ const std::set<int>& out_layers,
+ int prompt_template_encode_start_idx,
+ bool spell_quotes = false,
+ int max_length = 100000000,
+ const LLM::DeepStackImageEmbeds& deepstack_image_embeds = {},
+ const std::vector<LLM::ImageGrid>& image_grids = {},
+ const std::string& prompt_suffix = "",
+ sd::Tensor<float>* output_mask = nullptr,
+ const sd::PromptInputTemplate* input_template = nullptr,
+ LLM::PromptTokens* output_prompt_tokens = nullptr) {
+ LLM::PromptTokens prepared;
+ if (input_template != nullptr &&
+ !prepare_prompt_tokens(n_threads, *input_template, prompt, prompt_attn_range, min_length, max_length,
+ spell_quotes, prompt_suffix, image_embeds, deepstack_image_embeds, image_grids, prepared)) {
+ return {};
+ }
+ auto tokens_weights_mask = input_template == nullptr
+ ? tokenize(prompt, prompt_attn_range, min_length, max_length, spell_quotes, prompt_suffix, image_embeds)
+ : std::make_tuple(prepared.tokens, prepared.weights, prepared.mask);
+ auto& tokens = std::get<0>(tokens_weights_mask);
+ auto& weights = std::get<1>(tokens_weights_mask);
+ auto& mask = std::get<2>(tokens_weights_mask);
+
+ if (tokens.empty()) {
+ return {};
+ }
+ if (prompt_template_encode_start_idx < 0 || static_cast<size_t>(prompt_template_encode_start_idx) >= weights.size()) {
+ LOG_ERROR("Prompt template exceeds the text encoder context; shorten system or prompt");
+ return {};
+ }
+
+ sd::Tensor<int32_t> input_ids({static_cast<int64_t>(tokens.size())}, tokens);
+ sd::Tensor<float> attention_mask;
+ if (!mask.empty()) {
+ attention_mask = sd::Tensor<float>({static_cast<int64_t>(mask.size()), static_cast<int64_t>(mask.size())});
+ const float masked_attention_value = -std::numeric_limits<float>::max() / 4.0f;
+ for (size_t i1 = 0; i1 < mask.size(); ++i1) {
+ for (size_t i0 = 0; i0 < mask.size(); ++i0) {
+ float value = 0.0f;
+ if (mask[i0] == 0.0f) {
+ value += masked_attention_value;
+ }
+ if (i0 > i1) {
+ value += masked_attention_value;
+ }
+ attention_mask[static_cast<int64_t>(i0 + mask.size() * i1)] = value;
+ }
+ }
+ }
+
+ sd::Tensor<int32_t> position_ids;
+ if (sd_version_is_flux3(version)) {
+ position_ids = sd::Tensor<int32_t>::zeros({static_cast<int64_t>(weights.size() * 4)});
+ if (input_template != nullptr) {
+ position_ids.values() = LLM::LLMRunner::build_position_ids(llm->config, weights.size(), prepared.image_grids);
+ }
+ for (size_t axis = 0; axis < 4; ++axis) {
+ for (size_t i = 0; i < weights.size(); ++i) {
+ position_ids[axis * weights.size() + i] = mask[i] == 0.f ? 1 : (input_template == nullptr ? static_cast<int32_t>(i) : position_ids[axis * weights.size() + i]);
+ }
+ }
+ }
+ auto hidden_states = llm->compute(n_threads,
+ input_ids,
+ attention_mask,
+ input_template == nullptr ? image_embeds : prepared.image_embeds,
+ out_layers,
+ false,
+ false,
+ input_template == nullptr ? deepstack_image_embeds : prepared.deepstack_image_embeds,
+ input_template == nullptr ? image_grids : prepared.image_grids,
+ position_ids);
+ if (hidden_states.empty()) {
+ LOG_ERROR("LLM prompt encoding failed");
+ return {};
+ }
+ if (ph3_connector) {
+ hidden_states = ph3_connector->compute(n_threads, hidden_states);
+ if (hidden_states.empty()) {
+ return {};
+ }
+ } else if (clipproj_connector) {
+ hidden_states = clipproj_connector->compute(n_threads, hidden_states);
+ if (hidden_states.empty()) {
+ return {};
+ }
+ }
+ hidden_states = sd::apply_token_weights(std::move(hidden_states), weights);
+ GGML_ASSERT(hidden_states.shape()[1] > prompt_template_encode_start_idx);
+
+ int64_t zero_pad_len = 0;
+ if (hidden_states_min_length > 0) {
+ if (hidden_states.shape()[1] - prompt_template_encode_start_idx < hidden_states_min_length) {
+ zero_pad_len = hidden_states_min_length - hidden_states.shape()[1] + prompt_template_encode_start_idx;
+ }
+ }
+
+ sd::Tensor<float> new_hidden_states = sd::ops::slice(hidden_states,
+ 1,
+ prompt_template_encode_start_idx,
+ hidden_states.shape()[1]);
+ if (zero_pad_len > 0) {
+ auto pad_shape = new_hidden_states.shape();
+ pad_shape[1] = zero_pad_len;
+ new_hidden_states = sd::ops::concat(new_hidden_states,
+ sd::Tensor<float>::zeros(std::move(pad_shape)),
+ 1);
+ }
+
+ if (output_mask != nullptr) {
+ *output_mask = sd::Tensor<float>::zeros({new_hidden_states.shape()[1]});
+ for (size_t i = prompt_template_encode_start_idx; i < mask.size(); ++i) {
+ output_mask->data()[i - prompt_template_encode_start_idx] = mask[i];
+ }
+ }
+ if (output_prompt_tokens != nullptr && input_template != nullptr) {
+ *output_prompt_tokens = std::move(prepared);
+ }
+ return new_hidden_states;
+ }
+
+ static void fit_h3_vision_dims(int height, int width, int& h_bar, int& w_bar, int factor) {
+ const double area = static_cast<double>(h_bar) * w_bar;
+ if (area > 12845056) {
+ const double beta = std::sqrt(static_cast<double>(height) * width / 12845056);
+ h_bar = std::max(factor, static_cast<int>(std::floor(height / beta / factor)) * factor);
+ w_bar = std::max(factor, static_cast<int>(std::floor(width / beta / factor)) * factor);
+ } else if (area < 3136) {
+ const double beta = std::sqrt(3136.0 / (static_cast<double>(height) * width));
+ h_bar = static_cast<int>(std::ceil(height * beta / factor)) * factor;
+ w_bar = static_cast<int>(std::ceil(width * beta / factor)) * factor;
+ }
+ }
+
+ bool expand_vision_marker(const std::string& prompt,
+ size_t& marker_start,
+ std::vector<sd::Tensor<float>> outputs,
+ int grid_h,
+ int grid_w,
+ std::vector<std::pair<int, sd::Tensor<float>>>& image_embeds,
+ LLM::DeepStackImageEmbeds& deepstack_image_embeds,
+ std::vector<LLM::ImageGrid>& image_grids,
+ int max_length = std::numeric_limits<int>::max()) {
+ if (outputs.empty()) {
+ return false;
+ }
+ const std::string placeholder = "<|image_pad|>";
+ size_t position = prompt.find(placeholder, marker_start);
+ if (position == std::string::npos) {
+ LOG_ERROR("Reference image marker is missing");
+ return false;
+ }
+ std::vector<int> prefix_tokens;
+ if (!tokenizer->encode(prompt.substr(0, position), prefix_tokens, nullptr)) {
+ return false;
+ }
+ int index = static_cast<int>(prefix_tokens.size());
+ for (const auto& image_embed : image_embeds) {
+ index += static_cast<int>(image_embed.second.shape()[1]) - 1;
+ }
+ int count = static_cast<int>(outputs[0].shape()[1]);
+ if (index > max_length || count > max_length - index) {
+ LOG_ERROR("Reference images exceed the %d-token context", max_length);
+ return false;
+ }
+ if (deepstack_image_embeds.empty()) {
+ deepstack_image_embeds.resize(outputs.size() - 1);
+ }
+ GGML_ASSERT(deepstack_image_embeds.size() == outputs.size() - 1);
+ image_embeds.emplace_back(index, std::move(outputs[0]));
+ for (size_t layer = 1; layer < outputs.size(); ++layer) {
+ deepstack_image_embeds[layer - 1].emplace_back(index, std::move(outputs[layer]));
+ }
+ image_grids.push_back({index, count, grid_h, grid_w});
+ marker_start = position + placeholder.size();
+ return true;
+ }
+
+ SDCondition get_learned_condition(int n_threads,
+ const ConditionerParams& params) override {
+ ConditionerParams conditioner_params = params;
+ 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<int64_t>(32, std::llround(width * scale));
+ const auto h = std::max<int64_t>(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<sd::Tensor<float>>(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 {};
+ }
+ conditioner_params.text = input_template.text;
+ }
+ std::string prompt;
+ std::pair<int, int> prompt_attn_range;
+ std::vector<std::string> extra_prompts;
+ std::vector<std::pair<int, int>> extra_prompts_attn_range;
+ std::vector<std::pair<int, sd::Tensor<float>>> image_embeds;
+ LLM::DeepStackImageEmbeds deepstack_image_embeds;
+ std::vector<LLM::ImageGrid> image_grids;
+ int prompt_template_encode_start_idx = 34;
+ int min_length = 0; // pad tokens
+ int max_length = 100000000;
+ int hidden_states_min_length = 0; // zero pad hidden_states
+ bool spell_quotes = false;
+ std::set<int> out_layers;
+ std::string prompt_suffix;
+ sd::Tensor<float> text_mask;
+
+ int template_token_delta = 0;
+ bool dynamic_template_crop = false;
+ bool max_length_includes_template = false;
+ auto system_prefix = [&](const std::string& prefix) {
+ auto format = version == VERSION_FLUX2 ? sd::prompt_templates::RoleFormat::Mistral
+ : sd_version_is_lens(version) ? sd::prompt_templates::RoleFormat::GPTOSS
+ : sd_version_is_pid(version) ? sd::prompt_templates::RoleFormat::Gemma
+ : sd::prompt_templates::RoleFormat::ChatML;
+ auto result = sd::prompt_templates::with_system(prefix, conditioner_params.system_prompt, format);
+ if (result != prefix && !dynamic_template_crop) {
+ std::vector<int> before, after;
+ if ((!prefix.empty() && !tokenizer->encode(prefix, before)) ||
+ (!result.empty() && !tokenizer->encode(result, after)))
+ throw std::runtime_error("cannot tokenize prompt template");
+ template_token_delta += static_cast<int>(after.size()) - static_cast<int>(before.size());
+ }
+ return result;
+ };
+
+ int64_t t0 = ggml_time_ms();
+
+ if (sd_version_is_minimax_h3(version)) {
+ prompt = system_prefix("");
+ prompt_template_encode_start_idx = 0;
+ // The final tap is normalized; LLMRunner exposes it at num_layers + 1.
+ // clipproj taps out at layer 24 in all versions so far, so it should be fine to hardcode it there
+ out_layers = ph3_connector ? std::set<int>{13, 19, 25, 31, 37} : std::set<int>{clipproj_connector ? 24 : 50};
+ prompt_attn_range = {0, 0};
+
+ if (llm->enable_vision) {
+ const int patch_size = llm->config.vision.patch_size;
+ const int factor = patch_size * llm->config.vision.spatial_merge_size;
+
+ auto resize_for_vision = [&](const sd::Tensor<float>& image) {
+ int height = static_cast<int>(image.shape()[1]);
+ int width = static_cast<int>(image.shape()[0]);
+ int h_bar = std::max(factor, static_cast<int>(std::round(static_cast<double>(height) / factor)) * factor);
+ int w_bar = std::max(factor, static_cast<int>(std::round(static_cast<double>(width) / factor)) * factor);
+ fit_h3_vision_dims(height, width, h_bar, w_bar, factor);
+ auto resized = sd::ops::interpolate(
+ image,
+ std::vector<int64_t>{w_bar, h_bar, image.shape()[2], image.shape()[3]});
+ for (int64_t i = 0; i < resized.numel(); ++i) {
+ resized[i] = std::clamp(resized[i], 0.f, 1.f) * 2.f - 1.f;
+ }
+ return resized;
+ };
+
+ auto add_vision_outputs = [&](std::vector<sd::Tensor<float>> image_outputs,
+ int grid_h,
+ int grid_w) {
+ GGML_ASSERT(image_outputs.size() == 4);
+ prompt += "<|vision_start|>";
+ size_t marker_start = prompt.size();
+ prompt += "<|image_pad|><|vision_end|>";
+ return expand_vision_marker(prompt, marker_start, std::move(image_outputs), grid_h, grid_w,
+ image_embeds, deepstack_image_embeds, image_grids);
+ };
+
+ const auto* references = conditioner_params.minimax_h3_references;
+ if (references != nullptr && !references->empty()) {
+ int picture_index = 0;
+ int video_index = 0;
+ int audio_index = 0;
+ for (const auto& item : *references) {
+ if (item.kind == MiniMaxH3PresentationKind::AUDIO) {
+ prompt += "<Audio " + std::to_string(++audio_index) + ">: ";
+ continue;
+ }
+ if (item.kind == MiniMaxH3PresentationKind::IMAGE) {
+ GGML_ASSERT(item.frames.size() == 1);
+ auto resized = resize_for_vision(item.frames[0]);
+ prompt += "<Picture " + std::to_string(++picture_index) + ">: ";
+ if (!add_vision_outputs(llm->encode_image_outputs(n_threads,
+ resized,
+ false),
+ static_cast<int>(resized.shape()[1]) / patch_size,
+ static_cast<int>(resized.shape()[0]) / patch_size)) {
+ return {};
+ }
+ continue;
+ }
+
+ GGML_ASSERT(!item.frames.empty());
+ prompt += "<Video " + std::to_string(++video_index) + ">: ";
+ for (size_t frame = 0; frame < item.frames.size(); frame += 2) {
+ size_t next = std::min(frame + 1, item.frames.size() - 1);
+ float t0 = frame < item.timestamps.size() ? item.timestamps[frame] : frame / 2.f;
+ float t1 = next < item.timestamps.size() ? item.timestamps[next] : next / 2.f;
+ std::ostringstream timestamp;
+ timestamp << '<' << std::fixed << std::setprecision(1) << (t0 + t1) * 0.5f << " seconds>";
+ prompt += timestamp.str();
+
+ auto first = resize_for_vision(item.frames[frame]);
+ auto second = resize_for_vision(item.frames[next]);
+ if (first.shape()[0] != second.shape()[0] || first.shape()[1] != second.shape()[1]) {
+ second = sd::ops::interpolate(second,
+ std::vector<int64_t>{first.shape()[0],
+ first.shape()[1],
+ second.shape()[2],
+ second.shape()[3]});
+ }
+ auto pair = sd::ops::concat(first.unsqueeze(2), second.unsqueeze(2), 2);
+ if (!add_vision_outputs(llm->encode_video_block_outputs(n_threads,
+ pair,
+ false),
+ static_cast<int>(first.shape()[1]) / patch_size,
+ static_cast<int>(first.shape()[0]) / patch_size)) {
+ return {};
+ }
+ }
+ }
+ } else if (conditioner_params.ref_images != nullptr) {
+ for (size_t i = 0; i < conditioner_params.ref_images->size(); ++i) {
+ auto resized = resize_for_vision((*conditioner_params.ref_images)[i]);
+ prompt += version == VERSION_MINIMAX_H3_IMAGE
+ ? "Picture " + std::to_string(i + 1) + ": "
+ : "<Picture " + std::to_string(i + 1) + ">: ";
+ if (!add_vision_outputs(llm->encode_image_outputs(n_threads,
+ resized,
+ false),
+ static_cast<int>(resized.shape()[1]) / patch_size,
+ static_cast<int>(resized.shape()[0]) / patch_size)) {
+ return {};
+ }
+ }
+ }
+ }
+ auto text = conditioner_params.text;
+ if (version == VERSION_P_H3_IMAGE && !image_embeds.empty()) {
+ // Preserve explicit picture targets and structured briefs from the upstream upsampler.
+ static const std::regex verbatim(R"(^\s*(Edit <Picture \d+>|subject_definitions:))");
+ if (!std::regex_search(text, verbatim)) {
+ text = "Edit <Picture 1>. " + text;
+ } else {
+ text = trim(text);
+ }
+ }
+ prompt += text;
+ } else if (sd_version_is_hunyuan_video(version)) {
+ prompt_template_encode_start_idx = 98;
+ out_layers = {26};
+
+ prompt =
+ system_prefix(
+ "<|im_start|>system\nYou are a helpful assistant. Describe the video by detailing the following aspects:\n"
+ "1. The main content and theme of the video.\n"
+ "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects.\n"
+ "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects.\n"
+ "4. background environment, light, style and atmosphere.\n"
+ "5. camera angles, movements, and transitions used in the video.<|im_end|>\n"
+ "<|im_start|>user\n");
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ } else if (sd_version_is_lingbot_video(version)) {
+ dynamic_template_crop = true;
+ const int pad_token = 151643;
+ const std::string prompt_prefix =
+ system_prefix(
+ "<|im_start|>system\nGiven a user input that may include a text prompt alone, "
+ "a text prompt with an image reference, or a text prompt with a video reference "
+ "or a video reference alone, generate an \"Enhanced prompt\" that provides detailed "
+ "visual descriptions suitable for video generation. Evaluate the level of detail "
+ "in the user's input: if it is simple, enrich it by adding specifics about colors, "
+ "shapes, sizes, textures, lighting, motion dynamics, camera movement, temporal "
+ "progression, and spatial relationships to create vivid, concrete, and temporally "
+ "coherent scenes to create vivid and concrete scenes. Please generate only the "
+ "enhanced description for the prompt below and avoid including any additional "
+ "commentary or evaluations:<|im_end|>\n<|im_start|>user\n");
+
+ std::vector<int> prefix_tokens;
+ if (!conditioner_params.raw && !tokenizer->encode(prompt_prefix, prefix_tokens, nullptr)) {
+ return {};
+ }
+ prompt_template_encode_start_idx = 0;
+ for (int token : prefix_tokens) {
+ if (token != pad_token) {
+ prompt_template_encode_start_idx++;
+ }
+ }
+ LOG_VERBOSE("prompt_template_encode_start_idx %d", prompt_template_encode_start_idx);
+
+ prompt = prompt_prefix;
+ if (llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
+ LOG_INFO("LingBotVideoI2VPipeline");
+ const std::string placeholder = "<|image_pad|>";
+ std::string img_prompt;
+
+ for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
+ const auto& image = (*conditioner_params.ref_images)[i];
+ const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
+ int height = static_cast<int>(image.shape()[1]);
+ int width = static_cast<int>(image.shape()[0]);
+
+ int h_bar = std::max(factor, static_cast<int>(std::round(static_cast<double>(height) / factor) * factor));
+ int w_bar = std::max(factor, static_cast<int>(std::round(static_cast<double>(width) / factor) * factor));
+
+ if (std::max(height, width) > 200 * std::min(height, width)) {
+ LOG_WARN("LingBotVideo image aspect ratio is very large: %dx%d", width, height);
+ }
+
+ LOG_VERBOSE("resize LingBotVideo ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
+ auto resized_image = clip_preprocess(image, w_bar, h_bar);
+ auto image_embed = llm->encode_image(n_threads, resized_image, false);
+ if (image_embed.empty())
+ return {};
+
+ std::string image_prefix = prompt + img_prompt + "<|vision_start|>";
+ std::vector<int> prefix_tokens;
+ if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
+ return {};
+ }
+ int image_embed_idx = static_cast<int>(prefix_tokens.size());
+ for (const auto& previous_image : image_embeds) {
+ image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
+ }
+ image_embeds.emplace_back(image_embed_idx, image_embed);
+
+ img_prompt += "<|vision_start|>";
+ img_prompt += placeholder;
+ img_prompt += "<|vision_end|>";
+ }
+ prompt += img_prompt;
+ }
+
+ prompt += conditioner_params.text;
+ prompt_attn_range = {0, 0};
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ } else if (version == VERSION_QWEN_IMAGE_2_1) {
+ if (!llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
+ LOG_ERROR("Qwen Image 2.1 editing requires Qwen3-VL vision weights; provide --llm_vision or a combined encoder");
+ return {};
+ }
+ prompt = sd::prompt_templates::system_message(conditioner_params.system_prompt, "Comprehend and analyze the provided prompt.");
+ std::vector<int> system_tokens;
+ if (!conditioner_params.raw && !prompt.empty() && !tokenizer->encode(prompt, system_tokens, nullptr)) {
+ return {};
+ }
+ prompt_template_encode_start_idx = static_cast<int>(system_tokens.size());
+ out_layers = {static_cast<int>(llm->config.num_layers)};
+ prompt += "<|im_start|>user\n";
+ if (llm->enable_vision && conditioner_params.ref_images != nullptr) {
+ for (size_t i = 0; i < conditioner_params.ref_images->size(); ++i) {
+ const auto& source = (*conditioner_params.ref_images)[i];
+ const auto resized = sd::fit_image_tensor(source, 32, "Qwen Image 2.1 reference encoding");
+ const auto& image = resized.empty() ? source : resized;
+ int64_t width = image.shape()[0];
+ int64_t height = image.shape()[1];
+ int64_t pixels = width * height;
+ auto rgb = sd::Tensor<float>({width, height, 3, 1});
+ for (int64_t p = 0; p < pixels; ++p) {
+ float alpha = image.shape()[2] == 4 ? image[p + 3 * pixels] : 1.f;
+ for (int c = 0; c < 3; ++c) {
+ rgb[p + c * pixels] = 2.f * (image[p + c * pixels] * alpha + 1.f - alpha) - 1.f;
+ }
+ }
+ auto outputs = llm->encode_image_outputs(n_threads, rgb, false);
+ if (outputs.empty()) {
+ return {};
+ }
+ prompt += (i == 0 ? "" : " ") + std::string("<image") + std::to_string(i + 1) + "><|vision_start|>";
+ size_t marker_start = prompt.size();
+ prompt += "<|image_pad|><|vision_end|>";
+ if (!expand_vision_marker(prompt, marker_start, std::move(outputs),
+ static_cast<int>(height) / llm->config.vision.patch_size,
+ static_cast<int>(width) / llm->config.vision.patch_size,
+ image_embeds, deepstack_image_embeds, image_grids)) {
+ return {};
+ }
+ }
+ }
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text.empty() ? " " : conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ } else if (sd_version_is_qwen_image(version) || sd_version_is_mage_flow(version)) {
+ if (llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
+ LOG_INFO("%s", sd_version_is_mage_flow(version) ? "MageFlowEditPipeline" : "QwenImageEditPlusPipeline");
+ prompt_template_encode_start_idx = 64;
+
+ prompt = system_prefix("<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n");
+ std::string placeholder = "<|image_pad|>";
+ std::string img_prompt;
+
+ for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
+ const auto& image = (*conditioner_params.ref_images)[i];
+ const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
+ int height = static_cast<int>(image.shape()[1]);
+ int width = static_cast<int>(image.shape()[0]);
+ int h_bar = static_cast<int>(std::round(static_cast<double>(height) / factor) * factor);
+ int w_bar = static_cast<int>(std::round(static_cast<double>(width) / factor) * factor);
+
+ if (version == VERSION_QWEN_IMAGE) {
+ constexpr double target_area = 384.0 * 384.0;
+ const double scale = std::sqrt(target_area / (static_cast<double>(width) * height));
+ h_bar = std::max(factor, static_cast<int>(std::round(height * scale / factor)) * factor);
+ w_bar = std::max(factor, static_cast<int>(std::round(width * scale / factor)) * factor);
+ }
+
+ LOG_VERBOSE("resize conditioner ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
+
+ auto resized_image = clip_preprocess(image, w_bar, h_bar);
+
+ auto image_embed = llm->encode_image(n_threads, resized_image, false);
+ if (image_embed.empty())
+ return {};
+ std::string image_prefix = prompt + img_prompt + (sd_version_is_mage_flow(version) ? "Image " : "Picture ") + std::to_string(i + 1) + ": <|vision_start|>";
+ std::vector<int> prefix_tokens;
+ if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
+ return {};
+ }
+ int image_embed_idx = static_cast<int>(prefix_tokens.size());
+ for (const auto& previous_image : image_embeds) {
+ image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
+ }
+ image_embeds.emplace_back(image_embed_idx, image_embed);
+
+ img_prompt += (sd_version_is_mage_flow(version) ? "Image " : "Picture ") + std::to_string(i + 1) + ": <|vision_start|>";
+ img_prompt += placeholder;
+ img_prompt += "<|vision_end|>";
+ }
+
+ prompt += img_prompt;
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ } else {
+ prompt_template_encode_start_idx = 34;
+
+ prompt = system_prefix("<|im_start|>system\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>\n<|im_start|>user\n");
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ }
+ if (sd_version_is_mage_flow(version)) {
+ max_length = 2048 + prompt_template_encode_start_idx;
+ max_length_includes_template = true;
+ }
+ } else if (sd_version_is_boogu_image(version)) {
+ prompt_template_encode_start_idx = 0;
+
+ const std::string t2i_system_prompt =
+ "You are a helpful assistant that generates high-quality images based on user instructions. The instructions are as follows.";
+ const std::string edit_system_prompt =
+ "Describe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.";
+ const bool has_ref_images = llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty();
+ const bool text_empty = conditioner_params.text.find_first_not_of(" \t\r\n") == std::string::npos;
+
+ if (has_ref_images) {
+ LOG_INFO("BooguImageEditPipeline");
+ const std::string prompt_prefix = system_prefix("<|im_start|>system\n" + edit_system_prompt + "<|im_end|>\n<|im_start|>user\n");
+ std::string img_prompt;
+ const std::string placeholder = "<|image_pad|>";
+
+ for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
+ const auto& image = (*conditioner_params.ref_images)[i];
+ const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
+ int height = static_cast<int>(image.shape()[1]);
+ int width = static_cast<int>(image.shape()[0]);
+
+ int h_bar = std::max(factor,
+ static_cast<int>(std::round(static_cast<double>(height) / factor)) * factor);
+ int w_bar = std::max(factor,
+ static_cast<int>(std::round(static_cast<double>(width) / factor)) * factor);
+
+ LOG_VERBOSE("resize conditioner ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
+
+ auto resized_image = clip_preprocess(image, w_bar, h_bar);
+ auto image_embed = llm->encode_image(n_threads, resized_image, false);
+ if (image_embed.empty())
+ return {};
+
+ std::string image_prefix = prompt_prefix + img_prompt + "<|vision_start|>";
+ std::vector<int> prefix_tokens;
+ if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
+ return {};
+ }
+ int image_embed_idx = static_cast<int>(prefix_tokens.size());
+ for (const auto& previous_image : image_embeds) {
+ image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
+ }
+ image_embeds.emplace_back(image_embed_idx, image_embed);
+
+ img_prompt += "<|vision_start|>";
+ img_prompt += placeholder;
+ img_prompt += "<|vision_end|>";
+ }
+
+ prompt = prompt_prefix + img_prompt;
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+ prompt += "<|im_end|>\n";
+ } else {
+ const std::string& system_prompt = text_empty ? edit_system_prompt : t2i_system_prompt;
+ prompt = system_prefix("<|im_start|>system\n" + system_prompt + "<|im_end|>\n<|im_start|>user\n");
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+ prompt += "<|im_end|>\n";
+ }
+ } else if (sd_version_is_krea2(version)) {
+ prompt_template_encode_start_idx = 34;
+ out_layers = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35};
+
+ prompt = system_prefix("<|im_start|>system\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>\n<|im_start|>user\n");
+ if (llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
+ std::string img_prompt = "";
+ const std::string placeholder = "<|image_pad|>";
+ for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
+ const auto& image = (*conditioner_params.ref_images)[i];
+ const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
+ int height = static_cast<int>(image.shape()[1]);
+ int width = static_cast<int>(image.shape()[0]);
+
+ int h_bar = std::max(factor,
+ static_cast<int>(std::round(static_cast<double>(height) / factor)) * factor);
+ int w_bar = std::max(factor,
+ static_cast<int>(std::round(static_cast<double>(width) / factor)) * factor);
+
+ LOG_VERBOSE("resize conditioner ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
+
+ auto resized_image = clip_preprocess(image, w_bar, h_bar);
+ auto image_embed = llm->encode_image(n_threads, resized_image, false);
+ if (image_embed.empty())
+ return {};
+
+ std::string image_prefix = prompt + img_prompt + "Picture " + std::to_string(i + 1) + ": <|vision_start|>";
+ std::vector<int> prefix_tokens;
+ if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
+ return {};
+ }
+ int image_embed_idx = static_cast<int>(prefix_tokens.size());
+ for (const auto& previous_image : image_embeds) {
+ image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
+ }
+ image_embeds.emplace_back(image_embed_idx, image_embed);
+
+ img_prompt += "Picture " + std::to_string(i + 1) + ": <|vision_start|>";
+ img_prompt += placeholder;
+ img_prompt += "<|vision_end|>";
+ }
+ prompt += img_prompt;
+ }
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ } else if (sd_version_is_longcat(version)) {
+ spell_quotes = true;
+
+ if (llm->enable_vision && conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
+ LOG_INFO("LongCatEditPipeline");
+ prompt_template_encode_start_idx = 67;
+ min_length = 512 + prompt_template_encode_start_idx;
+
+ prompt = system_prefix("<|im_start|>system\nAs an image editing expert, first analyze the content and attributes of the input image(s). Then, based on the user's editing instructions, clearly and precisely determine how to modify the given image(s), ensuring that only the specified parts are altered and all other aspects remain consistent with the original(s).<|im_end|>\n<|im_start|>user\n");
+ std::string placeholder = "<|image_pad|>";
+ std::string img_prompt;
+
+ for (int i = 0; i < conditioner_params.ref_images->size(); i++) {
+ const auto& image = (*conditioner_params.ref_images)[i];
+ const int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
+ int height = static_cast<int>(image.shape()[1]);
+ int width = static_cast<int>(image.shape()[0]);
+ int h_bar = static_cast<int>(std::round(static_cast<double>(height) / factor) * factor);
+ int w_bar = static_cast<int>(std::round(static_cast<double>(width) / factor) * factor);
+
+ LOG_VERBOSE("resize conditioner ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
+
+ auto resized_image = clip_preprocess(image, w_bar, h_bar);
+ auto image_embed = llm->encode_image(n_threads, resized_image, false);
+ if (image_embed.empty())
+ return {};
+ std::string image_prefix = prompt + img_prompt + "<|vision_start|>";
+ std::vector<int> prefix_tokens;
+ if (!tokenizer->encode(image_prefix, prefix_tokens, nullptr)) {
+ return {};
+ }
+ int image_embed_idx = static_cast<int>(prefix_tokens.size());
+ for (const auto& previous_image : image_embeds) {
+ image_embed_idx += static_cast<int>(previous_image.second.shape()[1]) - 1;
+ }
+ image_embeds.emplace_back(image_embed_idx, image_embed);
+
+ img_prompt += "<|vision_start|>";
+ img_prompt += placeholder;
+ img_prompt += "<|vision_end|>";
+ }
+
+ prompt += img_prompt;
+ } else {
+ prompt_template_encode_start_idx = 36;
+ min_length = 512 + prompt_template_encode_start_idx;
+
+ prompt = system_prefix("<|im_start|>system\nAs an image captioning expert, generate a descriptive text prompt based on an image content, suitable for input to a text-to-image model.<|im_end|>\n<|im_start|>user\n");
+ }
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ } else if (version == VERSION_FLUX2) {
+ prompt_template_encode_start_idx = 0;
+ hidden_states_min_length = 512;
+ out_layers = {10, 20, 30};
+
+ prompt = system_prefix("[SYSTEM_PROMPT]You are an AI that reasons about image descriptions. You give structured responses focusing on object relationships, object\nattribution and actions without speculation.[/SYSTEM_PROMPT][INST]");
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "[/INST]";
+ } else if (sd_version_is_ideogram4(version)) {
+ prompt_template_encode_start_idx = 0;
+ out_layers = {1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 36};
+
+ prompt = system_prefix("<|im_start|>user\n");
+ prompt += conditioner_params.text;
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ prompt_attn_range = {0, 0};
+ } else if (sd_version_is_ernie_image(version)) {
+ prompt = system_prefix("");
+ prompt_template_encode_start_idx = 0;
+ out_layers = {25}; // -2
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+ } else if (sd_version_is_lens(version)) {
+ prompt_template_encode_start_idx = 97;
+ min_length = 0;
+ max_length = 512;
+ out_layers = {6, 12, 18, 24};
+
+ prompt =
+ system_prefix(
+ "<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.\n"
+ "Knowledge cutoff: 2024-06\n"
+ "Current date: 2026-05-26\n" // fix for current date
+ "\n"
+ "Reasoning: medium\n"
+ "\n"
+ "# Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions\n"
+ "\n"
+ "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background.\n"
+ "\n"
+ "<|end|><|start|>user<|message|>");
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "<|end|><|start|>assistant<|channel|>analysis<|message|>Need to generate one image according to the description.<|end|><|start|>assistant<|channel|>final<|message|>";
+ } else if (sd_version_is_z_image(version) || sd_version_is_z_image_l2p(version)) {
+ prompt_template_encode_start_idx = 0;
+ out_layers = {35}; // -2
+ if (conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
+ LOG_ERROR("Z-Image currently does not support reference-image conditioning");
+ return {};
+ }
+ if (conditioner_params.ref_images != nullptr && !conditioner_params.ref_images->empty()) {
+ LOG_INFO("ZImageOmniPipeline");
+ prompt = system_prefix("<|im_start|>user\n<|vision_start|>");
+ for (int i = 0; i < conditioner_params.ref_images->size() - 1; i++) {
+ extra_prompts.push_back("<|vision_end|><|vision_start|>");
+ }
+ extra_prompts.push_back("<|vision_end|>" + conditioner_params.text + "<|im_end|>\n<|im_start|>assistant\n<|vision_start|>");
+ extra_prompts.push_back("<|vision_end|><|im_end|>");
+ } else {
+ prompt = system_prefix("<|im_start|>user\n");
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ }
+ } else if (version == VERSION_MOSS_IMAGE) {
+ prompt_template_encode_start_idx = 0;
+ max_length = 4096;
+ prompt = system_prefix("<|im_start|>user\n");
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+ prompt += "<|im_end|>\n<|im_start|>assistant\n<think>\n";
+ } else if (sd_version_is_flux3(version)) {
+ prompt_template_encode_start_idx = 0;
+ max_length = 4096;
+ out_layers = {4, 8, 12, 16, 20, 24, 28, 32};
+ prompt = system_prefix("<|im_start|>user\n");
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ } else if (version == VERSION_FLUX2_KLEIN) {
+ prompt_template_encode_start_idx = 0;
+ min_length = 512;
+ out_layers = {9, 18, 27};
+
+ prompt = system_prefix("<|im_start|>user\n");
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n";
+ } else if (sd_version_is_sefi_image(version)) {
+ prompt_template_encode_start_idx = 0;
+ min_length = 1024;
+ out_layers = {9, 18, 27};
+
+ prompt = system_prefix("<|im_start|>user\n");
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "<|im_end|>\n<|im_start|>assistant\n";
+ } else if (version == VERSION_OVIS_IMAGE) {
+ prompt_template_encode_start_idx = 28;
+ min_length = prompt_template_encode_start_idx + 256;
+
+ prompt = system_prefix("<|im_start|>user\nDescribe the image by detailing the color, quantity, text, shape, size, texture, spatial relationships of the objects and background:");
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += " " + conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+
+ prompt += "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n";
+ } else if (sd_version_is_pid(version)) {
+ prompt = system_prefix("");
+ constexpr int pixeldit_max_length = 300;
+ const std::string chi_prompt =
+ "Given a user prompt, generate an \"Enhanced prompt\" that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:\n"
+ "- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.\n"
+ "- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.\n"
+ "Here are examples of how to transform or refine prompts:\n"
+ "- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.\n"
+ "- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.\n"
+ "Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:\n"
+ "User Prompt: ";
+ auto chi_tokens = conditioner_params.raw ? std::vector<int>{} : std::get<0>(tokenize(chi_prompt, {0, 0}));
+ if (!conditioner_params.raw && chi_tokens.empty()) {
+ return {};
+ }
+ size_t num_chi_tokens = chi_tokens.size();
+ max_length = conditioner_params.raw ? pixeldit_max_length : (int)num_chi_tokens + pixeldit_max_length - 2;
+ min_length = max_length;
+
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += " " + conditioner_params.text;
+ if (conditioner_params.raw)
+ prompt = conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+ if (conditioner_params.raw)
+ prompt_attn_range = {0, 0};
+
+ auto hidden_states = encode_prompt(n_threads,
+ prompt,
+ prompt_attn_range,
+ min_length,
+ 0,
+ image_embeds,
+ out_layers,
+ 0,
+ false,
+ max_length);
+ if (hidden_states.empty()) {
+ return {};
+ }
+
+ if (hidden_states.shape()[1] > pixeldit_max_length) {
+ auto bos = sd::ops::slice(hidden_states, 1, 0, 1);
+ auto tail = sd::ops::slice(hidden_states,
+ 1,
+ hidden_states.shape()[1] - (pixeldit_max_length - 1),
+ hidden_states.shape()[1]);
+ hidden_states = sd::ops::concat(bos, tail, 1);
+ }
+
+ int64_t t1 = ggml_time_ms();
+ LOG_INFO("computing condition graph completed, taking %" PRId64 " ms", t1 - t0);
+
+ SDCondition result;
+ result.c_crossattn = std::move(hidden_states);
+ return result;
+ } else if (version == VERSION_IRIS) {
+ dynamic_template_crop = true;
+ prompt =
+ system_prefix(
+ "<|im_start|>system\n"
+ "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial "
+ "relationships of the objects and background:<|im_end|>\n<|im_start|>user\n");
+ auto prefix_tokens = conditioner_params.raw ? std::vector<int>{} : std::get<0>(tokenize(prompt, {0, 0}));
+ if (!conditioner_params.raw && prefix_tokens.empty()) {
+ return {};
+ }
+ prompt_template_encode_start_idx = static_cast<int>(prefix_tokens.size());
+ hidden_states_min_length = 300;
+ max_length = prompt_template_encode_start_idx + hidden_states_min_length;
+ out_layers = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35};
+ prompt_attn_range.first = static_cast<int>(prompt.size());
+ prompt += conditioner_params.text;
+ prompt_attn_range.second = static_cast<int>(prompt.size());
+ prompt_suffix = "<|im_end|>\n<|im_start|>assistant\n";
+ } else {
+ GGML_ABORT("unknown version %d", version);
+ }
+
+ if (conditioner_params.raw) {
+ prompt = conditioner_params.text;
+ prompt_suffix.clear();
+ prompt_attn_range = {0, 0};
+ spell_quotes = false;
+ if (min_length > 0)
+ min_length = std::max(0, min_length - prompt_template_encode_start_idx);
+ if (max_length_includes_template)
+ max_length -= prompt_template_encode_start_idx;
+ prompt_template_encode_start_idx = 0;
+ } else if (conditioner_params.system_prompt && !dynamic_template_crop && prompt_template_encode_start_idx > 0) {
+ prompt_template_encode_start_idx += template_token_delta;
+ if (min_length > 0)
+ min_length += template_token_delta;
+ if (max_length_includes_template)
+ max_length += template_token_delta;
+ }
+
+ LLM::PromptTokens prompt_tokens;
+ auto hidden_states = encode_prompt(n_threads,
+ prompt,
+ prompt_attn_range,
+ min_length,
+ hidden_states_min_length,
+ image_embeds,
+ out_layers,
+ prompt_template_encode_start_idx,
+ spell_quotes,
+ max_length,
+ deepstack_image_embeds,
+ image_grids,
+ prompt_suffix,
+ version == VERSION_IRIS ? &text_mask : nullptr,
+ conditioner_params.prompt_input == nullptr ? nullptr : &input_template,
+ &prompt_tokens);
+ if (hidden_states.empty()) {
+ return {};
+ }
+ std::vector<sd::Tensor<float>> extra_hidden_states_vec;
+ if (sd_version_is_hunyuan_video(version) && byt5) {
+ std::vector<std::string> quoted_texts;
+ auto collect_quoted = [&](const std::string& open, const std::string& close) {
+ size_t begin = 0;
+ while ((begin = conditioner_params.text.find(open, begin)) != std::string::npos) {
+ size_t content_begin = begin + open.size();
+ size_t end = conditioner_params.text.find(close, content_begin);
+ if (end == std::string::npos) {
+ break;
+ }
+ quoted_texts.push_back(conditioner_params.text.substr(content_begin, end - content_begin));
+ begin = end + close.size();
+ }
+ };
+ collect_quoted("\"", "\"");
+ collect_quoted("\xE2\x80\x98", "\xE2\x80\x99");
+ collect_quoted("\xE2\x80\x9C", "\xE2\x80\x9D");
+
+ if (!quoted_texts.empty()) {
+ std::string byt5_text;
+ for (const auto& text : quoted_texts) {
+ byt5_text += "Text \"" + text + "\". ";
+ }
+ std::vector<int> tokens;
+ tokens.reserve(byt5_text.size() + 1);
+ for (unsigned char byte : byt5_text) {
+ tokens.push_back(static_cast<int>(byte) + 3);
+ }
+ tokens.push_back(1);
+ sd::Tensor<int32_t> input_ids({static_cast<int64_t>(tokens.size())}, tokens);
+ auto byt5_hidden_states = byt5->compute(n_threads,
+ input_ids,
+ sd::Tensor<float>(),
+ false);
+ if (byt5_hidden_states.empty())
+ return {};
+ extra_hidden_states_vec.push_back(std::move(byt5_hidden_states));
+ }
+ }
+ for (int i = 0; i < extra_prompts.size(); i++) {
+ auto extra_hidden_states = encode_prompt(n_threads,
+ extra_prompts[i],
+ extra_prompts_attn_range[i],
+ min_length,
+ hidden_states_min_length,
+ image_embeds,
+ out_layers,
+ prompt_template_encode_start_idx,
+ spell_quotes,
+ max_length);
+ if (extra_hidden_states.empty()) {
+ return {};
+ }
+ extra_hidden_states_vec.push_back(std::move(extra_hidden_states));
+ }
+
+ int64_t t1 = ggml_time_ms();
+ LOG_INFO("computing condition graph completed, taking %" PRId64 " ms", t1 - t0);
+ SDCondition result;
+ result.c_crossattn = std::move(hidden_states);
+ result.extra_c_crossattns = std::move(extra_hidden_states_vec);
+ result.c_vector = std::move(text_mask);
+ if (version == VERSION_QWEN_IMAGE_2_1) {
+ auto slots = sd::Tensor<int32_t>::zeros({result.c_crossattn.shape()[1]});
+ const auto& references = params.prompt_input == nullptr ? image_embeds : prompt_tokens.image_embeds;
+ for (size_t i = 0; i < references.size(); ++i) {
+ int64_t begin = references[i].first - prompt_template_encode_start_idx;
+ int64_t end = begin + references[i].second.shape()[1];
+ if (begin < 0 || end > slots.numel()) {
+ LOG_ERROR("Qwen Image 2.1 image slots exceed the encoded prompt");
+ return {};
+ }
+ for (int64_t j = begin; j < end; ++j) {
+ slots[j] = static_cast<int32_t>(i + 1);
+ }
+ }
+ result.c_token_types = std::move(slots);
+ }
+ if (sd_version_is_minimax_h3(version)) {
+ std::vector<int32_t> tags(static_cast<size_t>(result.c_crossattn.shape()[1]), 1);
+ const auto& images = params.prompt_input == nullptr ? image_embeds : prompt_tokens.image_embeds;
+ for (const auto& [index, image_embed] : images) {
+ int64_t begin = std::max<int64_t>(0, index - 1);
+ int64_t end = std::min<int64_t>(static_cast<int64_t>(tags.size()),
+ index + image_embed.shape()[1] + 1);
+ std::fill(tags.begin() + begin, tags.begin() + end, 0);
+ }
+ int64_t tag_count = static_cast<int64_t>(tags.size());
+ result.c_token_types = sd::Tensor<int32_t>({tag_count}, std::move(tags));
+ }
+
+ return result;
+ }
+};
+
+struct Fibo2Conditioner : public LLMEmbedder {
+ size_t max_reference_images() const override { return std::numeric_limits<size_t>::max(); }
+ using JSON = nlohmann::ordered_json;
+
+ Fibo2Conditioner(ggml_backend_t backend, const String2TensorStorage& weights, std::shared_ptr<RunnerWeightManager> weight_manager, const TokenizerConfig& tokenizers)
+ : LLMEmbedder(backend, weights, VERSION_FIBO2, true, weight_manager, tokenizers) {
+ if (llm->config.hidden_size != 2560 || llm->config.num_layers != 36) {
+ throw std::runtime_error("Fibo 2.0 requires its Qwen3-VL-4B text encoder");
+ }
+ }
+
+ static bool empty_value(const JSON& value) {
+ return value.is_null() ||
+ (value.is_string() && value.get_ref<const std::string&>().empty()) ||
+ ((value.is_array() || value.is_object()) && value.empty());
+ }
+
+ static JSON clean_caption(const JSON& value) {
+ if (value.is_object()) {
+ auto result = JSON::object();
+ for (auto it = value.begin(); it != value.end(); ++it) {
+ auto cleaned = clean_caption(it.value());
+ if (!empty_value(cleaned)) {
+ result[it.key()] = std::move(cleaned);
+ }
+ }
+ return result;
+ }
+ if (value.is_array()) {
+ auto result = JSON::array();
+ for (const auto& item : value) {
+ auto cleaned = clean_caption(item);
+ if (!empty_value(cleaned)) {
+ result.push_back(std::move(cleaned));
+ }
+ }
+ return result;
+ }
+ return value;
+ }
+
+ static std::pair<JSON, JSON> parse_prompt(const std::string& prompt) {
+ auto caption = JSON::parse(prompt, nullptr, false);
+ if (!caption.is_object()) {
+ return {prompt, nullptr};
+ }
+ JSON instruction;
+ if (caption.contains("edit_instruction")) {
+ instruction = caption["edit_instruction"];
+ caption.erase("edit_instruction");
+ }
+ if (caption.contains("structured_caption")) {
+ caption = JSON(caption["structured_caption"]);
+ if (!caption.is_object()) {
+ return {caption, instruction};
+ }
+ }
+ bool short_form = caption.size() == 2 && caption.contains("short_description") && caption.contains("text_render");
+ caption = clean_caption(caption);
+ for (const char* score : {"aesthetic_score", "preference_score"}) {
+ caption.erase(score);
+ for (auto& value : caption) {
+ if (value.is_object()) {
+ value.erase(score);
+ }
+ }
+ }
+ caption = clean_caption(caption);
+ if (short_form) {
+ caption = JSON{{"short_description", caption.value("short_description", JSON(""))},
+ {"text_render", caption.value("text_render", JSON::array())}};
+ }
+ return {caption, instruction};
+ }
+
+ static std::string format_prompt(const std::string& text, int num_images) {
+ auto [caption, instruction] = parse_prompt(text);
+ if (num_images > 0) {
+ if (instruction.is_null()) {
+ caption = nullptr;
+ instruction = text;
+ }
+ auto edit = JSON::object();
+ for (int i = 0; i < num_images; ++i) {
+ edit[num_images == 1 ? "image" : "image_" + std::to_string(i + 1)] = "<|vision_start|><|image_pad|><|vision_end|>";
+ }
+ if (!empty_value(caption)) {
+ edit["structured_caption"] = caption;
+ }
+ edit["edit_instruction"] = instruction;
+ return edit.dump();
+ }
+ if (text.empty()) {
+ return R"({"short_description":"","objects":[],"background_setting":"","lighting":{},"aesthetics":{},"photographic_characteristics":{},"style_medium":"","context":"","artistic_style":""})";
+ }
+ if (caption.is_string()) {
+ return caption.get<std::string>();
+ }
+ return empty_value(caption) ? "{}" : caption.dump();
+ }
+
+ static sd::Tensor<float> make_bundles(sd::Tensor<float> states, const std::set<int>& layers) {
+ constexpr int width = 2560;
+ constexpr int bundles[6][3] = {{9, 20, 31}, {5, 16, 27}, {7, 18, 29}, {9, 20, 31}, {11, 22, 33}, {13, 24, 35}};
+ for (int64_t token = 0; token < states.shape()[1]; ++token) {
+ for (size_t layer = 0; layer < layers.size(); ++layer) {
+ float sum = 0.f;
+ int64_t offset = token * states.shape()[0] + layer * width;
+ for (int i = 0; i < width; ++i) {
+ sum += states[offset + i] * states[offset + i];
+ }
+ float scale = 1.f / std::sqrt(sum / width + 1e-6f);
+ for (int i = 0; i < width; ++i) {
+ states[offset + i] *= scale;
+ }
+ }
+ }
+ sd::Tensor<float> result({6 * 3 * width, states.shape()[1]});
+ for (int b = 0; b < 6; ++b) {
+ for (int j = 0; j < 3; ++j) {
+ int index = static_cast<int>(std::distance(layers.begin(), layers.find(bundles[b][j])));
+ for (int64_t token = 0; token < states.shape()[1]; ++token) {
+ std::copy_n(states.data() + token * states.shape()[0] + index * width, width,
+ result.data() + token * result.shape()[0] + (b * 3 + j) * width);
+ }
+ }
+ }
+ return result;
+ }
+
+ SDCondition get_learned_condition(int n_threads, const ConditionerParams& params) override {
+ auto p = params;
+ sd::PromptInputTemplate input_template(p.prompt_input);
+ if (p.prompt_input != nullptr) {
+ p.text = input_template.text;
+ }
+ int image_count = p.ref_images ? static_cast<int>(p.ref_images->size()) : 0;
+ if (image_count && !llm->enable_vision) {
+ LOG_ERROR("Fibo 2.0 editing requires vision weights");
+ return {};
+ }
+ std::string prompt = p.raw ? p.text : sd::prompt_templates::with_system("<|im_start|>user\n", p.system_prompt) + format_prompt(p.text, image_count) + "<|im_end|>\n<|im_start|>assistant\n";
+ std::vector<std::pair<int, sd::Tensor<float>>> images;
+ LLM::DeepStackImageEmbeds deepstack;
+ std::vector<LLM::ImageGrid> grids;
+ size_t marker_start = 0;
+ for (int i = 0; i < image_count; ++i) {
+ const auto& image = (*p.ref_images)[i];
+ int factor = llm->config.vision.patch_size * llm->config.vision.spatial_merge_size;
+ int height = static_cast<int>(image.shape()[1]), width = static_cast<int>(image.shape()[0]);
+ int h = std::max(factor, static_cast<int>(std::round(static_cast<double>(height) / factor)) * factor);
+ int w = std::max(factor, static_cast<int>(std::round(static_cast<double>(width) / factor)) * factor);
+ auto pixels = sd::ops::interpolate(image, {w, h, image.shape()[2], image.shape()[3]}, sd::ops::InterpolateMode::Bicubic, false, true);
+ auto rgb = sd::Tensor<float>({w, h, 3, 1});
+ for (int64_t pixel = 0; pixel < int64_t(w) * h; ++pixel) {
+ float alpha = pixels.shape()[2] == 4 ? pixels[pixel + 3 * w * h] : 1.f;
+ for (int channel = 0; channel < 3; ++channel) {
+ rgb[pixel + channel * w * h] = 2.f * std::clamp(pixels[pixel + channel * w * h] * alpha + 1.f - alpha, 0.f, 1.f) - 1.f;
+ }
+ }
+ auto outputs = llm->encode_image_outputs(n_threads, rgb, false);
+ if (!expand_vision_marker(prompt, marker_start, std::move(outputs),
+ h / llm->config.vision.patch_size, w / llm->config.vision.patch_size,
+ images, deepstack, grids, 4096)) {
+ return {};
+ }
+ }
+ const std::set<int> layers = {5, 7, 9, 11, 13, 16, 18, 20, 22, 24, 27, 29, 31, 33, 35};
+ auto states = encode_prompt(n_threads, prompt, {0, 0}, 0, 0, images, layers, 0, false, 4096, deepstack, grids,
+ "", nullptr, p.prompt_input == nullptr ? nullptr : &input_template);
+ if (states.empty()) {
+ return {};
+ }
+ SDCondition result;
+ result.c_crossattn = make_bundles(std::move(states), layers);
+ return result;
+ }
+};
+
+namespace sd {
+
+ std::shared_ptr<Conditioner> make_llm_conditioner(ggml_backend_t backend,
+ const String2TensorStorage& weights,
+ SDVersion version,
+ bool enable_vision,
+ std::shared_ptr<DeviceResidencyManager> weight_manager,
+ const TokenizerConfig& tokenizers) {
+ return std::make_shared<LLMEmbedder>(backend, weights, version, enable_vision, std::move(weight_manager), tokenizers);
+ }
+
+ std::shared_ptr<Conditioner> make_fibo2_conditioner(ggml_backend_t backend,
+ const String2TensorStorage& weights,
+ std::shared_ptr<DeviceResidencyManager> weight_manager,
+ const TokenizerConfig& tokenizers) {
+ return std::make_shared<Fibo2Conditioner>(backend, weights, std::move(weight_manager), tokenizers);
+ }
+
+} // namespace sd
diff --git a/src/conditioning/llm_conditioner.h b/src/conditioning/llm_conditioner.h
new file mode 100644
index 0000000..68c09a7
--- /dev/null
+++ b/src/conditioning/llm_conditioner.h
@@ -0,0 +1,28 @@
+#ifndef __SD_CONDITIONING_LLM_CONDITIONER_H__
+#define __SD_CONDITIONING_LLM_CONDITIONER_H__
+
+#include <memory>
+
+#include "model.h"
+
+struct Conditioner;
+struct DeviceResidencyManager;
+class TokenizerConfig;
+
+namespace sd {
+
+ std::shared_ptr<Conditioner> make_llm_conditioner(ggml_backend_t backend,
+ const String2TensorStorage& weights,
+ SDVersion version,
+ bool enable_vision,
+ std::shared_ptr<DeviceResidencyManager> weight_manager,
+ const TokenizerConfig& tokenizers);
+
+ std::shared_ptr<Conditioner> make_fibo2_conditioner(ggml_backend_t backend,
+ const String2TensorStorage& weights,
+ std::shared_ptr<DeviceResidencyManager> weight_manager,
+ const TokenizerConfig& tokenizers);
+
+} // namespace sd
+
+#endif // __SD_CONDITIONING_LLM_CONDITIONER_H__
diff --git a/src/core/util.cpp b/src/core/util.cpp
index 74c7a2c..e56dac1 100644
--- a/src/core/util.cpp
+++ b/src/core/util.cpp
@@ -856,6 +856,47 @@ sd::Tensor<float> sd_image_to_tensor(sd::Image image,
return tensor;
}
+bool sd::preprocess_canny(sd::Image img, float high_threshold, float low_threshold, float weak, float strong, bool inverse) {
+ float kX[9] = {
+ -1, 0, 1,
+ -2, 0, 2,
+ -1, 0, 1};
+
+ float kY[9] = {
+ 1, 2, 1,
+ 0, 0, 0,
+ -1, -2, -1};
+
+ sd::Tensor<float> gkernel = gaussian_kernel_tensor(5);
+ sd::Tensor<float> sf_kx({3, 3, 1, 1}, std::vector<float>(kX, kX + 9));
+ sd::Tensor<float> sf_ky({3, 3, 1, 1}, std::vector<float>(kY, kY + 9));
+
+ sd::Tensor<float> image = sd_image_to_preprocessing_tensor(img);
+ sd::Tensor<float> image_gray = grayscale_tensor(image);
+ image_gray = convolve_tensor(image_gray, gkernel, 2);
+ sd::Tensor<float> iX = convolve_tensor(image_gray, sf_kx, 1);
+ sd::Tensor<float> iY = convolve_tensor(image_gray, sf_ky, 1);
+ sd::Tensor<float> G = tensor_hypot(iX, iY);
+ normalize_tensor(&G);
+ sd::Tensor<float> theta = tensor_arctan2(iX, iY);
+ image_gray = non_max_supression(G, theta);
+ threshold_hystersis(&image_gray, high_threshold, low_threshold, weak, strong);
+
+ const uint32_t color_channels = img.channel == 2 || img.channel == 4 ? img.channel - 1 : img.channel;
+ for (uint32_t iy = 0; iy < img.height; ++iy) {
+ for (uint32_t ix = 0; ix < img.width; ++ix) {
+ float gray = preprocessing_get_4d(image_gray, ix, iy, 0, 0);
+ gray = inverse ? 1.0f - gray : gray;
+ for (uint32_t c = 0; c < color_channels; ++c) {
+ preprocessing_set_4d(image, gray, ix, iy, c, 0);
+ }
+ }
+ }
+
+ preprocessing_tensor_to_sd_image(image, img.data);
+ return true;
+}
+
// Constants for means and std
float means[3] = {0.48145466f, 0.4578275f, 0.40821073f};
float stds[3] = {0.26862954f, 0.26130258f, 0.27577711f};
diff --git a/src/dgl/bindings/components.cpp b/src/dgl/bindings/components.cpp
index 7d840d5..19ab183 100644
--- a/src/dgl/bindings/components.cpp
+++ b/src/dgl/bindings/components.cpp
@@ -4,7 +4,7 @@
#include <cmath>
#include <type_traits>
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
#include "core/rng.hpp"
#include "dgl/bindings/arguments.h"
#include "dgl/bindings/audio.h"
diff --git a/src/dgl/bindings/condition.cpp b/src/dgl/bindings/condition.cpp
index 7dc9ae5..961e3c2 100644
--- a/src/dgl/bindings/condition.cpp
+++ b/src/dgl/bindings/condition.cpp
@@ -3,7 +3,7 @@
#include <algorithm>
#include <iterator>
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
#include "dgl/bindings/arguments.h"
#include "dgl/ops/tensor.h"
diff --git a/src/dgl/models/component_builders.cpp b/src/dgl/models/component_builders.cpp
index b13e2da..3cbbf41 100644
--- a/src/dgl/models/component_builders.cpp
+++ b/src/dgl/models/component_builders.cpp
@@ -6,7 +6,7 @@
#include <cstring>
#include <utility>
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
#include "core/ggml_extend_backend.h"
#include "core/util.h"
#include "dgl/models/control.h"
diff --git a/src/dgl/models/control.cpp b/src/dgl/models/control.cpp
index 701d9bd..50ec963 100644
--- a/src/dgl/models/control.cpp
+++ b/src/dgl/models/control.cpp
@@ -1,6 +1,6 @@
#include "dgl/models/control.h"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
#include "dgl/models/component_builders.h"
#include "dgl/models/component_sources.h"
#include "dgl/models/dit.h"
diff --git a/src/dgl/models/denoising_parameterization.h b/src/dgl/models/denoising_parameterization.h
index b661492..84b5d6b 100644
--- a/src/dgl/models/denoising_parameterization.h
+++ b/src/dgl/models/denoising_parameterization.h
@@ -4,9 +4,10 @@
#include <memory>
#include <vector>
+#include <model.h>
+
#include "core/option_types.h"
#include "core/tensor.hpp"
-#include "model.h"
struct Denoiser;
diff --git a/src/dgl/models/dit.cpp b/src/dgl/models/dit.cpp
index 206d40c..00b66bc 100644
--- a/src/dgl/models/dit.cpp
+++ b/src/dgl/models/dit.cpp
@@ -2,7 +2,7 @@
#include <utility>
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
#include "core/ggml_tensor_utils.h"
#include "core/util.h"
#include "dgl/diagnostic.h"
diff --git a/src/dgl/models/photomaker_prompt.h b/src/dgl/models/photomaker_prompt.h
index ad55692..a8500e8 100644
--- a/src/dgl/models/photomaker_prompt.h
+++ b/src/dgl/models/photomaker_prompt.h
@@ -1,7 +1,7 @@
#ifndef __SD_DGL_MODELS_PHOTOMAKER_PROMPT_H__
#define __SD_DGL_MODELS_PHOTOMAKER_PROMPT_H__
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
namespace sd::dgl::models {
struct PhotoMakerPrompt {
diff --git a/src/dgl/ops/control.cpp b/src/dgl/ops/control.cpp
index 2479193..a674244 100644
--- a/src/dgl/ops/control.cpp
+++ b/src/dgl/ops/control.cpp
@@ -1,6 +1,5 @@
#include "dgl/ops/control.h"
-#include "conditioning/conditioner.hpp"
#include "dgl/models/fwd.h"
namespace sd::dgl::ops {
diff --git a/src/dgl/ops/predictor.h b/src/dgl/ops/predictor.h
index 8ad4fa5..a04e631 100644
--- a/src/dgl/ops/predictor.h
+++ b/src/dgl/ops/predictor.h
@@ -11,7 +11,7 @@
#include <set>
#include <variant>
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
#include "dgl/models/denoising_parameterization.h"
#include "dgl/models/diffusion_model.h"
#include "dgl/models/diffusion_prediction.h"
diff --git a/src/dgl/ops/prompt.cpp b/src/dgl/ops/prompt.cpp
index abf1a57..cf4b438 100644
--- a/src/dgl/ops/prompt.cpp
+++ b/src/dgl/ops/prompt.cpp
@@ -3,9 +3,11 @@
#include <algorithm>
#include <filesystem>
#include <set>
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
+#include "conditioning/textual_inversion.h"
#include "core/file_access.h"
#include "core/image_tensor.h"
+#include "core/util.h"
#include "dgl/models/text_encoder.h"
#include "dgl/ops/image.h"
#include "dgl/ops/video.h"
diff --git a/src/model/common/ggml_block.cpp b/src/model/common/ggml_block.cpp
new file mode 100644
index 0000000..e2fb334
--- /dev/null
+++ b/src/model/common/ggml_block.cpp
@@ -0,0 +1,103 @@
+#include "model/common/ggml_block.hpp"
+
+int64_t GGMLBlock::weight_scale_elements(const TensorStorage& storage, int64_t features, const std::string& name) {
+ const auto elements = storage.nelements();
+ if (elements != 1 && elements != features) {
+ throw std::runtime_error("unsupported weight scale for '" + name + "': [" +
+ std::to_string(storage.ne[0]) + ", " + std::to_string(storage.ne[1]) + ", " +
+ std::to_string(storage.ne[2]) + ", " + std::to_string(storage.ne[3]) +
+ "], expected a scalar or " + std::to_string(features) + " output scales");
+ }
+ return elements;
+}
+
+ggml_type GGMLBlock::get_type(const std::string& name, const String2TensorStorage& tensor_storage_map, ggml_type default_type) {
+ ggml_type wtype = default_type;
+ auto iter = tensor_storage_map.find(name);
+ if (iter != tensor_storage_map.end()) {
+ const TensorStorage& tensor_storage = iter->second;
+ if (tensor_storage.expected_type != GGML_TYPE_COUNT) {
+ wtype = tensor_storage.expected_type;
+ } else {
+ wtype = tensor_storage.type;
+ }
+ }
+ return wtype;
+}
+
+void GGMLBlock::init_blocks(ggml_context* ctx, const String2TensorStorage& tensor_storage_map, const std::string prefix) {
+ for (auto& pair : blocks) {
+ auto& block = pair.second;
+ block->init(ctx, tensor_storage_map, prefix + pair.first);
+ }
+}
+
+void GGMLBlock::init(ggml_context* ctx, const String2TensorStorage& tensor_storage_map, std::string prefix) {
+ if (prefix.size() > 0) {
+ prefix = prefix + ".";
+ }
+ init_params(ctx, tensor_storage_map, prefix);
+ init_blocks(ctx, tensor_storage_map, prefix);
+}
+
+size_t GGMLBlock::get_params_num() {
+ size_t num_tensors = params.size();
+ for (auto& pair : blocks) {
+ auto& block = pair.second;
+
+ num_tensors += block->get_params_num();
+ }
+ return num_tensors;
+}
+
+size_t GGMLBlock::get_params_mem_size() {
+ size_t mem_size = 0;
+ for (auto& pair : blocks) {
+ auto& block = pair.second;
+
+ mem_size += block->get_params_mem_size();
+ }
+
+ for (auto& pair : params) {
+ mem_size += ggml_nbytes(pair.second);
+ }
+
+ return mem_size;
+}
+
+void GGMLBlock::get_param_tensors(std::map<std::string, ggml_tensor*>& tensors, std::string prefix) {
+ if (prefix.size() > 0) {
+ prefix = prefix + ".";
+ }
+ for (auto& pair : blocks) {
+ auto& block = pair.second;
+ block->get_param_tensors(tensors, prefix + pair.first);
+ }
+
+ for (auto& pair : params) {
+ ggml_tensor* param = pair.second;
+ tensors[prefix + pair.first] = pair.second;
+ ggml_set_name(param, (prefix + pair.first).c_str());
+ }
+}
+
+void GGMLBlock::get_param_tensor_ops(std::map<ggml_tensor*, enum ggml_op>& tensor_ops) {
+ for (auto& pair : blocks) {
+ pair.second->get_param_tensor_ops(tensor_ops);
+ }
+ for (auto& pair : params) {
+ enum ggml_op op = param_usage_op(pair.first);
+ if (op != GGML_OP_NONE) {
+ tensor_ops[pair.second] = op;
+ }
+ }
+}
+
+void GGMLBlock::get_all_blocks(std::vector<GGMLBlock*>& result) {
+ result.push_back(this);
+ for (auto& block_iter : blocks) {
+ if (block_iter.second) {
+ block_iter.second->get_all_blocks(result);
+ }
+ }
+}
diff --git a/src/model/common/ggml_block.hpp b/src/model/common/ggml_block.hpp
index 76155b4..203b699 100644
--- a/src/model/common/ggml_block.hpp
+++ b/src/model/common/ggml_block.hpp
@@ -25,37 +25,11 @@ protected:
GGMLBlockMap blocks;
ParameterMap params;
- static int64_t weight_scale_elements(const TensorStorage& storage, int64_t features, const std::string& name) {
- const auto elements = storage.nelements();
- if (elements != 1 && elements != features) {
- throw std::runtime_error("unsupported weight scale for '" + name + "': [" +
- std::to_string(storage.ne[0]) + ", " + std::to_string(storage.ne[1]) + ", " +
- std::to_string(storage.ne[2]) + ", " + std::to_string(storage.ne[3]) +
- "], expected a scalar or " + std::to_string(features) + " output scales");
- }
- return elements;
- }
-
- ggml_type get_type(const std::string& name, const String2TensorStorage& tensor_storage_map, ggml_type default_type) {
- ggml_type wtype = default_type;
- auto iter = tensor_storage_map.find(name);
- if (iter != tensor_storage_map.end()) {
- const TensorStorage& tensor_storage = iter->second;
- if (tensor_storage.expected_type != GGML_TYPE_COUNT) {
- wtype = tensor_storage.expected_type;
- } else {
- wtype = tensor_storage.type;
- }
- }
- return wtype;
- }
+ static int64_t weight_scale_elements(const TensorStorage& storage, int64_t features, const std::string& name);
- void init_blocks(ggml_context* ctx, const String2TensorStorage& tensor_storage_map = {}, const std::string prefix = "") {
- for (auto& pair : blocks) {
- auto& block = pair.second;
- block->init(ctx, tensor_storage_map, prefix + pair.first);
- }
- }
+ ggml_type get_type(const std::string& name, const String2TensorStorage& tensor_storage_map, ggml_type default_type);
+
+ void init_blocks(ggml_context* ctx, const String2TensorStorage& tensor_storage_map = {}, const std::string prefix = "");
virtual void init_params(ggml_context* ctx, const String2TensorStorage& tensor_storage_map = {}, const std::string prefix = "") {}
@@ -65,79 +39,21 @@ protected:
}
public:
- void init(ggml_context* ctx, const String2TensorStorage& tensor_storage_map = {}, std::string prefix = "") {
- if (prefix.size() > 0) {
- prefix = prefix + ".";
- }
- init_params(ctx, tensor_storage_map, prefix);
- init_blocks(ctx, tensor_storage_map, prefix);
- }
-
- size_t get_params_num() {
- size_t num_tensors = params.size();
- for (auto& pair : blocks) {
- auto& block = pair.second;
-
- num_tensors += block->get_params_num();
- }
- return num_tensors;
- };
-
- size_t get_params_mem_size() {
- size_t mem_size = 0;
- for (auto& pair : blocks) {
- auto& block = pair.second;
-
- mem_size += block->get_params_mem_size();
- }
+ void init(ggml_context* ctx, const String2TensorStorage& tensor_storage_map = {}, std::string prefix = "");
- for (auto& pair : params) {
- mem_size += ggml_nbytes(pair.second);
- }
+ size_t get_params_num();
- return mem_size;
- }
+ size_t get_params_mem_size();
- void get_param_tensors(std::map<std::string, ggml_tensor*>& tensors, std::string prefix = "") {
- if (prefix.size() > 0) {
- prefix = prefix + ".";
- }
- for (auto& pair : blocks) {
- auto& block = pair.second;
- block->get_param_tensors(tensors, prefix + pair.first);
- }
-
- for (auto& pair : params) {
- ggml_tensor* param = pair.second;
- tensors[prefix + pair.first] = pair.second;
- ggml_set_name(param, (prefix + pair.first).c_str());
- }
- }
+ void get_param_tensors(std::map<std::string, ggml_tensor*>& tensors, std::string prefix = "");
- void get_param_tensor_ops(std::map<ggml_tensor*, enum ggml_op>& tensor_ops) {
- for (auto& pair : blocks) {
- pair.second->get_param_tensor_ops(tensor_ops);
- }
- for (auto& pair : params) {
- enum ggml_op op = param_usage_op(pair.first);
- if (op != GGML_OP_NONE) {
- tensor_ops[pair.second] = op;
- }
- }
- }
+ void get_param_tensor_ops(std::map<ggml_tensor*, enum ggml_op>& tensor_ops);
virtual std::string get_desc() {
return "GGMLBlock";
}
- void get_all_blocks(std::vector<GGMLBlock*>& result) {
- result.push_back(this);
- for (auto& block_iter : blocks) {
- if (block_iter.second) {
- block_iter.second->get_all_blocks(result);
- }
- }
- }
+ void get_all_blocks(std::vector<GGMLBlock*>& result);
};
class UnaryBlock : public GGMLBlock {
diff --git a/src/model/diffusion/hidream_o1.hpp b/src/model/diffusion/hidream_o1.hpp
index b6939d8..85c709f 100644
--- a/src/model/diffusion/hidream_o1.hpp
+++ b/src/model/diffusion/hidream_o1.hpp
@@ -10,11 +10,13 @@
#include <utility>
#include <vector>
-#include "conditioning/conditioner.hpp"
+#include "conditioning/conditioner.h"
+#include "conditioning/prompt_templates.h"
#include "core/util.h"
#include "model/diffusion/dit.hpp"
#include "model/diffusion/model.hpp"
#include "model/te/llm.hpp"
+#include "tokenizers/tokenizer_config.h"
namespace HiDreamO1 {
constexpr int HIDREAM_O1_GRAPH_SIZE = 32768;
diff --git a/src/model/diffusion/minimax_h3_reference.hpp b/src/model/diffusion/minimax_h3_reference.hpp
new file mode 100644
index 0000000..a54f7aa
--- /dev/null
+++ b/src/model/diffusion/minimax_h3_reference.hpp
@@ -0,0 +1,19 @@
+#ifndef __SD_MODEL_DIFFUSION_MINIMAX_H3_REFERENCE_HPP__
+#define __SD_MODEL_DIFFUSION_MINIMAX_H3_REFERENCE_HPP__
+
+#include <cstdint>
+
+enum class MiniMaxH3ReferenceKind : int32_t {
+ IMAGE,
+ VIDEO,
+ AUDIO,
+ VIDEO_AUDIO,
+};
+
+struct MiniMaxH3ReferenceBlock {
+ MiniMaxH3ReferenceKind kind = MiniMaxH3ReferenceKind::IMAGE;
+ int32_t video_index = -1;
+ int32_t audio_index = -1;
+};
+
+#endif // __SD_MODEL_DIFFUSION_MINIMAX_H3_REFERENCE_HPP__
diff --git a/src/model/diffusion/model.hpp b/src/model/diffusion/model.hpp
index 993624b..f9a3ae6 100644
--- a/src/model/diffusion/model.hpp
+++ b/src/model/diffusion/model.hpp
@@ -8,6 +8,7 @@
#include "core/ggml_runner.h"
#include "core/tensor_ggml.hpp"
#include "model/common/rope_circular.hpp"
+#include "model/diffusion/minimax_h3_reference.hpp"
#include "model_manager.h"
enum class UNetBlockStage { Down,
@@ -88,19 +89,6 @@ struct LTXAVDiffusionExtra {
const sd::Tensor<float>* audio_context = nullptr;
};
-enum class MiniMaxH3ReferenceKind : int32_t {
- IMAGE,
- VIDEO,
- AUDIO,
- VIDEO_AUDIO,
-};
-
-struct MiniMaxH3ReferenceBlock {
- MiniMaxH3ReferenceKind kind = MiniMaxH3ReferenceKind::IMAGE;
- int32_t video_index = -1;
- int32_t audio_index = -1;
-};
-
struct MiniMaxH3DiffusionExtra {
const sd::Tensor<int32_t>* text_token_tags = nullptr;
const sd::Tensor<int32_t>* keyframe_indices = nullptr;
diff --git a/src/model/integrations/boogu_image.cpp b/src/model/integrations/boogu_image.cpp
index e8c6e68..180c88d 100644
--- a/src/model/integrations/boogu_image.cpp
+++ b/src/model/integrations/boogu_image.cpp
@@ -1,4 +1,4 @@
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model/diffusion/boogu.hpp"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_boogu_image(const sd::model_builders::Context& ctx, const Toke
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- true,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ true,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Boogu::BooguImageRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/ernie_image.cpp b/src/model/integrations/ernie_image.cpp
index 9375b29..6dac1f7 100644
--- a/src/model/integrations/ernie_image.cpp
+++ b/src/model/integrations/ernie_image.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/ernie_image.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_ernie_image(const sd::model_builders::Context& ctx, const Toke
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- false,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ false,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<ErnieImage::ErnieImageRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/fibo2.cpp b/src/model/integrations/fibo2.cpp
index 82ef70f..38fc0c4 100644
--- a/src/model/integrations/fibo2.cpp
+++ b/src/model/integrations/fibo2.cpp
@@ -1,6 +1,5 @@
#include "model/diffusion/fibo2.hpp"
-#include "conditioning/conditioner.hpp"
-#include "conditioning/fibo2.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -10,8 +9,8 @@ static bool build_fibo2(const sd::model_builders::Context& ctx, const TokenizerC
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<Fibo2Conditioner>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map, weight_manager, tokenizers);
+ result.conditioner = sd::make_fibo2_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map, weight_manager, tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Fibo2::Fibo2Runner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/flux.cpp b/src/model/integrations/flux.cpp
index 2a84205..d70da35 100644
--- a/src/model/integrations/flux.cpp
+++ b/src/model/integrations/flux.cpp
@@ -1,5 +1,6 @@
#include "model/diffusion/flux.hpp"
#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model/integrations/flux.hpp"
#include "model_build_context.h"
#include "model_definition.h"
@@ -21,13 +22,12 @@ static bool build_flux(const sd::model_builders::Context& ctx, const TokenizerCo
}
} else if (version == VERSION_OVIS_IMAGE) {
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- false,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ false,
+ weight_manager,
+ tokenizers);
}
} else {
if (ctx.build_conditioner) {
diff --git a/src/model/integrations/flux2.cpp b/src/model/integrations/flux2.cpp
index 02a060a..abf7d71 100644
--- a/src/model/integrations/flux2.cpp
+++ b/src/model/integrations/flux2.cpp
@@ -1,4 +1,4 @@
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model/diffusion/flux.hpp"
#include "model/integrations/flux.hpp"
#include "model_build_context.h"
@@ -11,13 +11,12 @@ static bool build_flux2(const sd::model_builders::Context& ctx, const TokenizerC
const auto& weight_manager = ctx.weight_manager;
bool is_chroma = false;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- false,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ false,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Flux::FluxRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/flux3.cpp b/src/model/integrations/flux3.cpp
index 73db452..d15b989 100644
--- a/src/model/integrations/flux3.cpp
+++ b/src/model/integrations/flux3.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/flux3.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,8 +9,8 @@ static bool build_flux3(const sd::model_builders::Context& ctx, const TokenizerC
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map, version, "", false, weight_manager, tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map, version, false, weight_manager, tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Flux3::Flux3Runner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/hidream_o1.cpp b/src/model/integrations/hidream_o1.cpp
index ca56e02..a342602 100644
--- a/src/model/integrations/hidream_o1.cpp
+++ b/src/model/integrations/hidream_o1.cpp
@@ -1,5 +1,4 @@
#include "model/diffusion/hidream_o1.hpp"
-#include "conditioning/conditioner.hpp"
#include "model_build_context.h"
#include "model_definition.h"
diff --git a/src/model/integrations/hunyuan_video.cpp b/src/model/integrations/hunyuan_video.cpp
index 321a554..5b3a509 100644
--- a/src/model/integrations/hunyuan_video.cpp
+++ b/src/model/integrations/hunyuan_video.cpp
@@ -1,4 +1,4 @@
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model/diffusion/hunyuan.hpp"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_hunyuan_video(const sd::model_builders::Context& ctx, const To
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- false,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ false,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Hunyuan::HunyuanVideoRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/ideogram4.cpp b/src/model/integrations/ideogram4.cpp
index 0a63b81..cc4f124 100644
--- a/src/model/integrations/ideogram4.cpp
+++ b/src/model/integrations/ideogram4.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/ideogram4.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_ideogram4(const sd::model_builders::Context& ctx, const Tokeni
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- false,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ false,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Ideogram4::Ideogram4Runner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/iris.cpp b/src/model/integrations/iris.cpp
index ed638a2..0a93608 100644
--- a/src/model/integrations/iris.cpp
+++ b/src/model/integrations/iris.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/iris.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,8 +9,8 @@ static bool build_iris(const sd::model_builders::Context& ctx, const TokenizerCo
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map, version, "", false, weight_manager, tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map, version, false, weight_manager, tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Iris::IrisRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/krea2.cpp b/src/model/integrations/krea2.cpp
index 8560f97..00a64ed 100644
--- a/src/model/integrations/krea2.cpp
+++ b/src/model/integrations/krea2.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/krea2.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_krea2(const sd::model_builders::Context& ctx, const TokenizerC
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- true,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ true,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Krea2::Krea2Runner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/lens.cpp b/src/model/integrations/lens.cpp
index 5df9d52..4f70755 100644
--- a/src/model/integrations/lens.cpp
+++ b/src/model/integrations/lens.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/lens.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_lens(const sd::model_builders::Context& ctx, const TokenizerCo
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- false,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ false,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Lens::LensRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/lingbot_video.cpp b/src/model/integrations/lingbot_video.cpp
index e0319cc..3101101 100644
--- a/src/model/integrations/lingbot_video.cpp
+++ b/src/model/integrations/lingbot_video.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/lingbot_video.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -16,13 +16,12 @@ static bool build_lingbot_video(const sd::model_builders::Context& ctx, const To
}
}
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- enable_vision,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ enable_vision,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<LingBotVideo::LingBotVideoRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/longcat.cpp b/src/model/integrations/longcat.cpp
index d34fdc0..0a5887e 100644
--- a/src/model/integrations/longcat.cpp
+++ b/src/model/integrations/longcat.cpp
@@ -1,4 +1,4 @@
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model/diffusion/flux.hpp"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_longcat(const sd::model_builders::Context& ctx, const Tokenize
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- true,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ true,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Flux::FluxRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/mage_flow.cpp b/src/model/integrations/mage_flow.cpp
index 32660e6..89055c0 100644
--- a/src/model/integrations/mage_flow.cpp
+++ b/src/model/integrations/mage_flow.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/mage_flow.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_mage_flow(const sd::model_builders::Context& ctx, const Tokeni
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- true,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ true,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<MageFlow::MageFlowRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/minimax_h3.cpp b/src/model/integrations/minimax_h3.cpp
index e6ca906..0f7376e 100644
--- a/src/model/integrations/minimax_h3.cpp
+++ b/src/model/integrations/minimax_h3.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/minimax_h3.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_minimax_h3(const sd::model_builders::Context& ctx, const Token
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- true,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ true,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<MiniMaxH3::MiniMaxH3Runner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/moss_image.cpp b/src/model/integrations/moss_image.cpp
index 8226426..14ee4f2 100644
--- a/src/model/integrations/moss_image.cpp
+++ b/src/model/integrations/moss_image.cpp
@@ -1,6 +1,6 @@
#include "model_definition.h"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model/diffusion/moss_image.hpp"
#include "model_build_context.h"
@@ -8,9 +8,9 @@ static bool build_moss_image(const sd::model_builders::Context& ctx,
const TokenizerConfig& tokenizers,
sd::model_builders::CoreRunners& runners) {
if (ctx.build_conditioner) {
- runners.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- ctx.tensor_storage_map, ctx.version, "", true,
- ctx.weight_manager, tokenizers);
+ runners.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ ctx.tensor_storage_map, ctx.version, true,
+ ctx.weight_manager, tokenizers);
}
if (ctx.build_diffusion) {
runners.diffusion = std::make_shared<MOSSImage::MOSSImageRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/pid.cpp b/src/model/integrations/pid.cpp
index 5f0858d..c117bef 100644
--- a/src/model/integrations/pid.cpp
+++ b/src/model/integrations/pid.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/pid.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_pid(const sd::model_builders::Context& ctx, const TokenizerCon
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- false,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ false,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<Pid::PiDRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/qwen_image.cpp b/src/model/integrations/qwen_image.cpp
index c45c948..dcdc412 100644
--- a/src/model/integrations/qwen_image.cpp
+++ b/src/model/integrations/qwen_image.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/qwen_image.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model/diffusion/qwen_image_2_1.hpp"
#include "model_build_context.h"
#include "model_definition.h"
@@ -11,13 +11,12 @@ static bool build_qwen_image(const sd::model_builders::Context& ctx, const Token
const auto& weight_manager = ctx.weight_manager;
bool enable_vision = version != VERSION_QWEN_IMAGE_LAYERED;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- enable_vision,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ enable_vision,
+ weight_manager,
+ tokenizers);
}
if (version == VERSION_QWEN_IMAGE_2_1) {
if (ctx.build_diffusion) {
diff --git a/src/model/integrations/z_image.cpp b/src/model/integrations/z_image.cpp
index d3a40b9..2484d7a 100644
--- a/src/model/integrations/z_image.cpp
+++ b/src/model/integrations/z_image.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/z_image.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_z_image(const sd::model_builders::Context& ctx, const Tokenize
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- false,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ false,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<ZImage::ZImageRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model/integrations/z_image_l2p.cpp b/src/model/integrations/z_image_l2p.cpp
index fbcd22b..5cd5fff 100644
--- a/src/model/integrations/z_image_l2p.cpp
+++ b/src/model/integrations/z_image_l2p.cpp
@@ -1,5 +1,5 @@
#include "model/diffusion/z_image_l2p.hpp"
-#include "conditioning/conditioner.hpp"
+#include "conditioning/llm_conditioner.h"
#include "model_build_context.h"
#include "model_definition.h"
@@ -9,13 +9,12 @@ static bool build_z_image_l2p(const sd::model_builders::Context& ctx, const Toke
const auto version = ctx.version;
const auto& weight_manager = ctx.weight_manager;
if (ctx.build_conditioner) {
- result.conditioner = std::make_shared<LLMEmbedder>(ctx.backends.runtime_backend(SDBackendModule::TE),
- tensor_storage_map,
- version,
- "",
- false,
- weight_manager,
- tokenizers);
+ result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE),
+ tensor_storage_map,
+ version,
+ false,
+ weight_manager,
+ tokenizers);
}
if (ctx.build_diffusion) {
result.diffusion = std::make_shared<ZImageL2P::ZImageL2PRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),
diff --git a/src/model_manager.cpp b/src/model_manager.cpp
index 13f98e3..6a52159 100644
--- a/src/model_manager.cpp
+++ b/src/model_manager.cpp
@@ -592,7 +592,7 @@ bool ModelManager::load_all_params_eagerly(const Resource& resource) {
const auto devices = split_devices_for({state.get()});
const bool fits = !devices.empty() && std::all_of(devices.begin(), devices.end(), [&](const auto& device) {
return check_capacity({device.first, 0, device_bytes[device.first] + bytes + compute_reserve, 0, device.second}, {},
- DeviceMemoryCheck::Inspect)
+ DeviceMemoryCheck::Inspect)
.fits();
});
if (fits) {
diff --git a/src/runtime/preprocessing.hpp b/src/runtime/preprocessing.hpp
index da91e46..069e550 100644
--- a/src/runtime/preprocessing.hpp
+++ b/src/runtime/preprocessing.hpp
@@ -295,45 +295,4 @@ static inline void threshold_hystersis(sd::Tensor<float>* img, float high_thresh
}
}
-bool sd::preprocess_canny(sd::Image img, float high_threshold, float low_threshold, float weak, float strong, bool inverse) {
- float kX[9] = {
- -1, 0, 1,
- -2, 0, 2,
- -1, 0, 1};
-
- float kY[9] = {
- 1, 2, 1,
- 0, 0, 0,
- -1, -2, -1};
-
- sd::Tensor<float> gkernel = gaussian_kernel_tensor(5);
- sd::Tensor<float> sf_kx({3, 3, 1, 1}, std::vector<float>(kX, kX + 9));
- sd::Tensor<float> sf_ky({3, 3, 1, 1}, std::vector<float>(kY, kY + 9));
-
- sd::Tensor<float> image = sd_image_to_preprocessing_tensor(img);
- sd::Tensor<float> image_gray = grayscale_tensor(image);
- image_gray = convolve_tensor(image_gray, gkernel, 2);
- sd::Tensor<float> iX = convolve_tensor(image_gray, sf_kx, 1);
- sd::Tensor<float> iY = convolve_tensor(image_gray, sf_ky, 1);
- sd::Tensor<float> G = tensor_hypot(iX, iY);
- normalize_tensor(&G);
- sd::Tensor<float> theta = tensor_arctan2(iX, iY);
- image_gray = non_max_supression(G, theta);
- threshold_hystersis(&image_gray, high_threshold, low_threshold, weak, strong);
-
- const uint32_t color_channels = img.channel == 2 || img.channel == 4 ? img.channel - 1 : img.channel;
- for (uint32_t iy = 0; iy < img.height; ++iy) {
- for (uint32_t ix = 0; ix < img.width; ++ix) {
- float gray = preprocessing_get_4d(image_gray, ix, iy, 0, 0);
- gray = inverse ? 1.0f - gray : gray;
- for (uint32_t c = 0; c < color_channels; ++c) {
- preprocessing_set_4d(image, gray, ix, iy, c, 0);
- }
- }
- }
-
- preprocessing_tensor_to_sd_image(image, img.data);
- return true;
-}
-
#endif // __SD_RUNTIME_PREPROCESSING_HPP__