Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,12 @@ jobs:
SD_FP8_TARGET: ${{ matrix.target }}
SD_REQUIRE_RUNTIME: "1"
GGML_VK_VISIBLE_DEVICES: "0"
- name: Required LoRAs
if: runner.os != 'Windows' && matrix.smoke
run: python3 -m unittest discover -s tests -p test_lora_required_runtime.py -v
env:
SD_LORA_REQUIRED_TARGET: ${{ matrix.target }}
SD_REQUIRE_RUNTIME: "1"
- name: Split graph evaluation
# Metal needs a Mac: GitHub's macOS runners list no Metal device.
if: runner.os != 'Windows' && matrix.smoke
Expand Down Expand Up @@ -302,6 +308,12 @@ jobs:
SD_FP8_TARGET: macos-arm64
SD_REQUIRE_RUNTIME: "1"
GGML_VK_VISIBLE_DEVICES: "0"
- name: Required LoRAs
if: matrix.first == 'macos-arm64'
run: python3 -m unittest discover -s tests -p test_lora_required_runtime.py -v
env:
SD_LORA_REQUIRED_TARGET: macos-arm64
SD_REQUIRE_RUNTIME: "1"
- name: Split graph evaluation
# Metal needs a Mac: GitHub's macOS runners list no Metal device.
if: matrix.first == 'macos-arm64'
Expand Down
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ sd_native_carry_patch(fp8_metal_f16_load.patch src/model_manager.cpp src/core/ba
sd_native_carry_patch(lora_immediate_fallback.patch src/pipeline/diffusion_engine.cpp)
sd_native_carry_patch(intrinsic_tiny_decoder_policy.patch src/stable-diffusion.cpp src/pipeline/diffusion_engine.cpp)
sd_native_carry_patch(loader_scratch_vm_allocate.patch src/model_loader.cpp)
sd_native_carry_patch(lora_required_v1.patch src/model_manager.cpp src/model_manager_files.cpp src/pipeline/diffusion_engine.cpp src/stable-diffusion.cpp)
execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${SD_NATIVE_UPSTREAM_DIR}/ggml" rev-parse HEAD
OUTPUT_VARIABLE ggml_commit OUTPUT_STRIP_TRAILING_WHITESPACE RESULT_VARIABLE ggml_revision_result)
if(NOT ggml_revision_result EQUAL 0)
Expand Down
37 changes: 35 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -663,8 +663,9 @@ The fixed master-1104 source candidate has its
[migration decisions, ABI proof and pending qualification gates](docs/upstream_1104_qualification.md).
The [1017 record](docs/upstream_1017_qualification.md) and
[982 inventory](docs/upstream_982_qualification.md) preserve earlier evidence.
Six [owned patches](patches/README.md) remain applied: pickle spans, ZIP lookup,
FP8 load/fit, LoRA fallback, intrinsic tiny-decoder policy and loader scratch.
Seven [owned patches](patches/README.md) remain applied: pickle spans, ZIP lookup,
FP8 load/fit, LoRA fallback, intrinsic tiny-decoder policy, loader scratch and
required LoRAs.
The two ggml Apple allocator backports remain historical controls; this exact
candidate selects upstream's equivalent allocation/free sources experimentally.
They are not declared retired: original iOS causal qualification is pending.
Expand Down Expand Up @@ -779,5 +780,37 @@ SD_FULL_VAE_MODEL=<sd-turbo.gguf> python3 -m unittest discover -s tests
refuses the SDXS-to-SD-Turbo replacement, and keeps an unrestricted reload
control on CPU and the available Metal backend.

### Required LoRAs

`sd_dart_generate_image_required_loras_v1(ctx, params, images, count)` is
`sd_dart_generate_image()` for a caller that must not get an image without
the LoRAs it asked for. stable-diffusion.cpp warns and generates without a
LoRA that cannot be registered or loaded, has no tensor for any model
component, or changes no weight because its tensors match no model tensor or
only incompatible shapes. This export fails the generation instead, with no
images, and `sd_dart_last_error()` names the LoRA's path. "Applied" means a
LoRA tensor met a compatible model weight: a LoRA that applied some of its
tensors passes, and so does one at multiplier 0.

The verdict follows what upstream applies in each mode. Immediately, a LoRA
is merged into each weight as its component loads; at runtime it is used in
the conditioner and diffusion graphs and the full VAE, never the TAESD. So a
TAESD-only LoRA passes immediately and is refused at runtime.
A LoRA that cannot be registered (missing, or tensors past the end of the
file) fails before sampling in both modes, and so does one that at runtime
fails to load or has no tensor for any component. Applied immediately, a LoRA
is loaded as each component loads, so one that fails to load, has no tensors
or matches nothing fails only after the generation: its progress reports are
recorded by then, so go by the return value. A LoRA file or model file
replaced in place is checked again on the next call.

A context can switch between this export and `sd_dart_generate_image()` with
the same LoRAs without applying them again. The versioned export is the
capability probe; this is the owner prerequisite for
[llamadart #1223](https://github.com/leehack/llamadart/issues/1223). Run
`SD_LORA_REQUIRED_TARGET=<target> python3 -m unittest discover -s tests
-p test_lora_required_runtime.py`; it builds its model and LoRAs, nothing is
downloaded. CI runs it on the smoke targets.

The full-VAE iPhone decode is addressed by the graph split ("Graph
splitting"), which the same issue qualifies on a physical iPhone.
4 changes: 3 additions & 1 deletion patches/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ reports.

| `loader_scratch_vm_allocate.patch` | `src/model_loader.cpp` | On iOS 18 the loader's per-thread read, convert and zip scratch vectors and `convert_tensor`'s buffer leave about 240 MiB in libmalloc's cache after an unload, which still counts toward the jetsam limit ([llamadart #2004](https://github.com/leehack/llamadart/issues/2004)). On Apple they come from `vm_allocate`/`vm_deallocate`; other platforms keep `std::vector`. **Patch-specific maintainer exception:** no upstream report is filed; [owner #45](https://github.com/leehack/stable-diffusion-native/issues/45) tracks retirement until one is authorized. Retire when upstream's loader no longer takes tensor-sized scratch from the heap on Apple. | `tests/test_loader_scratch_runtime.py` |

| `lora_required_v1.patch` | `src/model_manager.cpp`, `src/pipeline/diffusion_engine.cpp`, `src/stable-diffusion.cpp` | Owner-only `sd_dart_generate_image_required_loras_v1` contract for [llamadart #1223](https://github.com/leehack/llamadart/issues/1223), not an upstream defect: upstream skips a LoRA it cannot use with a warning, and its public `sd_lora_t` has no `required` field. The caller's LoRAs are marked required (upstream's internal flag, set until now only by conversion and PhotoMaker), a register failure names the path, a runtime LoRA with no tensor for any component fails before sampling, and a generation whose LoRA changed no weight in either apply mode fails after it. Applied immediately, the caller's LoRAs are required only to register: upstream fails a required LoRA that does not load in the middle of a component's compute, where the conditioner then aborts. Immediate counts belong to the LoRA epoch; upstream starts one when a LoRA file changes, and `ModelManager::set_loader()` also starts one when a model file is replaced in place while LoRAs are set, so its LoRAs are merged and counted again. Retire when upstream's C API can require a LoRA. | `tests/test_lora_required_runtime.py` |

Patches touching the same source compose in declaration order. Each next
patch applies to the preceding build-tree copy; the submodule stays pristine.

## Master-1104 candidate selection

The six non-ggml patches above remain applied. LoRA and tiny-decoder insertion
The seven non-ggml patches above remain applied. LoRA and tiny-decoder insertion
contexts are rebased without dropping candidate packed-INT4 checks or owner
policy checks. E4M3 Metal rejection in ggml is only partial FP8 overlap:
E5M2, all-backend FP8 LoRA, effective-F16 fit and runtime value/layout controls
Expand Down
264 changes: 264 additions & 0 deletions patches/lora_required_v1.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
--- a/src/model_manager.cpp
+++ b/src/model_manager.cpp
@@ -4,6 +4,7 @@
#include <cstdint>
#include <cstring>
#include <iterator>
+#include <map>
#include <mutex>
#include <tuple>
#include <unordered_set>
@@ -102,9 +103,69 @@
return supported;
}

+// sd_dart_generate_image_required_loras_v1() (patches/lora_required_v1.patch):
+// how many tensors each LoRA applied immediately in the manager's current LoRA
+// epoch. A weight merged in an earlier generation stays merged until the epoch
+// changes, so the count is kept across generations of one epoch. A changed LoRA
+// set or LoRA file starts a new epoch upstream; a model file replaced in place
+// does too, through this patch's check in ModelManager::set_loader(). The
+// count resets before the first merge attempt of the new epoch, even if the
+// LoRA fails to load or has no tensors.
+namespace {
+struct LoraApplied {
+ uint64_t epoch = 0;
+ size_t count = 0;
+};
+
+struct LoraAppliedCounts {
+ std::mutex mutex;
+ std::map<std::pair<std::uintptr_t, ModelLoader::FileId>, LoraApplied> counts;
+};
+
+std::uintptr_t manager_key(const ModelManager* manager) {
+ return reinterpret_cast<std::uintptr_t>(manager);
+}
+
+LoraAppliedCounts& lora_applied_counts() {
+ // Never destroyed: a generation can still run while exit() destroys statics.
+ static auto* value = new LoraAppliedCounts();
+ return *value;
+}
+
+void forget_lora_applied_counts(const ModelManager* manager) {
+ auto& state = lora_applied_counts();
+ std::lock_guard<std::mutex> lock(state.mutex);
+ const std::uintptr_t key = manager_key(manager);
+ auto it = state.counts.lower_bound({key, ModelLoader::FileId{}});
+ while (it != state.counts.end() && it->first.first == key) {
+ it = state.counts.erase(it);
+ }
+}
+} // namespace
+
+// The LoRA tensors that changed a model weight: applied, less those skipped as
+// incompatible with the weight's shape.
+size_t sd_dart_lora_tensors_applied(const LoraModel& lora) {
+ size_t applied = 0;
+ for (const auto& name : lora.applied_lora_tensors) {
+ if (lora.skipped_incompatible_lora_tensors.count(name) == 0) {
+ applied++;
+ }
+ }
+ return applied;
+}
+
+size_t sd_dart_lora_tensors_applied_immediately(const ModelManager* manager, ModelLoader::FileId file_id) {
+ auto& state = lora_applied_counts();
+ std::lock_guard<std::mutex> lock(state.mutex);
+ const auto found = state.counts.find({manager_key(manager), file_id});
+ return found == state.counts.end() ? 0 : found->second.count;
+}
+
ModelManager::~ModelManager() {
release_all();
release_prefetch();
+ forget_lora_applied_counts(this);
}

void ModelManager::set_common_ignore_tensors(std::set<std::string> ignore_tensors) {
@@ -118,8 +179,10 @@
for (auto spec : loras) {
const std::string prefix = spec.is_high_noise ? "lora.model.high_noise_" : "lora.";
if (!candidate.add_file(spec.path, prefix, &spec.file_id, false, ModelLoader::FileScope::Isolated)) {
- if (spec.required)
+ if (spec.required) {
+ LOG_ERROR("cannot register required LoRA source '%s'", spec.path.c_str());
return false;
+ }
LOG_WARN("cannot register LoRA source '%s'", spec.path.c_str());
continue;
}
@@ -158,6 +221,7 @@
loras_ = std::move(loras);
lora_version_ = version;
current_lora_epoch_++;
+ forget_lora_applied_counts(this);
reset_lora_applied_params();
return true;
}
@@ -736,6 +800,14 @@
if (group.model_tensors.empty()) {
continue;
}
+ {
+ auto& state = lora_applied_counts();
+ std::lock_guard<std::mutex> lock(state.mutex);
+ LoraApplied& entry = state.counts[{manager_key(this), lora_spec.file_id}];
+ if (entry.epoch != current_lora_epoch_) {
+ entry = {current_lora_epoch_, 0};
+ }
+ }

std::string id = lora_id(lora_spec);
const auto* target = group.states.front();
@@ -768,6 +840,12 @@
lora->multiplier = lora_spec.multiplier;
if (!lora->apply(group.model_tensors, all_tensor_names, lora_version_, n_threads_, false))
return false;
+ {
+ auto& state = lora_applied_counts();
+ std::lock_guard<std::mutex> lock(state.mutex);
+ LoraApplied& entry = state.counts[{manager_key(this), lora_spec.file_id}];
+ entry.count += sd_dart_lora_tensors_applied(*lora);
+ }
lora->release_loaded_tensors();
}

--- a/src/model_manager_files.cpp
+++ b/src/model_manager_files.cpp
@@ -97,6 +97,19 @@
for (const auto& spec : loras_) {
lora_changed |= loader.file_revision(spec.file_id) != spec.file_revision;
}
+ // sd_dart_generate_image_required_loras_v1() (patches/lora_required_v1.patch)
+ // counts each LoRA's tensors per LoRA epoch. A model file replaced in place
+ // can match a LoRA differently, so it starts a new epoch too: the weights
+ // are merged again and counted again.
+ if (!loras_.empty()) {
+ for (const auto& entry : model_loader_.file_versions()) {
+ const ModelLoader::FileId id = entry.first;
+ const uint64_t revision = loader.file_revision(id);
+ if (lora_sources_.count(id) == 0 && revision != 0 && revision != entry.second) {
+ lora_changed = true;
+ }
+ }
+ }
std::unordered_set<TensorState*> changed;
for (const auto& state : tensor_states_) {
const auto sources = find_tensor_sources(*state, sources_for(*state));
--- a/src/pipeline/diffusion_engine.cpp
+++ b/src/pipeline/diffusion_engine.cpp
@@ -1880,8 +1880,47 @@
}
}

+// Implemented by the owner wrapper and patches/lora_required_v1.patch.
+bool sd_dart_required_loras_active();
+size_t sd_dart_lora_tensors_applied(const LoraModel& lora);
+size_t sd_dart_lora_tensors_applied_immediately(const ModelManager* manager, ModelLoader::FileId file_id);
+
+// The caller's LoRAs of a sd_dart_generate_image_required_loras_v1() call are
+// the first `lora_count` entries of conditioning_loras_.
+static bool runtime_lora_has_tensors(const StableDiffusionGGML& sd, const ModelManager::LoraSpec& spec) {
+ return std::any_of(sd.runtime_lora_models.begin(), sd.runtime_lora_models.end(), [&](const auto& entry) {
+ return entry.model != nullptr && entry.matches(spec);
+ });
+}
+
+bool sd_dart_required_loras_applied(const StableDiffusionGGML& sd, uint32_t lora_count) {
+ if (sd.conditioning_loras_.size() < lora_count) {
+ LOG_ERROR("required LoRAs: %zu of %u resolved", sd.conditioning_loras_.size(), lora_count);
+ return false;
+ }
+ for (uint32_t i = 0; i < lora_count; i++) {
+ const auto& spec = sd.conditioning_loras_[i];
+ size_t applied = 0;
+ if (sd.apply_lora_immediately) {
+ applied = sd_dart_lora_tensors_applied_immediately(sd.model_manager.get(), spec.file_id);
+ } else {
+ for (const auto& entry : sd.runtime_lora_models) {
+ if (entry.model != nullptr && entry.matches(spec)) {
+ applied += sd_dart_lora_tensors_applied(*entry.model);
+ }
+ }
+ }
+ if (applied == 0) {
+ LOG_ERROR("required LoRA applied no tensor to the model: %s", spec.path.c_str());
+ return false;
+ }
+ }
+ return true;
+}
+
bool StableDiffusionGGML::apply_loras(const sd_lora_t* loras, uint32_t lora_count) {
generation_progress.report("preparing", "loras");
+ const bool loras_required = sd_dart_required_loras_active();
std::vector<ModelManager::LoraSpec> all_loras;
all_loras.reserve(lora_count);
for (uint32_t i = 0; i < lora_count; i++) {
@@ -1890,6 +1929,7 @@
lora_spec.path = lora_id;
lora_spec.multiplier = loras[i].multiplier;
lora_spec.is_high_noise = loras[i].is_high_noise;
+ lora_spec.required = loras_required;
all_loras.push_back(std::move(lora_spec));
if (loras[i].is_high_noise) {
lora_id = "|high_noise|" + lora_id;
@@ -1908,6 +1948,13 @@
conditioning_cache_->clear();
return false;
}
+ // Applied immediately, a LoRA loads in the middle of a component's compute,
+ // where a required one that fails to load aborts the process
+ // (GGML_ASSERT in the conditioner). There the caller's LoRAs are required
+ // only to register; one that loads no tensor fails after the generation.
+ for (uint32_t i = 0; loras_required && apply_lora_immediately && i < lora_count && i < all_loras.size(); i++) {
+ all_loras[i].required = false;
+ }
if (!std::equal(all_loras.begin(), all_loras.end(),
conditioning_loras_.begin(), conditioning_loras_.end(),
[](const ModelManager::LoraSpec& a, const ModelManager::LoraSpec& b) {
@@ -1923,8 +1970,16 @@
});
}),
runtime_lora_models.end());
- const bool success = apply_lora_immediately ? apply_loras_immediately(all_loras)
- : apply_loras_at_runtime(all_loras);
+ bool success = apply_lora_immediately ? apply_loras_immediately(all_loras)
+ : apply_loras_at_runtime(all_loras);
+ // At runtime a LoRA is loaded per component, and one with no tensor for
+ // any component is skipped even when required.
+ for (uint32_t i = 0; success && loras_required && !apply_lora_immediately && i < lora_count; i++) {
+ if (!runtime_lora_has_tensors(*this, all_loras[i])) {
+ LOG_ERROR("required LoRA has no tensor for any model component: %s", all_loras[i].path.c_str());
+ success = false;
+ }
+ }
if (!success) {
conditioning_cache_->clear();
clear_lora_adapters();
--- a/src/stable-diffusion.cpp
+++ b/src/stable-diffusion.cpp
@@ -15,6 +15,9 @@
// Implemented by the owner wrapper; policy state outlives C exit teardown.
bool sd_dart_intrinsic_tiny_required(const void* engine);
void sd_dart_set_intrinsic_tiny_required(const void* engine, bool required);
+// patches/lora_required_v1.patch
+bool sd_dart_required_loras_active();
+bool sd_dart_required_loras_applied(const StableDiffusionGGML& sd, uint32_t lora_count);

#define NONE_STR "NONE"

@@ -874,6 +877,10 @@
free_sd_images(images, count);
return false;
}
+ if (sd_dart_required_loras_active() && !sd_dart_required_loras_applied(*sd_ctx->sd, params->lora_count)) {
+ free_sd_images(images, count);
+ return false;
+ }
} catch (const std::exception& e) {
LOG_ERROR("image generation failed: %s", e.what());
free_sd_images(images, count);
Loading
Loading