Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc6a0723a5 | ||
|
|
6184b74809 | ||
|
|
9948cb3433 | ||
|
|
6cb9bbe868 | ||
|
|
561b73630c | ||
|
|
51efa670e0 | ||
|
|
d188a3764b | ||
|
|
f1d0630729 | ||
|
|
0cd1032073 | ||
|
|
d01b085082 | ||
|
|
0583ba2675 | ||
|
|
dcc37d7ab6 | ||
|
|
583b22a4bf | ||
|
|
ebe01efc49 | ||
|
|
41e8a2b61c | ||
|
|
22e4a5d202 | ||
|
|
017e3fc7fe |
@@ -0,0 +1,13 @@
|
||||
.github/
|
||||
tests/
|
||||
tools/
|
||||
scripts/
|
||||
web/src/
|
||||
web/tests/
|
||||
AGENTS.md
|
||||
.releaserc.cjs
|
||||
eslint.config.js
|
||||
package-lock.json
|
||||
package.json
|
||||
tsconfig.json
|
||||
vitest.config.ts
|
||||
@@ -1,3 +1,59 @@
|
||||
# [1.10.0](https://github.com/Artificial-Sweetener/SimpleSyrup/compare/v1.9.3...v1.10.0) (2026-09-21)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **loaders:** add Krea 2 model loader ([166f029](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/166f029d12e5fce019133cc38be7279d05a5ecbc))
|
||||
|
||||
## [1.9.3](https://github.com/Artificial-Sweetener/SimpleSyrup/compare/v1.9.2...v1.9.3) (2026-09-20)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **attention-coupling:** restore regional LoRA sampling ([0255a0f](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/0255a0f5044278f14452b6b2582ec6646083f756))
|
||||
|
||||
## [1.9.2](https://github.com/Artificial-Sweetener/SimpleSyrup/compare/v1.9.1...v1.9.2) (2026-09-20)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **registry:** remove flagged package content ([f3a53b5](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/f3a53b5ec6c080d98f7e9599cf55e849cf338021))
|
||||
|
||||
## [1.9.1](https://github.com/Artificial-Sweetener/SimpleSyrup/compare/v1.9.0...v1.9.1) (2026-09-20)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **contextual-diffusion:** project reference latents into views ([4cd780a](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/4cd780a2451aa472ce826834e4426b65693c46e8))
|
||||
|
||||
# [1.9.0](https://github.com/Artificial-Sweetener/SimpleSyrup/compare/v1.8.0...v1.9.0) (2026-09-19)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **prompts:** add automatic NegPiP support ([6d052e9](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/6d052e9800985696972bf431fa7dae4972a56313))
|
||||
|
||||
# [1.8.0](https://github.com/Artificial-Sweetener/SimpleSyrup/compare/v1.7.1...v1.8.0) (2026-09-19)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **downloads:** keep unknown sizes indeterminate ([a31467c](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/a31467cd3a4299e9e3929d44281018dba0322b3e))
|
||||
* **models:** hide installed catalog choices ([d887e87](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/d887e87e03eb6d0d9d5325fe43b67fbd9e47cf71))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **models:** add curated ultralytics downloads ([b907fa2](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/b907fa2a17afa30170bc22cf1134a750241e55c2))
|
||||
* **models:** prioritize installed ultralytics choices ([d30e04f](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/d30e04f229366d3e1d2388bd4d713b2b47a12a1f))
|
||||
|
||||
## [1.7.1](https://github.com/Artificial-Sweetener/SimpleSyrup/compare/v1.7.0...v1.7.1) (2026-09-11)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **regional:** preserve shared model patch ancestry ([6059a3f](https://github.com/Artificial-Sweetener/SimpleSyrup/commit/6059a3f913a9502671666e83faeb8686a7a8da27))
|
||||
|
||||
# [1.7.0](https://github.com/Artificial-Sweetener/SimpleSyrup/compare/v1.6.0...v1.7.0) (2026-09-05)
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ The pack now covers model loading, regional prompting and segmentation, high-res
|
||||
|
||||
## Highlights
|
||||
|
||||
- Loaders that keep checkpoints, Anima, FLUX.1, and FLUX.2 models together with the text encoders, VAE, precision, and device choices they need.
|
||||
- Loaders that keep checkpoints, Anima, FLUX.1, FLUX.2, and Krea 2 models together with the text encoders, VAE, precision, and device choices they need.
|
||||
- My original Contextual Diffusion method for coherent high-resolution edits, plus MultiDiffusion and Mixture of Diffusers tiled sampling.
|
||||
- Impact-compatible SEGS detection, segmentation, interactive preview, batching, and detailers.
|
||||
- ADetailer-style `[SEP]` prompt batches, masked conditioning, and regional samplers, with optional Prompt Control scheduling and LoRA hooks.
|
||||
@@ -74,7 +74,9 @@ Loading a checkpoint used to feel like choosing one file. Newer model families c
|
||||
|
||||
**Simple Load FLUX** handles FLUX.1 with CLIP-L, T5-XXL, and its VAE. **Simple Load FLUX.2** inspects the selected diffusion model and chooses the matching text encoder family for FLUX.2 dev, Klein 4B, or Klein 9B/KV conditioning. Both loaders can find or download their known text encoders and VAEs with visible Comfy progress.
|
||||
|
||||
The FLUX loaders only download those revision-locked, checksum-pinned support files. You still install and select the diffusion model. They also expose manual component selection, diffusion weight precision, and text-encoder device placement. Moving text encoding to the CPU can save VRAM, although it will take longer.
|
||||
**Simple Load Krea 2** validates the selected Raw or Turbo diffusion model and loads the required Qwen3-VL 4B encoder with Krea's layered conditioning plus the Qwen Image VAE. Auto uses the official FP8-scaled encoder; the advanced encoder choice can download either the checksum-pinned FP8-scaled or BF16 file.
|
||||
|
||||
The FLUX and Krea 2 loaders only download those revision-locked, checksum-pinned support files. You still install and select the diffusion model. They also expose manual component selection, diffusion weight precision, and text-encoder device placement. Moving text encoding to the CPU can save VRAM, although it will take longer.
|
||||
|
||||
## Large images and high-resolution edits
|
||||
|
||||
@@ -164,7 +166,7 @@ SimpleSyrup adds three ComfyUI settings:
|
||||
- **SimpleSyrup: External LLM endpoint** stores the OpenAI-compatible base URL used to discover provider models and run the external prompt nodes.
|
||||
- **SimpleSyrup: External LLM API key** stores the provider key in OS credential storage.
|
||||
|
||||
With downloadable models enabled, selecting a known missing catalog entry lets its loader download the required files. With the setting disabled, the dropdowns contain models SimpleSyrup can verify locally. Anima, FLUX.1, and FLUX.2 support components are resolved by their own loaders and use checksum-pinned automatic choices.
|
||||
With downloadable models enabled, selecting a known missing catalog entry lets its loader download the required files. With the setting disabled, the dropdowns contain models SimpleSyrup can verify locally. Anima, FLUX.1, FLUX.2, and Krea 2 support components are resolved by their own loaders and use checksum-pinned automatic choices. Automatic resolution checks cached and official paths first, then recognizes renamed files with matching size and checksum inside the appropriate ComfyUI model category. Known local support files are represented by their automatic choice instead of appearing again as manual dropdown entries.
|
||||
|
||||
Saving the external LLM endpoint and API key refreshes the provider models available in connected SimpleSyrup nodes. Image inputs require a provider model with vision support.
|
||||
|
||||
@@ -189,6 +191,7 @@ SimpleSyrup owes a lot to other projects:
|
||||
- [ComfyUI Layer Style Advance](https://github.com/chflame163/ComfyUI_LayerStyle_Advance) provides the SAM model bundle SimpleSyrup can adapt.
|
||||
- [Tiled Diffusion & VAE for AUTOMATIC1111](https://github.com/pkuliyi2015/multidiffusion-upscaler-for-automatic1111) informed the practical tiled diffusion and Mixture of Diffusers behavior reimplemented here.
|
||||
- [RES4LYF](https://github.com/ClownsharkBatwing/RES4LYF) is the source of the beta57 scheduler preset reimplemented here.
|
||||
- [ComfyUI-ppm](https://github.com/pamparamm/ComfyUI-ppm) by pamparamm provides the ModelPatcher-based NegPiP behavior adapted here and builds on the [ComfyUI port](https://github.com/laksjdjf/cd-tuner_negpip-ComfyUI) by laksjdjf and the [original WebUI implementation](https://github.com/hako-mikan/sd-webui-negpip) by hako-mikan.
|
||||
|
||||
SimpleSyrup also vendors or reimplements selected third-party behavior for SAM-HQ, MobileSAM, GroundingDINO, AUTOMATIC1111 sampler behavior, k-diffusion, and tiled diffusion. See [third_party/NOTICE.md](third_party/NOTICE.md) for the complete notices.
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "simple-syrup-comfyui",
|
||||
"version": "1.7.0",
|
||||
"version": "1.10.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "simple-syrup-comfyui",
|
||||
"version": "1.7.0",
|
||||
"version": "1.10.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "simple-syrup-comfyui",
|
||||
"version": "1.7.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"type": "module",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
|
||||
[project]
|
||||
name = "SimpleSyrup"
|
||||
description = "Workflow-focused ComfyUI extensions for image generation."
|
||||
version = "1.7.0"
|
||||
version = "1.10.0"
|
||||
license = "AGPL-3.0-or-later"
|
||||
license-files = ["LICENSE"]
|
||||
requires-python = ">=3.11"
|
||||
|
||||
@@ -6,6 +6,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "1.7.0"
|
||||
__version__ = "1.10.0"
|
||||
|
||||
__all__: list[str] = ["__version__"]
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Detect effective negative weights in Comfy-style prompt emphasis."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _WeightedPromptSegment:
|
||||
"""Retain one parsed prompt fragment and its effective scalar weight."""
|
||||
|
||||
text: str
|
||||
weight: float
|
||||
|
||||
|
||||
def contains_negative_prompt_weight(text: str) -> bool:
|
||||
"""Return whether valid nested emphasis gives any prompt text a negative weight."""
|
||||
|
||||
if not isinstance(text, str):
|
||||
raise TypeError("Negative prompt-weight detection requires text.")
|
||||
escaped = text.replace(r"\)", "\0\1").replace(r"\(", "\0\2")
|
||||
return any(
|
||||
segment.text and segment.weight < 0.0
|
||||
for segment in _weighted_segments(escaped, 1.0)
|
||||
)
|
||||
|
||||
|
||||
def _weighted_segments(
|
||||
text: str,
|
||||
current_weight: float,
|
||||
) -> tuple[_WeightedPromptSegment, ...]:
|
||||
"""Parse emphasis with the same nesting and final-colon rules as ComfyUI."""
|
||||
|
||||
parsed: list[_WeightedPromptSegment] = []
|
||||
for item in _parenthesized_items(text):
|
||||
weight = current_weight
|
||||
if len(item) >= 2 and item[0] == "(" and item[-1] == ")":
|
||||
inner = item[1:-1]
|
||||
delimiter = inner.rfind(":")
|
||||
weight *= 1.1
|
||||
if delimiter > 0:
|
||||
try:
|
||||
weight = float(inner[delimiter + 1 :])
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
inner = inner[:delimiter]
|
||||
parsed.extend(_weighted_segments(inner, weight))
|
||||
continue
|
||||
parsed.append(
|
||||
_WeightedPromptSegment(
|
||||
item.replace("\0\1", ")").replace("\0\2", "("),
|
||||
current_weight,
|
||||
)
|
||||
)
|
||||
return tuple(parsed)
|
||||
|
||||
|
||||
def _parenthesized_items(text: str) -> tuple[str, ...]:
|
||||
"""Split top-level parenthesized regions while preserving malformed input."""
|
||||
|
||||
result: list[str] = []
|
||||
current = ""
|
||||
nesting = 0
|
||||
for character in text:
|
||||
if character == "(":
|
||||
if nesting == 0:
|
||||
if current:
|
||||
result.append(current)
|
||||
current = "("
|
||||
else:
|
||||
current += character
|
||||
nesting += 1
|
||||
elif character == ")":
|
||||
nesting -= 1
|
||||
if nesting == 0:
|
||||
result.append(f"{current})")
|
||||
current = ""
|
||||
else:
|
||||
current += character
|
||||
else:
|
||||
current += character
|
||||
if current:
|
||||
result.append(current)
|
||||
return tuple(result)
|
||||
@@ -30,6 +30,7 @@ class ProcessedRegionalAttentionEntry:
|
||||
schedule: ConditioningScheduleRange
|
||||
cross_attention: torch.Tensor
|
||||
strength: float
|
||||
cross_attention_value_multiplier: torch.Tensor | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Validate entry order, model context, and finite scalar strength."""
|
||||
@@ -62,6 +63,21 @@ class ProcessedRegionalAttentionEntry:
|
||||
if not math.isfinite(float(self.strength)):
|
||||
raise ValueError("Processed conditioning strength must be finite.")
|
||||
object.__setattr__(self, "strength", float(self.strength))
|
||||
multiplier = self.cross_attention_value_multiplier
|
||||
if multiplier is None:
|
||||
return
|
||||
if (
|
||||
not isinstance(multiplier, torch.Tensor)
|
||||
or multiplier.shape != (*self.cross_attention.shape[:2], 1)
|
||||
or not multiplier.is_floating_point()
|
||||
or multiplier.device != self.cross_attention.device
|
||||
or multiplier.dtype != self.cross_attention.dtype
|
||||
or not bool(torch.isfinite(multiplier).all().item())
|
||||
):
|
||||
raise ValueError(
|
||||
"Processed attention value multiplier must be a finite floating "
|
||||
"BxSx1 tensor aligned with cross_attention."
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
||||
@@ -48,6 +48,7 @@ class BatchedRegionalAttentionEntry:
|
||||
entry_index: int
|
||||
context: torch.Tensor
|
||||
strengths: tuple[float, ...]
|
||||
cross_attention_value_multiplier: torch.Tensor | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Validate entry order, aligned context, and finite sample strengths."""
|
||||
@@ -70,6 +71,11 @@ class BatchedRegionalAttentionEntry:
|
||||
)
|
||||
if not math.isfinite(float(strength)):
|
||||
raise ValueError("Regional attention entry strength must be finite.")
|
||||
_validate_value_multiplier(
|
||||
self.cross_attention_value_multiplier,
|
||||
self.context,
|
||||
name="entry",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -109,6 +115,7 @@ class BatchedRegionalAttentionContexts:
|
||||
chunks: tuple[RegionalAttentionChunkBatch, ...]
|
||||
base_context: torch.Tensor
|
||||
regions: tuple[BatchedRegionalAttentionRegion, ...]
|
||||
base_value_multiplier: torch.Tensor | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Validate complete chunk and tensor alignment."""
|
||||
@@ -141,6 +148,11 @@ class BatchedRegionalAttentionContexts:
|
||||
expected_batch=expected_start,
|
||||
name="base",
|
||||
)
|
||||
_validate_value_multiplier(
|
||||
self.base_value_multiplier,
|
||||
self.base_context,
|
||||
name="base",
|
||||
)
|
||||
if not isinstance(self.regions, tuple):
|
||||
raise TypeError("Regional attention regions must be a tuple.")
|
||||
if tuple(region.region_index for region in self.regions) != tuple(
|
||||
@@ -189,3 +201,27 @@ def _validate_aligned_context(
|
||||
raise ValueError(
|
||||
f"Regional attention {name} context must contain finite floating values."
|
||||
)
|
||||
|
||||
|
||||
def _validate_value_multiplier(
|
||||
multiplier: object,
|
||||
context: torch.Tensor,
|
||||
*,
|
||||
name: str,
|
||||
) -> None:
|
||||
"""Validate one optional value multiplier against its aligned context."""
|
||||
|
||||
if multiplier is None:
|
||||
return
|
||||
if (
|
||||
not isinstance(multiplier, torch.Tensor)
|
||||
or multiplier.shape != (*context.shape[:2], 1)
|
||||
or not multiplier.is_floating_point()
|
||||
or multiplier.device != context.device
|
||||
or multiplier.dtype != context.dtype
|
||||
or not bool(torch.isfinite(multiplier).all().item())
|
||||
):
|
||||
raise ValueError(
|
||||
f"Regional attention {name} value multiplier must be a finite "
|
||||
"floating BxSx1 tensor aligned with its context."
|
||||
)
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from ..runtime.model_catalog import grounding_dino_choices, sam_choices
|
||||
from ..runtime.model_choices import ModelChoiceService, default_choice
|
||||
from ..runtime.model_metadata import GroundedSAMModelMetadata
|
||||
from . import tooltips
|
||||
|
||||
@@ -17,6 +17,7 @@ class GroundedSAMModelInfo:
|
||||
"""Expose selected grounded SAM source and local path metadata."""
|
||||
|
||||
_metadata = GroundedSAMModelMetadata()
|
||||
_choices = ModelChoiceService()
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("model_info",)
|
||||
@@ -31,19 +32,27 @@ class GroundedSAMModelInfo:
|
||||
def INPUT_TYPES(cls) -> dict[str, dict[str, tuple[Any, ...]]]:
|
||||
"""Declare deterministic model metadata inputs."""
|
||||
|
||||
sam_model_choices = cls._choices.sam_choices()
|
||||
grounding_dino_model_choices = cls._choices.grounding_dino_choices()
|
||||
return {
|
||||
"required": {
|
||||
"sam_model": (
|
||||
sam_choices(),
|
||||
sam_model_choices,
|
||||
{
|
||||
"default": "sam_hq_vit_b (379MB)",
|
||||
"default": default_choice(
|
||||
sam_model_choices,
|
||||
"sam_hq_vit_b (379MB)",
|
||||
),
|
||||
"tooltip": tooltips.SAM_MODEL_INPUT,
|
||||
},
|
||||
),
|
||||
"grounding_dino_model": (
|
||||
grounding_dino_choices(),
|
||||
grounding_dino_model_choices,
|
||||
{
|
||||
"default": "GroundingDINO_SwinT_OGC (694MB)",
|
||||
"default": default_choice(
|
||||
grounding_dino_model_choices,
|
||||
"GroundingDINO_SwinT_OGC (694MB)",
|
||||
),
|
||||
"tooltip": tooltips.GROUNDING_DINO_MODEL_INPUT,
|
||||
},
|
||||
),
|
||||
@@ -53,4 +62,6 @@ class GroundedSAMModelInfo:
|
||||
def describe(self, sam_model: str, grounding_dino_model: str) -> tuple[str]:
|
||||
"""Return JSON metadata for selected model entries."""
|
||||
|
||||
self._choices.reject_sentinel(sam_model)
|
||||
self._choices.reject_sentinel(grounding_dino_model)
|
||||
return (self._metadata.describe_selection(sam_model, grounding_dino_model),)
|
||||
|
||||
@@ -8,6 +8,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from ..runtime.model_downloads import ComfyProgressReporter
|
||||
from ..runtime.ultralytics_loader import UltralyticsLoaderService
|
||||
|
||||
|
||||
@@ -40,7 +41,8 @@ class LoadUltralyticsModel:
|
||||
{
|
||||
"default": choices[0],
|
||||
"tooltip": (
|
||||
"Ultralytics model file in the ComfyUI models folder."
|
||||
"A local Ultralytics model or a curated model that "
|
||||
"downloads to ComfyUI's Impact Pack-compatible folders."
|
||||
),
|
||||
},
|
||||
)
|
||||
@@ -50,5 +52,8 @@ class LoadUltralyticsModel:
|
||||
def load(self, model_name: str) -> tuple[object, object, object]:
|
||||
"""Load the selected detector and paired compatibility facades."""
|
||||
|
||||
loaded = self.service_class().load(model_name)
|
||||
loaded = self.service_class().load(
|
||||
model_name,
|
||||
progress=ComfyProgressReporter(),
|
||||
)
|
||||
return loaded.detector_model, loaded.bbox_detector, loaded.segm_detector
|
||||
|
||||
@@ -11,10 +11,13 @@ from types import ModuleType
|
||||
from typing import Any
|
||||
|
||||
from ..domain.anima_quantization import AnimaQuantizationRecipe
|
||||
from ..runtime.anima_artifacts import ANIMA_QWEN_TEXT_ENCODER
|
||||
from ..runtime.auto_model_choices import automatic_component_choices
|
||||
from ..runtime.diffusion_model_loader import DIFFUSION_WEIGHT_DTYPES
|
||||
from ..runtime.model_downloads import ComfyProgressReporter
|
||||
from ..runtime.quantization_capabilities import QuantizationCapabilityCatalog
|
||||
from ..runtime.quantization_progress import ComfyQuantizationProgressReporter
|
||||
from ..runtime.qwen_artifacts import QWEN_IMAGE_VAE
|
||||
from ..runtime.vae_loader import vae_choices
|
||||
from ..services.anima_loader_service import (
|
||||
AUTO_CHOICE,
|
||||
@@ -84,7 +87,12 @@ class SimpleLoadAnima:
|
||||
},
|
||||
),
|
||||
"text_encoder": (
|
||||
_choices_with_auto(folder_paths.get_filename_list("text_encoders")),
|
||||
automatic_component_choices(
|
||||
installed=folder_paths.get_filename_list("text_encoders"),
|
||||
artifacts=(ANIMA_QWEN_TEXT_ENCODER,),
|
||||
leading_choices=(AUTO_CHOICE,),
|
||||
folder_paths_module=folder_paths,
|
||||
),
|
||||
{
|
||||
"default": AUTO_CHOICE,
|
||||
"advanced": True,
|
||||
@@ -106,7 +114,12 @@ class SimpleLoadAnima:
|
||||
},
|
||||
),
|
||||
"vae": (
|
||||
_choices_with_auto(vae_choices(folder_paths)),
|
||||
automatic_component_choices(
|
||||
installed=vae_choices(folder_paths),
|
||||
artifacts=(QWEN_IMAGE_VAE,),
|
||||
leading_choices=(AUTO_CHOICE,),
|
||||
folder_paths_module=folder_paths,
|
||||
),
|
||||
{
|
||||
"default": AUTO_CHOICE,
|
||||
"advanced": True,
|
||||
@@ -142,12 +155,6 @@ class SimpleLoadAnima:
|
||||
)
|
||||
|
||||
|
||||
def _choices_with_auto(choices: list[str]) -> list[str]:
|
||||
"""Return choices with the automatic selection first and deduplicated."""
|
||||
|
||||
return [AUTO_CHOICE, *(choice for choice in choices if choice != AUTO_CHOICE)]
|
||||
|
||||
|
||||
def _folder_paths() -> ModuleType:
|
||||
"""Import ComfyUI folder paths lazily."""
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ def get_nodes() -> list[type[object]]:
|
||||
from .simple_load_checkpoint import SimpleLoadCheckpointV3
|
||||
from .simple_load_flux import SimpleLoadFluxV3
|
||||
from .simple_load_flux2 import SimpleLoadFlux2V3
|
||||
from .simple_load_krea2 import SimpleLoadKrea2V3
|
||||
from .tag_segs_with_external_llm import TagSEGSWithExternalLLMV3
|
||||
from .tag_segs_with_wd14 import TagSEGSWithWD14V3
|
||||
from .tile_and_tag_segs import TileAndTagSEGSV3
|
||||
@@ -121,6 +122,7 @@ def get_nodes() -> list[type[object]]:
|
||||
SimpleLoadCheckpointV3,
|
||||
SimpleLoadFluxV3,
|
||||
SimpleLoadFlux2V3,
|
||||
SimpleLoadKrea2V3,
|
||||
SimpleVAEEncodeV3,
|
||||
TagSEGSWithExternalLLMV3,
|
||||
TagSEGSWithWD14V3,
|
||||
@@ -135,6 +137,7 @@ def get_nodes() -> list[type[object]]:
|
||||
if not prompt_control_is_available():
|
||||
return nodes
|
||||
|
||||
from .apply_automatic_negpip import ApplyAutomaticNegpipV3
|
||||
from .attach_regional_global_conditioning import (
|
||||
AttachRegionalGlobalConditioningV3,
|
||||
)
|
||||
@@ -149,6 +152,7 @@ def get_nodes() -> list[type[object]]:
|
||||
|
||||
return [
|
||||
*nodes,
|
||||
ApplyAutomaticNegpipV3,
|
||||
AttachRegionalGlobalConditioningV3,
|
||||
EncodePromptBatchWithPromptControl,
|
||||
LabelRegionalLoraHooksV3,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Internal Comfy v3 node for model-family automatic NegPiP preparation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from importlib import import_module
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from ..services.negpip_model_service import NEGPIP_MODEL_SERVICE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
class _ComfyNodeBase:
|
||||
"""Type-checking base for Comfy v3 nodes."""
|
||||
|
||||
pass
|
||||
|
||||
else:
|
||||
_ComfyNodeBase = import_module("comfy_api.latest").io.ComfyNode
|
||||
|
||||
_comfy_io: Any = None if TYPE_CHECKING else import_module("comfy_api.latest").io
|
||||
|
||||
|
||||
class ApplyAutomaticNegpipV3(_ComfyNodeBase):
|
||||
"""Patch supported MODEL/CLIP pairs after a negative prompt-weight trigger."""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls) -> Any:
|
||||
"""Declare the internal runtime patch boundary."""
|
||||
|
||||
return _comfy_io.Schema(
|
||||
node_id="SimpleSyrup.ApplyAutomaticNegpip",
|
||||
display_name="Apply Automatic NegPiP (Internal)",
|
||||
category="SimpleSyrup/Internal",
|
||||
description=(
|
||||
"Internal model-family NegPiP preparation injected by Schedule & "
|
||||
"Encode Prompts after detecting a negative prompt weight."
|
||||
),
|
||||
is_dev_only=True,
|
||||
inputs=[
|
||||
_comfy_io.Model.Input(
|
||||
"model",
|
||||
tooltip="MODEL inspected and cloned only when NegPiP is supported.",
|
||||
),
|
||||
_comfy_io.Clip.Input(
|
||||
"clip",
|
||||
tooltip="CLIP cloned with the matching NegPiP encoder behavior.",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
_comfy_io.Model.Output(
|
||||
"model",
|
||||
tooltip="MODEL carrying one supported NegPiP attention patch set.",
|
||||
),
|
||||
_comfy_io.Clip.Output(
|
||||
"clip",
|
||||
tooltip="CLIP carrying matching negative-weight encoding behavior.",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, model: object, clip: object) -> tuple[object, object]:
|
||||
"""Return the supported patched pair or the original unsupported pair."""
|
||||
|
||||
return NEGPIP_MODEL_SERVICE.prepare(model, clip)
|
||||
@@ -53,12 +53,14 @@ class KSamplerAttentionCouplingV3(_ComfyNodeBase):
|
||||
"With conditioning batches and masks, denoises supported Anima "
|
||||
"and standard SD/SDXL models through one "
|
||||
"shared trajectory while coupling global and masked regional "
|
||||
"cross-attention. The input MODEL may carry a global LoRA. Anima "
|
||||
"regions may also carry ordered, independently scheduled Prompt "
|
||||
"Control model LoRAs whose overlapping deltas compose in declared "
|
||||
"order. Runtime scales with active adapters, ranks, and targets. "
|
||||
"Standard SD/SDXL regional model-side hooks and unsupported Anima "
|
||||
"adapter targets fail before sampling."
|
||||
"cross-attention. LoRAs on the input MODEL and Prompt Control model "
|
||||
"LoRAs on global conditioning entry 0 apply across the image. Regions "
|
||||
"may also carry ordered, independently scheduled model LoRAs "
|
||||
"whose overlapping deltas compose in declared order. Runtime scales "
|
||||
"with active adapters, ranks, and targets. "
|
||||
"Global LoRA and regional LoRA retain independent schedules; "
|
||||
"regional model-side hooks are supported on admitted model families. "
|
||||
"Unsupported adapter targets fail before sampling."
|
||||
),
|
||||
search_aliases=[
|
||||
"attention coupling",
|
||||
|
||||
@@ -50,12 +50,14 @@ class KSamplerContextualAttentionCouplingV3(_ComfyNodeBase):
|
||||
description=(
|
||||
"Preserves large-image composition through Contextual Diffusion "
|
||||
"while coupling regional attention in every local and reduced-global "
|
||||
"Anima or standard SD/SDXL view. Global LoRAs remain on the input "
|
||||
"model. Anima regional LoRA stacks are prepared once, retain "
|
||||
"Anima or standard SD/SDXL view. LoRAs on the input MODEL and Prompt "
|
||||
"Control model LoRAs on global conditioning entry 0 apply in every "
|
||||
"view. Regional LoRA stacks are prepared once, retain "
|
||||
"independent schedules and full quality, and skip inactive work. "
|
||||
"Optional SEGS guide the shared local tile plan. Standard SD/SDXL "
|
||||
"regional model-side hooks and unsupported Anima targets fail before "
|
||||
"sampling."
|
||||
"Global LoRA and regional LoRA stacks remain independently scheduled; "
|
||||
"regional model-side hooks are supported on admitted model families. "
|
||||
"Optional SEGS guide the shared local tile plan. Unsupported adapter "
|
||||
"targets fail before sampling."
|
||||
),
|
||||
search_aliases=[
|
||||
"contextual attention coupling",
|
||||
|
||||
@@ -248,7 +248,8 @@ def attention_coupling_ksampler_inputs(
|
||||
"model",
|
||||
tooltip=(
|
||||
"Supported Anima or standard SD/SDXL model used for one shared "
|
||||
"denoiser trajectory; apply global model LoRAs before connecting it."
|
||||
"denoiser trajectory. LoRAs patched on this model and Prompt Control "
|
||||
"model LoRAs on conditioning entry 0 apply globally."
|
||||
),
|
||||
),
|
||||
*base[1:6],
|
||||
@@ -258,8 +259,8 @@ def attention_coupling_ksampler_inputs(
|
||||
tooltip=(
|
||||
"Global-first positive conditioning: entry 0 is global and later "
|
||||
"entries pair with masks. Regional Prompt Control WeightHooks may "
|
||||
"contain ordered full-rank Anima LoRA stacks with independent "
|
||||
"schedules; standard SD/SDXL rejects regional model-side hooks."
|
||||
"contain ordered regional LoRA stacks with independent schedules. "
|
||||
"Model LoRA hooks on entry 0 apply across the image."
|
||||
),
|
||||
),
|
||||
comfy_io.MultiType.Input(
|
||||
@@ -267,8 +268,9 @@ def attention_coupling_ksampler_inputs(
|
||||
[comfy_io.Conditioning, conditioning_batch],
|
||||
tooltip=(
|
||||
"Global-first negative conditioning aligned to the same masks; "
|
||||
"Anima regional LoRA hooks retain their negative-branch ownership "
|
||||
"and independent schedules."
|
||||
"its global model hooks must match the positive global entry. "
|
||||
"Regional LoRA hooks retain their negative-branch ownership and "
|
||||
"independent schedules."
|
||||
),
|
||||
),
|
||||
comfy_io.Mask.Input(
|
||||
@@ -278,7 +280,7 @@ def attention_coupling_ksampler_inputs(
|
||||
"Optional ordered masks paired with conditioning entries 1 onward. "
|
||||
"Leave disconnected with ordinary conditioning to bypass Attention "
|
||||
"Coupling. In overlaps, prompt contributions are normalized while "
|
||||
"Anima regional LoRA deltas add in declared adapter and region order."
|
||||
"regional LoRA deltas add in declared adapter and region order."
|
||||
),
|
||||
),
|
||||
comfy_io.Float.Input(
|
||||
@@ -291,7 +293,7 @@ def attention_coupling_ksampler_inputs(
|
||||
tooltip=(
|
||||
"Balances regional cross-attention against the global prompt from "
|
||||
"0 (global only) to 1 (regional only inside solid masks); regional "
|
||||
"Anima LoRA strength remains controlled by each hook."
|
||||
"LoRA strength remains controlled by each hook."
|
||||
),
|
||||
),
|
||||
comfy_io.Int.Input(
|
||||
@@ -301,7 +303,7 @@ def attention_coupling_ksampler_inputs(
|
||||
max=512,
|
||||
step=1,
|
||||
tooltip=(
|
||||
"Softens Attention Coupling and Anima regional LoRA boundaries by "
|
||||
"Softens Attention Coupling and regional LoRA boundaries by "
|
||||
"this many image pixels; 0 preserves authored mask values."
|
||||
),
|
||||
),
|
||||
|
||||
@@ -54,12 +54,15 @@ class KSamplerTiledAttentionCouplingV3(_ComfyNodeBase):
|
||||
"batches and masks, denoises large Anima and standard SD/SDXL "
|
||||
"latents in tiles through "
|
||||
"one shared model trajectory per tile batch while coupling global "
|
||||
"and masked regional cross-attention. The input MODEL may carry "
|
||||
"global LoRAs. Anima regions may carry independently scheduled "
|
||||
"and masked regional cross-attention. LoRAs on the input MODEL and "
|
||||
"Prompt Control model LoRAs on global conditioning entry 0 apply "
|
||||
"across every tile. Regions may carry independently scheduled "
|
||||
"regional LoRA stacks; inactive attention and LoRA work is pruned "
|
||||
"without changing quality. MultiDiffusion or Mixture of Diffusers "
|
||||
"fuses restored tile predictions. Standard SD/SDXL regional "
|
||||
"model-side hooks and unsupported Anima targets fail before sampling."
|
||||
"fuses restored tile predictions. Global LoRA and regional LoRA "
|
||||
"stacks retain independent schedules; regional model-side hooks are "
|
||||
"supported on admitted model families. Unsupported adapter targets "
|
||||
"fail before sampling."
|
||||
),
|
||||
search_aliases=[
|
||||
"attention coupling tiled",
|
||||
|
||||
@@ -60,8 +60,6 @@ _HIDDEN_INPUTS = {
|
||||
"DYNPROMPT": "dynprompt",
|
||||
"EXTRA_PNGINFO": "extra_pnginfo",
|
||||
"UNIQUE_ID": "unique_id",
|
||||
"AUTH_TOKEN_COMFY_ORG": "auth_token_comfy_org",
|
||||
"API_KEY_COMFY_ORG": "api_key_comfy_org",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,9 @@ from types import ModuleType
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from ..nodes import tooltips
|
||||
from ..runtime.auto_model_choices import automatic_component_choices
|
||||
from ..runtime.diffusion_model_loader import DIFFUSION_WEIGHT_DTYPES
|
||||
from ..runtime.flux_artifacts import FLUX_CLIP_L, FLUX_T5_XXL, FLUX_VAE
|
||||
from ..runtime.model_downloads import ComfyProgressReporter
|
||||
from ..runtime.text_encoder_loader import TEXT_ENCODER_DEVICES
|
||||
from ..runtime.vae_loader import vae_choices
|
||||
@@ -44,9 +46,7 @@ class SimpleLoadFluxV3(_ComfyNodeBase):
|
||||
"""Declare the separate FLUX.1 loader schema."""
|
||||
|
||||
folder_paths = _folder_paths()
|
||||
text_encoder_choices = _choices_with_auto(
|
||||
list(folder_paths.get_filename_list("text_encoders"))
|
||||
)
|
||||
installed_text_encoders = list(folder_paths.get_filename_list("text_encoders"))
|
||||
return _comfy_io.Schema(
|
||||
node_id="SimpleSyrup.SimpleLoadFlux",
|
||||
display_name="Simple Load FLUX",
|
||||
@@ -77,7 +77,12 @@ class SimpleLoadFluxV3(_ComfyNodeBase):
|
||||
),
|
||||
_comfy_io.Combo.Input(
|
||||
"clip_l",
|
||||
options=text_encoder_choices,
|
||||
options=automatic_component_choices(
|
||||
installed=installed_text_encoders,
|
||||
artifacts=(FLUX_CLIP_L,),
|
||||
leading_choices=(AUTO_CHOICE,),
|
||||
folder_paths_module=folder_paths,
|
||||
),
|
||||
default=AUTO_CHOICE,
|
||||
advanced=True,
|
||||
tooltip=(
|
||||
@@ -87,7 +92,12 @@ class SimpleLoadFluxV3(_ComfyNodeBase):
|
||||
),
|
||||
_comfy_io.Combo.Input(
|
||||
"t5_xxl",
|
||||
options=text_encoder_choices,
|
||||
options=automatic_component_choices(
|
||||
installed=installed_text_encoders,
|
||||
artifacts=(FLUX_T5_XXL,),
|
||||
leading_choices=(AUTO_CHOICE,),
|
||||
folder_paths_module=folder_paths,
|
||||
),
|
||||
default=AUTO_CHOICE,
|
||||
advanced=True,
|
||||
tooltip=(
|
||||
@@ -107,7 +117,12 @@ class SimpleLoadFluxV3(_ComfyNodeBase):
|
||||
),
|
||||
_comfy_io.Combo.Input(
|
||||
"vae",
|
||||
options=_choices_with_auto(vae_choices(folder_paths)),
|
||||
options=automatic_component_choices(
|
||||
installed=vae_choices(folder_paths),
|
||||
artifacts=(FLUX_VAE,),
|
||||
leading_choices=(AUTO_CHOICE,),
|
||||
folder_paths_module=folder_paths,
|
||||
),
|
||||
default=AUTO_CHOICE,
|
||||
advanced=True,
|
||||
tooltip=(
|
||||
@@ -146,12 +161,6 @@ class SimpleLoadFluxV3(_ComfyNodeBase):
|
||||
)
|
||||
|
||||
|
||||
def _choices_with_auto(choices: list[str]) -> list[str]:
|
||||
"""Return deduplicated choices with automatic selection first."""
|
||||
|
||||
return [AUTO_CHOICE, *(choice for choice in choices if choice != AUTO_CHOICE)]
|
||||
|
||||
|
||||
def _folder_paths() -> ModuleType:
|
||||
"""Import ComfyUI folder paths lazily for schema declaration."""
|
||||
|
||||
|
||||
@@ -11,7 +11,9 @@ from types import ModuleType
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from ..nodes import tooltips
|
||||
from ..runtime.auto_model_choices import automatic_component_choices
|
||||
from ..runtime.diffusion_model_loader import DIFFUSION_WEIGHT_DTYPES
|
||||
from ..runtime.flux_artifacts import FLUX2_TEXT_ENCODERS, FLUX2_VAE
|
||||
from ..runtime.model_downloads import ComfyProgressReporter
|
||||
from ..runtime.text_encoder_loader import TEXT_ENCODER_DEVICES
|
||||
from ..runtime.vae_loader import vae_choices
|
||||
@@ -75,8 +77,11 @@ class SimpleLoadFlux2V3(_ComfyNodeBase):
|
||||
),
|
||||
_comfy_io.Combo.Input(
|
||||
"text_encoder",
|
||||
options=_choices_with_auto(
|
||||
list(folder_paths.get_filename_list("text_encoders"))
|
||||
options=automatic_component_choices(
|
||||
installed=list(folder_paths.get_filename_list("text_encoders")),
|
||||
artifacts=tuple(FLUX2_TEXT_ENCODERS.values()),
|
||||
leading_choices=(AUTO_CHOICE,),
|
||||
folder_paths_module=folder_paths,
|
||||
),
|
||||
default=AUTO_CHOICE,
|
||||
advanced=True,
|
||||
@@ -98,7 +103,12 @@ class SimpleLoadFlux2V3(_ComfyNodeBase):
|
||||
),
|
||||
_comfy_io.Combo.Input(
|
||||
"vae",
|
||||
options=_choices_with_auto(vae_choices(folder_paths)),
|
||||
options=automatic_component_choices(
|
||||
installed=vae_choices(folder_paths),
|
||||
artifacts=(FLUX2_VAE,),
|
||||
leading_choices=(AUTO_CHOICE,),
|
||||
folder_paths_module=folder_paths,
|
||||
),
|
||||
default=AUTO_CHOICE,
|
||||
advanced=True,
|
||||
tooltip=(
|
||||
@@ -135,12 +145,6 @@ class SimpleLoadFlux2V3(_ComfyNodeBase):
|
||||
)
|
||||
|
||||
|
||||
def _choices_with_auto(choices: list[str]) -> list[str]:
|
||||
"""Return deduplicated choices with automatic selection first."""
|
||||
|
||||
return [AUTO_CHOICE, *(choice for choice in choices if choice != AUTO_CHOICE)]
|
||||
|
||||
|
||||
def _folder_paths() -> ModuleType:
|
||||
"""Import ComfyUI folder paths lazily for schema declaration."""
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Expose cohesive Krea 2 component loading through Comfy's v3 API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from types import ModuleType
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from ..nodes import tooltips
|
||||
from ..runtime.auto_model_choices import automatic_component_choices
|
||||
from ..runtime.diffusion_model_loader import DIFFUSION_WEIGHT_DTYPES
|
||||
from ..runtime.krea2_artifacts import (
|
||||
KREA2_AUTO_TEXT_ENCODER,
|
||||
KREA2_QWEN3_VL_4B_BF16,
|
||||
KREA2_QWEN3_VL_4B_FP8,
|
||||
)
|
||||
from ..runtime.model_downloads import ComfyProgressReporter
|
||||
from ..runtime.qwen_artifacts import QWEN_IMAGE_VAE
|
||||
from ..runtime.text_encoder_loader import TEXT_ENCODER_DEVICES
|
||||
from ..runtime.vae_loader import vae_choices
|
||||
from ..services.krea2_loader_service import AUTO_CHOICE, Krea2LoaderService
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
class _ComfyNodeBase:
|
||||
"""Type-checking base for Comfy v3 nodes."""
|
||||
|
||||
RETURN_TYPES: ClassVar[list[str]]
|
||||
RETURN_NAMES: ClassVar[list[str]]
|
||||
|
||||
else:
|
||||
_ComfyNodeBase = importlib.import_module("comfy_api.latest").io.ComfyNode
|
||||
|
||||
_comfy_io: Any = (
|
||||
None if TYPE_CHECKING else importlib.import_module("comfy_api.latest").io
|
||||
)
|
||||
|
||||
|
||||
class SimpleLoadKrea2V3(_ComfyNodeBase):
|
||||
"""Load a Krea 2 diffusion model with its Qwen encoder and image VAE."""
|
||||
|
||||
_service = Krea2LoaderService()
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls) -> Any:
|
||||
"""Declare the Krea 2 loader schema and downloadable component choices."""
|
||||
|
||||
folder_paths = _folder_paths()
|
||||
return _comfy_io.Schema(
|
||||
node_id="SimpleSyrup.SimpleLoadKrea2",
|
||||
display_name="Simple Load Krea 2",
|
||||
category="SimpleSyrup/Loaders",
|
||||
description=(
|
||||
"Loads Krea 2 with its Qwen3-VL 4B encoder and Qwen Image VAE; "
|
||||
"automatic components are downloaded from checksum-pinned "
|
||||
"Hugging Face files."
|
||||
),
|
||||
search_aliases=["krea", "krea 2", "k2", "load krea"],
|
||||
inputs=[
|
||||
_comfy_io.Combo.Input(
|
||||
"diffusion_model",
|
||||
options=list(folder_paths.get_filename_list("diffusion_models")),
|
||||
tooltip=(
|
||||
"Krea 2 Raw or Turbo diffusion model to load. This node "
|
||||
"validates the architecture and never downloads this file."
|
||||
),
|
||||
),
|
||||
_comfy_io.Combo.Input(
|
||||
"diffusion_weight_dtype",
|
||||
options=list(DIFFUSION_WEIGHT_DTYPES),
|
||||
default="default",
|
||||
advanced=True,
|
||||
tooltip=(
|
||||
"Load-time diffusion precision; default preserves the "
|
||||
"selected file's stored BF16, FP8, INT8, MXFP8, or NVFP4 "
|
||||
"format."
|
||||
),
|
||||
),
|
||||
_comfy_io.Combo.Input(
|
||||
"text_encoder",
|
||||
options=automatic_component_choices(
|
||||
installed=list(folder_paths.get_filename_list("text_encoders")),
|
||||
artifacts=(
|
||||
KREA2_QWEN3_VL_4B_FP8,
|
||||
KREA2_QWEN3_VL_4B_BF16,
|
||||
),
|
||||
leading_choices=(
|
||||
KREA2_AUTO_TEXT_ENCODER,
|
||||
KREA2_QWEN3_VL_4B_FP8.filename,
|
||||
KREA2_QWEN3_VL_4B_BF16.filename,
|
||||
),
|
||||
folder_paths_module=folder_paths,
|
||||
),
|
||||
default=KREA2_AUTO_TEXT_ENCODER,
|
||||
advanced=True,
|
||||
tooltip=(
|
||||
"Qwen3-VL 4B encoder loaded with Krea 2's required 12-layer "
|
||||
"conditioning. Auto uses FP8; selecting official FP8 or BF16 "
|
||||
"downloads that checksum-pinned file when missing."
|
||||
),
|
||||
),
|
||||
_comfy_io.Combo.Input(
|
||||
"text_encoder_device",
|
||||
options=list(TEXT_ENCODER_DEVICES),
|
||||
default="default",
|
||||
advanced=True,
|
||||
tooltip=(
|
||||
"Device for Qwen3-VL; CPU saves GPU memory but makes prompt "
|
||||
"encoding slower."
|
||||
),
|
||||
),
|
||||
_comfy_io.Combo.Input(
|
||||
"vae",
|
||||
options=automatic_component_choices(
|
||||
installed=vae_choices(folder_paths),
|
||||
artifacts=(QWEN_IMAGE_VAE,),
|
||||
leading_choices=(AUTO_CHOICE,),
|
||||
folder_paths_module=folder_paths,
|
||||
),
|
||||
default=AUTO_CHOICE,
|
||||
advanced=True,
|
||||
tooltip=(
|
||||
"VAE used to decode Krea 2 latents. Auto finds or downloads "
|
||||
"the checksum-pinned Qwen Image VAE with visible progress."
|
||||
),
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
_comfy_io.Model.Output("model", tooltip=tooltips.MODEL_OUTPUT),
|
||||
_comfy_io.Clip.Output("clip", tooltip=tooltips.CLIP_OUTPUT),
|
||||
_comfy_io.Vae.Output("vae", tooltip=tooltips.VAE_OUTPUT),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(
|
||||
cls,
|
||||
diffusion_model: str,
|
||||
diffusion_weight_dtype: str,
|
||||
text_encoder: str,
|
||||
text_encoder_device: str,
|
||||
vae: str,
|
||||
) -> tuple[object, object, object]:
|
||||
"""Load and return validated Krea 2 MODEL, CLIP, and VAE objects."""
|
||||
|
||||
return cls._service.load_models(
|
||||
diffusion_model=diffusion_model,
|
||||
diffusion_weight_dtype=diffusion_weight_dtype,
|
||||
text_encoder=text_encoder,
|
||||
text_encoder_device=text_encoder_device,
|
||||
vae=vae,
|
||||
progress=ComfyProgressReporter(),
|
||||
)
|
||||
|
||||
|
||||
def _folder_paths() -> ModuleType:
|
||||
"""Import ComfyUI folder paths lazily for schema declaration."""
|
||||
|
||||
module: Any = importlib.import_module("folder_paths")
|
||||
if not isinstance(module, ModuleType):
|
||||
raise TypeError("folder_paths import did not return a module.")
|
||||
return module
|
||||
@@ -7,6 +7,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from .auto_model_artifact import AutoModelArtifact
|
||||
from .qwen_artifacts import QWEN_IMAGE_VAE
|
||||
|
||||
ANIMA_QWEN_TEXT_ENCODER = AutoModelArtifact(
|
||||
cache_id="anima_qwen_text_encoder",
|
||||
@@ -20,20 +21,7 @@ ANIMA_QWEN_TEXT_ENCODER = AutoModelArtifact(
|
||||
source_repo="circlestone-labs/Anima",
|
||||
description="Anima Qwen3 0.6B text encoder",
|
||||
sha256="cd2a512003e2f9f3cd3c32a9c3573f820bb28c940f73c57b1ddaa983d9223eba",
|
||||
file_size_bytes=1_192_135_096,
|
||||
)
|
||||
|
||||
ANIMA_QWEN_VAE = AutoModelArtifact(
|
||||
cache_id="anima_qwen_vae",
|
||||
filename="qwen_image_vae.safetensors",
|
||||
folder_name="vae",
|
||||
canonical_subfolder="qwen",
|
||||
source_url=(
|
||||
"https://huggingface.co/circlestone-labs/Anima/resolve/main/"
|
||||
"split_files/vae/qwen_image_vae.safetensors"
|
||||
),
|
||||
source_repo="circlestone-labs/Anima",
|
||||
description="Anima Qwen Image VAE",
|
||||
sha256="a70580f0213e67967ee9c95f05bb400e8fb08307e017a924bf3441223e023d1f",
|
||||
)
|
||||
|
||||
ANIMA_AUTO_ARTIFACTS = (ANIMA_QWEN_TEXT_ENCODER, ANIMA_QWEN_VAE)
|
||||
ANIMA_AUTO_ARTIFACTS = (ANIMA_QWEN_TEXT_ENCODER, QWEN_IMAGE_VAE)
|
||||
|
||||
@@ -8,16 +8,19 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import comfy.model_patcher
|
||||
from comfy.patcher_extension import CallbacksMP
|
||||
|
||||
from ..model_attention_patch_mutations import ModelAttn2PatchesMutation
|
||||
from ..model_patcher_mutations import ModelKeyedCallbackMutation
|
||||
from ..patcher_lifecycle import PATCHER_LIFECYCLE, ModelMutation
|
||||
from ..regional_lora.standard_unet_native_admission import (
|
||||
StandardUnetNativeLoraAdmission,
|
||||
from ..ppm_negpip_interop import PpmNegpipInterop
|
||||
from ..regional_lora.operation_assembly import REGIONAL_OPERATION_ASSEMBLER
|
||||
from ..regional_lora.standard_unet_operation_preparation import (
|
||||
StandardUnetOperationAdmission,
|
||||
)
|
||||
from ..regional_lora.standard_unet_variant_runtime import (
|
||||
StandardUnetVariantRuntimeMutation,
|
||||
)
|
||||
from ..regional_lora.standard_unet_variant_template import (
|
||||
STANDARD_UNET_VARIANT_TEMPLATE_CACHE,
|
||||
from ..regional_lora.standard_unet_operation_session import (
|
||||
StandardUnetRegionalOperationSession,
|
||||
)
|
||||
from .unet_attention_context_wrapper import unet_attention_context_wrapper_mutation
|
||||
from .unet_attention_phase_session import StandardUnetAttentionPhaseSession
|
||||
@@ -42,60 +45,72 @@ class StandardUnetAttentionBackend:
|
||||
*,
|
||||
model: object,
|
||||
state: StandardUnetAttentionState,
|
||||
admission: StandardUnetNativeLoraAdmission,
|
||||
admission: StandardUnetOperationAdmission,
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> StandardUnetAttentionModel:
|
||||
"""Return a direct MODEL child containing only the paired UNet patches."""
|
||||
|
||||
if not isinstance(state, StandardUnetAttentionState):
|
||||
raise TypeError("Standard UNet backend requires attention state.")
|
||||
if not isinstance(admission, StandardUnetNativeLoraAdmission):
|
||||
raise TypeError("Standard UNet backend requires native admission.")
|
||||
if not isinstance(admission, StandardUnetOperationAdmission):
|
||||
raise TypeError("Standard UNet backend requires operation admission.")
|
||||
if admission.adaptation.plan != state.plan.lora_plan:
|
||||
raise ValueError(
|
||||
"Standard UNet admission and processed conditioning must share "
|
||||
"the same regional LoRA plan."
|
||||
)
|
||||
if negpip is not None and not isinstance(negpip, PpmNegpipInterop):
|
||||
raise TypeError("Standard UNet backend NegPiP state has an invalid type.")
|
||||
attention_phase = StandardUnetAttentionPhaseSession()
|
||||
template = (
|
||||
STANDARD_UNET_VARIANT_TEMPLATE_CACHE.resolve(model, admission)
|
||||
if admission.adaptation.plan.adapters
|
||||
else None
|
||||
)
|
||||
variant_mutations = (
|
||||
(
|
||||
StandardUnetVariantRuntimeMutation(
|
||||
state,
|
||||
admission,
|
||||
attention_phase,
|
||||
template,
|
||||
operation_session: StandardUnetRegionalOperationSession | None = None
|
||||
operation_mutations: tuple[ModelMutation, ...] = ()
|
||||
if admission.adaptation.plan.adapters:
|
||||
if (
|
||||
not isinstance(model, comfy.model_patcher.ModelPatcher)
|
||||
or admission.binding is None
|
||||
or admission.cache is None
|
||||
):
|
||||
raise TypeError(
|
||||
"Standard UNet regional operations require complete MODEL "
|
||||
"admission."
|
||||
)
|
||||
assembly = REGIONAL_OPERATION_ASSEMBLER.assemble(
|
||||
admission.binding,
|
||||
model=model,
|
||||
cache=admission.cache,
|
||||
)
|
||||
operation_session = StandardUnetRegionalOperationSession(
|
||||
admission.adaptation.plan,
|
||||
state.plan.mask_bank,
|
||||
admission.module_roles,
|
||||
assembly.call_scope,
|
||||
)
|
||||
operation_mutations = (
|
||||
assembly.cache_lifecycle.mutation(),
|
||||
ModelKeyedCallbackMutation(
|
||||
CallbacksMP.ON_DETACH,
|
||||
"simple_syrup.standard_unet_regional_operation_schedule",
|
||||
operation_session.clear,
|
||||
),
|
||||
)
|
||||
if template is not None
|
||||
else ()
|
||||
patches = UnetAttn2PatchPair(
|
||||
StandardUnetAttn2ExecutionResolver(state),
|
||||
operation_scope=operation_session,
|
||||
)
|
||||
derivation_source = (
|
||||
template.bind_request(model) if template is not None else model
|
||||
)
|
||||
attention_mutations: tuple[ModelMutation, ...] = ()
|
||||
if template is None:
|
||||
patches = UnetAttn2PatchPair(
|
||||
StandardUnetAttn2ExecutionResolver(state),
|
||||
)
|
||||
attention_mutations = (
|
||||
ModelAttn2PatchesMutation(
|
||||
patches.input_patch,
|
||||
patches.output_patch,
|
||||
),
|
||||
)
|
||||
derived = PATCHER_LIFECYCLE.derive_model(
|
||||
derivation_source,
|
||||
model,
|
||||
(
|
||||
unet_attention_context_wrapper_mutation(
|
||||
state,
|
||||
attention_phase,
|
||||
operation_session,
|
||||
),
|
||||
*attention_mutations,
|
||||
*variant_mutations,
|
||||
ModelAttn2PatchesMutation(
|
||||
patches.input_patch,
|
||||
patches.output_patch,
|
||||
(() if negpip is None else (negpip.attention_patch,)),
|
||||
),
|
||||
*operation_mutations,
|
||||
),
|
||||
operation="standard UNet Attention Coupling",
|
||||
)
|
||||
|
||||
@@ -6,12 +6,17 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import ExitStack
|
||||
|
||||
import torch
|
||||
|
||||
from ..diffusion_wrapper_executor import DiffusionWrapperExecutor
|
||||
from ..diffusion_wrapper_invocation import DIFFUSION_WRAPPER_INVOCATION_VALIDATOR
|
||||
from ..model_patcher_mutations import ModelDiffusionWrapperMutation
|
||||
from ..regional_attention_model_call import RegionalAttentionModelCallResolver
|
||||
from ..regional_lora.standard_unet_operation_session import (
|
||||
StandardUnetRegionalOperationSession,
|
||||
)
|
||||
from .standard_unet_model_output_validation import (
|
||||
STANDARD_UNET_MODEL_OUTPUT_VALIDATOR,
|
||||
StandardUnetModelOutputValidator,
|
||||
@@ -32,6 +37,7 @@ class StandardUnetAttentionContextDiffusionWrapper:
|
||||
self,
|
||||
state: StandardUnetAttentionState,
|
||||
attention_phase: StandardUnetAttentionPhaseSession,
|
||||
operation_session: StandardUnetRegionalOperationSession | None = None,
|
||||
*,
|
||||
model_call_resolver: RegionalAttentionModelCallResolver = (
|
||||
STANDARD_UNET_MODEL_CALL_RESOLVER
|
||||
@@ -46,12 +52,18 @@ class StandardUnetAttentionContextDiffusionWrapper:
|
||||
raise TypeError("Standard UNet context wrapper requires attention state.")
|
||||
if not isinstance(attention_phase, StandardUnetAttentionPhaseSession):
|
||||
raise TypeError("Standard UNet context wrapper requires phase state.")
|
||||
if operation_session is not None and not isinstance(
|
||||
operation_session,
|
||||
StandardUnetRegionalOperationSession,
|
||||
):
|
||||
raise TypeError("Standard UNet operation session has an invalid type.")
|
||||
if not isinstance(model_call_resolver, RegionalAttentionModelCallResolver):
|
||||
raise TypeError(
|
||||
"Standard UNet context wrapper requires a model-call resolver."
|
||||
)
|
||||
self._state = state
|
||||
self._attention_phase = attention_phase
|
||||
self._operation_session = operation_session
|
||||
self._model_call_resolver = model_call_resolver
|
||||
if not isinstance(output_validator, StandardUnetModelOutputValidator):
|
||||
raise TypeError("Standard UNet output validator has an invalid type.")
|
||||
@@ -90,11 +102,14 @@ class StandardUnetAttentionContextDiffusionWrapper:
|
||||
transformer_options=args[5],
|
||||
)
|
||||
forwarded_args = (*args[:2], contexts.base_context, *args[3:])
|
||||
with (
|
||||
self._attention_phase.activate(args[5]),
|
||||
self._state.execution_context.activate(contexts),
|
||||
self._state.resolution_cache.activate(),
|
||||
):
|
||||
with ExitStack() as scopes:
|
||||
scopes.enter_context(self._attention_phase.activate(args[5]))
|
||||
scopes.enter_context(self._state.execution_context.activate(contexts))
|
||||
scopes.enter_context(self._state.resolution_cache.activate())
|
||||
if self._operation_session is not None:
|
||||
scopes.enter_context(
|
||||
self._operation_session.activate(contexts, args[5])
|
||||
)
|
||||
output = executor(*forwarded_args, **kwargs)
|
||||
return self._output_validator.validate(output, model_input=args[0])
|
||||
|
||||
@@ -102,6 +117,7 @@ class StandardUnetAttentionContextDiffusionWrapper:
|
||||
def unet_attention_context_wrapper_mutation(
|
||||
state: StandardUnetAttentionState,
|
||||
attention_phase: StandardUnetAttentionPhaseSession,
|
||||
operation_session: StandardUnetRegionalOperationSession | None = None,
|
||||
) -> ModelDiffusionWrapperMutation:
|
||||
"""Return the clone-local standard-UNet context wrapper mutation."""
|
||||
|
||||
@@ -110,5 +126,6 @@ def unet_attention_context_wrapper_mutation(
|
||||
StandardUnetAttentionContextDiffusionWrapper(
|
||||
state,
|
||||
attention_phase,
|
||||
operation_session,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -21,3 +21,4 @@ class AutoModelArtifact:
|
||||
source_repo: str
|
||||
description: str
|
||||
sha256: str
|
||||
file_size_bytes: int
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Build component choices without duplicating automatic local artifacts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Any
|
||||
|
||||
from .auto_model_artifact import AutoModelArtifact
|
||||
|
||||
|
||||
def automatic_component_choices(
|
||||
installed: Sequence[str],
|
||||
artifacts: Sequence[AutoModelArtifact],
|
||||
leading_choices: Sequence[str],
|
||||
folder_paths_module: ModuleType,
|
||||
) -> list[str]:
|
||||
"""Return leading choices plus local files not represented automatically."""
|
||||
|
||||
if not artifacts:
|
||||
raise ValueError("Automatic component choices require at least one artifact.")
|
||||
folder_names = {artifact.folder_name for artifact in artifacts}
|
||||
if len(folder_names) != 1:
|
||||
raise ValueError("Automatic component artifacts must share one model category.")
|
||||
|
||||
folder_name = next(iter(folder_names))
|
||||
automatic_names = {artifact.filename for artifact in artifacts}
|
||||
automatic_sizes = {artifact.file_size_bytes for artifact in artifacts}
|
||||
choices = list(dict.fromkeys(leading_choices))
|
||||
seen = set(choices)
|
||||
for choice in installed:
|
||||
if choice in seen or choice in automatic_names:
|
||||
continue
|
||||
if _installed_file_has_known_size(
|
||||
folder_paths_module,
|
||||
folder_name,
|
||||
choice,
|
||||
automatic_sizes,
|
||||
):
|
||||
continue
|
||||
choices.append(choice)
|
||||
seen.add(choice)
|
||||
return choices
|
||||
|
||||
|
||||
def _installed_file_has_known_size(
|
||||
folder_paths_module: ModuleType,
|
||||
folder_name: str,
|
||||
choice: str,
|
||||
automatic_sizes: set[int],
|
||||
) -> bool:
|
||||
"""Identify a likely automatic artifact without hashing during schema creation."""
|
||||
|
||||
get_full_path: Any = getattr(folder_paths_module, "get_full_path", None)
|
||||
if not callable(get_full_path):
|
||||
return False
|
||||
path_value: Any = get_full_path(folder_name, choice)
|
||||
if path_value is None:
|
||||
return False
|
||||
try:
|
||||
path = Path(str(path_value))
|
||||
return path.is_file() and path.stat().st_size in automatic_sizes
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
__all__ = ["automatic_component_choices"]
|
||||
@@ -150,8 +150,6 @@ class AutoModelResolver:
|
||||
return False
|
||||
if entry.sha256 != artifact.sha256:
|
||||
return False
|
||||
if entry.path.name != artifact.filename:
|
||||
return False
|
||||
if not entry.path.is_file():
|
||||
return False
|
||||
try:
|
||||
@@ -163,6 +161,8 @@ class AutoModelResolver:
|
||||
except ValueError:
|
||||
return False
|
||||
stat = entry.path.stat()
|
||||
if stat.st_size != artifact.file_size_bytes:
|
||||
return False
|
||||
if entry.file_size is not None and entry.modified_time_ns is not None:
|
||||
return (
|
||||
entry.file_size == stat.st_size
|
||||
@@ -175,19 +175,33 @@ def find_model_artifact(
|
||||
artifact: AutoModelArtifact,
|
||||
folder_paths_module: ModuleType | None = None,
|
||||
) -> Path | None:
|
||||
"""Return the first same-named local file matching the catalog checksum."""
|
||||
"""Find an artifact by the cheapest reliable checks within its model category."""
|
||||
|
||||
_validate_basename(artifact.filename)
|
||||
for root in get_model_folder_paths(artifact.folder_name, folder_paths_module):
|
||||
roots = get_model_folder_paths(artifact.folder_name, folder_paths_module)
|
||||
canonical = canonical_auto_destination(artifact, folder_paths_module)
|
||||
if _candidate_matches_artifact(canonical, artifact):
|
||||
return canonical
|
||||
|
||||
checked: set[Path] = {canonical.resolve()}
|
||||
for root in roots:
|
||||
if not root.is_dir():
|
||||
continue
|
||||
matches = sorted(
|
||||
path for path in root.rglob(artifact.filename) if path.is_file()
|
||||
)
|
||||
for match in matches:
|
||||
if match.name != artifact.filename or not _path_is_under(match, root):
|
||||
if not _candidate_has_expected_size(match, artifact):
|
||||
continue
|
||||
if sha256_file(match).lower() == artifact.sha256.lower():
|
||||
resolved_match = match.resolve()
|
||||
if (
|
||||
resolved_match in checked
|
||||
or match.name != artifact.filename
|
||||
or not _path_is_under(match, root)
|
||||
):
|
||||
continue
|
||||
checked.add(resolved_match)
|
||||
if _candidate_checksum_matches(match, artifact):
|
||||
return match
|
||||
LOGGER.warning(
|
||||
"same-named auto model artifact has a different checksum",
|
||||
@@ -197,9 +211,63 @@ def find_model_artifact(
|
||||
"artifact_filename": artifact.filename,
|
||||
},
|
||||
)
|
||||
|
||||
for root in roots:
|
||||
if not root.is_dir():
|
||||
continue
|
||||
for candidate in root.rglob("*"):
|
||||
if not _candidate_has_expected_size(candidate, artifact):
|
||||
continue
|
||||
if not _path_is_under(candidate, root):
|
||||
continue
|
||||
resolved_candidate = candidate.resolve()
|
||||
if resolved_candidate in checked:
|
||||
continue
|
||||
checked.add(resolved_candidate)
|
||||
if not _candidate_checksum_matches(candidate, artifact):
|
||||
continue
|
||||
LOGGER.info(
|
||||
"auto model artifact found under alternate filename",
|
||||
extra={
|
||||
"cache_id": artifact.cache_id,
|
||||
"path": str(candidate),
|
||||
"artifact_filename": artifact.filename,
|
||||
},
|
||||
)
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def _candidate_matches_artifact(
|
||||
candidate: Path,
|
||||
artifact: AutoModelArtifact,
|
||||
) -> bool:
|
||||
"""Verify a candidate only when its inexpensive file checks match first."""
|
||||
|
||||
return _candidate_has_expected_size(
|
||||
candidate,
|
||||
artifact,
|
||||
) and _candidate_checksum_matches(candidate, artifact)
|
||||
|
||||
|
||||
def _candidate_has_expected_size(
|
||||
candidate: Path,
|
||||
artifact: AutoModelArtifact,
|
||||
) -> bool:
|
||||
"""Return whether a regular file has the artifact's exact byte size."""
|
||||
|
||||
return candidate.is_file() and candidate.stat().st_size == artifact.file_size_bytes
|
||||
|
||||
|
||||
def _candidate_checksum_matches(
|
||||
candidate: Path,
|
||||
artifact: AutoModelArtifact,
|
||||
) -> bool:
|
||||
"""Return whether an already size-matched candidate has the trusted digest."""
|
||||
|
||||
return sha256_file(candidate).lower() == artifact.sha256.lower()
|
||||
|
||||
|
||||
def find_model_by_basename(
|
||||
folder_name: str,
|
||||
basename: str,
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, cast
|
||||
|
||||
@@ -50,6 +51,79 @@ class ClipHookScheduleMutation:
|
||||
register_hooks(self.hooks, self.target)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClipCallableObjectPatchMutation:
|
||||
"""Patch one callable text-encoder object on a derived CLIP patcher."""
|
||||
|
||||
path: str
|
||||
replacement: Callable[..., object]
|
||||
|
||||
def apply(self, clip: object) -> None:
|
||||
"""Validate the path and collision state before installing the callback."""
|
||||
|
||||
if (
|
||||
not isinstance(self.path, str)
|
||||
or not self.path
|
||||
or any(not segment for segment in self.path.split("."))
|
||||
):
|
||||
raise ValueError("CLIP callable patch path must be a dotted path.")
|
||||
if not callable(self.replacement):
|
||||
raise TypeError("CLIP callable object replacement must be callable.")
|
||||
patcher = _required_attribute(clip, "patcher", value_name="CLIP")
|
||||
getter = getattr(patcher, "get_model_object", None)
|
||||
adder = getattr(patcher, "add_object_patch", None)
|
||||
object_patches = getattr(patcher, "object_patches", None)
|
||||
if (
|
||||
not callable(getter)
|
||||
or not callable(adder)
|
||||
or not isinstance(object_patches, dict)
|
||||
):
|
||||
raise TypeError("CLIP patcher does not expose callable object patches.")
|
||||
if self.path in object_patches:
|
||||
raise ValueError(f"CLIP object path '{self.path}' already has a patch.")
|
||||
if not callable(getter(self.path)):
|
||||
raise TypeError(f"CLIP object path '{self.path}' must be callable.")
|
||||
adder(self.path, self.replacement)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClipTokenizerMutation:
|
||||
"""Replace the tokenizer on a derived CLIP after exact source validation."""
|
||||
|
||||
expected_source: object
|
||||
replacement: object
|
||||
|
||||
def apply(self, clip: object) -> None:
|
||||
"""Install one tokenizer proxy only on the expected cloned source value."""
|
||||
|
||||
if getattr(clip, "tokenizer", None) is not self.expected_source:
|
||||
raise ValueError("Derived CLIP tokenizer does not match its source.")
|
||||
cast(Any, clip).tokenizer = self.replacement
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClipBooleanOptionMutation:
|
||||
"""Publish one collision-safe boolean option on a derived CLIP patcher."""
|
||||
|
||||
key: str
|
||||
value: bool
|
||||
|
||||
def apply(self, clip: object) -> None:
|
||||
"""Set an approved ownership marker after validating the option mapping."""
|
||||
|
||||
if self.key not in {"ppm_negpip", "simple_syrup_negpip"}:
|
||||
raise ValueError("Unsupported CLIP boolean option marker.")
|
||||
if not isinstance(self.value, bool):
|
||||
raise TypeError("CLIP option marker value must be boolean.")
|
||||
patcher = _required_attribute(clip, "patcher", value_name="CLIP")
|
||||
options = getattr(patcher, "model_options", None)
|
||||
if not isinstance(options, dict):
|
||||
raise TypeError("CLIP patcher model_options must be a dictionary.")
|
||||
if self.key in options:
|
||||
raise ValueError(f"CLIP option '{self.key}' is already present.")
|
||||
options[self.key] = self.value
|
||||
|
||||
|
||||
def _required_attribute(value: object, name: str, *, value_name: str) -> object:
|
||||
"""Return a required dynamic ComfyUI boundary attribute."""
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Validate ComfyUI text-encoder type availability before model downloads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ComfyClipTypeSupport:
|
||||
"""Validate named ComfyUI CLIP types at the runtime boundary."""
|
||||
|
||||
def require(self, clip_type_name: str) -> None:
|
||||
"""Raise an actionable error when ComfyUI lacks a required CLIP type."""
|
||||
|
||||
comfy_sd: Any = importlib.import_module("comfy.sd")
|
||||
if hasattr(comfy_sd.CLIPType, clip_type_name):
|
||||
return
|
||||
raise RuntimeError(
|
||||
f"This loader requires ComfyUI CLIP type '{clip_type_name}'. "
|
||||
"Update ComfyUI before using this node."
|
||||
)
|
||||
@@ -27,6 +27,7 @@ from ..services.attention_coupling_preparation_service import (
|
||||
AttentionCouplingPreparation,
|
||||
)
|
||||
from .attention_coupling.context_validation import RegionalContextValidator
|
||||
from .ppm_negpip_interop import PpmNegpipInterop
|
||||
|
||||
|
||||
class ComfyRegionalConditioningProcessor:
|
||||
@@ -40,6 +41,7 @@ class ComfyRegionalConditioningProcessor:
|
||||
noise: torch.Tensor,
|
||||
device: torch.device,
|
||||
context_validator: RegionalContextValidator,
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> ProcessedRegionalAttentionPlan:
|
||||
"""Return model-ready positive and negative context banks."""
|
||||
|
||||
@@ -57,6 +59,8 @@ class ComfyRegionalConditioningProcessor:
|
||||
raise TypeError("Regional context processing device must be torch.device.")
|
||||
if not isinstance(context_validator, RegionalContextValidator):
|
||||
raise TypeError("Regional context validator has an invalid type.")
|
||||
if negpip is not None and not isinstance(negpip, PpmNegpipInterop):
|
||||
raise TypeError("Regional conditioning NegPiP state has an invalid type.")
|
||||
base_model = getattr(model, "model", None)
|
||||
extra_conds = getattr(base_model, "extra_conds", None)
|
||||
if not callable(extra_conds):
|
||||
@@ -75,6 +79,7 @@ class ComfyRegionalConditioningProcessor:
|
||||
noise=noise,
|
||||
device=device,
|
||||
context_validator=context_validator,
|
||||
negpip=negpip,
|
||||
)
|
||||
negative = self._process_branch(
|
||||
preparation.plan.negative,
|
||||
@@ -84,6 +89,7 @@ class ComfyRegionalConditioningProcessor:
|
||||
noise=noise,
|
||||
device=device,
|
||||
context_validator=context_validator,
|
||||
negpip=negpip,
|
||||
)
|
||||
return ProcessedRegionalAttentionPlan(
|
||||
positive=positive,
|
||||
@@ -102,6 +108,7 @@ class ComfyRegionalConditioningProcessor:
|
||||
noise: torch.Tensor,
|
||||
device: torch.device,
|
||||
context_validator: RegionalContextValidator,
|
||||
negpip: PpmNegpipInterop | None,
|
||||
) -> ProcessedRegionalAttentionBranch:
|
||||
"""Process one base plus its ordered regional context bank."""
|
||||
|
||||
@@ -115,6 +122,7 @@ class ComfyRegionalConditioningProcessor:
|
||||
noise=noise,
|
||||
device=device,
|
||||
context_validator=context_validator,
|
||||
negpip=negpip,
|
||||
)
|
||||
regional = tuple(
|
||||
self._process_context(
|
||||
@@ -127,6 +135,7 @@ class ComfyRegionalConditioningProcessor:
|
||||
noise=noise,
|
||||
device=device,
|
||||
context_validator=context_validator,
|
||||
negpip=negpip,
|
||||
)
|
||||
for context in branch.regional_contexts
|
||||
)
|
||||
@@ -144,6 +153,7 @@ class ComfyRegionalConditioningProcessor:
|
||||
noise: torch.Tensor,
|
||||
device: torch.device,
|
||||
context_validator: RegionalContextValidator,
|
||||
negpip: PpmNegpipInterop | None,
|
||||
) -> ProcessedRegionalAttentionContext:
|
||||
"""Convert and extract one exact post-adapter Anima context tensor."""
|
||||
|
||||
@@ -168,6 +178,7 @@ class ComfyRegionalConditioningProcessor:
|
||||
conditioning_index=conditioning_index,
|
||||
prompt_type=prompt_type,
|
||||
context_validator=context_validator,
|
||||
negpip=negpip,
|
||||
)
|
||||
for entry_index, encoded_item in enumerate(encoded)
|
||||
)
|
||||
@@ -185,6 +196,7 @@ class ComfyRegionalConditioningProcessor:
|
||||
conditioning_index: int,
|
||||
prompt_type: str,
|
||||
context_validator: RegionalContextValidator,
|
||||
negpip: PpmNegpipInterop | None,
|
||||
) -> ProcessedRegionalAttentionEntry:
|
||||
"""Extract one exact post-adapter Anima context and Comfy strength."""
|
||||
|
||||
@@ -233,6 +245,11 @@ class ComfyRegionalConditioningProcessor:
|
||||
),
|
||||
cross_attention=context,
|
||||
strength=float(strength),
|
||||
cross_attention_value_multiplier=(
|
||||
None
|
||||
if negpip is None
|
||||
else negpip.extract_value_multiplier(model_conds, context)
|
||||
),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -49,6 +49,7 @@ class ContextualDiffusionModelWrapper:
|
||||
self._tile_predictions = TilePredictionAccumulator(
|
||||
plan.tile_plan,
|
||||
diffusion_mode=diffusion_mode,
|
||||
project_canvas_reference_latents=True,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -110,6 +111,7 @@ class ContextualDiffusionModelWrapper:
|
||||
global_args = make_spatial_view_model_args(
|
||||
args=args,
|
||||
layout=global_layout,
|
||||
project_canvas_reference_latents=True,
|
||||
)
|
||||
global_prediction = self._call_original(apply_model, global_args)
|
||||
global_view = self._plan.global_view
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Inspect tensor-derived metadata exposed by loaded ComfyUI diffusion models."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from ..shared.logging import get_logger
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiffusionModelMetadata:
|
||||
"""Describe architecture fields relevant to component selection."""
|
||||
|
||||
image_model: str | None
|
||||
context_input_dimension: int | None
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ModelPatcherBoundary(Protocol):
|
||||
"""Expose the loaded model objects required for architecture inspection."""
|
||||
|
||||
def get_model_object(self, name: str) -> object:
|
||||
"""Return a named object owned by ComfyUI's model patcher."""
|
||||
|
||||
|
||||
class DiffusionModelMetadataInspector:
|
||||
"""Read normalized architecture metadata from a loaded model patcher."""
|
||||
|
||||
def inspect(self, model: object) -> DiffusionModelMetadata | None:
|
||||
"""Return narrowed model metadata or None when it is unavailable."""
|
||||
|
||||
if not isinstance(model, ModelPatcherBoundary):
|
||||
return None
|
||||
try:
|
||||
model_config = model.get_model_object("model_config")
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
LOGGER.warning(
|
||||
"loaded model does not expose inspectable model configuration"
|
||||
)
|
||||
return None
|
||||
|
||||
unet_config = getattr(model_config, "unet_config", None)
|
||||
if not isinstance(unet_config, Mapping):
|
||||
return None
|
||||
image_model_value = unet_config.get("image_model")
|
||||
context_dimension_value = unet_config.get("context_in_dim")
|
||||
return DiffusionModelMetadata(
|
||||
image_model=(
|
||||
image_model_value if isinstance(image_model_value, str) else None
|
||||
),
|
||||
context_input_dimension=(
|
||||
context_dimension_value
|
||||
if isinstance(context_dimension_value, int)
|
||||
and not isinstance(context_dimension_value, bool)
|
||||
else None
|
||||
),
|
||||
)
|
||||
@@ -21,6 +21,7 @@ FLUX_CLIP_L = AutoModelArtifact(
|
||||
source_repo="comfyanonymous/flux_text_encoders",
|
||||
description="FLUX CLIP-L text encoder",
|
||||
sha256="660c6f5b1abae9dc498ac2d21e1347d2abdb0cf6c0c0c8576cd796491d9a6cdd",
|
||||
file_size_bytes=246_144_152,
|
||||
)
|
||||
|
||||
FLUX_T5_XXL = AutoModelArtifact(
|
||||
@@ -35,6 +36,7 @@ FLUX_T5_XXL = AutoModelArtifact(
|
||||
source_repo="comfyanonymous/flux_text_encoders",
|
||||
description="FLUX T5-XXL FP16 text encoder",
|
||||
sha256="6e480b09fae049a72d2a8c5fbccb8d3e92febeb233bbe9dfe7256958a9167635",
|
||||
file_size_bytes=9_787_841_024,
|
||||
)
|
||||
|
||||
FLUX_VAE = AutoModelArtifact(
|
||||
@@ -50,6 +52,7 @@ FLUX_VAE = AutoModelArtifact(
|
||||
source_repo="Comfy-Org/Lumina_Image_2.0_Repackaged",
|
||||
description="FLUX autoencoder VAE",
|
||||
sha256="afc8e28272cd15db3919bacdb6918ce9c1ed22e96cb12c4d5ed0fba823529e38",
|
||||
file_size_bytes=335_304_388,
|
||||
)
|
||||
|
||||
FLUX2_DEV_TEXT_ENCODER = AutoModelArtifact(
|
||||
@@ -65,6 +68,7 @@ FLUX2_DEV_TEXT_ENCODER = AutoModelArtifact(
|
||||
source_repo="Comfy-Org/flux2-dev",
|
||||
description="FLUX.2 dev Mistral 3 Small text encoder",
|
||||
sha256="7d79902f60b1aeb3a6de2cfad02f4367b5e300a1387de3d03ac717cfa3df117c",
|
||||
file_size_bytes=35_584_897_447,
|
||||
)
|
||||
|
||||
FLUX2_KLEIN_4B_TEXT_ENCODER = AutoModelArtifact(
|
||||
@@ -80,6 +84,7 @@ FLUX2_KLEIN_4B_TEXT_ENCODER = AutoModelArtifact(
|
||||
source_repo="Comfy-Org/vae-text-encorder-for-flux-klein-4b",
|
||||
description="FLUX.2 Klein 4B Qwen3 text encoder",
|
||||
sha256="6c671498573ac2f7a5501502ccce8d2b08ea6ca2f661c458e708f36b36edfc5a",
|
||||
file_size_bytes=8_044_982_048,
|
||||
)
|
||||
|
||||
FLUX2_KLEIN_9B_TEXT_ENCODER = AutoModelArtifact(
|
||||
@@ -95,6 +100,7 @@ FLUX2_KLEIN_9B_TEXT_ENCODER = AutoModelArtifact(
|
||||
source_repo="Comfy-Org/vae-text-encorder-for-flux-klein-9b",
|
||||
description="FLUX.2 Klein 9B Qwen3 8B FP8-mixed text encoder",
|
||||
sha256="abad16806e0cbabc54e0325d6565847443fe396d5f0be38bb3cd3fe75a1201d6",
|
||||
file_size_bytes=8_664_848_742,
|
||||
)
|
||||
|
||||
FLUX2_VAE = AutoModelArtifact(
|
||||
@@ -110,6 +116,7 @@ FLUX2_VAE = AutoModelArtifact(
|
||||
source_repo="Comfy-Org/flux2-dev",
|
||||
description="FLUX.2 VAE",
|
||||
sha256="d64f3a68e1cc4f9f4e29b6e0da38a0204fe9a49f2d4053f0ec1fa1ca02f9c4b5",
|
||||
file_size_bytes=336_213_556,
|
||||
)
|
||||
|
||||
FLUX2_TEXT_ENCODERS: dict[Flux2TextEncoderProfile, AutoModelArtifact] = {
|
||||
|
||||
@@ -6,49 +6,42 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Protocol, runtime_checkable
|
||||
from typing import Protocol
|
||||
|
||||
from ..domain.flux_profiles import FluxModelProfile, classify_flux_profile
|
||||
from ..shared.logging import get_logger
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ModelPatcherBoundary(Protocol):
|
||||
"""Expose the loaded model objects required for architecture inspection."""
|
||||
|
||||
def get_model_object(self, name: str) -> object:
|
||||
"""Return a named object owned by ComfyUI's model patcher."""
|
||||
from .diffusion_model_metadata import (
|
||||
DiffusionModelMetadata,
|
||||
DiffusionModelMetadataInspector,
|
||||
)
|
||||
|
||||
|
||||
class FluxModelInspector:
|
||||
"""Read ComfyUI's tensor-derived model configuration after model loading."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
metadata_inspector: DiffusionModelMetadataInspectorBoundary | None = None,
|
||||
) -> None:
|
||||
"""Create a FLUX classifier over shared metadata inspection."""
|
||||
|
||||
self._metadata_inspector = (
|
||||
metadata_inspector or DiffusionModelMetadataInspector()
|
||||
)
|
||||
|
||||
def inspect(self, model: object) -> FluxModelProfile | None:
|
||||
"""Return a detected FLUX profile or None for unavailable metadata."""
|
||||
|
||||
if not isinstance(model, ModelPatcherBoundary):
|
||||
metadata = self._metadata_inspector.inspect(model)
|
||||
if metadata is None:
|
||||
return None
|
||||
try:
|
||||
model_config = model.get_model_object("model_config")
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
LOGGER.warning(
|
||||
"loaded model does not expose inspectable model configuration"
|
||||
)
|
||||
return None
|
||||
|
||||
unet_config = getattr(model_config, "unet_config", None)
|
||||
if not isinstance(unet_config, Mapping):
|
||||
return None
|
||||
image_model_value = unet_config.get("image_model")
|
||||
context_dimension_value = unet_config.get("context_in_dim")
|
||||
image_model = image_model_value if isinstance(image_model_value, str) else None
|
||||
context_dimension = (
|
||||
context_dimension_value
|
||||
if isinstance(context_dimension_value, int)
|
||||
and not isinstance(context_dimension_value, bool)
|
||||
else None
|
||||
return classify_flux_profile(
|
||||
metadata.image_model,
|
||||
metadata.context_input_dimension,
|
||||
)
|
||||
return classify_flux_profile(image_model, context_dimension)
|
||||
|
||||
|
||||
class DiffusionModelMetadataInspectorBoundary(Protocol):
|
||||
"""Expose normalized loaded diffusion-model metadata."""
|
||||
|
||||
def inspect(self, model: object) -> DiffusionModelMetadata | None:
|
||||
"""Return normalized metadata when available."""
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Compose global-first conditioning hooks for conventional regional sampling."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, TypeAlias
|
||||
|
||||
from comfy.hooks import HookGroup
|
||||
|
||||
from .regional_lora_conditioning_sources import conditioning_hook_groups
|
||||
|
||||
Conditioning: TypeAlias = list[list[Any]]
|
||||
|
||||
|
||||
class GlobalFirstConditioningHookComposer:
|
||||
"""Apply one global HookGroup to every regional conditioning model state."""
|
||||
|
||||
def global_hooks(
|
||||
self,
|
||||
conditioning: Conditioning,
|
||||
*,
|
||||
source_label: str,
|
||||
) -> HookGroup | None:
|
||||
"""Return the single uniform HookGroup carried by global conditioning."""
|
||||
|
||||
groups = conditioning_hook_groups(conditioning)
|
||||
if not groups:
|
||||
return None
|
||||
authority = groups[0]
|
||||
if any(group is not authority for group in groups[1:]):
|
||||
raise ValueError(
|
||||
f"{source_label} uses different HookGroups across conditioning "
|
||||
"entries. Keep one shared Prompt Control hook schedule on the "
|
||||
"global segment."
|
||||
)
|
||||
return authority
|
||||
|
||||
def compose(
|
||||
self,
|
||||
conditioning: Conditioning,
|
||||
global_hooks: HookGroup | None,
|
||||
*,
|
||||
source_label: str,
|
||||
cache: dict[tuple[HookGroup, HookGroup], HookGroup],
|
||||
) -> Conditioning:
|
||||
"""Prepend global hooks to every local HookGroup without mutating inputs."""
|
||||
|
||||
if global_hooks is None:
|
||||
return [[item[0], dict(item[1])] for item in conditioning]
|
||||
composed: Conditioning = []
|
||||
for item_index, item in enumerate(conditioning):
|
||||
metadata = dict(item[1])
|
||||
local_hooks = metadata.get("hooks")
|
||||
if local_hooks is None:
|
||||
metadata["hooks"] = global_hooks
|
||||
elif not isinstance(local_hooks, HookGroup):
|
||||
raise TypeError(
|
||||
f"{source_label} item {item_index} hooks must be a Comfy HookGroup."
|
||||
)
|
||||
else:
|
||||
key = (global_hooks, local_hooks)
|
||||
combined = cache.get(key)
|
||||
if combined is None:
|
||||
combined = global_hooks.clone_and_combine(local_hooks)
|
||||
cache[key] = combined
|
||||
metadata["hooks"] = combined
|
||||
composed.append([item[0], metadata])
|
||||
return composed
|
||||
|
||||
|
||||
GLOBAL_FIRST_CONDITIONING_HOOK_COMPOSER = GlobalFirstConditioningHookComposer()
|
||||
@@ -0,0 +1,63 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Resolve the effective Comfy MODEL before global conditioning hooks execute."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import cast
|
||||
|
||||
from ..domain.conditioning_batch import select_conditioning
|
||||
from .regional_lora_conditioning_sources import conditioning_hook_groups
|
||||
|
||||
|
||||
class GlobalHookModelResolver:
|
||||
"""Mirror Comfy's dynamic-to-static handoff before regional derivation."""
|
||||
|
||||
def resolve(
|
||||
self,
|
||||
model: object,
|
||||
*,
|
||||
positive: object,
|
||||
negative: object,
|
||||
) -> object:
|
||||
"""Return the model that Comfy will use for global hooked conditioning."""
|
||||
|
||||
if not self._has_global_hooks(positive) and not self._has_global_hooks(
|
||||
negative
|
||||
):
|
||||
return model
|
||||
is_dynamic = getattr(model, "is_dynamic", None)
|
||||
if not callable(is_dynamic):
|
||||
raise TypeError(
|
||||
"Global conditioning hooks require MODEL dynamic-mode state."
|
||||
)
|
||||
dynamic = is_dynamic()
|
||||
if not isinstance(dynamic, bool):
|
||||
raise TypeError("MODEL is_dynamic() must return a bool.")
|
||||
if not dynamic:
|
||||
return model
|
||||
delegate_factory = getattr(model, "get_non_dynamic_delegate", None)
|
||||
if not callable(delegate_factory):
|
||||
raise TypeError(
|
||||
"Dynamic MODEL global conditioning hooks require Comfy's "
|
||||
"get_non_dynamic_delegate()."
|
||||
)
|
||||
resolved = delegate_factory()
|
||||
if resolved is model:
|
||||
raise RuntimeError("Dynamic MODEL returned itself as its static delegate.")
|
||||
resolved_is_dynamic = getattr(resolved, "is_dynamic", None)
|
||||
if not callable(resolved_is_dynamic) or resolved_is_dynamic() is not False:
|
||||
raise RuntimeError("Global conditioning hook delegate must be static.")
|
||||
return cast(object, resolved)
|
||||
|
||||
@staticmethod
|
||||
def _has_global_hooks(conditioning: object) -> bool:
|
||||
"""Report hooks only on consumer-defined global entry zero."""
|
||||
|
||||
global_conditioning = select_conditioning(conditioning, 0)
|
||||
return bool(conditioning_hook_groups(global_conditioning))
|
||||
|
||||
|
||||
GLOBAL_HOOK_MODEL_RESOLVER = GlobalHookModelResolver()
|
||||
@@ -0,0 +1,56 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Declare trusted automatic artifacts and selections for Krea 2."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .auto_model_artifact import AutoModelArtifact
|
||||
|
||||
KREA2_AUTO_TEXT_ENCODER = "auto"
|
||||
|
||||
KREA2_QWEN3_VL_4B_FP8 = AutoModelArtifact(
|
||||
cache_id="krea2_qwen3vl_4b_fp8_scaled",
|
||||
filename="qwen3vl_4b_fp8_scaled.safetensors",
|
||||
folder_name="text_encoders",
|
||||
canonical_subfolder="krea2",
|
||||
source_url=(
|
||||
"https://huggingface.co/Comfy-Org/Krea-2/resolve/"
|
||||
"e5ea8b4dd7f38f348b138eb0fe29f92c0e367e96/text_encoders/"
|
||||
"qwen3vl_4b_fp8_scaled.safetensors"
|
||||
),
|
||||
source_repo="Comfy-Org/Krea-2",
|
||||
description="Krea 2 Qwen3-VL 4B FP8-scaled text encoder",
|
||||
sha256="54bd5144df0bbc25dd6ccadfcb826b521445a1b06ae5a42570bdd2974ca87094",
|
||||
file_size_bytes=5_242_467_968,
|
||||
)
|
||||
|
||||
KREA2_QWEN3_VL_4B_BF16 = AutoModelArtifact(
|
||||
cache_id="krea2_qwen3vl_4b_bf16",
|
||||
filename="qwen3vl_4b_bf16.safetensors",
|
||||
folder_name="text_encoders",
|
||||
canonical_subfolder="krea2",
|
||||
source_url=(
|
||||
"https://huggingface.co/Comfy-Org/Krea-2/resolve/"
|
||||
"e5ea8b4dd7f38f348b138eb0fe29f92c0e367e96/text_encoders/"
|
||||
"qwen3vl_4b_bf16.safetensors"
|
||||
),
|
||||
source_repo="Comfy-Org/Krea-2",
|
||||
description="Krea 2 Qwen3-VL 4B BF16 text encoder",
|
||||
sha256="36f3ff447ef59201722e8f9ce6020c9819fdcfba6aa2608c4e09b1c0ce114e34",
|
||||
file_size_bytes=8_875_719_384,
|
||||
)
|
||||
|
||||
KREA2_TEXT_ENCODER_ARTIFACTS = {
|
||||
KREA2_QWEN3_VL_4B_FP8.filename: KREA2_QWEN3_VL_4B_FP8,
|
||||
KREA2_QWEN3_VL_4B_BF16.filename: KREA2_QWEN3_VL_4B_BF16,
|
||||
}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"KREA2_AUTO_TEXT_ENCODER",
|
||||
"KREA2_QWEN3_VL_4B_BF16",
|
||||
"KREA2_QWEN3_VL_4B_FP8",
|
||||
"KREA2_TEXT_ENCODER_ARTIFACTS",
|
||||
]
|
||||
@@ -22,6 +22,7 @@ def _apply_paired_attention_patches(
|
||||
attention_name: str,
|
||||
input_patch: Callable[..., object],
|
||||
output_patch: Callable[..., object],
|
||||
trailing_input_patches: tuple[Callable[..., object], ...],
|
||||
) -> None:
|
||||
"""Validate and atomically install one paired attention callback surface."""
|
||||
|
||||
@@ -29,6 +30,12 @@ def _apply_paired_attention_patches(
|
||||
raise TypeError(f"MODEL {attention_name} input patch must be callable.")
|
||||
if not callable(output_patch):
|
||||
raise TypeError(f"MODEL {attention_name} output patch must be callable.")
|
||||
if not isinstance(trailing_input_patches, tuple) or any(
|
||||
not callable(patch) for patch in trailing_input_patches
|
||||
):
|
||||
raise TypeError(
|
||||
f"MODEL {attention_name} preserved input patches must be callables."
|
||||
)
|
||||
input_setter = _require_bound_method(
|
||||
model,
|
||||
f"set_model_{attention_name}_patch",
|
||||
@@ -54,11 +61,21 @@ def _apply_paired_attention_patches(
|
||||
output_name = f"{attention_name}_output_patch"
|
||||
input_exists = _require_callable_patch_list(patches, input_name)
|
||||
output_exists = _require_callable_patch_list(patches, output_name)
|
||||
if input_exists:
|
||||
existing_input = patches.get(input_name, [])
|
||||
if input_exists and (
|
||||
not trailing_input_patches or existing_input != list(trailing_input_patches)
|
||||
):
|
||||
raise ValueError(f"MODEL {attention_name} input patch is already installed.")
|
||||
if not input_exists and trailing_input_patches:
|
||||
raise ValueError(
|
||||
f"MODEL {attention_name} preserved input patch is not installed."
|
||||
)
|
||||
if output_exists:
|
||||
raise ValueError(f"MODEL {attention_name} output patch is already installed.")
|
||||
input_setter(input_patch)
|
||||
if trailing_input_patches:
|
||||
patches[input_name] = [input_patch, *trailing_input_patches]
|
||||
else:
|
||||
input_setter(input_patch)
|
||||
output_setter(output_patch)
|
||||
|
||||
|
||||
@@ -68,6 +85,7 @@ class ModelAttn2PatchesMutation:
|
||||
|
||||
input_patch: Callable[..., object]
|
||||
output_patch: Callable[..., object]
|
||||
trailing_input_patches: tuple[Callable[..., object], ...] = ()
|
||||
|
||||
def apply(self, model: object) -> None:
|
||||
"""Validate both attn2 surfaces before either mutation."""
|
||||
@@ -77,4 +95,5 @@ class ModelAttn2PatchesMutation:
|
||||
attention_name="attn2",
|
||||
input_patch=self.input_patch,
|
||||
output_patch=self.output_patch,
|
||||
trailing_input_patches=self.trailing_input_patches,
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Known model metadata for grounded SAM masking."""
|
||||
"""Known model metadata for downloadable SimpleSyrup model loaders."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -11,13 +11,14 @@ from enum import StrEnum
|
||||
|
||||
|
||||
class ModelFamily(StrEnum):
|
||||
"""Catalog families used by grounded SAM model selection."""
|
||||
"""Catalog families used by SimpleSyrup model selection."""
|
||||
|
||||
SAM = "sam"
|
||||
GROUNDING_DINO = "grounding_dino"
|
||||
TEXT_ENCODER = "text_encoder"
|
||||
VITMATTE = "vitmatte"
|
||||
WD14_TAGGER = "wd14_tagger"
|
||||
ULTRALYTICS = "ultralytics"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -29,6 +30,7 @@ class ModelArtifact:
|
||||
folder_name: str
|
||||
source_url: str
|
||||
description: str
|
||||
sha256: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -386,6 +388,298 @@ WD14_TAGGER_ENTRIES: tuple[ModelEntry, ...] = (
|
||||
)
|
||||
|
||||
|
||||
_ANZHCS_YOLOS_REVISION = "f5a2306d7fed4f3cfc26c25ff1ab2e3f3cfce855"
|
||||
_ANZHCS_YOLOS_REPOSITORY = "Anzhc/Anzhcs_YOLOs"
|
||||
|
||||
|
||||
def _huggingface_yolo_entry(
|
||||
*,
|
||||
entry_id: str,
|
||||
display_name: str,
|
||||
filename: str,
|
||||
folder_name: str,
|
||||
model_type: str,
|
||||
source_repo: str,
|
||||
revision: str,
|
||||
license_note: str,
|
||||
description: str,
|
||||
sha256: str,
|
||||
) -> ModelEntry:
|
||||
"""Build one revision-pinned Hugging Face Ultralytics catalog entry."""
|
||||
|
||||
encoded_filename = filename.replace(" ", "%20")
|
||||
return ModelEntry(
|
||||
entry_id=entry_id,
|
||||
display_name=display_name,
|
||||
family=ModelFamily.ULTRALYTICS,
|
||||
model_type=model_type,
|
||||
source_repo=source_repo,
|
||||
license_note=license_note,
|
||||
artifacts=(
|
||||
ModelArtifact(
|
||||
artifact_id=f"{entry_id}_checkpoint",
|
||||
filename=filename,
|
||||
folder_name=folder_name,
|
||||
source_url=(
|
||||
f"https://huggingface.co/{source_repo}/resolve/{revision}/"
|
||||
f"{encoded_filename}"
|
||||
),
|
||||
description=description,
|
||||
sha256=sha256,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _anzhc_yolo_entry(
|
||||
*,
|
||||
entry_id: str,
|
||||
display_name: str,
|
||||
filename: str,
|
||||
folder_name: str,
|
||||
model_type: str,
|
||||
description: str,
|
||||
sha256: str,
|
||||
) -> ModelEntry:
|
||||
"""Build one revision-pinned Anzhc Ultralytics catalog entry."""
|
||||
|
||||
return _huggingface_yolo_entry(
|
||||
entry_id=entry_id,
|
||||
display_name=display_name,
|
||||
filename=filename,
|
||||
folder_name=folder_name,
|
||||
model_type=model_type,
|
||||
source_repo=_ANZHCS_YOLOS_REPOSITORY,
|
||||
revision=_ANZHCS_YOLOS_REVISION,
|
||||
license_note="AGPL-3.0",
|
||||
description=description,
|
||||
sha256=sha256,
|
||||
)
|
||||
|
||||
|
||||
ULTRALYTICS_ENTRIES: tuple[ModelEntry, ...] = (
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_face_seg",
|
||||
display_name="Anzhc Face -seg (6.52MB)",
|
||||
filename="Anzhc Face -seg.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc face segmentation model",
|
||||
sha256="dbf083201298a495e332113de0612d1be1ae8307628628eb7972a31979cdbbb3",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_face_seg_640_v2_y8n",
|
||||
display_name="Anzhc Face seg 640 v2 y8n (6.56MB)",
|
||||
filename="Anzhc Face seg 640 v2 y8n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc face segmentation model",
|
||||
sha256="d473e8bccc4c833d8eb36c95e566ce6460ffdc8b2899c859910e380c85def276",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_face_seg_768_v2_y8n",
|
||||
display_name="Anzhc Face seg 768 v2 y8n (6.58MB)",
|
||||
filename="Anzhc Face seg 768 v2 y8n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc face segmentation model",
|
||||
sha256="9a1e5b154c1d190812447431bda6b8f260f132877812b4a2f163981f54558355",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_face_seg_768ms_v2_y8n",
|
||||
display_name="Anzhc Face seg 768MS v2 y8n (6.60MB)",
|
||||
filename="Anzhc Face seg 768MS v2 y8n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc multi-scale face segmentation model",
|
||||
sha256="429e88d9aecb9fa4167ffd41a6ebc42c97b7fa785aa5468a7eb302ceb9837aae",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_face_seg_1024_v2_y8n",
|
||||
display_name="Anzhc Face seg 1024 v2 y8n (6.63MB)",
|
||||
filename="Anzhc Face seg 1024 v2 y8n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc face segmentation model",
|
||||
sha256="1bbcfd7a9f407c6f6e4389a371dbcc392f9444421cf7f824152e92bf563dc6a3",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_face_seg_640_v3_y11n",
|
||||
display_name="Anzhc Face seg 640 v3 y11n (5.80MB)",
|
||||
filename="Anzhc Face seg 640 v3 y11n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc YOLO11 face segmentation model",
|
||||
sha256="96437afc773bacd118e275e6cddc1fb7263c78dc11299989c7a00a26506c45bf",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_face_seg_640_v4_y11n",
|
||||
display_name="Anzhc Face seg 640 v4 y11n (5.74MB)",
|
||||
filename="Anzhc Face seg 640 v4 y11n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc YOLO11 face segmentation model",
|
||||
sha256="1e77ad7bd349babd8a4a90478bfc965348642b63a8d95d3b43ee13db42fd0a64",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhcs_manface_v02_1024_y8n",
|
||||
display_name="Anzhcs ManFace v02 1024 y8n (6.06MB)",
|
||||
filename="Anzhcs ManFace v02 1024 y8n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc male face segmentation model",
|
||||
sha256="184b9a680afb3c4a559e46e2fe692338fe7bdd6267979fa4ef10526fa96c1b31",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhcs_womanface_v05_1024_y8n",
|
||||
display_name="Anzhcs WomanFace v05 1024 y8n (6.07MB)",
|
||||
filename="Anzhcs WomanFace v05 1024 y8n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc female face segmentation model",
|
||||
sha256="84db37616e1ca975c4e23fa5a300acf0edd9144ec287bbbdbd1ad0f4a3afa9c1",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_eyes_seg_hd",
|
||||
display_name="Anzhc Eyes -seg-hd (6.59MB)",
|
||||
filename="Anzhc Eyes -seg-hd.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc eye segmentation model",
|
||||
sha256="6be1c13ca7a51c2425e278e07e7ae3d4c94ee125b874a0104a142f4f5a35a308",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_headhair_seg_y8n",
|
||||
display_name="Anzhc HeadHair seg y8n (6.50MB)",
|
||||
filename="Anzhc HeadHair seg y8n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc head and hair segmentation model",
|
||||
sha256="a6e99b1305f600c35e7f6400741c2322b198ae03755f91dc1c59d7a78d77f13c",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_headhair_seg_y8m",
|
||||
display_name="Anzhc HeadHair seg y8m (52.34MB)",
|
||||
filename="Anzhc HeadHair seg y8m.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc head and hair segmentation model",
|
||||
sha256="f63aa1cdb63a26c0025a4a984588248241a5838aff4edfeea93d9c155efe0b5e",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_breasts_seg_v1_1024n",
|
||||
display_name="Anzhc Breasts Seg v1 1024n (6.58MB)",
|
||||
filename="Anzhc Breasts Seg v1 1024n.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc breast segmentation model",
|
||||
sha256="d469bd7abdcbe32a946e0e342bc1fe96aa021987787d51245f97a29e114cb31b",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_breasts_seg_v1_1024s",
|
||||
display_name="Anzhc Breasts Seg v1 1024s (22.86MB)",
|
||||
filename="Anzhc Breasts Seg v1 1024s.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc breast segmentation model",
|
||||
sha256="413a9b948a40f96a83769a882816ef0dd2b91b49673c91bff75463660077b395",
|
||||
),
|
||||
_anzhc_yolo_entry(
|
||||
entry_id="anzhc_breasts_seg_v1_1024m",
|
||||
display_name="Anzhc Breasts Seg v1 1024m (52.39MB)",
|
||||
filename="Anzhc Breasts Seg v1 1024m.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
description="Anzhc breast segmentation model",
|
||||
sha256="53d15e82a8308f8056f4929838e00e42c8da576b661e0c2b4fef5837d8b5b2b4",
|
||||
),
|
||||
_huggingface_yolo_entry(
|
||||
entry_id="bingsu_face_yolov8n_v2",
|
||||
display_name="Bingsu Face YOLOv8n v2 (6.23MB)",
|
||||
filename="face_yolov8n_v2.pt",
|
||||
folder_name="ultralytics_bbox",
|
||||
model_type="detect",
|
||||
source_repo="Bingsu/adetailer",
|
||||
revision="53cc19de382014514d9d4038601d261a7faa9b7b",
|
||||
license_note="Apache-2.0",
|
||||
description="Bingsu ADetailer face detection model",
|
||||
sha256="8f5f2110f83c4e00712993fab48c771d26036e2e80ec62bd5b9cb37c29e36b36",
|
||||
),
|
||||
_huggingface_yolo_entry(
|
||||
entry_id="bingsu_face_yolov8s",
|
||||
display_name="Bingsu Face YOLOv8s (22.5MB)",
|
||||
filename="face_yolov8s.pt",
|
||||
folder_name="ultralytics_bbox",
|
||||
model_type="detect",
|
||||
source_repo="Bingsu/adetailer",
|
||||
revision="53cc19de382014514d9d4038601d261a7faa9b7b",
|
||||
license_note="Apache-2.0",
|
||||
description="Bingsu ADetailer face detection model",
|
||||
sha256="c7237eff25787377de196961140ceaed324d859ee8de5a775d93d33a0e3fab78",
|
||||
),
|
||||
_huggingface_yolo_entry(
|
||||
entry_id="bingsu_hand_yolov8n",
|
||||
display_name="Bingsu Hand YOLOv8n (6.23MB)",
|
||||
filename="hand_yolov8n.pt",
|
||||
folder_name="ultralytics_bbox",
|
||||
model_type="detect",
|
||||
source_repo="Bingsu/adetailer",
|
||||
revision="53cc19de382014514d9d4038601d261a7faa9b7b",
|
||||
license_note="Apache-2.0",
|
||||
description="Bingsu ADetailer hand detection model",
|
||||
sha256="3991202eb69e9ddcb3b9ba80cdeb41e734ffaf844403d6c9f47d515cd88c6f29",
|
||||
),
|
||||
_huggingface_yolo_entry(
|
||||
entry_id="bingsu_hand_yolov8s",
|
||||
display_name="Bingsu Hand YOLOv8s (22.5MB)",
|
||||
filename="hand_yolov8s.pt",
|
||||
folder_name="ultralytics_bbox",
|
||||
model_type="detect",
|
||||
source_repo="Bingsu/adetailer",
|
||||
revision="53cc19de382014514d9d4038601d261a7faa9b7b",
|
||||
license_note="Apache-2.0",
|
||||
description="Bingsu ADetailer hand detection model",
|
||||
sha256="70b540063fbc385736d8258970744a4afbc4cbf7932134bae3b24cdadeadec06",
|
||||
),
|
||||
_huggingface_yolo_entry(
|
||||
entry_id="bingsu_person_yolov8n_seg",
|
||||
display_name="Bingsu Person YOLOv8n-seg (6.78MB)",
|
||||
filename="person_yolov8n-seg.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
source_repo="Bingsu/adetailer",
|
||||
revision="53cc19de382014514d9d4038601d261a7faa9b7b",
|
||||
license_note="Apache-2.0",
|
||||
description="Bingsu ADetailer person segmentation model",
|
||||
sha256="38fc8aaae97cb6e70be4ec44770005b26ed473471362afcda62a0037d7ccf432",
|
||||
),
|
||||
_huggingface_yolo_entry(
|
||||
entry_id="bingsu_person_yolov8s_seg",
|
||||
display_name="Bingsu Person YOLOv8s-seg (23.9MB)",
|
||||
filename="person_yolov8s-seg.pt",
|
||||
folder_name="ultralytics_segm",
|
||||
model_type="segment",
|
||||
source_repo="Bingsu/adetailer",
|
||||
revision="53cc19de382014514d9d4038601d261a7faa9b7b",
|
||||
license_note="Apache-2.0",
|
||||
description="Bingsu ADetailer person segmentation model",
|
||||
sha256="53c54aec2239355faffc6c5b70d0f3d05042f386f956cbec39cec46ad456f050",
|
||||
),
|
||||
_huggingface_yolo_entry(
|
||||
entry_id="fuyucchi_yolov8x6_animeface",
|
||||
display_name="Fuyucchi YOLOv8x6 Anime Face (195MB)",
|
||||
filename="yolov8x6_animeface.pt",
|
||||
folder_name="ultralytics_bbox",
|
||||
model_type="detect",
|
||||
source_repo="Fuyucchi/yolov8_animeface",
|
||||
revision="b0841ce930453c0f23ceb8086d6554c17de5fe4a",
|
||||
license_note="AGPL-3.0",
|
||||
description="Fuyucchi high-resolution anime face detection model",
|
||||
sha256="f3cdc1a6266347322439fd9b3c8f5a1222668eb10c8adf00e17b28c48b95213c",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def sam_choices() -> list[str]:
|
||||
"""Return deterministic SAM dropdown choices."""
|
||||
|
||||
@@ -410,6 +704,12 @@ def wd14_tagger_choices() -> list[str]:
|
||||
return [entry.display_name for entry in WD14_TAGGER_ENTRIES]
|
||||
|
||||
|
||||
def ultralytics_choices() -> list[str]:
|
||||
"""Return deterministic Ultralytics dropdown choices."""
|
||||
|
||||
return [entry.display_name for entry in ULTRALYTICS_ENTRIES]
|
||||
|
||||
|
||||
def get_sam_entry(selection: str) -> ModelEntry:
|
||||
"""Return the SAM catalog entry matching an id or display name."""
|
||||
|
||||
@@ -434,6 +734,12 @@ def get_wd14_tagger_entry(selection: str) -> ModelEntry:
|
||||
return _get_entry(selection, WD14_TAGGER_ENTRIES, "WD14 tagger")
|
||||
|
||||
|
||||
def get_ultralytics_entry(selection: str) -> ModelEntry:
|
||||
"""Return the Ultralytics catalog entry matching an id or display name."""
|
||||
|
||||
return _get_entry(selection, ULTRALYTICS_ENTRIES, "Ultralytics")
|
||||
|
||||
|
||||
def _get_entry(
|
||||
selection: str,
|
||||
entries: tuple[ModelEntry, ...],
|
||||
|
||||
@@ -6,24 +6,17 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import ModuleType
|
||||
from typing import Protocol
|
||||
|
||||
from .model_catalog import (
|
||||
GROUNDING_DINO_ENTRIES,
|
||||
SAM_ENTRIES,
|
||||
VITMATTE_ENTRIES,
|
||||
WD14_TAGGER_ENTRIES,
|
||||
ModelEntry,
|
||||
grounding_dino_choices,
|
||||
sam_choices,
|
||||
ultralytics_choices,
|
||||
vitmatte_choices,
|
||||
wd14_tagger_choices,
|
||||
)
|
||||
from .model_folders import resolve_model_file
|
||||
from .settings import SimpleSyrupSettings
|
||||
from .settings_repository import SimpleSyrupSettingsRepository
|
||||
from .vitmatte_loader import ViTMatteLoaderService
|
||||
|
||||
NO_LOCAL_SAM_MODELS = "No local SAM models found"
|
||||
NO_LOCAL_GROUNDING_DINO_MODELS = "No local GroundingDINO models found"
|
||||
@@ -44,69 +37,52 @@ class ModelChoiceService:
|
||||
def __init__(
|
||||
self,
|
||||
settings_repository: SettingsProvider | None = None,
|
||||
folder_paths_module: ModuleType | None = None,
|
||||
) -> None:
|
||||
"""Create the choice service with injectable external boundaries."""
|
||||
"""Create the choice service with an injectable settings boundary."""
|
||||
|
||||
self._settings_repository = (
|
||||
settings_repository or SimpleSyrupSettingsRepository()
|
||||
)
|
||||
self._folder_paths_module = folder_paths_module
|
||||
self._vitmatte_loader = ViTMatteLoaderService(
|
||||
folder_paths_module=folder_paths_module
|
||||
)
|
||||
|
||||
def sam_choices(self) -> list[str]:
|
||||
"""Return settings-aware SAM dropdown choices."""
|
||||
"""Return curated SAM choices when catalog models are visible."""
|
||||
|
||||
if self._show_downloadable_models():
|
||||
return sam_choices()
|
||||
|
||||
choices = [
|
||||
entry.display_name
|
||||
for entry in SAM_ENTRIES
|
||||
if self._entry_artifacts_are_local(entry)
|
||||
]
|
||||
return choices or [NO_LOCAL_SAM_MODELS]
|
||||
return [NO_LOCAL_SAM_MODELS]
|
||||
|
||||
def grounding_dino_choices(self) -> list[str]:
|
||||
"""Return settings-aware GroundingDINO dropdown choices."""
|
||||
"""Return curated GroundingDINO choices when catalog models are visible."""
|
||||
|
||||
if self._show_downloadable_models():
|
||||
return grounding_dino_choices()
|
||||
|
||||
choices = [
|
||||
entry.display_name
|
||||
for entry in GROUNDING_DINO_ENTRIES
|
||||
if self._entry_artifacts_are_local(entry)
|
||||
]
|
||||
return choices or [NO_LOCAL_GROUNDING_DINO_MODELS]
|
||||
return [NO_LOCAL_GROUNDING_DINO_MODELS]
|
||||
|
||||
def vitmatte_choices(self) -> list[str]:
|
||||
"""Return settings-aware ViTMatte dropdown choices."""
|
||||
"""Return curated ViTMatte choices when catalog models are visible."""
|
||||
|
||||
if self._show_downloadable_models():
|
||||
return vitmatte_choices()
|
||||
|
||||
choices = [
|
||||
entry.display_name
|
||||
for entry in VITMATTE_ENTRIES
|
||||
if self._vitmatte_entry_is_local(entry)
|
||||
]
|
||||
return choices or [NO_LOCAL_VITMATTE_MODELS]
|
||||
return [NO_LOCAL_VITMATTE_MODELS]
|
||||
|
||||
def wd14_tagger_choices(self) -> list[str]:
|
||||
"""Return settings-aware WD14 tagger dropdown choices."""
|
||||
"""Return curated WD14 tagger choices when catalog models are visible."""
|
||||
|
||||
if self._show_downloadable_models():
|
||||
return wd14_tagger_choices()
|
||||
|
||||
choices = [
|
||||
entry.display_name
|
||||
for entry in WD14_TAGGER_ENTRIES
|
||||
if self._entry_artifacts_are_local(entry)
|
||||
]
|
||||
return choices or [NO_LOCAL_WD14_TAGGER_MODELS]
|
||||
return [NO_LOCAL_WD14_TAGGER_MODELS]
|
||||
|
||||
def ultralytics_choices(self) -> list[str]:
|
||||
"""Return curated Ultralytics choices when catalog models are visible."""
|
||||
|
||||
if self._show_downloadable_models():
|
||||
return ultralytics_choices()
|
||||
|
||||
return []
|
||||
|
||||
def reject_sentinel(self, selection: str) -> None:
|
||||
"""Reject placeholder dropdown selections before loader work begins."""
|
||||
@@ -143,28 +119,6 @@ class ModelChoiceService:
|
||||
|
||||
return self._settings_repository.load().show_downloadable_models
|
||||
|
||||
def _entry_artifacts_are_local(self, entry: ModelEntry) -> bool:
|
||||
"""Return whether every catalog artifact exists locally."""
|
||||
|
||||
return all(
|
||||
resolve_model_file(
|
||||
artifact.folder_name,
|
||||
artifact.filename,
|
||||
self._folder_paths_module,
|
||||
)
|
||||
is not None
|
||||
for artifact in entry.artifacts
|
||||
)
|
||||
|
||||
def _vitmatte_entry_is_local(self, entry: ModelEntry) -> bool:
|
||||
"""Return whether a valid ViTMatte directory exists locally."""
|
||||
|
||||
try:
|
||||
self._vitmatte_loader.resolve_model_directory(entry, auto_download=False)
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def default_choice(choices: list[str], preferred: str) -> str:
|
||||
"""Return the preferred default when visible, otherwise the first choice."""
|
||||
|
||||
@@ -59,30 +59,30 @@ class ComfyProgressReporter:
|
||||
"""Initialize an empty ComfyUI progress reporter."""
|
||||
|
||||
self._progress_bar: object | None = None
|
||||
self._total = 1
|
||||
self._total: int | None = None
|
||||
|
||||
def start(self, label: str, total: int | None) -> None:
|
||||
"""Create a ComfyUI progress bar for one artifact."""
|
||||
|
||||
comfy_utils = importlib.import_module("comfy.utils")
|
||||
progress_bar_class = comfy_utils.ProgressBar
|
||||
self._total = total if total and total > 0 else 1
|
||||
self._progress_bar = progress_bar_class(self._total)
|
||||
self._total = total if total and total > 0 else None
|
||||
progress_total = self._total or 1
|
||||
self._progress_bar = progress_bar_class(progress_total)
|
||||
self.advance(0, total)
|
||||
LOGGER.info("download progress started", extra={"label": label, "total": total})
|
||||
|
||||
def advance(self, current: int, total: int | None) -> None:
|
||||
"""Update the ComfyUI progress bar."""
|
||||
"""Update known-size downloads without falsely completing unknown ones."""
|
||||
|
||||
if self._progress_bar is None:
|
||||
return
|
||||
if total and total > 0 and total != self._total:
|
||||
if total is None or total <= 0:
|
||||
return
|
||||
if total != self._total:
|
||||
self._total = total
|
||||
value = (
|
||||
current if total and total > 0 else min(current // CHUNK_SIZE, self._total)
|
||||
)
|
||||
progress_bar = cast(_ComfyProgressBar, self._progress_bar)
|
||||
progress_bar.update_absolute(value, self._total)
|
||||
progress_bar.update_absolute(current, self._total)
|
||||
|
||||
def finish(self) -> None:
|
||||
"""Mark the current ComfyUI progress bar complete."""
|
||||
@@ -90,7 +90,8 @@ class ComfyProgressReporter:
|
||||
if self._progress_bar is None:
|
||||
return
|
||||
progress_bar = cast(_ComfyProgressBar, self._progress_bar)
|
||||
progress_bar.update_absolute(self._total, self._total)
|
||||
total = self._total or 1
|
||||
progress_bar.update_absolute(total, total)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -78,6 +78,7 @@ class GroundedSAMModelMetadata:
|
||||
"artifact_id": artifact.artifact_id,
|
||||
"filename": artifact.filename,
|
||||
"source_url": artifact.source_url,
|
||||
"sha256": artifact.sha256,
|
||||
"expected_path": str(expected),
|
||||
"local_path": str(local_path) if local_path else None,
|
||||
"installed": local_path is not None,
|
||||
|
||||
@@ -237,6 +237,102 @@ class ModelDiffusionWrapperMutation:
|
||||
).apply(model)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelInteropDiffusionWrapperMutation:
|
||||
"""Install the exact legacy key required for PPM Anima interoperability."""
|
||||
|
||||
key: str
|
||||
wrapper: Callable[..., object]
|
||||
|
||||
def apply(self, model: object) -> None:
|
||||
"""Install only the documented PPM Anima wrapper surface."""
|
||||
|
||||
if self.key != "ppm_negpip_anima":
|
||||
raise ValueError("NegPiP interop wrapper must use PPM's Anima key.")
|
||||
getter = _require_bound_method(model, "get_wrappers", ("wrapper_type", "key"))
|
||||
adder = _require_bound_method(
|
||||
model,
|
||||
"add_wrapper_with_key",
|
||||
("wrapper_type", "key", "wrapper"),
|
||||
)
|
||||
existing = getter(WrappersMP.DIFFUSION_MODEL, self.key)
|
||||
if not isinstance(existing, list) or any(
|
||||
not callable(callback) for callback in existing
|
||||
):
|
||||
raise TypeError("Existing NegPiP wrappers must be a callable list.")
|
||||
if existing:
|
||||
raise ValueError("PPM's Anima NegPiP wrapper key is already installed.")
|
||||
adder(WrappersMP.DIFFUSION_MODEL, self.key, self.wrapper)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelAttentionPatchMutation:
|
||||
"""Append one validated Comfy attention patch to a derived MODEL."""
|
||||
|
||||
patch_name: str
|
||||
callback: Callable[..., object]
|
||||
|
||||
def apply(self, model: object) -> None:
|
||||
"""Install an attn1 or attn2 callback through the public patcher setter."""
|
||||
|
||||
if self.patch_name not in {"attn1", "attn2"}:
|
||||
raise ValueError("MODEL attention patch name must be 'attn1' or 'attn2'.")
|
||||
if not callable(self.callback):
|
||||
raise TypeError("MODEL attention patch callback must be callable.")
|
||||
setter = getattr(model, f"set_model_{self.patch_name}_patch", None)
|
||||
if not callable(setter):
|
||||
raise TypeError(f"MODEL does not support {self.patch_name} patches.")
|
||||
setter(self.callback)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelBooleanOptionMutation:
|
||||
"""Publish one collision-safe boolean MODEL option marker."""
|
||||
|
||||
key: str
|
||||
value: bool
|
||||
|
||||
def apply(self, model: object) -> None:
|
||||
"""Set one supported marker only when no value already owns the key."""
|
||||
|
||||
if self.key != "ppm_negpip":
|
||||
raise ValueError("Unsupported MODEL boolean option marker.")
|
||||
if not isinstance(self.value, bool):
|
||||
raise TypeError("MODEL option marker value must be boolean.")
|
||||
options = _require_dictionary_attribute(model, "model_options")
|
||||
if self.key in options:
|
||||
raise ValueError(f"MODEL option '{self.key}' is already present.")
|
||||
options[self.key] = self.value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelCallableObjectPatchMutation:
|
||||
"""Replace one callable model object after collision validation."""
|
||||
|
||||
path: str
|
||||
replacement: Callable[..., object]
|
||||
|
||||
def apply(self, model: object) -> None:
|
||||
"""Patch one callable path without relying on bound-method identity."""
|
||||
|
||||
if (
|
||||
not isinstance(self.path, str)
|
||||
or not self.path
|
||||
or any(not segment for segment in self.path.split("."))
|
||||
):
|
||||
raise ValueError("MODEL callable patch path must be a dotted path.")
|
||||
if not callable(self.replacement):
|
||||
raise TypeError("MODEL callable object replacement must be callable.")
|
||||
getter = _require_bound_method(model, "get_model_object", ("name",))
|
||||
adder = _require_bound_method(model, "add_object_patch", ("name", "obj"))
|
||||
object_patches = _require_dictionary_attribute(model, "object_patches")
|
||||
if self.path in object_patches:
|
||||
raise ValueError(f"MODEL object path '{self.path}' already has a patch.")
|
||||
if not callable(getter(self.path)):
|
||||
raise TypeError(f"MODEL object path '{self.path}' must be callable.")
|
||||
adder(self.path, self.replacement)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelExactObjectPatchMutation:
|
||||
"""Replace one exact model object after collision and identity validation."""
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Provide model-family NegPiP runtime adapters."""
|
||||
@@ -0,0 +1,108 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Apply PPM-compatible value-mask NegPiP behavior to Anima."""
|
||||
|
||||
# NegPiP behavior is adapted from ComfyUI-ppm and its credited predecessors.
|
||||
# See third_party/manifest.toml and third_party/NOTICE.md.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from comfy import conds
|
||||
|
||||
WRAPPER_KEY = "ppm_negpip_anima"
|
||||
CONDITION_MASK_KEY = "c_ppm_negpip_mask"
|
||||
TRANSFORMER_MASK_KEY = "ppm_negpip_mask"
|
||||
|
||||
|
||||
def anima_extra_conds_negpip_wrapper(
|
||||
previous_extra_conds: Callable[..., dict[str, object]],
|
||||
) -> Callable[..., dict[str, object]]:
|
||||
"""Convert signed T5 weights into a model condition while preserving magnitude."""
|
||||
|
||||
def wrapped_extra_conds(**kwargs: object) -> dict[str, object]:
|
||||
"""Publish a sequence-aligned value multiplier for one conditioning."""
|
||||
|
||||
weights = kwargs.get("t5xxl_weights")
|
||||
multiplier: torch.Tensor | None = None
|
||||
if weights is not None:
|
||||
if not isinstance(weights, torch.Tensor):
|
||||
raise TypeError("Anima NegPiP T5 weights must be a tensor.")
|
||||
magnitude = weights.abs()
|
||||
multiplier = (
|
||||
torch.where(
|
||||
weights < 0.0,
|
||||
weights.new_tensor(-1.0),
|
||||
weights.new_tensor(1.0),
|
||||
)
|
||||
.unsqueeze(0)
|
||||
.unsqueeze(-1)
|
||||
)
|
||||
if multiplier.shape[1] < 512:
|
||||
multiplier = torch.nn.functional.pad(
|
||||
multiplier,
|
||||
(0, 0, 0, 512 - multiplier.shape[1]),
|
||||
value=1.0,
|
||||
)
|
||||
kwargs["t5xxl_weights"] = magnitude
|
||||
|
||||
output = previous_extra_conds(**kwargs)
|
||||
if not isinstance(output, dict):
|
||||
raise TypeError("Anima extra conditions must be a dictionary.")
|
||||
if multiplier is not None:
|
||||
output[CONDITION_MASK_KEY] = conds.CONDRegular(multiplier)
|
||||
return output
|
||||
|
||||
return wrapped_extra_conds
|
||||
|
||||
|
||||
def anima_diffusion_negpip_wrapper(
|
||||
executor: Callable[..., object],
|
||||
*args: object,
|
||||
**kwargs: object,
|
||||
) -> object:
|
||||
"""Move the processed Anima multiplier into isolated transformer options."""
|
||||
|
||||
if len(args) < 3 or not isinstance(args[2], torch.Tensor):
|
||||
raise TypeError("Anima NegPiP wrapper requires tensor conditioning context.")
|
||||
context = args[2]
|
||||
transformer_options = kwargs.get("transformer_options", {})
|
||||
if not isinstance(transformer_options, dict):
|
||||
raise TypeError("Anima transformer options must be a dictionary.")
|
||||
prepared = transformer_options.copy()
|
||||
multiplier = kwargs.get(CONDITION_MASK_KEY)
|
||||
if multiplier is not None:
|
||||
if not isinstance(multiplier, torch.Tensor):
|
||||
raise TypeError("Anima NegPiP multiplier must be a tensor.")
|
||||
prepared[TRANSFORMER_MASK_KEY] = multiplier.to(context)
|
||||
kwargs["transformer_options"] = prepared
|
||||
return executor(*args, **kwargs)
|
||||
|
||||
|
||||
def anima_attn2_negpip(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
pe: torch.Tensor | None = None,
|
||||
attn_mask: torch.Tensor | None = None,
|
||||
extra_options: dict[str, Any] | None = None,
|
||||
) -> dict[str, torch.Tensor | None]:
|
||||
"""Apply the signed multiplier only to Anima cross-attention values."""
|
||||
|
||||
multiplier = (
|
||||
None if extra_options is None else extra_options.get(TRANSFORMER_MASK_KEY)
|
||||
)
|
||||
if multiplier is not None and not isinstance(multiplier, torch.Tensor):
|
||||
raise TypeError("Anima NegPiP attention multiplier must be a tensor.")
|
||||
return {
|
||||
"q": query,
|
||||
"k": key,
|
||||
"v": value if multiplier is None else value * multiplier,
|
||||
"pe": pe,
|
||||
"attn_mask": attn_mask,
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Adapt NegPiP value masking to Krea 2's layered Qwen conditioning."""
|
||||
|
||||
# NegPiP behavior is adapted from ComfyUI-ppm and its credited predecessors.
|
||||
# See third_party/manifest.toml and third_party/NOTICE.md.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from comfy import conds
|
||||
|
||||
CLIP_MARKER = "simple_syrup_negpip"
|
||||
WRAPPER_KEY = "simple_syrup.negpip.krea2"
|
||||
ENCODER_MASK_KEY = "simple_syrup_negpip_mask"
|
||||
CONDITION_MASK_KEY = "c_simple_syrup_negpip_mask"
|
||||
TRANSFORMER_MASK_KEY = "simple_syrup_negpip_mask"
|
||||
KREA_TOKEN_KEY = "qwen3vl_4b"
|
||||
IM_START_TOKEN = 151644
|
||||
USER_TOKEN = 872
|
||||
NEWLINE_TOKEN = 198
|
||||
IMAGE_PAD_TOKEN = 151655
|
||||
|
||||
|
||||
class Krea2NegpipTokenizer:
|
||||
"""Preserve Krea templates while enabling Comfy prompt-weight tokenization."""
|
||||
|
||||
def __init__(self, source: object) -> None:
|
||||
"""Retain one cloned CLIP's shared source tokenizer without mutating it."""
|
||||
|
||||
self._source = source
|
||||
|
||||
def __getattr__(self, name: str) -> object:
|
||||
"""Delegate tokenizer metadata and helpers to the installed Krea tokenizer."""
|
||||
|
||||
return getattr(self._source, name)
|
||||
|
||||
def tokenize_with_weights(
|
||||
self,
|
||||
text: str,
|
||||
return_word_ids: bool = False,
|
||||
llama_template: str | None = None,
|
||||
images: Sequence[torch.Tensor] = (),
|
||||
prevent_empty_text: bool = False,
|
||||
thinking: bool = True,
|
||||
**kwargs: object,
|
||||
) -> dict[str, list[list[tuple[object, ...]]]]:
|
||||
"""Tokenize the normal Krea template while retaining parsed scalar weights."""
|
||||
|
||||
image = kwargs.pop("image", None)
|
||||
if image is not None and not images:
|
||||
if not isinstance(image, torch.Tensor):
|
||||
raise TypeError("Krea tokenizer image input must be a tensor.")
|
||||
images = tuple(image[index : index + 1] for index in range(image.shape[0]))
|
||||
skip_template = bool(kwargs.pop("skip_template", False)) or text.startswith(
|
||||
"<|im_start|>"
|
||||
)
|
||||
kwargs.pop("disable_weights", None)
|
||||
if prevent_empty_text and text == "":
|
||||
text = " "
|
||||
|
||||
if skip_template:
|
||||
prepared_text = text
|
||||
else:
|
||||
template = llama_template
|
||||
if template is None:
|
||||
template_name = (
|
||||
"llama_template" if not images else "llama_template_images"
|
||||
)
|
||||
template = getattr(self._source, template_name)
|
||||
if not isinstance(template, str):
|
||||
raise TypeError("Krea tokenizer template must be text.")
|
||||
if len(images) > 1:
|
||||
vision_block = "<|vision_start|><|image_pad|><|vision_end|>"
|
||||
template = template.replace(
|
||||
vision_block,
|
||||
vision_block * len(images),
|
||||
1,
|
||||
)
|
||||
prepared_text = template.format(text)
|
||||
if not thinking:
|
||||
prepared_text += "<think>\n\n</think>\n\n"
|
||||
|
||||
inner = getattr(self._source, KREA_TOKEN_KEY)
|
||||
tokens = inner.tokenize_with_weights(
|
||||
prepared_text,
|
||||
return_word_ids=return_word_ids,
|
||||
disable_weights=False,
|
||||
**kwargs,
|
||||
)
|
||||
embedded_count = 0
|
||||
for section in tokens:
|
||||
for index, pair in enumerate(section):
|
||||
token = pair[0]
|
||||
if (
|
||||
isinstance(token, (int, float))
|
||||
and token == IMAGE_PAD_TOKEN
|
||||
and embedded_count < len(images)
|
||||
):
|
||||
section[index] = (
|
||||
{
|
||||
"type": "image",
|
||||
"data": images[embedded_count],
|
||||
"original_type": "image",
|
||||
},
|
||||
*pair[1:],
|
||||
)
|
||||
embedded_count += 1
|
||||
return {KREA_TOKEN_KEY: tokens}
|
||||
|
||||
|
||||
def encode_krea2_token_weights_negpip(
|
||||
original: Callable[..., tuple[object, ...]],
|
||||
token_weight_pairs: dict[str, list[list[tuple[object, ...]]]],
|
||||
template_end: int = -1,
|
||||
) -> tuple[object, ...]:
|
||||
"""Encode absolute Krea magnitudes and publish a post-template sign mask."""
|
||||
|
||||
sections = token_weight_pairs.get(KREA_TOKEN_KEY)
|
||||
if not isinstance(sections, list) or len(sections) != 1:
|
||||
raise ValueError("Krea NegPiP requires exactly one Qwen token section.")
|
||||
source_section = sections[0]
|
||||
absolute_section = [
|
||||
(pair[0], abs(_token_weight(pair)), *pair[2:]) for pair in source_section
|
||||
]
|
||||
absolute_tokens = dict(token_weight_pairs)
|
||||
absolute_tokens[KREA_TOKEN_KEY] = [absolute_section]
|
||||
encoded = original(absolute_tokens, template_end=template_end)
|
||||
if len(encoded) < 3 or not isinstance(encoded[0], torch.Tensor):
|
||||
raise TypeError("Krea NegPiP encoder must return tensor conditioning metadata.")
|
||||
extra = encoded[2]
|
||||
if not isinstance(extra, dict):
|
||||
raise TypeError("Krea NegPiP encoder metadata must be a dictionary.")
|
||||
cut = _template_end(source_section) if template_end == -1 else template_end
|
||||
signs = [
|
||||
-1.0 if _token_weight(pair) < 0.0 else 1.0 for pair in source_section[cut:]
|
||||
]
|
||||
sequence_length = int(encoded[0].shape[1])
|
||||
if len(signs) != sequence_length:
|
||||
raise ValueError(
|
||||
"Krea NegPiP sign mask does not match post-template conditioning: "
|
||||
f"{len(signs)} signs for {sequence_length} tokens."
|
||||
)
|
||||
prepared_extra = dict(extra)
|
||||
prepared_extra[ENCODER_MASK_KEY] = torch.tensor(signs).reshape(1, -1, 1)
|
||||
return encoded[0], encoded[1], prepared_extra
|
||||
|
||||
|
||||
def krea2_extra_conds_negpip_wrapper(
|
||||
previous_extra_conds: Callable[..., dict[str, object]],
|
||||
) -> Callable[..., dict[str, object]]:
|
||||
"""Publish the Krea token-sign mask as a processed model condition."""
|
||||
|
||||
def wrapped_extra_conds(**kwargs: object) -> dict[str, object]:
|
||||
"""Attach a validated sequence multiplier without altering other conditions."""
|
||||
|
||||
output = previous_extra_conds(**kwargs)
|
||||
if not isinstance(output, dict):
|
||||
raise TypeError("Krea extra conditions must be a dictionary.")
|
||||
multiplier = kwargs.get(ENCODER_MASK_KEY)
|
||||
if multiplier is not None:
|
||||
if not isinstance(multiplier, torch.Tensor):
|
||||
raise TypeError("Krea NegPiP sign mask must be a tensor.")
|
||||
if (
|
||||
multiplier.ndim != 3
|
||||
or multiplier.shape[0] != 1
|
||||
or multiplier.shape[2] != 1
|
||||
):
|
||||
raise ValueError(
|
||||
"Krea NegPiP sign mask must have shape (1, sequence, 1)."
|
||||
)
|
||||
output[CONDITION_MASK_KEY] = conds.CONDRegular(multiplier)
|
||||
return output
|
||||
|
||||
return wrapped_extra_conds
|
||||
|
||||
|
||||
def krea2_diffusion_negpip_wrapper(
|
||||
executor: Callable[..., object],
|
||||
*args: object,
|
||||
**kwargs: object,
|
||||
) -> object:
|
||||
"""Move a processed Krea sign mask into call-local transformer options."""
|
||||
|
||||
positional_options = args[5] if len(args) > 5 else None
|
||||
transformer_options = (
|
||||
positional_options
|
||||
if positional_options is not None
|
||||
else kwargs.get("transformer_options", {})
|
||||
)
|
||||
if not isinstance(transformer_options, dict):
|
||||
raise TypeError("Krea transformer options must be a dictionary.")
|
||||
prepared = transformer_options.copy()
|
||||
multiplier = kwargs.get(CONDITION_MASK_KEY)
|
||||
if multiplier is not None:
|
||||
if not isinstance(multiplier, torch.Tensor):
|
||||
raise TypeError("Krea NegPiP processed mask must be a tensor.")
|
||||
prepared[TRANSFORMER_MASK_KEY] = multiplier
|
||||
if len(args) > 5:
|
||||
prepared_args = list(args)
|
||||
prepared_args[5] = prepared
|
||||
return executor(*prepared_args, **kwargs)
|
||||
kwargs["transformer_options"] = prepared
|
||||
return executor(*args, **kwargs)
|
||||
|
||||
|
||||
def krea2_attn1_negpip(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
pe: torch.Tensor | None = None,
|
||||
attn_mask: torch.Tensor | None = None,
|
||||
extra_options: dict[str, Any] | None = None,
|
||||
) -> dict[str, torch.Tensor | None]:
|
||||
"""Apply negative signs only to Krea text values in the joint token stream."""
|
||||
|
||||
options = {} if extra_options is None else extra_options
|
||||
multiplier = options.get(TRANSFORMER_MASK_KEY)
|
||||
if multiplier is None:
|
||||
return {"q": query, "k": key, "v": value, "pe": pe, "attn_mask": attn_mask}
|
||||
if not isinstance(multiplier, torch.Tensor):
|
||||
raise TypeError("Krea NegPiP attention mask must be a tensor.")
|
||||
image_slice = options.get("img_slice")
|
||||
if (
|
||||
not isinstance(image_slice, (list, tuple))
|
||||
or len(image_slice) != 2
|
||||
or any(
|
||||
isinstance(item, bool) or not isinstance(item, int) for item in image_slice
|
||||
)
|
||||
):
|
||||
raise ValueError("Krea NegPiP requires the model's text/image token boundary.")
|
||||
text_length = image_slice[0]
|
||||
if text_length != multiplier.shape[1] or value.shape[2] < text_length:
|
||||
raise ValueError(
|
||||
"Krea NegPiP mask does not match the joint attention sequence."
|
||||
)
|
||||
if multiplier.shape[0] not in {1, value.shape[0]} or multiplier.shape[2] != 1:
|
||||
raise ValueError("Krea NegPiP mask has an incompatible batch or channel shape.")
|
||||
text_multiplier = multiplier.to(device=value.device, dtype=value.dtype).unsqueeze(1)
|
||||
prepared_value = value.to(copy=True)
|
||||
prepared_value[:, :, :text_length, :] *= text_multiplier
|
||||
return {
|
||||
"q": query,
|
||||
"k": key,
|
||||
"v": prepared_value,
|
||||
"pe": pe,
|
||||
"attn_mask": attn_mask,
|
||||
}
|
||||
|
||||
|
||||
def _token_weight(pair: tuple[object, ...]) -> float:
|
||||
"""Return one finite scalar token weight from a tokenizer tuple."""
|
||||
|
||||
if (
|
||||
len(pair) < 2
|
||||
or isinstance(pair[1], bool)
|
||||
or not isinstance(pair[1], (int, float))
|
||||
):
|
||||
raise TypeError("Krea token weights must be numeric.")
|
||||
weight = float(pair[1])
|
||||
if not torch.isfinite(torch.tensor(weight)):
|
||||
raise ValueError("Krea token weights must be finite.")
|
||||
return weight
|
||||
|
||||
|
||||
def _template_end(section: list[tuple[object, ...]]) -> int:
|
||||
"""Resolve the exact Krea system and user-opening prefix boundary."""
|
||||
|
||||
count = 0
|
||||
template_end = -1
|
||||
for index, pair in enumerate(section):
|
||||
token = pair[0]
|
||||
if (
|
||||
not isinstance(token, torch.Tensor)
|
||||
and token == IM_START_TOKEN
|
||||
and count < 2
|
||||
):
|
||||
template_end = index
|
||||
count += 1
|
||||
if (
|
||||
len(section) > template_end + 3
|
||||
and section[template_end + 1][0] == USER_TOKEN
|
||||
and section[template_end + 2][0] == NEWLINE_TOKEN
|
||||
):
|
||||
template_end += 3
|
||||
return template_end
|
||||
@@ -0,0 +1,123 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Apply PPM-compatible NegPiP encoding for standard cross-attention models."""
|
||||
|
||||
# NegPiP behavior is adapted from ComfyUI-ppm and its credited predecessors.
|
||||
# See third_party/manifest.toml and third_party/NOTICE.md.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from comfy import model_management
|
||||
from comfy.sd1_clip import SDClipModel, gen_empty_tokens
|
||||
|
||||
|
||||
def standard_attn2_negpip(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
extra_options: dict[str, Any],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Select magnitude embeddings for keys and signed embeddings for values."""
|
||||
|
||||
del extra_options
|
||||
return query, key[:, 0::2], value[:, 1::2]
|
||||
|
||||
|
||||
def encode_token_weights_negpip(
|
||||
encoder: SDClipModel,
|
||||
token_weight_pairs: list[list[tuple[object, float]]],
|
||||
) -> tuple[object, ...]:
|
||||
"""Encode absolute prompt magnitude and interleave signed value embeddings."""
|
||||
|
||||
tokens_to_encode: list[list[object]] = []
|
||||
maximum_length = 0
|
||||
has_weights = False
|
||||
for section in token_weight_pairs:
|
||||
tokens = [pair[0] for pair in section]
|
||||
maximum_length = max(len(tokens), maximum_length)
|
||||
has_weights = has_weights or any(pair[1] != 1.0 for pair in section)
|
||||
tokens_to_encode.append(tokens)
|
||||
|
||||
section_count = len(tokens_to_encode)
|
||||
if has_weights or section_count == 0:
|
||||
if hasattr(encoder, "gen_empty_tokens"):
|
||||
empty_tokens = encoder.gen_empty_tokens(
|
||||
encoder.special_tokens,
|
||||
maximum_length,
|
||||
)
|
||||
else:
|
||||
empty_tokens = gen_empty_tokens(encoder.special_tokens, maximum_length)
|
||||
tokens_to_encode.append(empty_tokens)
|
||||
|
||||
encoded = encoder.encode(tokens_to_encode)
|
||||
output_tensor, pooled = encoded[:2]
|
||||
if not isinstance(output_tensor, torch.Tensor):
|
||||
raise TypeError("NegPiP text encoder output must be a tensor.")
|
||||
first_pooled = (
|
||||
pooled[0:1].to(device=model_management.intermediate_device())
|
||||
if isinstance(pooled, torch.Tensor)
|
||||
else pooled
|
||||
)
|
||||
|
||||
outputs: list[torch.Tensor] = []
|
||||
for section_index in range(section_count):
|
||||
key_embedding = output_tensor[section_index : section_index + 1].to(copy=True)
|
||||
value_embedding = key_embedding.to(copy=True)
|
||||
if has_weights:
|
||||
empty_embedding = output_tensor[-1]
|
||||
for batch_index in range(len(key_embedding)):
|
||||
for token_index in range(len(key_embedding[batch_index])):
|
||||
weight = token_weight_pairs[section_index][token_index][1]
|
||||
if weight == 1.0:
|
||||
continue
|
||||
magnitude = abs(weight)
|
||||
key_embedding[batch_index][token_index] = (
|
||||
key_embedding[batch_index][token_index]
|
||||
- empty_embedding[token_index]
|
||||
) * magnitude + empty_embedding[token_index]
|
||||
value_embedding[batch_index][token_index] = (
|
||||
value_embedding[batch_index][token_index]
|
||||
- empty_embedding[token_index]
|
||||
) * magnitude + empty_embedding[token_index]
|
||||
if weight < 0.0:
|
||||
value_embedding[batch_index][token_index].neg_()
|
||||
|
||||
interleaved = torch.zeros_like(key_embedding).repeat(1, 2, 1)
|
||||
interleaved[:, 0::2, :] = key_embedding
|
||||
interleaved[:, 1::2, :] = value_embedding
|
||||
outputs.append(interleaved)
|
||||
|
||||
if outputs:
|
||||
result: tuple[object, ...] = (
|
||||
torch.cat(outputs, dim=-2).to(
|
||||
device=model_management.intermediate_device()
|
||||
),
|
||||
first_pooled,
|
||||
)
|
||||
else:
|
||||
result = (
|
||||
output_tensor[-1:].to(device=model_management.intermediate_device()),
|
||||
first_pooled,
|
||||
)
|
||||
|
||||
if len(encoded) <= 2:
|
||||
return result
|
||||
source_extra = encoded[2]
|
||||
if not isinstance(source_extra, dict):
|
||||
raise TypeError("NegPiP text encoder metadata must be a dictionary.")
|
||||
extra: dict[str, object] = {}
|
||||
for key, value in source_extra.items():
|
||||
if key == "attention_mask" and isinstance(value, torch.Tensor):
|
||||
value = (
|
||||
value[:section_count]
|
||||
.flatten()
|
||||
.unsqueeze(dim=0)
|
||||
.to(device=model_management.intermediate_device())
|
||||
)
|
||||
extra[str(key)] = value
|
||||
return (*result, extra)
|
||||
@@ -7,7 +7,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import Protocol, TypeVar, cast
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Protocol, TypeVar, cast
|
||||
|
||||
from .clip_patcher_model_alignment import align_clip_text_encoder_with_patcher
|
||||
|
||||
@@ -27,6 +28,14 @@ class ClipMutation(Protocol):
|
||||
|
||||
|
||||
PatcherValue = TypeVar("PatcherValue")
|
||||
_MODEL_FALLBACK_BOUNDARY_ATTACHMENT = "simple_syrup.model_fallback_boundary"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _ModelFallbackBoundary:
|
||||
"""Retain the durable Comfy patcher beneath consecutive Syrup derivations."""
|
||||
|
||||
patcher: object
|
||||
|
||||
|
||||
class ComfyPatcherLifecycle:
|
||||
@@ -48,6 +57,7 @@ class ComfyPatcherLifecycle:
|
||||
disable_dynamic=disable_dynamic,
|
||||
)
|
||||
self._require_direct_parent(source, derived, operation=operation)
|
||||
self._stabilize_model_fallback(source, derived)
|
||||
for mutation in mutations:
|
||||
mutation.apply(derived)
|
||||
return derived
|
||||
@@ -66,13 +76,19 @@ class ComfyPatcherLifecycle:
|
||||
getter = getattr(model_override_source, "get_clone_model_override", None)
|
||||
if not callable(getter):
|
||||
raise TypeError(f"{operation} requires a model-override source.")
|
||||
model_override = getter()
|
||||
derived = self._clone(
|
||||
source,
|
||||
operation=operation,
|
||||
disable_dynamic=disable_dynamic,
|
||||
model_override=getter(),
|
||||
model_override=model_override,
|
||||
)
|
||||
self._require_direct_parent(source, derived, operation=operation)
|
||||
self._stabilize_model_fallback(
|
||||
source,
|
||||
derived,
|
||||
explicit_boundary=model_override_source,
|
||||
)
|
||||
for mutation in mutations:
|
||||
mutation.apply(derived)
|
||||
return derived
|
||||
@@ -107,6 +123,7 @@ class ComfyPatcherLifecycle:
|
||||
derived_patcher,
|
||||
operation=operation,
|
||||
)
|
||||
self._stabilize_model_fallback(source_patcher, derived_patcher)
|
||||
align_clip_text_encoder_with_patcher(derived)
|
||||
for mutation in mutations:
|
||||
mutation.apply(derived)
|
||||
@@ -181,6 +198,41 @@ class ComfyPatcherLifecycle:
|
||||
f"{operation} produced a derived patcher without its source as parent."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _stabilize_model_fallback(
|
||||
source: object,
|
||||
derived: object,
|
||||
*,
|
||||
explicit_boundary: object | None = None,
|
||||
) -> None:
|
||||
"""Collapse Syrup-only lineage onto the durable same-model boundary."""
|
||||
|
||||
derived_attachments = getattr(derived, "attachments", None)
|
||||
if not isinstance(derived_attachments, dict):
|
||||
return
|
||||
boundary = explicit_boundary
|
||||
if boundary is None:
|
||||
source_attachments = getattr(source, "attachments", None)
|
||||
inherited = (
|
||||
source_attachments.get(_MODEL_FALLBACK_BOUNDARY_ATTACHMENT)
|
||||
if isinstance(source_attachments, dict)
|
||||
else None
|
||||
)
|
||||
if inherited is not None and not isinstance(
|
||||
inherited,
|
||||
_ModelFallbackBoundary,
|
||||
):
|
||||
raise TypeError("SimpleSyrup MODEL fallback boundary is invalid.")
|
||||
boundary = inherited.patcher if inherited is not None else source
|
||||
|
||||
if getattr(boundary, "model", None) is not getattr(derived, "model", None):
|
||||
derived_attachments.pop(_MODEL_FALLBACK_BOUNDARY_ATTACHMENT, None)
|
||||
return
|
||||
cast(Any, derived).parent = boundary
|
||||
derived_attachments[_MODEL_FALLBACK_BOUNDARY_ATTACHMENT] = (
|
||||
_ModelFallbackBoundary(boundary)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _required_clip_patcher(value: object, *, value_name: str) -> object:
|
||||
"""Return the CLIP patcher required for lineage validation."""
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Adapt the complete installed PPM NegPiP patch family to regional execution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
from comfy.patcher_extension import WrappersMP
|
||||
|
||||
from ..domain.regional_model_capabilities import RegionalModelFamily
|
||||
|
||||
_MODEL_MARKER = "ppm_negpip"
|
||||
_ANIMA_WRAPPER_KEY = "ppm_negpip_anima"
|
||||
_ANIMA_CONDITION_KEY = "c_ppm_negpip_mask"
|
||||
_ANIMA_TRANSFORMER_KEY = "ppm_negpip_mask"
|
||||
_EXTRA_CONDS_PATH = "extra_conds"
|
||||
_ATTN2_PATCH_NAME = "attn2_patch"
|
||||
_UNET_CALLBACKS = (
|
||||
("src.negpip.unet_negpip", "sdxl_attn2_negpip"),
|
||||
("simple_syrup.runtime.negpip.standard", "standard_attn2_negpip"),
|
||||
)
|
||||
_ANIMA_CALLBACKS = (
|
||||
("src.negpip.anima_negpip", "cosmos_attn2_negpip"),
|
||||
("simple_syrup.runtime.negpip.anima", "anima_attn2_negpip"),
|
||||
)
|
||||
_ANIMA_WRAPPERS = (
|
||||
("src.negpip.anima_negpip", "cosmos_diffusion_negpip_wrapper"),
|
||||
(
|
||||
"simple_syrup.runtime.negpip.anima",
|
||||
"anima_diffusion_negpip_wrapper",
|
||||
),
|
||||
)
|
||||
_ANIMA_EXTRA_CONDS_CALLBACKS = (
|
||||
(
|
||||
"src.negpip.anima_negpip",
|
||||
"anima_extra_conds_negpip_wrapper.<locals>._anima_extra_conds_negpip_wrapper",
|
||||
),
|
||||
(
|
||||
"simple_syrup.runtime.negpip.anima",
|
||||
"anima_extra_conds_negpip_wrapper.<locals>.wrapped_extra_conds",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class PpmNegpipSemantics(StrEnum):
|
||||
"""Identify the family-specific NegPiP conditioning representation."""
|
||||
|
||||
STANDARD_UNET_SPLIT_KEY_VALUE = "standard-unet-split-key-value"
|
||||
ANIMA_VALUE_MASK = "anima-value-mask"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PpmNegpipInterop:
|
||||
"""Retain identity-validated PPM objects needed by regional execution."""
|
||||
|
||||
semantics: PpmNegpipSemantics
|
||||
attention_patch: Callable[..., object]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Require one typed semantic mode and callable preserved callback."""
|
||||
|
||||
if not isinstance(self.semantics, PpmNegpipSemantics):
|
||||
raise TypeError("NegPiP semantics have an invalid type.")
|
||||
if not callable(self.attention_patch):
|
||||
raise TypeError("NegPiP attention patch must be callable.")
|
||||
|
||||
def extract_value_multiplier(
|
||||
self,
|
||||
model_conditions: dict[object, object],
|
||||
context: torch.Tensor,
|
||||
) -> torch.Tensor | None:
|
||||
"""Return one validated Anima value multiplier or no UNet multiplier."""
|
||||
|
||||
if self.semantics is PpmNegpipSemantics.STANDARD_UNET_SPLIT_KEY_VALUE:
|
||||
return None
|
||||
condition = model_conditions.get(_ANIMA_CONDITION_KEY)
|
||||
if condition is None:
|
||||
return context.new_ones((*context.shape[:2], 1))
|
||||
multiplier = getattr(condition, "cond", None)
|
||||
if not isinstance(multiplier, torch.Tensor):
|
||||
raise TypeError("Anima NegPiP value mask condition must contain a tensor.")
|
||||
if (
|
||||
multiplier.ndim != 3
|
||||
or int(multiplier.shape[0]) != int(context.shape[0])
|
||||
or int(multiplier.shape[1]) != int(context.shape[1])
|
||||
or int(multiplier.shape[2]) != 1
|
||||
):
|
||||
raise ValueError(
|
||||
"Anima NegPiP value mask must match the conditioning batch and "
|
||||
"sequence with one multiplier channel."
|
||||
)
|
||||
multiplier = multiplier.to(device=context.device, dtype=context.dtype)
|
||||
if not bool(((multiplier == 1) | (multiplier == -1)).all().item()):
|
||||
raise ValueError("Anima NegPiP value mask must contain only -1 and 1.")
|
||||
return multiplier
|
||||
|
||||
def prepare_anima_transformer_options(
|
||||
self,
|
||||
source: dict[str, object],
|
||||
packed_multiplier: torch.Tensor,
|
||||
) -> dict[str, object]:
|
||||
"""Publish a packed mask on an isolated Anima cross-attention call."""
|
||||
|
||||
if self.semantics is not PpmNegpipSemantics.ANIMA_VALUE_MASK:
|
||||
raise ValueError("Only Anima NegPiP semantics can publish a value mask.")
|
||||
if not isinstance(packed_multiplier, torch.Tensor):
|
||||
raise TypeError("Packed Anima NegPiP multiplier must be a tensor.")
|
||||
prepared = source.copy()
|
||||
prepared[_ANIMA_TRANSFORMER_KEY] = packed_multiplier
|
||||
return prepared
|
||||
|
||||
|
||||
class PpmNegpipInteropValidator:
|
||||
"""Admit only one complete identity-validated PPM NegPiP family."""
|
||||
|
||||
def validate(
|
||||
self,
|
||||
family: RegionalModelFamily,
|
||||
*,
|
||||
model_options: dict[object, object],
|
||||
wrappers: dict[str, dict[object, list[object]]],
|
||||
object_patches: dict[object, object],
|
||||
transformer_patches: dict[str, list[object]],
|
||||
) -> PpmNegpipInterop | None:
|
||||
"""Return preserved NegPiP state or reject every partial/conflicting form."""
|
||||
|
||||
if not isinstance(family, RegionalModelFamily):
|
||||
raise TypeError("NegPiP interop requires a model family.")
|
||||
marker = model_options.get(_MODEL_MARKER, False)
|
||||
if not isinstance(marker, bool):
|
||||
raise TypeError("MODEL ppm_negpip marker must be boolean.")
|
||||
attention = transformer_patches.get(_ATTN2_PATCH_NAME, [])
|
||||
anima_wrappers = wrappers.get(WrappersMP.DIFFUSION_MODEL, {}).get(
|
||||
_ANIMA_WRAPPER_KEY,
|
||||
[],
|
||||
)
|
||||
extra_conds = object_patches.get(_EXTRA_CONDS_PATH)
|
||||
recognized_surface = any(
|
||||
(
|
||||
any(_matches_any_identity(item, _UNET_CALLBACKS) for item in attention),
|
||||
any(
|
||||
_matches_any_identity(item, _ANIMA_CALLBACKS) for item in attention
|
||||
),
|
||||
bool(anima_wrappers),
|
||||
_matches_any_identity(extra_conds, _ANIMA_EXTRA_CONDS_CALLBACKS),
|
||||
)
|
||||
)
|
||||
if not marker:
|
||||
if recognized_surface:
|
||||
raise ValueError(
|
||||
"MODEL contains an incomplete NegPiP patch family without its "
|
||||
"marker. Reapply CLIP NegPip to a clean MODEL."
|
||||
)
|
||||
return None
|
||||
if family is RegionalModelFamily.STANDARD_UNET:
|
||||
return self._validate_standard_unet(
|
||||
attention,
|
||||
anima_wrappers=anima_wrappers,
|
||||
extra_conds=extra_conds,
|
||||
)
|
||||
if family is RegionalModelFamily.ANIMA:
|
||||
return self._validate_anima(
|
||||
attention,
|
||||
anima_wrappers=anima_wrappers,
|
||||
extra_conds=extra_conds,
|
||||
)
|
||||
raise ValueError(f"NegPiP does not support model family {family.value!r}.")
|
||||
|
||||
@staticmethod
|
||||
def _validate_standard_unet(
|
||||
attention: list[object],
|
||||
*,
|
||||
anima_wrappers: list[object],
|
||||
extra_conds: object,
|
||||
) -> PpmNegpipInterop:
|
||||
"""Require exactly PPM's single UNet split-K/V callback surface."""
|
||||
|
||||
if (
|
||||
len(attention) != 1
|
||||
or not _matches_any_identity(attention[0], _UNET_CALLBACKS)
|
||||
or anima_wrappers
|
||||
or _matches_any_identity(extra_conds, _ANIMA_EXTRA_CONDS_CALLBACKS)
|
||||
):
|
||||
raise ValueError(
|
||||
"Standard UNet NegPiP requires exactly its PPM split-K/V attention "
|
||||
"patch and no Anima NegPiP surfaces."
|
||||
)
|
||||
return PpmNegpipInterop(
|
||||
PpmNegpipSemantics.STANDARD_UNET_SPLIT_KEY_VALUE,
|
||||
cast(Callable[..., object], attention[0]),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _validate_anima(
|
||||
attention: list[object],
|
||||
*,
|
||||
anima_wrappers: list[object],
|
||||
extra_conds: object,
|
||||
) -> PpmNegpipInterop:
|
||||
"""Require PPM's exact callback, wrapper, and extra-condition surfaces."""
|
||||
|
||||
if (
|
||||
len(attention) != 1
|
||||
or not _matches_any_identity(attention[0], _ANIMA_CALLBACKS)
|
||||
or len(anima_wrappers) != 1
|
||||
or not _matches_any_identity(anima_wrappers[0], _ANIMA_WRAPPERS)
|
||||
or not _matches_any_identity(extra_conds, _ANIMA_EXTRA_CONDS_CALLBACKS)
|
||||
):
|
||||
raise ValueError(
|
||||
"Anima NegPiP requires exactly its PPM attention patch, keyed "
|
||||
"diffusion wrapper, and extra_conds object patch."
|
||||
)
|
||||
return PpmNegpipInterop(
|
||||
PpmNegpipSemantics.ANIMA_VALUE_MASK,
|
||||
cast(Callable[..., object], attention[0]),
|
||||
)
|
||||
|
||||
|
||||
def _is_identity(
|
||||
value: object,
|
||||
module_suffix: str,
|
||||
qualified_name: str,
|
||||
) -> bool:
|
||||
"""Match one callable by its stable defining module suffix and qualified name."""
|
||||
|
||||
if not callable(value):
|
||||
return False
|
||||
module = getattr(value, "__module__", None)
|
||||
qualname = getattr(value, "__qualname__", None)
|
||||
return (
|
||||
isinstance(module, str)
|
||||
and (module == module_suffix or module.endswith(f".{module_suffix}"))
|
||||
and qualname == qualified_name
|
||||
)
|
||||
|
||||
|
||||
def _matches_any_identity(
|
||||
value: object,
|
||||
identities: tuple[tuple[str, str], ...],
|
||||
) -> bool:
|
||||
"""Match a callable against either the installed PPM or owned equivalent."""
|
||||
|
||||
return any(_is_identity(value, *identity) for identity in identities)
|
||||
|
||||
|
||||
PPM_NEGPIP_INTEROP_VALIDATOR = PpmNegpipInteropValidator()
|
||||
@@ -86,6 +86,28 @@ class PromptControlGraphAdapter:
|
||||
self.merge_expand(expand, negative.expand, "negative LoRA scheduling")
|
||||
return negative.args[0], negative.args[1]
|
||||
|
||||
def apply_automatic_negpip(
|
||||
self,
|
||||
*,
|
||||
model: Any,
|
||||
clip: Any,
|
||||
expand: dict[str, dict[str, Any]],
|
||||
) -> tuple[Any, Any]:
|
||||
"""Insert the runtime family check after a negative prompt-weight trigger."""
|
||||
|
||||
graph = self._graph_utils.GraphBuilder()
|
||||
prepared = graph.node(
|
||||
"SimpleSyrup.ApplyAutomaticNegpip",
|
||||
model=model,
|
||||
clip=clip,
|
||||
)
|
||||
self.merge_expand(
|
||||
expand,
|
||||
cast(dict[str, dict[str, Any]], graph.finalize()),
|
||||
"automatic NegPiP preparation",
|
||||
)
|
||||
return prepared.out(0), prepared.out(1)
|
||||
|
||||
def encode_segment(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -8,6 +8,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from ..domain.negative_prompt_weights import contains_negative_prompt_weight
|
||||
from ..domain.prompt_batch_parser import DEFAULT_PROMPT_BATCH_SEPARATOR
|
||||
from ..domain.prompt_control_prompt import PreparedPromptSide, apply_encode_style
|
||||
from ..services.prompt_control_segment_planning_service import (
|
||||
@@ -48,6 +49,12 @@ class PromptControlScheduleEncodeGraphBuilder:
|
||||
)
|
||||
adapter = self.graph_adapter_class.load(PROMPT_CONTROL_MISSING_MESSAGE)
|
||||
expand: dict[str, dict[str, Any]] = {}
|
||||
if self._requires_negpip(plan):
|
||||
model, clip = adapter.apply_automatic_negpip(
|
||||
model=model,
|
||||
clip=clip,
|
||||
expand=expand,
|
||||
)
|
||||
scheduled_model, encoding_clip = self._sampling_inputs(
|
||||
model=model,
|
||||
clip=clip,
|
||||
@@ -84,6 +91,16 @@ class PromptControlScheduleEncodeGraphBuilder:
|
||||
expand=expand,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _requires_negpip(plan: PromptControlSegmentPlan) -> bool:
|
||||
"""Return whether any cleaned positive or negative segment needs NegPiP."""
|
||||
|
||||
return any(
|
||||
contains_negative_prompt_weight(chunk.text)
|
||||
for side in (plan.positive, plan.negative)
|
||||
for chunk in side.chunks
|
||||
)
|
||||
|
||||
def _sampling_inputs(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Declare shared checksum-pinned Qwen model artifacts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .auto_model_artifact import AutoModelArtifact
|
||||
|
||||
QWEN_IMAGE_VAE = AutoModelArtifact(
|
||||
cache_id="qwen_image_vae",
|
||||
filename="qwen_image_vae.safetensors",
|
||||
folder_name="vae",
|
||||
canonical_subfolder="qwen",
|
||||
source_url=(
|
||||
"https://huggingface.co/Comfy-Org/Krea-2/resolve/"
|
||||
"e5ea8b4dd7f38f348b138eb0fe29f92c0e367e96/vae/"
|
||||
"qwen_image_vae.safetensors"
|
||||
),
|
||||
source_repo="Comfy-Org/Krea-2",
|
||||
description="Qwen Image VAE",
|
||||
sha256="a70580f0213e67967ee9c95f05bb400e8fb08307e017a924bf3441223e023d1f",
|
||||
file_size_bytes=253_806_246,
|
||||
)
|
||||
|
||||
__all__ = ["QWEN_IMAGE_VAE"]
|
||||
@@ -7,6 +7,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as functional
|
||||
from comfy.utils import repeat_to_batch_size
|
||||
|
||||
from ..domain.processed_regional_attention import (
|
||||
@@ -143,6 +144,13 @@ class RegionalAttentionBatchingService:
|
||||
)
|
||||
for region_index in range(plan.mask_bank.region_count)
|
||||
),
|
||||
base_value_multiplier=self._align_value_multiplier(
|
||||
tuple(chunk.base_entry for chunk in selected),
|
||||
latent_batch_size=latent_batch_size,
|
||||
device=aligned_base_context.device,
|
||||
dtype=aligned_base_context.dtype,
|
||||
target_sequence_length=target_sequence_length,
|
||||
),
|
||||
)
|
||||
|
||||
def _align_region(
|
||||
@@ -163,6 +171,7 @@ class RegionalAttentionBatchingService:
|
||||
for entry_index in range(entry_count):
|
||||
context_parts: list[torch.Tensor] = []
|
||||
strengths: list[float] = []
|
||||
multiplier_entries: list[ProcessedRegionalAttentionEntry] = []
|
||||
for chunk, source in zip(chunks, sources, strict=True):
|
||||
if source is None:
|
||||
entry = chunk.base_entry
|
||||
@@ -186,12 +195,20 @@ class RegionalAttentionBatchingService:
|
||||
target_length=target_sequence_length,
|
||||
)
|
||||
context_parts.append(repeated)
|
||||
multiplier_entries.append(entry)
|
||||
strengths.extend((strength,) * latent_batch_size)
|
||||
entries.append(
|
||||
BatchedRegionalAttentionEntry(
|
||||
entry_index,
|
||||
torch.cat(context_parts, dim=0),
|
||||
tuple(strengths),
|
||||
self._align_value_multiplier(
|
||||
tuple(multiplier_entries),
|
||||
latent_batch_size=latent_batch_size,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
target_sequence_length=target_sequence_length,
|
||||
),
|
||||
)
|
||||
)
|
||||
return BatchedRegionalAttentionRegion(region_index, tuple(entries))
|
||||
@@ -201,6 +218,7 @@ class RegionalAttentionBatchingService:
|
||||
|
||||
entries = self._entries(plan)
|
||||
authority = entries[0].cross_attention
|
||||
has_value_multiplier = entries[0].cross_attention_value_multiplier is not None
|
||||
for entry in entries[1:]:
|
||||
tensor = entry.cross_attention
|
||||
shape_mismatch = (
|
||||
@@ -216,6 +234,48 @@ class RegionalAttentionBatchingService:
|
||||
raise ValueError("Regional attention context devices must match.")
|
||||
if tensor.dtype != authority.dtype:
|
||||
raise ValueError("Regional attention context dtypes must match.")
|
||||
if (
|
||||
entry.cross_attention_value_multiplier is not None
|
||||
) is not has_value_multiplier:
|
||||
raise ValueError(
|
||||
"Regional attention value multiplier presence must be uniform."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _align_value_multiplier(
|
||||
entries: tuple[ProcessedRegionalAttentionEntry, ...],
|
||||
*,
|
||||
latent_batch_size: int,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
target_sequence_length: int,
|
||||
) -> torch.Tensor | None:
|
||||
"""Repeat and sequence-align one chunk-major value-multiplier bank."""
|
||||
|
||||
if not entries or entries[0].cross_attention_value_multiplier is None:
|
||||
return None
|
||||
parts: list[torch.Tensor] = []
|
||||
for entry in entries:
|
||||
multiplier = entry.cross_attention_value_multiplier
|
||||
if multiplier is None:
|
||||
raise ValueError(
|
||||
"Regional attention value multiplier presence must be uniform."
|
||||
)
|
||||
repeated = repeat_to_batch_size(multiplier, latent_batch_size).to(
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
sequence_length = int(repeated.shape[1])
|
||||
if sequence_length < target_sequence_length:
|
||||
repeated = functional.pad(
|
||||
repeated,
|
||||
(0, 0, 0, target_sequence_length - sequence_length),
|
||||
value=1.0,
|
||||
)
|
||||
elif sequence_length > target_sequence_length:
|
||||
repeated = repeated[:, :target_sequence_length]
|
||||
parts.append(repeated)
|
||||
return torch.cat(parts, dim=0)
|
||||
|
||||
@staticmethod
|
||||
def _entries(
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from ..patcher_lifecycle import ModelMutation
|
||||
from ..ppm_negpip_interop import PpmNegpipInterop
|
||||
from .anima_activation_context import (
|
||||
ANIMA_ACTIVATION_CONTEXT,
|
||||
AnimaActivationContext,
|
||||
@@ -75,6 +76,7 @@ def anima_attention_coupling_mutations(
|
||||
),
|
||||
phase_context: AnimaCompositionPhaseContext = (ANIMA_COMPOSITION_PHASE_CONTEXT),
|
||||
query_mask_context: AnimaQueryMaskContext = ANIMA_QUERY_MASK_CONTEXT,
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> tuple[ModelMutation, ...]:
|
||||
"""Return attention-only or complete regional-LoRA mutation composition."""
|
||||
|
||||
@@ -106,6 +108,7 @@ def anima_attention_coupling_mutations(
|
||||
invocation_context=cross_attention_context,
|
||||
phase_context=phase_context,
|
||||
query_activity=query_activity,
|
||||
negpip=negpip,
|
||||
)
|
||||
phase_wrapper = anima_composition_phase_wrapper_mutation(
|
||||
surface,
|
||||
|
||||
@@ -18,6 +18,7 @@ from ...domain.regional_conditioning_output import (
|
||||
RegionalConditioningOutputCombiner,
|
||||
)
|
||||
from ..model_patcher_mutations import ModelExactObjectPatchMutation
|
||||
from ..ppm_negpip_interop import PpmNegpipInterop
|
||||
from .anima_activation_context import (
|
||||
ANIMA_ACTIVATION_CONTEXT,
|
||||
AnimaActivationContext,
|
||||
@@ -26,6 +27,7 @@ from .anima_activation_context import (
|
||||
from .anima_attention_execution import AnimaRegionalAttentionExecution
|
||||
from .anima_branch_batch import (
|
||||
ANIMA_BASE_BRANCH_KEY,
|
||||
AnimaRegionalBranchBatch,
|
||||
AnimaRegionalBranchKey,
|
||||
)
|
||||
from .anima_composition_phase_context import AnimaCompositionPhaseContext
|
||||
@@ -71,6 +73,7 @@ class AnimaRegionalCrossAttentionPatch(nn.Module):
|
||||
),
|
||||
weighting: RegionalAttentionWeightingPolicy | None = None,
|
||||
entry_combiner: RegionalConditioningOutputCombiner | None = None,
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> None:
|
||||
"""Retain the exact original attention owner and focused collaborators."""
|
||||
|
||||
@@ -92,6 +95,9 @@ class AnimaRegionalCrossAttentionPatch(nn.Module):
|
||||
self._query_activity = query_activity
|
||||
self._weighting = weighting or ANIMA_CROSS_ATTENTION_WEIGHTING_POLICY
|
||||
self._entry_combiner = entry_combiner or REGIONAL_CONDITIONING_OUTPUT_COMBINER
|
||||
if negpip is not None and not isinstance(negpip, PpmNegpipInterop):
|
||||
raise TypeError("Anima cross-attention NegPiP state has an invalid type.")
|
||||
self._negpip = negpip
|
||||
|
||||
def __setattr__(self, name: str, value: Any) -> None:
|
||||
"""Keep later exact child patches synchronized with installed attention."""
|
||||
@@ -143,14 +149,18 @@ class AnimaRegionalCrossAttentionPatch(nn.Module):
|
||||
branch_batch = activity.attention_branches
|
||||
branch_x = branch_batch.pack_source(x)
|
||||
branch_context = branch_batch.pack_branch_values(branch_values)
|
||||
original_options = {} if transformer_options is None else transformer_options
|
||||
forwarded_options = self._prepare_transformer_options(
|
||||
original_options,
|
||||
branch_batch,
|
||||
execution_contexts,
|
||||
)
|
||||
with self._invocation_context.activate(branch_batch.invocation):
|
||||
branch_output = self._backing.module(
|
||||
branch_x,
|
||||
branch_context,
|
||||
rope_emb=rope_emb,
|
||||
transformer_options=(
|
||||
{} if transformer_options is None else transformer_options
|
||||
),
|
||||
transformer_options=forwarded_options,
|
||||
)
|
||||
if not isinstance(branch_output, torch.Tensor):
|
||||
raise TypeError("Original Anima cross-attention must return a tensor.")
|
||||
@@ -186,6 +196,41 @@ class AnimaRegionalCrossAttentionPatch(nn.Module):
|
||||
regional_outputs=torch.stack(regional_outputs),
|
||||
)
|
||||
|
||||
def _prepare_transformer_options(
|
||||
self,
|
||||
source: dict[str, Any],
|
||||
branch_batch: AnimaRegionalBranchBatch,
|
||||
contexts: BatchedRegionalAttentionContexts,
|
||||
) -> dict[str, object]:
|
||||
"""Pack NegPiP multipliers or preserve ordinary option identity."""
|
||||
|
||||
if self._negpip is None:
|
||||
if contexts.base_value_multiplier is not None:
|
||||
raise ValueError(
|
||||
"Anima value multipliers require admitted NegPiP semantics."
|
||||
)
|
||||
return source
|
||||
if not isinstance(branch_batch, AnimaRegionalBranchBatch):
|
||||
raise TypeError("Anima NegPiP branch batch has an invalid type.")
|
||||
base_multiplier = contexts.base_value_multiplier
|
||||
if base_multiplier is None:
|
||||
raise ValueError("Anima NegPiP requires an aligned base value multiplier.")
|
||||
values = {ANIMA_BASE_BRANCH_KEY: base_multiplier}
|
||||
for region in contexts.regions:
|
||||
for entry in region.entries:
|
||||
multiplier = entry.cross_attention_value_multiplier
|
||||
if multiplier is None:
|
||||
raise ValueError(
|
||||
"Anima NegPiP requires every regional value multiplier."
|
||||
)
|
||||
values[
|
||||
AnimaRegionalBranchKey(region.region_index, entry.entry_index)
|
||||
] = multiplier
|
||||
return self._negpip.prepare_anima_transformer_options(
|
||||
source,
|
||||
branch_batch.pack_branch_values(values),
|
||||
)
|
||||
|
||||
def _validate_inputs(
|
||||
self,
|
||||
*,
|
||||
@@ -246,6 +291,7 @@ def anima_cross_attention_mutations(
|
||||
query_activity: AnimaRegionalQueryActivityContext = (
|
||||
ANIMA_REGIONAL_QUERY_ACTIVITY_CONTEXT
|
||||
),
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> tuple[ModelExactObjectPatchMutation, ...]:
|
||||
"""Build one exact clone-local cross-attention replacement per Anima block."""
|
||||
|
||||
@@ -262,6 +308,7 @@ def anima_cross_attention_mutations(
|
||||
invocation_context=invocation_context,
|
||||
phase_context=phase_context,
|
||||
query_activity=query_activity,
|
||||
negpip=negpip,
|
||||
),
|
||||
)
|
||||
for block in surface.blocks
|
||||
|
||||
@@ -10,6 +10,7 @@ from dataclasses import dataclass
|
||||
|
||||
from ...domain.processed_regional_attention import ProcessedRegionalAttentionPlan
|
||||
from ..patcher_lifecycle import PATCHER_LIFECYCLE
|
||||
from ..ppm_negpip_interop import PpmNegpipInterop
|
||||
from ..regional_attention_template import build_regional_attention_template
|
||||
from ..regional_lora_plan_adapter import RegionalLoraPlanAdaptation
|
||||
from .anima_attention_context_wrapper import (
|
||||
@@ -19,7 +20,6 @@ from .anima_attention_coupling import anima_attention_coupling_mutations
|
||||
from .anima_attention_execution import AnimaRegionalAttentionExecution
|
||||
from .anima_composition import AnimaRegionalLoraComposition
|
||||
from .anima_execution_scope import AnimaRegionalLoraAdapterExecution
|
||||
from .anima_global_lora_overlap import ANIMA_GLOBAL_REGIONAL_LORA_OVERLAP_VALIDATOR
|
||||
from .anima_model_patcher_surface import ANIMA_MODEL_PATCHER_SURFACE_RESOLVER
|
||||
from .anima_plan_admission import ANIMA_REGIONAL_LORA_PLAN_ADMISSION_SERVICE
|
||||
from .execution_cache import ModelCloneLineage, RegionalLoraExecutionCache
|
||||
@@ -44,6 +44,7 @@ class FullContextAnimaAttentionBackend:
|
||||
adaptation: RegionalLoraPlanAdaptation,
|
||||
region_strengths: tuple[float, ...],
|
||||
latent_batch_size: int,
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> FullContextAnimaAttentionModel:
|
||||
"""Return one collision-safe clone prepared for dynamic sampler calls."""
|
||||
|
||||
@@ -51,8 +52,9 @@ class FullContextAnimaAttentionBackend:
|
||||
raise TypeError("Anima backend requires a processed attention plan.")
|
||||
if not isinstance(adaptation, RegionalLoraPlanAdaptation):
|
||||
raise TypeError("Anima backend requires a regional LoRA adaptation.")
|
||||
if negpip is not None and not isinstance(negpip, PpmNegpipInterop):
|
||||
raise TypeError("Anima backend NegPiP state has an invalid type.")
|
||||
admitted = ANIMA_REGIONAL_LORA_PLAN_ADMISSION_SERVICE.admit(adaptation)
|
||||
ANIMA_GLOBAL_REGIONAL_LORA_OVERLAP_VALIDATOR.validate(model, admitted)
|
||||
template = build_regional_attention_template(
|
||||
processed_plan,
|
||||
latent_batch_size=latent_batch_size,
|
||||
@@ -89,6 +91,7 @@ class FullContextAnimaAttentionBackend:
|
||||
surface,
|
||||
attention,
|
||||
composition=composition,
|
||||
negpip=negpip,
|
||||
),
|
||||
)
|
||||
derived = PATCHER_LIFECYCLE.derive_model(
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Reject exact static-global and admitted-regional Anima LoRA overlap."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
|
||||
import torch
|
||||
from comfy.weight_adapter.lora import LoRAAdapter
|
||||
|
||||
from .anima_plan_admission import (
|
||||
AnimaRegionalLoraAdapterAdmission,
|
||||
AnimaRegionalLoraPlanAdmission,
|
||||
)
|
||||
from .standard_adapter import StandardLoraTarget
|
||||
|
||||
|
||||
class AnimaGlobalRegionalLoraOverlapError(ValueError):
|
||||
"""Report regional adapters already present in the static global MODEL."""
|
||||
|
||||
|
||||
class AnimaGlobalRegionalLoraOverlapValidator:
|
||||
"""Compare exact admitted regional A/B tensors with static global patches."""
|
||||
|
||||
def validate(
|
||||
self,
|
||||
model: object,
|
||||
admission: AnimaRegionalLoraPlanAdmission,
|
||||
) -> None:
|
||||
"""Reject every regional adapter whose complete content is global."""
|
||||
|
||||
if not isinstance(admission, AnimaRegionalLoraPlanAdmission):
|
||||
raise TypeError("Anima global LoRA overlap requires an admitted plan.")
|
||||
patches = getattr(model, "patches", None)
|
||||
if not isinstance(patches, Mapping):
|
||||
raise TypeError("Anima global LoRA overlap requires MODEL patches.")
|
||||
duplicates = tuple(
|
||||
adapter.adapter_plan.adapter_identity.value
|
||||
for adapter in admission.adapters
|
||||
if self._duplicates_global_content(patches, adapter)
|
||||
)
|
||||
unique_duplicates = tuple(dict.fromkeys(duplicates))
|
||||
if unique_duplicates:
|
||||
identities = ", ".join(repr(value) for value in unique_duplicates)
|
||||
raise AnimaGlobalRegionalLoraOverlapError(
|
||||
"Regional Anima LoRA content is already applied globally to the "
|
||||
f"input MODEL: {identities}. Remove either the global or regional "
|
||||
"application before sampling."
|
||||
)
|
||||
|
||||
def _duplicates_global_content(
|
||||
self,
|
||||
patches: Mapping[object, object],
|
||||
adapter: AnimaRegionalLoraAdapterAdmission,
|
||||
) -> bool:
|
||||
"""Return whether every admitted regional target has an exact global pair."""
|
||||
|
||||
targets = adapter.admission.targets
|
||||
return bool(targets) and all(
|
||||
self._target_matches(patches, target.adapter) for target in targets
|
||||
)
|
||||
|
||||
def _target_matches(
|
||||
self,
|
||||
patches: Mapping[object, object],
|
||||
regional: StandardLoraTarget,
|
||||
) -> bool:
|
||||
"""Match one regional target against nonzero comparable static patches."""
|
||||
|
||||
key = f"{regional.target}.weight"
|
||||
entries = patches.get(key, ())
|
||||
if entries == ():
|
||||
return False
|
||||
if not isinstance(entries, list):
|
||||
raise TypeError(f"MODEL patches[{key!r}] must be a list.")
|
||||
for index, entry in enumerate(entries):
|
||||
if not isinstance(entry, tuple) or len(entry) < 3:
|
||||
raise TypeError(
|
||||
f"MODEL patches[{key!r}][{index}] must be a Comfy patch tuple."
|
||||
)
|
||||
if _nonzero_strength(entry[0], key=key, index=index) and _matches_pair(
|
||||
entry[1],
|
||||
regional,
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _nonzero_strength(value: object, *, key: str, index: int) -> bool:
|
||||
"""Validate one installed static patch strength and report its activity."""
|
||||
|
||||
if isinstance(value, bool) or not isinstance(value, int | float):
|
||||
raise TypeError(f"MODEL patches[{key!r}][{index}] strength must be numeric.")
|
||||
strength = float(value)
|
||||
if not math.isfinite(strength):
|
||||
raise ValueError(f"MODEL patches[{key!r}][{index}] strength must be finite.")
|
||||
return strength != 0.0
|
||||
|
||||
|
||||
def _matches_pair(value: object, regional: StandardLoraTarget) -> bool:
|
||||
"""Compare one installed standard LoRA patch without copies or transfers."""
|
||||
|
||||
if not isinstance(value, LoRAAdapter):
|
||||
return False
|
||||
weights = value.weights
|
||||
if not isinstance(weights, tuple) or len(weights) != 6:
|
||||
return False
|
||||
up, down, alpha, mid, dora_scale, reshape = weights
|
||||
if any(item is not None for item in (alpha, mid, dora_scale, reshape)):
|
||||
return False
|
||||
if not isinstance(down, torch.Tensor) or not isinstance(up, torch.Tensor):
|
||||
return False
|
||||
return _same_tensor(down, regional.down) and _same_tensor(up, regional.up)
|
||||
|
||||
|
||||
def _same_tensor(left: torch.Tensor, right: torch.Tensor) -> bool:
|
||||
"""Use an identity fast path before exact same-residency tensor equality."""
|
||||
|
||||
if left is right:
|
||||
return True
|
||||
if (
|
||||
left.shape != right.shape
|
||||
or left.dtype != right.dtype
|
||||
or left.device != right.device
|
||||
):
|
||||
return False
|
||||
return bool(torch.equal(left, right))
|
||||
|
||||
|
||||
ANIMA_GLOBAL_REGIONAL_LORA_OVERLAP_VALIDATOR = AnimaGlobalRegionalLoraOverlapValidator()
|
||||
@@ -5,22 +5,62 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import ModuleType
|
||||
from typing import Protocol, cast, runtime_checkable
|
||||
|
||||
import torch
|
||||
|
||||
from .fused_active_accumulation_kernel import (
|
||||
MAX_FUSED_ADAPTERS_PER_LAUNCH,
|
||||
REGIONAL_LORA_FUSED_ACCUMULATION_KERNEL,
|
||||
from .fused_active_accumulation_contract import MAX_FUSED_ADAPTERS_PER_LAUNCH
|
||||
from .triton_runtime import TRITON_RUNTIME_RESOLVER, TritonRuntimeResolver
|
||||
|
||||
_TRITON_BACKEND_MODULE = (
|
||||
"simple_syrup.runtime.regional_lora.fused_active_accumulation_kernel"
|
||||
)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class _FusedAccumulationKernel(Protocol):
|
||||
"""Describe the lazily resolved fused CUDA launch surface."""
|
||||
|
||||
def launch(
|
||||
self,
|
||||
output: torch.Tensor,
|
||||
*,
|
||||
rank_values: torch.Tensor,
|
||||
up: torch.Tensor,
|
||||
multipliers: tuple[torch.Tensor, ...],
|
||||
indices: torch.Tensor | None,
|
||||
adapter_start: int,
|
||||
target_indices: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
"""Launch one validated fused accumulation chunk."""
|
||||
|
||||
...
|
||||
|
||||
|
||||
class _FusedAccumulationBackend(Protocol):
|
||||
"""Describe the exported lazy backend module surface."""
|
||||
|
||||
REGIONAL_LORA_FUSED_ACCUMULATION_KERNEL: _FusedAccumulationKernel
|
||||
|
||||
|
||||
class RegionalLoraFusedActiveAccumulator:
|
||||
"""Own verified CUDA fusion for B projection and ordered output updates."""
|
||||
|
||||
@staticmethod
|
||||
def supports(output: torch.Tensor, up: torch.Tensor) -> bool:
|
||||
def __init__(
|
||||
self,
|
||||
resolver: TritonRuntimeResolver = TRITON_RUNTIME_RESOLVER,
|
||||
) -> None:
|
||||
"""Retain the process-level optional acceleration authority."""
|
||||
|
||||
if not isinstance(resolver, TritonRuntimeResolver):
|
||||
raise TypeError("Fused accumulation requires a Triton resolver.")
|
||||
self._resolver = resolver
|
||||
|
||||
def supports(self, output: torch.Tensor, up: torch.Tensor) -> bool:
|
||||
"""Admit only verified contiguous CUDA bf16/fp16 projection shapes."""
|
||||
|
||||
return (
|
||||
eligible = (
|
||||
isinstance(output, torch.Tensor)
|
||||
and isinstance(up, torch.Tensor)
|
||||
and output.device.type == "cuda"
|
||||
@@ -32,6 +72,7 @@ class RegionalLoraFusedActiveAccumulator:
|
||||
and output.is_contiguous()
|
||||
and up.is_contiguous()
|
||||
)
|
||||
return eligible and self._backend() is not None
|
||||
|
||||
def add(
|
||||
self,
|
||||
@@ -59,7 +100,7 @@ class RegionalLoraFusedActiveAccumulator:
|
||||
return output
|
||||
for start in range(0, adapter_count, MAX_FUSED_ADAPTERS_PER_LAUNCH):
|
||||
stop = min(start + MAX_FUSED_ADAPTERS_PER_LAUNCH, adapter_count)
|
||||
REGIONAL_LORA_FUSED_ACCUMULATION_KERNEL.launch(
|
||||
self._require_backend().launch(
|
||||
output,
|
||||
rank_values=rank_values,
|
||||
up=up,
|
||||
@@ -97,7 +138,7 @@ class RegionalLoraFusedActiveAccumulator:
|
||||
)
|
||||
if active_row_count == 0:
|
||||
return output
|
||||
REGIONAL_LORA_FUSED_ACCUMULATION_KERNEL.launch(
|
||||
self._require_backend().launch(
|
||||
output,
|
||||
rank_values=rank_values,
|
||||
up=up,
|
||||
@@ -137,7 +178,7 @@ class RegionalLoraFusedActiveAccumulator:
|
||||
return output
|
||||
for start in range(0, len(multipliers), MAX_FUSED_ADAPTERS_PER_LAUNCH):
|
||||
stop = min(start + MAX_FUSED_ADAPTERS_PER_LAUNCH, len(multipliers))
|
||||
REGIONAL_LORA_FUSED_ACCUMULATION_KERNEL.launch(
|
||||
self._require_backend().launch(
|
||||
output,
|
||||
rank_values=rank_values,
|
||||
up=up,
|
||||
@@ -148,9 +189,28 @@ class RegionalLoraFusedActiveAccumulator:
|
||||
)
|
||||
return output
|
||||
|
||||
@classmethod
|
||||
def _backend(self) -> _FusedAccumulationKernel | None:
|
||||
"""Return the cached optional fused kernel without hiding failures."""
|
||||
|
||||
backend = self._resolver.resolve(_TRITON_BACKEND_MODULE)
|
||||
if backend is None:
|
||||
return None
|
||||
module = cast(_FusedAccumulationBackend, cast(ModuleType, backend))
|
||||
kernel = module.REGIONAL_LORA_FUSED_ACCUMULATION_KERNEL
|
||||
if not isinstance(kernel, _FusedAccumulationKernel):
|
||||
raise TypeError("Triton fused backend has an invalid kernel surface.")
|
||||
return kernel
|
||||
|
||||
def _require_backend(self) -> _FusedAccumulationKernel:
|
||||
"""Return the admitted kernel or reject an invalid direct fused call."""
|
||||
|
||||
backend = self._backend()
|
||||
if backend is None:
|
||||
raise RuntimeError("Triton fused accumulation is unavailable.")
|
||||
return backend
|
||||
|
||||
def _validate_mapped_projection(
|
||||
cls,
|
||||
self,
|
||||
output: torch.Tensor,
|
||||
rank_values: torch.Tensor,
|
||||
up: torch.Tensor,
|
||||
@@ -159,7 +219,7 @@ class RegionalLoraFusedActiveAccumulator:
|
||||
) -> None:
|
||||
"""Require one unique-target batch and valid declared group mapping."""
|
||||
|
||||
if not cls.supports(output, up):
|
||||
if not self.supports(output, up):
|
||||
raise ValueError("Mapped fused accumulation received an unsupported path.")
|
||||
if (
|
||||
rank_values.device != output.device
|
||||
@@ -191,9 +251,8 @@ class RegionalLoraFusedActiveAccumulator:
|
||||
):
|
||||
raise ValueError("Mapped fused output indices are misaligned.")
|
||||
|
||||
@classmethod
|
||||
def _validate_projection(
|
||||
cls,
|
||||
self,
|
||||
output: torch.Tensor,
|
||||
rank_values: torch.Tensor,
|
||||
up: torch.Tensor,
|
||||
@@ -201,7 +260,7 @@ class RegionalLoraFusedActiveAccumulator:
|
||||
) -> None:
|
||||
"""Require one complete aligned CUDA projection contract."""
|
||||
|
||||
if not cls.supports(output, up):
|
||||
if not self.supports(output, up):
|
||||
raise ValueError("Fused active accumulation received an unsupported path.")
|
||||
if (
|
||||
rank_values.device != output.device
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Define the shared launch-width contract for fused LoRA accumulation."""
|
||||
|
||||
MAX_FUSED_ADAPTERS_PER_LAUNCH = 8
|
||||
@@ -14,7 +14,8 @@ import torch
|
||||
import triton # type: ignore[import-untyped]
|
||||
import triton.language as tl # type: ignore[import-untyped]
|
||||
|
||||
MAX_FUSED_ADAPTERS_PER_LAUNCH = 8
|
||||
from .fused_active_accumulation_contract import MAX_FUSED_ADAPTERS_PER_LAUNCH
|
||||
|
||||
_BLOCK_ROWS = 16
|
||||
_BLOCK_OUTPUT_FEATURES = 64
|
||||
|
||||
|
||||
@@ -1,67 +1,48 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
# mypy: disable-error-code="no-untyped-def"
|
||||
# ruff: noqa: ANN001, ANN202
|
||||
|
||||
"""Accumulate ordered adapter outputs with exact execution-dtype rounding."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, cast
|
||||
from types import ModuleType
|
||||
from typing import Protocol, cast
|
||||
|
||||
import torch
|
||||
import triton # type: ignore[import-untyped]
|
||||
import triton.language as tl # type: ignore[import-untyped]
|
||||
|
||||
_MAX_DELTAS_PER_LAUNCH = 8
|
||||
_BLOCK_SIZE = 256
|
||||
from .triton_runtime import TRITON_RUNTIME_RESOLVER, TritonRuntimeResolver
|
||||
|
||||
_TRITON_BACKEND_MODULE = (
|
||||
"simple_syrup.runtime.regional_lora.ordered_accumulation_triton"
|
||||
)
|
||||
|
||||
|
||||
@triton.jit # type: ignore[untyped-decorator]
|
||||
def _ordered_accumulation_kernel(
|
||||
output,
|
||||
base,
|
||||
delta_0,
|
||||
delta_1,
|
||||
delta_2,
|
||||
delta_3,
|
||||
delta_4,
|
||||
delta_5,
|
||||
delta_6,
|
||||
delta_7,
|
||||
element_count,
|
||||
delta_count: tl.constexpr,
|
||||
execution_dtype: tl.constexpr,
|
||||
block_size: tl.constexpr,
|
||||
):
|
||||
"""Add one ordered chunk and round after every declared adapter."""
|
||||
class _OrderedAccumulationBackend(Protocol):
|
||||
"""Describe the lazy CUDA backend surface consumed by this owner."""
|
||||
|
||||
offsets = tl.program_id(0) * block_size + tl.arange(0, block_size)
|
||||
active = offsets < element_count
|
||||
value = tl.load(base + offsets, mask=active)
|
||||
if delta_count > 0:
|
||||
value = (value + tl.load(delta_0 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 1:
|
||||
value = (value + tl.load(delta_1 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 2:
|
||||
value = (value + tl.load(delta_2 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 3:
|
||||
value = (value + tl.load(delta_3 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 4:
|
||||
value = (value + tl.load(delta_4 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 5:
|
||||
value = (value + tl.load(delta_5 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 6:
|
||||
value = (value + tl.load(delta_6 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 7:
|
||||
value = (value + tl.load(delta_7 + offsets, mask=active)).to(execution_dtype)
|
||||
tl.store(output + offsets, value, mask=active)
|
||||
def accumulate(
|
||||
self,
|
||||
base: torch.Tensor,
|
||||
deltas: tuple[torch.Tensor, ...],
|
||||
) -> torch.Tensor:
|
||||
"""Accumulate validated CUDA tensors in declared order."""
|
||||
|
||||
...
|
||||
|
||||
|
||||
class OrderedTensorAccumulator:
|
||||
"""Own exact ordered accumulation and its CUDA launch policy."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
resolver: TritonRuntimeResolver = TRITON_RUNTIME_RESOLVER,
|
||||
) -> None:
|
||||
"""Retain the process-level optional acceleration authority."""
|
||||
|
||||
if not isinstance(resolver, TritonRuntimeResolver):
|
||||
raise TypeError("Ordered accumulation requires a Triton resolver.")
|
||||
self._resolver = resolver
|
||||
|
||||
def accumulate(
|
||||
self,
|
||||
base: torch.Tensor,
|
||||
@@ -74,25 +55,13 @@ class OrderedTensorAccumulator:
|
||||
return base
|
||||
if base.device.type != "cuda":
|
||||
return self._torch_accumulate(base, deltas)
|
||||
execution_dtype = self._triton_dtype(base.dtype)
|
||||
remaining = deltas
|
||||
result = base
|
||||
while remaining:
|
||||
chunk = remaining[:_MAX_DELTAS_PER_LAUNCH]
|
||||
remaining = remaining[_MAX_DELTAS_PER_LAUNCH:]
|
||||
padded = (*chunk, *((result,) * (_MAX_DELTAS_PER_LAUNCH - len(chunk))))
|
||||
grid = (triton.cdiv(result.numel(), _BLOCK_SIZE),)
|
||||
kernel = cast(Any, _ordered_accumulation_kernel)
|
||||
kernel[grid](
|
||||
result,
|
||||
result,
|
||||
*padded,
|
||||
result.numel(),
|
||||
delta_count=len(chunk),
|
||||
execution_dtype=execution_dtype,
|
||||
block_size=_BLOCK_SIZE,
|
||||
)
|
||||
return result
|
||||
backend = self._resolver.resolve(_TRITON_BACKEND_MODULE)
|
||||
if backend is None:
|
||||
return self._torch_accumulate(base, deltas)
|
||||
return cast(_OrderedAccumulationBackend, cast(ModuleType, backend)).accumulate(
|
||||
base,
|
||||
deltas,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _torch_accumulate(
|
||||
@@ -106,18 +75,6 @@ class OrderedTensorAccumulator:
|
||||
result.add_(delta)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _triton_dtype(dtype: torch.dtype) -> Any:
|
||||
"""Map the admitted floating execution dtype to a Triton scalar dtype."""
|
||||
|
||||
if dtype is torch.bfloat16:
|
||||
return tl.bfloat16
|
||||
if dtype is torch.float16:
|
||||
return tl.float16
|
||||
if dtype is torch.float32:
|
||||
return tl.float32
|
||||
raise TypeError(f"Ordered CUDA accumulation does not support {dtype}.")
|
||||
|
||||
@staticmethod
|
||||
def _validate(
|
||||
base: torch.Tensor,
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
# mypy: disable-error-code="no-untyped-def"
|
||||
# ruff: noqa: ANN001, ANN202
|
||||
|
||||
"""Provide the lazily imported Triton ordered-accumulation backend."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, cast
|
||||
|
||||
import torch
|
||||
import triton # type: ignore[import-untyped]
|
||||
import triton.language as tl # type: ignore[import-untyped]
|
||||
|
||||
_MAX_DELTAS_PER_LAUNCH = 8
|
||||
_BLOCK_SIZE = 256
|
||||
|
||||
|
||||
@triton.jit # type: ignore[untyped-decorator]
|
||||
def _ordered_accumulation_kernel(
|
||||
output,
|
||||
base,
|
||||
delta_0,
|
||||
delta_1,
|
||||
delta_2,
|
||||
delta_3,
|
||||
delta_4,
|
||||
delta_5,
|
||||
delta_6,
|
||||
delta_7,
|
||||
element_count,
|
||||
delta_count: tl.constexpr,
|
||||
execution_dtype: tl.constexpr,
|
||||
block_size: tl.constexpr,
|
||||
):
|
||||
"""Add one ordered chunk and round after every declared adapter."""
|
||||
|
||||
offsets = tl.program_id(0) * block_size + tl.arange(0, block_size)
|
||||
active = offsets < element_count
|
||||
value = tl.load(base + offsets, mask=active)
|
||||
if delta_count > 0:
|
||||
value = (value + tl.load(delta_0 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 1:
|
||||
value = (value + tl.load(delta_1 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 2:
|
||||
value = (value + tl.load(delta_2 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 3:
|
||||
value = (value + tl.load(delta_3 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 4:
|
||||
value = (value + tl.load(delta_4 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 5:
|
||||
value = (value + tl.load(delta_5 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 6:
|
||||
value = (value + tl.load(delta_6 + offsets, mask=active)).to(execution_dtype)
|
||||
if delta_count > 7:
|
||||
value = (value + tl.load(delta_7 + offsets, mask=active)).to(execution_dtype)
|
||||
tl.store(output + offsets, value, mask=active)
|
||||
|
||||
|
||||
def accumulate(base: torch.Tensor, deltas: tuple[torch.Tensor, ...]) -> torch.Tensor:
|
||||
"""Accumulate CUDA deltas with the established launch and rounding policy."""
|
||||
|
||||
execution_dtype = _triton_dtype(base.dtype)
|
||||
remaining = deltas
|
||||
result = base
|
||||
while remaining:
|
||||
chunk = remaining[:_MAX_DELTAS_PER_LAUNCH]
|
||||
remaining = remaining[_MAX_DELTAS_PER_LAUNCH:]
|
||||
padded = (*chunk, *((result,) * (_MAX_DELTAS_PER_LAUNCH - len(chunk))))
|
||||
grid = (triton.cdiv(result.numel(), _BLOCK_SIZE),)
|
||||
kernel = cast(Any, _ordered_accumulation_kernel)
|
||||
kernel[grid](
|
||||
result,
|
||||
result,
|
||||
*padded,
|
||||
result.numel(),
|
||||
delta_count=len(chunk),
|
||||
execution_dtype=execution_dtype,
|
||||
block_size=_BLOCK_SIZE,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _triton_dtype(dtype: torch.dtype) -> Any:
|
||||
"""Map the admitted floating execution dtype to a Triton scalar dtype."""
|
||||
|
||||
if dtype is torch.bfloat16:
|
||||
return tl.bfloat16
|
||||
if dtype is torch.float16:
|
||||
return tl.float16
|
||||
if dtype is torch.float32:
|
||||
return tl.float32
|
||||
raise TypeError(f"Ordered CUDA accumulation does not support {dtype}.")
|
||||
@@ -0,0 +1,126 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Admit complete standard-UNet regional LoRA operation surfaces."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import comfy.model_patcher
|
||||
from torch import nn
|
||||
|
||||
from ..attention_coupling.family_admission import AttentionCouplingFamilyAdmission
|
||||
from ..regional_lora_plan_adapter import RegionalLoraPlanAdaptation
|
||||
from .comfy_adapter_resolver import COMFY_REGIONAL_ADAPTER_RESOLVER
|
||||
from .execution_cache import RegionalLoraExecutionCache
|
||||
from .resolved_operation_translator import COMFY_RESOLVED_OPERATION_TRANSLATOR
|
||||
from .standard_unet_target_capabilities import (
|
||||
STANDARD_UNET_TARGET_CAPABILITY_CLASSIFIER,
|
||||
)
|
||||
from .target_binder import REGIONAL_LORA_TARGET_BINDER
|
||||
from .target_binding import (
|
||||
BoundRegionalLoraSpatialCapability,
|
||||
RegionalLoraBindingResult,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StandardUnetOperationAdmission(AttentionCouplingFamilyAdmission):
|
||||
"""Retain target bindings and exact runtime consumer-role evidence."""
|
||||
|
||||
binding: RegionalLoraBindingResult | None
|
||||
module_roles: dict[str, BoundRegionalLoraSpatialCapability]
|
||||
cache: RegionalLoraExecutionCache | None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Require either an empty admission or a complete executable surface."""
|
||||
|
||||
AttentionCouplingFamilyAdmission.__post_init__(self)
|
||||
if not self.adaptation.plan.adapters:
|
||||
if self.binding is not None or self.module_roles or self.cache is not None:
|
||||
raise ValueError("Empty standard admission cannot retain operations.")
|
||||
return
|
||||
if (
|
||||
not isinstance(self.binding, RegionalLoraBindingResult)
|
||||
or not self.binding.admissible
|
||||
or not self.binding.entries
|
||||
):
|
||||
raise ValueError("Standard admission requires complete target binding.")
|
||||
if not self.module_roles or not isinstance(
|
||||
self.cache,
|
||||
RegionalLoraExecutionCache,
|
||||
):
|
||||
raise ValueError("Standard admission requires roles and execution cache.")
|
||||
|
||||
|
||||
class StandardUnetOperationPreparation:
|
||||
"""Resolve, translate, bind, and classify regional LoRA operations."""
|
||||
|
||||
def admit(
|
||||
self,
|
||||
model: object,
|
||||
adaptation: RegionalLoraPlanAdaptation,
|
||||
) -> StandardUnetOperationAdmission:
|
||||
"""Return complete immutable evidence before installing call-scoped work."""
|
||||
|
||||
if not isinstance(adaptation, RegionalLoraPlanAdaptation):
|
||||
raise TypeError("Standard UNet operation admission requires adaptation.")
|
||||
if not adaptation.plan.adapters:
|
||||
return StandardUnetOperationAdmission(adaptation, None, {}, None)
|
||||
if not isinstance(model, comfy.model_patcher.ModelPatcher):
|
||||
raise TypeError("Standard UNet operation admission requires a MODEL.")
|
||||
graph_root = model.model
|
||||
if not isinstance(graph_root, nn.Module):
|
||||
raise TypeError("Standard UNet MODEL graph must be an nn.Module.")
|
||||
capabilities = STANDARD_UNET_TARGET_CAPABILITY_CLASSIFIER.classify(graph_root)
|
||||
resolution = COMFY_REGIONAL_ADAPTER_RESOLVER.resolve(
|
||||
adaptation,
|
||||
model=model,
|
||||
)
|
||||
operations = COMFY_RESOLVED_OPERATION_TRANSLATOR.translate(resolution)
|
||||
binding = REGIONAL_LORA_TARGET_BINDER.bind(
|
||||
source=model,
|
||||
candidate=model,
|
||||
resolution=resolution,
|
||||
operations=operations,
|
||||
linear_spatial_capabilities=capabilities.linear_roles,
|
||||
)
|
||||
if not binding.admissible:
|
||||
messages = tuple(issue.message for issue in binding.issues)
|
||||
raise ValueError(
|
||||
f"Standard UNet regional LoRA target admission failed: {messages!r}."
|
||||
)
|
||||
unavailable = tuple(
|
||||
entry.descriptor.target.parameter_path
|
||||
for entry in binding.entries
|
||||
if entry.spatial_capability
|
||||
in (
|
||||
BoundRegionalLoraSpatialCapability.GLOBAL_ONLY,
|
||||
BoundRegionalLoraSpatialCapability.UNSUPPORTED,
|
||||
)
|
||||
)
|
||||
if unavailable:
|
||||
raise ValueError(
|
||||
"Standard UNet regional LoRA targets lack executable consumer roles: "
|
||||
f"{unavailable!r}."
|
||||
)
|
||||
module_roles: dict[str, BoundRegionalLoraSpatialCapability] = {}
|
||||
for entry in binding.entries:
|
||||
path = entry.descriptor.target.model_target
|
||||
role = entry.spatial_capability
|
||||
previous = module_roles.setdefault(path, role)
|
||||
if previous is not role:
|
||||
raise ValueError(
|
||||
f"Standard UNet operation {path!r} has conflicting roles."
|
||||
)
|
||||
return StandardUnetOperationAdmission(
|
||||
adaptation,
|
||||
binding,
|
||||
module_roles,
|
||||
RegionalLoraExecutionCache(),
|
||||
)
|
||||
|
||||
|
||||
STANDARD_UNET_OPERATION_PREPARATION = StandardUnetOperationPreparation()
|
||||
@@ -0,0 +1,333 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Resolve spatial regional LoRA operations within one standard-UNet call."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator, Mapping
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from ...domain.regional_activation_geometry import (
|
||||
RegionalActivationGeometry,
|
||||
RegionalActivationLayout,
|
||||
RegionalTemporalOwnership,
|
||||
)
|
||||
from ...domain.regional_attention_batch import BatchedRegionalAttentionContexts
|
||||
from ...domain.regional_lora_plan import RegionalLoraPlan
|
||||
from ...domain.regional_mask_bank import RegionalMaskBank
|
||||
from ...domain.spatial_views import SpatialBatchLayout
|
||||
from ...masking.regional_activation_mask_projection import (
|
||||
REGIONAL_ACTIVATION_MASK_PROJECTOR,
|
||||
)
|
||||
from ...masking.regional_mask_projection import (
|
||||
RegionalMaskForm,
|
||||
RegionalMaskProjectionMode,
|
||||
)
|
||||
from ..attention_coupling.unet_attn2_execution import UnetAttn2Execution
|
||||
from ..spatial_model_arguments import (
|
||||
SIMPLE_SYRUP_TRANSFORMER_NAMESPACE,
|
||||
SPATIAL_BATCH_LAYOUT_KEY,
|
||||
)
|
||||
from .activation_batch_alignment import (
|
||||
REGIONAL_ACTIVATION_BATCH_ALIGNMENT_RESOLVER,
|
||||
)
|
||||
from .convolution_execution_plan import RegionalConvolutionExecutionPlan
|
||||
from .convolution_rank_geometry import REGIONAL_CONVOLUTION_RANK_GEOMETRY_RESOLVER
|
||||
from .linear_execution_plan import RegionalLinearExecutionPlan
|
||||
from .operation_call_scope import RegionalOperationCallScope
|
||||
from .operation_invocation import (
|
||||
REGIONAL_OPERATION_INVOCATION_CONTEXT,
|
||||
RegionalOperationExecutionPlan,
|
||||
RegionalOperationInvocation,
|
||||
RegionalOperationInvocationContext,
|
||||
)
|
||||
from .operation_mask_resolution import REGIONAL_OPERATION_MASK_RESOLVER
|
||||
from .standard_unet_lora_schedule import StandardUnetLoraSchedule
|
||||
from .standard_unet_packed_operation_masks import (
|
||||
STANDARD_UNET_PACKED_OPERATION_MASK_RESOLVER,
|
||||
)
|
||||
from .target_binding import BoundRegionalLoraSpatialCapability
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _ActiveStandardUnetOperationCall:
|
||||
"""Retain call authorities and optional compact attn2 execution state."""
|
||||
|
||||
contexts: BatchedRegionalAttentionContexts
|
||||
transformer_options: dict[str, object]
|
||||
schedule_strengths: tuple[float, ...]
|
||||
packed_execution: UnetAttn2Execution | None = None
|
||||
|
||||
|
||||
class StandardUnetRegionalOperationSession:
|
||||
"""Own one shared UNet trajectory with spatial regional LoRA deltas."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
plan: RegionalLoraPlan,
|
||||
mask_bank: RegionalMaskBank,
|
||||
module_roles: Mapping[str, BoundRegionalLoraSpatialCapability],
|
||||
call_scope: RegionalOperationCallScope,
|
||||
*,
|
||||
invocation_context: RegionalOperationInvocationContext = (
|
||||
REGIONAL_OPERATION_INVOCATION_CONTEXT
|
||||
),
|
||||
) -> None:
|
||||
"""Retain immutable composition, mask, role, and operation authorities."""
|
||||
|
||||
if not isinstance(plan, RegionalLoraPlan) or not plan.adapters:
|
||||
raise ValueError("Standard UNet operation session requires adapters.")
|
||||
if not isinstance(mask_bank, RegionalMaskBank):
|
||||
raise TypeError("Standard UNet operation session requires a mask bank.")
|
||||
if not isinstance(module_roles, Mapping) or not module_roles:
|
||||
raise ValueError("Standard UNet operation session requires module roles.")
|
||||
roles = dict(module_roles)
|
||||
if any(not isinstance(path, str) or not path for path in roles):
|
||||
raise ValueError("Standard UNet operation paths must be nonempty.")
|
||||
supported = (
|
||||
BoundRegionalLoraSpatialCapability.SPATIAL_TOKENS,
|
||||
BoundRegionalLoraSpatialCapability.PACKED_IMAGE_TOKENS,
|
||||
BoundRegionalLoraSpatialCapability.PACKED_CONTEXT_TOKENS,
|
||||
BoundRegionalLoraSpatialCapability.DIRECT,
|
||||
)
|
||||
if any(role not in supported for role in roles.values()):
|
||||
raise ValueError("Standard UNet operation role is unsupported.")
|
||||
if not isinstance(call_scope, RegionalOperationCallScope):
|
||||
raise TypeError("Standard UNet operation session requires a call scope.")
|
||||
if not isinstance(invocation_context, RegionalOperationInvocationContext):
|
||||
raise TypeError(
|
||||
"Standard UNet operation session requires invocation context."
|
||||
)
|
||||
self._mask_bank = mask_bank
|
||||
self._module_roles = roles
|
||||
self._call_scope = call_scope
|
||||
self._invocation_context = invocation_context
|
||||
self._schedule = StandardUnetLoraSchedule(plan)
|
||||
self._active: ContextVar[_ActiveStandardUnetOperationCall | None] = ContextVar(
|
||||
"simple_syrup_standard_unet_regional_operation_call",
|
||||
default=None,
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def activate(
|
||||
self,
|
||||
contexts: BatchedRegionalAttentionContexts,
|
||||
transformer_options: dict[str, object],
|
||||
) -> Iterator[None]:
|
||||
"""Publish operation masks and install wrappers for one model call."""
|
||||
|
||||
if not isinstance(contexts, BatchedRegionalAttentionContexts):
|
||||
raise TypeError("Standard UNet operation call requires contexts.")
|
||||
if not isinstance(transformer_options, dict):
|
||||
raise TypeError("Standard UNet operation call requires options.")
|
||||
active = _ActiveStandardUnetOperationCall(
|
||||
contexts,
|
||||
transformer_options,
|
||||
self._schedule.resolve(transformer_options),
|
||||
)
|
||||
token = self._active.set(active)
|
||||
try:
|
||||
with (
|
||||
self._invocation_context.activate(self),
|
||||
self._call_scope.activate(),
|
||||
):
|
||||
yield
|
||||
finally:
|
||||
active.packed_execution = None
|
||||
self._active.reset(token)
|
||||
|
||||
def begin_packed(self, execution: UnetAttn2Execution) -> None:
|
||||
"""Publish compact attn2 execution until its paired output callback."""
|
||||
|
||||
active = self._require_active()
|
||||
if active.packed_execution is not None:
|
||||
raise ValueError("Standard UNet operation call already has packed state.")
|
||||
if not isinstance(execution, UnetAttn2Execution):
|
||||
raise TypeError("Standard UNet packed state requires attn2 execution.")
|
||||
active.packed_execution = execution
|
||||
|
||||
def end_packed(self, execution: UnetAttn2Execution) -> None:
|
||||
"""Clear only the compact execution opened by the input callback."""
|
||||
|
||||
active = self._require_active()
|
||||
if active.packed_execution is not execution:
|
||||
raise ValueError("Standard UNet packed output does not match input state.")
|
||||
active.packed_execution = None
|
||||
|
||||
def resolve(
|
||||
self,
|
||||
module_path: str,
|
||||
plan: RegionalOperationExecutionPlan,
|
||||
inputs: torch.Tensor,
|
||||
) -> RegionalOperationInvocation | None:
|
||||
"""Resolve one installed operation from its declared consumer role."""
|
||||
|
||||
active = self._require_active()
|
||||
role = self._module_roles.get(module_path)
|
||||
if role is None:
|
||||
return None
|
||||
strengths = tuple(
|
||||
active.schedule_strengths[use.composition_index] for use in plan.uses
|
||||
)
|
||||
if role is BoundRegionalLoraSpatialCapability.PACKED_IMAGE_TOKENS:
|
||||
execution = self._require_packed(active)
|
||||
if not isinstance(plan, RegionalLinearExecutionPlan):
|
||||
raise TypeError("Packed image role requires a Linear plan.")
|
||||
masks = STANDARD_UNET_PACKED_OPERATION_MASK_RESOLVER.resolve_image_tokens(
|
||||
execution,
|
||||
uses=plan.uses,
|
||||
inputs=inputs,
|
||||
)
|
||||
elif role is BoundRegionalLoraSpatialCapability.PACKED_CONTEXT_TOKENS:
|
||||
execution = self._require_packed(active)
|
||||
if not isinstance(plan, RegionalLinearExecutionPlan):
|
||||
raise TypeError("Packed context role requires a Linear plan.")
|
||||
masks = STANDARD_UNET_PACKED_OPERATION_MASK_RESOLVER.resolve_context_tokens(
|
||||
execution,
|
||||
uses=plan.uses,
|
||||
inputs=inputs,
|
||||
)
|
||||
else:
|
||||
if active.packed_execution is not None:
|
||||
raise ValueError("Ordinary regional operation ran inside packed attn2.")
|
||||
geometry = self._ordinary_geometry(
|
||||
role,
|
||||
plan=plan,
|
||||
inputs=inputs,
|
||||
active=active,
|
||||
)
|
||||
spatial = REGIONAL_ACTIVATION_MASK_PROJECTOR.project(
|
||||
bank=self._mask_bank,
|
||||
geometry=geometry,
|
||||
form=RegionalMaskForm.CONDITIONING,
|
||||
mode=RegionalMaskProjectionMode.CONTINUOUS_COVERAGE,
|
||||
device=inputs.device,
|
||||
dtype=inputs.dtype,
|
||||
)
|
||||
masks = REGIONAL_OPERATION_MASK_RESOLVER.resolve(
|
||||
spatial,
|
||||
contexts=active.contexts,
|
||||
uses=plan.uses,
|
||||
)
|
||||
return RegionalOperationInvocation(masks, strengths)
|
||||
|
||||
def clear(self, model: object, unpatch_all: bool) -> None:
|
||||
"""Release retained sampling schedule state on model detach."""
|
||||
|
||||
del model, unpatch_all
|
||||
self._schedule.clear()
|
||||
|
||||
def _ordinary_geometry(
|
||||
self,
|
||||
role: BoundRegionalLoraSpatialCapability,
|
||||
*,
|
||||
plan: RegionalOperationExecutionPlan,
|
||||
inputs: torch.Tensor,
|
||||
active: _ActiveStandardUnetOperationCall,
|
||||
) -> RegionalActivationGeometry:
|
||||
"""Resolve exact ordinary token or convolution activation geometry."""
|
||||
|
||||
layout = _spatial_layout(active.transformer_options)
|
||||
alignment = REGIONAL_ACTIVATION_BATCH_ALIGNMENT_RESOLVER.resolve(
|
||||
active.contexts,
|
||||
spatial_layout=layout,
|
||||
)
|
||||
if role is BoundRegionalLoraSpatialCapability.SPATIAL_TOKENS:
|
||||
if not isinstance(plan, RegionalLinearExecutionPlan) or inputs.ndim != 3:
|
||||
raise ValueError("Spatial-token role requires B/S/C Linear inputs.")
|
||||
activation_shape = _activation_shape(active.transformer_options)
|
||||
if int(inputs.shape[0]) != activation_shape[0] or int(inputs.shape[1]) != (
|
||||
activation_shape[2] * activation_shape[3]
|
||||
):
|
||||
raise ValueError("Spatial-token inputs must match live activation H/W.")
|
||||
return RegionalActivationGeometry(
|
||||
RegionalActivationLayout.CONSUMER_SPATIALIZED,
|
||||
tuple(inputs.shape),
|
||||
2,
|
||||
activation_shape[2],
|
||||
activation_shape[3],
|
||||
alignment,
|
||||
)
|
||||
if role is not BoundRegionalLoraSpatialCapability.DIRECT or not isinstance(
|
||||
plan,
|
||||
RegionalConvolutionExecutionPlan,
|
||||
):
|
||||
raise ValueError("Standard UNet ordinary operation role is inconsistent.")
|
||||
use = plan.uses[0]
|
||||
spatial = REGIONAL_CONVOLUTION_RANK_GEOMETRY_RESOLVER.resolve(
|
||||
tuple(int(value) for value in inputs.shape[2:]),
|
||||
use,
|
||||
)
|
||||
rank_channels = int(use.preparation.down.shape[0]) * use.parameters.groups
|
||||
layouts = {
|
||||
1: RegionalActivationLayout.DIRECT_CONVOLUTION_1D,
|
||||
2: RegionalActivationLayout.DIRECT_CONVOLUTION_2D,
|
||||
3: RegionalActivationLayout.DIRECT_CONVOLUTION_3D,
|
||||
}
|
||||
return RegionalActivationGeometry(
|
||||
layouts[use.parameters.dimension],
|
||||
(int(inputs.shape[0]), rank_channels, *spatial),
|
||||
1,
|
||||
1 if use.parameters.dimension == 1 else spatial[-2],
|
||||
spatial[-1],
|
||||
alignment,
|
||||
temporal_axis=2 if use.parameters.dimension == 3 else None,
|
||||
temporal_ownership=(
|
||||
RegionalTemporalOwnership.REPEAT_SPATIAL_MASK
|
||||
if use.parameters.dimension == 3
|
||||
else RegionalTemporalOwnership.NONE
|
||||
),
|
||||
)
|
||||
|
||||
def _require_active(self) -> _ActiveStandardUnetOperationCall:
|
||||
"""Return the current call or reject execution outside its owner."""
|
||||
|
||||
active = self._active.get()
|
||||
if active is None:
|
||||
raise RuntimeError("Standard UNet regional operation ran outside a call.")
|
||||
return active
|
||||
|
||||
@staticmethod
|
||||
def _require_packed(
|
||||
active: _ActiveStandardUnetOperationCall,
|
||||
) -> UnetAttn2Execution:
|
||||
"""Return the compact attn2 authority for the current projection."""
|
||||
|
||||
if active.packed_execution is None:
|
||||
raise RuntimeError("Packed regional operation ran outside attn2 scope.")
|
||||
return active.packed_execution
|
||||
|
||||
|
||||
def _activation_shape(options: dict[str, object]) -> tuple[int, int, int, int]:
|
||||
"""Narrow Comfy's live spatial-transformer BCHW metadata."""
|
||||
|
||||
value = options.get("activations_shape")
|
||||
if not isinstance(value, list | tuple) or len(value) != 4:
|
||||
raise TypeError("Standard UNet activations_shape must be a BCHW sequence.")
|
||||
shape = tuple(value)
|
||||
if any(
|
||||
isinstance(item, bool) or not isinstance(item, int) or item < 1
|
||||
for item in shape
|
||||
):
|
||||
raise ValueError("Standard UNet activation dimensions must be positive.")
|
||||
return shape[0], shape[1], shape[2], shape[3]
|
||||
|
||||
|
||||
def _spatial_layout(options: dict[str, object]) -> SpatialBatchLayout | None:
|
||||
"""Return the optional authoritative full, tiled, or Contextual layout."""
|
||||
|
||||
namespace = options.get(SIMPLE_SYRUP_TRANSFORMER_NAMESPACE)
|
||||
if namespace is None:
|
||||
return None
|
||||
if not isinstance(namespace, dict):
|
||||
raise TypeError("Standard UNet SimpleSyrup namespace must be a dictionary.")
|
||||
layout = namespace.get(SPATIAL_BATCH_LAYOUT_KEY)
|
||||
if layout is not None and not isinstance(layout, SpatialBatchLayout):
|
||||
raise TypeError("Standard UNet spatial layout has an invalid type.")
|
||||
return layout
|
||||
@@ -0,0 +1,147 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Resolve regional operation masks for compact standard-UNet attn2 rows."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import torch
|
||||
|
||||
from ...domain.regional_activation_geometry import (
|
||||
RegionalActivationBatchAlignment,
|
||||
RegionalActivationGeometry,
|
||||
RegionalActivationLayout,
|
||||
)
|
||||
from ..attention_coupling.unet_attn2_execution import UnetAttn2Execution
|
||||
from .operation_mask_resolution import (
|
||||
REGIONAL_OPERATION_BRANCH_GATE_RESOLVER,
|
||||
RegionalOperationMaskBatch,
|
||||
RegionalOperationMaskUse,
|
||||
)
|
||||
|
||||
|
||||
class StandardUnetPackedOperationMaskResolver:
|
||||
"""Map regional uses onto exact compact attn2 image or context rows."""
|
||||
|
||||
def resolve_image_tokens(
|
||||
self,
|
||||
execution: UnetAttn2Execution,
|
||||
*,
|
||||
uses: Sequence[RegionalOperationMaskUse],
|
||||
inputs: torch.Tensor,
|
||||
) -> RegionalOperationMaskBatch:
|
||||
"""Return query-grid masks for packed query and output projections."""
|
||||
|
||||
self._validate(execution, uses=uses, inputs=inputs)
|
||||
if int(inputs.shape[1]) != execution.query_height * execution.query_width:
|
||||
raise ValueError("Packed image tokens must match attn2 query H/W.")
|
||||
use_masks = tuple(
|
||||
self._packed_use_mask(execution, use=use, inputs=inputs, spatial=True)
|
||||
for use in uses
|
||||
)
|
||||
geometry = RegionalActivationGeometry(
|
||||
RegionalActivationLayout.CONSUMER_SPATIALIZED,
|
||||
tuple(inputs.shape),
|
||||
2,
|
||||
execution.query_height,
|
||||
execution.query_width,
|
||||
RegionalActivationBatchAlignment(int(inputs.shape[0]), 1),
|
||||
)
|
||||
return RegionalOperationMaskBatch(
|
||||
torch.stack(use_masks),
|
||||
geometry,
|
||||
tuple(use.composition_index for use in uses),
|
||||
)
|
||||
|
||||
def resolve_context_tokens(
|
||||
self,
|
||||
execution: UnetAttn2Execution,
|
||||
*,
|
||||
uses: Sequence[RegionalOperationMaskUse],
|
||||
inputs: torch.Tensor,
|
||||
) -> RegionalOperationMaskBatch:
|
||||
"""Return branch gates broadcast over untouched context tokens."""
|
||||
|
||||
self._validate(execution, uses=uses, inputs=inputs)
|
||||
use_masks = tuple(
|
||||
self._packed_use_mask(execution, use=use, inputs=inputs, spatial=False)
|
||||
for use in uses
|
||||
)
|
||||
geometry = RegionalActivationGeometry(
|
||||
RegionalActivationLayout.BRANCH_TOKENS,
|
||||
tuple(inputs.shape),
|
||||
2,
|
||||
1,
|
||||
int(inputs.shape[1]),
|
||||
RegionalActivationBatchAlignment(int(inputs.shape[0]), 1),
|
||||
)
|
||||
return RegionalOperationMaskBatch(
|
||||
torch.stack(use_masks),
|
||||
geometry,
|
||||
tuple(use.composition_index for use in uses),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _validate(
|
||||
execution: object,
|
||||
*,
|
||||
uses: Sequence[RegionalOperationMaskUse],
|
||||
inputs: object,
|
||||
) -> None:
|
||||
"""Require one exact packed B/S/C activation and ordered use sequence."""
|
||||
|
||||
if not isinstance(execution, UnetAttn2Execution):
|
||||
raise TypeError("Packed operation masks require an attn2 execution.")
|
||||
if not isinstance(inputs, torch.Tensor) or inputs.ndim != 3:
|
||||
raise ValueError("Packed operation inputs must use B/S/C layout.")
|
||||
if int(inputs.shape[0]) != execution.branches.packed_batch_size:
|
||||
raise ValueError("Packed operation batch must match attn2 branches.")
|
||||
if not isinstance(uses, Sequence) or not uses:
|
||||
raise ValueError("Packed operation masks require target uses.")
|
||||
composition = tuple(use.composition_index for use in uses)
|
||||
if composition != tuple(sorted(composition)):
|
||||
raise ValueError("Packed operation uses must follow composition order.")
|
||||
|
||||
@staticmethod
|
||||
def _packed_use_mask(
|
||||
execution: UnetAttn2Execution,
|
||||
*,
|
||||
use: RegionalOperationMaskUse,
|
||||
inputs: torch.Tensor,
|
||||
spatial: bool,
|
||||
) -> torch.Tensor:
|
||||
"""Return one use mask in exact compact branch-segment order."""
|
||||
|
||||
if use.region_index >= int(execution.query_masks.shape[0]):
|
||||
raise ValueError("Packed operation use references an unavailable region.")
|
||||
source_gate = REGIONAL_OPERATION_BRANCH_GATE_RESOLVER.resolve(
|
||||
execution.contexts,
|
||||
branch=use.branch,
|
||||
authority=inputs,
|
||||
)
|
||||
segments: list[torch.Tensor] = []
|
||||
for segment in execution.branches.segments:
|
||||
count = int(segment.source_indices.shape[0])
|
||||
if segment.key.region_index != use.region_index:
|
||||
segments.append(inputs.new_zeros((count, int(inputs.shape[1]), 1)))
|
||||
continue
|
||||
gate = source_gate.index_select(0, segment.source_indices).reshape(
|
||||
count,
|
||||
1,
|
||||
1,
|
||||
)
|
||||
if spatial:
|
||||
mask = execution.query_masks[use.region_index].index_select(
|
||||
0,
|
||||
segment.source_indices,
|
||||
)
|
||||
segments.append(mask.unsqueeze(-1) * gate)
|
||||
else:
|
||||
segments.append(gate.expand(-1, int(inputs.shape[1]), -1))
|
||||
return torch.cat(tuple(segments))
|
||||
|
||||
|
||||
STANDARD_UNET_PACKED_OPERATION_MASK_RESOLVER = StandardUnetPackedOperationMaskResolver()
|
||||
@@ -10,6 +10,7 @@ from ..attention_coupling.unet_attn2_execution_resolver import (
|
||||
UnetAttn2ExecutionResolver,
|
||||
)
|
||||
from ..attention_coupling.unet_attn2_patch import UnetAttn2PatchPair
|
||||
from ..ppm_negpip_interop import PpmNegpipInterop
|
||||
|
||||
_INPUT_PATCH_KEY = "attn2_patch"
|
||||
_OUTPUT_PATCH_KEY = "attn2_output_patch"
|
||||
@@ -18,12 +19,20 @@ _OUTPUT_PATCH_KEY = "attn2_output_patch"
|
||||
class StandardUnetVariantBaseAttention:
|
||||
"""Install Attention Couple only on graph-local unpatched base execution."""
|
||||
|
||||
def __init__(self, resolver: UnetAttn2ExecutionResolver) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
resolver: UnetAttn2ExecutionResolver,
|
||||
*,
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> None:
|
||||
"""Retain one paired callback authority for the active request state."""
|
||||
|
||||
if not isinstance(resolver, UnetAttn2ExecutionResolver):
|
||||
raise TypeError("Standard UNet base attention requires a resolver.")
|
||||
self._patches = UnetAttn2PatchPair(resolver)
|
||||
if negpip is not None and not isinstance(negpip, PpmNegpipInterop):
|
||||
raise TypeError("Standard UNet base attention NegPiP state is invalid.")
|
||||
self._negpip = negpip
|
||||
|
||||
def prepare(self, source: dict[str, object]) -> dict[str, object]:
|
||||
"""Return isolated transformer options with one collision-free pair."""
|
||||
@@ -40,10 +49,22 @@ class StandardUnetVariantBaseAttention:
|
||||
patches = source_patches.copy()
|
||||
else:
|
||||
raise TypeError("Standard UNet transformer patches must be a dictionary.")
|
||||
for key in (_INPUT_PATCH_KEY, _OUTPUT_PATCH_KEY):
|
||||
if key in patches:
|
||||
raise ValueError(f"Standard UNet base graph already contains {key!r}.")
|
||||
patches[_INPUT_PATCH_KEY] = [self._patches.input_patch]
|
||||
expected_input = [] if self._negpip is None else [self._negpip.attention_patch]
|
||||
if (
|
||||
self._negpip is None
|
||||
and _INPUT_PATCH_KEY in patches
|
||||
or self._negpip is not None
|
||||
and patches.get(_INPUT_PATCH_KEY) != expected_input
|
||||
):
|
||||
raise ValueError(
|
||||
"Standard UNet base graph already contains an unadmitted attn2 "
|
||||
"input patch."
|
||||
)
|
||||
if _OUTPUT_PATCH_KEY in patches:
|
||||
raise ValueError(
|
||||
"Standard UNet base graph already contains 'attn2_output_patch'."
|
||||
)
|
||||
patches[_INPUT_PATCH_KEY] = [self._patches.input_patch, *expected_input]
|
||||
patches[_OUTPUT_PATCH_KEY] = [self._patches.output_patch]
|
||||
prepared["patches"] = patches
|
||||
return prepared
|
||||
|
||||
@@ -22,6 +22,7 @@ from ..model_patcher_mutations import (
|
||||
ModelKeyedCallbackMutation,
|
||||
ModelKeyedWrapperMutation,
|
||||
)
|
||||
from ..ppm_negpip_interop import PpmNegpipInterop
|
||||
from .standard_unet_cold_sampling import (
|
||||
StandardUnetColdSamplingDiagnosticsMutation,
|
||||
)
|
||||
@@ -48,6 +49,7 @@ class StandardUnetVariantRuntimeMutation:
|
||||
admission: StandardUnetNativeLoraAdmission
|
||||
attention_phase: StandardUnetAttentionPhaseSession
|
||||
template: StandardUnetVariantTemplate
|
||||
negpip: PpmNegpipInterop | None = None
|
||||
|
||||
def apply(self, model: object) -> None:
|
||||
"""Build persistent variants before installing the private root clone."""
|
||||
@@ -69,7 +71,8 @@ class StandardUnetVariantRuntimeMutation:
|
||||
),
|
||||
attention_phase=self.attention_phase,
|
||||
base_attention=StandardUnetVariantBaseAttention(
|
||||
StandardUnetAttn2ExecutionResolver(self.state)
|
||||
StandardUnetAttn2ExecutionResolver(self.state),
|
||||
negpip=self.negpip,
|
||||
),
|
||||
)
|
||||
execution.prime()
|
||||
|
||||
@@ -148,8 +148,10 @@ class StandardUnetVariantTemplate:
|
||||
)
|
||||
if not isinstance(request, ModelPatcher) or request.is_dynamic():
|
||||
raise TypeError("Comfy did not bind a static standard-UNet request.")
|
||||
if request.parent is not source:
|
||||
raise RuntimeError("Static standard-UNet request lost source lineage.")
|
||||
if request.parent is not self.model:
|
||||
raise RuntimeError(
|
||||
"Static standard-UNet request lost its template fallback boundary."
|
||||
)
|
||||
if "diffusion_model" in request.object_patches_backup:
|
||||
ModelSharedObjectPatchMutation(
|
||||
"diffusion_model",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Resolve optional Triton backends without importing them on Torch paths."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from importlib import import_module
|
||||
from threading import Lock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TritonRuntimeResolver:
|
||||
"""Own thread-safe lazy backend imports and optional-package fallback."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
import_module: Callable[[str], object] = import_module,
|
||||
) -> None:
|
||||
"""Retain an injectable importer and empty process-lifetime cache."""
|
||||
|
||||
if not callable(import_module):
|
||||
raise TypeError("Triton runtime importer must be callable.")
|
||||
self._import_module = import_module
|
||||
self._lock = Lock()
|
||||
self._backends: dict[str, object | None] = {}
|
||||
self._missing_warning_emitted = False
|
||||
|
||||
def resolve(self, backend_module: str) -> object | None:
|
||||
"""Return one cached backend or None only when Triton is absent."""
|
||||
|
||||
if not isinstance(backend_module, str) or not backend_module:
|
||||
raise ValueError("Triton backend module must be a non-empty string.")
|
||||
with self._lock:
|
||||
if backend_module in self._backends:
|
||||
return self._backends[backend_module]
|
||||
try:
|
||||
backend = self._import_module(backend_module)
|
||||
except ModuleNotFoundError as error:
|
||||
if error.name != "triton" and not (
|
||||
isinstance(error.name, str) and error.name.startswith("triton.")
|
||||
):
|
||||
raise RuntimeError(
|
||||
f"Triton backend {backend_module!r} failed to initialize."
|
||||
) from error
|
||||
backend = None
|
||||
if not self._missing_warning_emitted:
|
||||
LOGGER.warning(
|
||||
"Triton acceleration is unavailable; using the Torch "
|
||||
"execution path",
|
||||
extra={
|
||||
"backend_module": backend_module,
|
||||
"missing_dependency": error.name,
|
||||
},
|
||||
)
|
||||
self._missing_warning_emitted = True
|
||||
except Exception as error:
|
||||
raise RuntimeError(
|
||||
f"Triton backend {backend_module!r} failed to initialize."
|
||||
) from error
|
||||
self._backends[backend_module] = backend
|
||||
return backend
|
||||
|
||||
|
||||
TRITON_RUNTIME_RESOLVER = TritonRuntimeResolver()
|
||||
@@ -68,8 +68,7 @@ class RegionalLoraConditioningSourceCollector:
|
||||
|
||||
if not isinstance(plan, RawRegionalAttentionPlan):
|
||||
raise TypeError("Regional LoRA source collection requires a plan.")
|
||||
self._require_unhooked_base("positive", plan.positive)
|
||||
self._require_unhooked_base("negative", plan.negative)
|
||||
self._require_compatible_base_hooks(plan)
|
||||
return (
|
||||
*self._branch_sources(plan.positive, branch=RegionalLoraBranch.POSITIVE),
|
||||
*self._branch_sources(plan.negative, branch=RegionalLoraBranch.NEGATIVE),
|
||||
@@ -112,31 +111,49 @@ class RegionalLoraConditioningSourceCollector:
|
||||
)
|
||||
return tuple(sources)
|
||||
|
||||
def _require_unhooked_base(
|
||||
def _require_compatible_base_hooks(
|
||||
self,
|
||||
plan: RawRegionalAttentionPlan,
|
||||
) -> None:
|
||||
"""Require one shared global model-hook schedule across CFG branches."""
|
||||
|
||||
positive = self._base_hook_signature("positive", plan.positive)
|
||||
negative = self._base_hook_signature("negative", plan.negative)
|
||||
if positive != negative:
|
||||
raise ValueError(
|
||||
"Attention Coupling global model hooks must match across positive "
|
||||
"and negative conditioning. Encode both branches through the same "
|
||||
"Prompt Control global segment."
|
||||
)
|
||||
|
||||
def _base_hook_signature(
|
||||
self,
|
||||
branch_name: str,
|
||||
branch: RawRegionalAttentionBranch,
|
||||
) -> None:
|
||||
"""Require only model-active global LoRAs to arrive on the input MODEL."""
|
||||
) -> tuple[tuple[object, ...], ...]:
|
||||
"""Return one uniform global model-hook signature for a CFG branch."""
|
||||
|
||||
groups = conditioning_hook_groups(branch.base_conditioning)
|
||||
model_hook_count = sum(
|
||||
len(
|
||||
signatures = tuple(
|
||||
self._group_signature(
|
||||
self._model_hook_selection(
|
||||
group,
|
||||
source_label=(
|
||||
f"Attention Coupling {branch_name} global conditioning"
|
||||
),
|
||||
).model_hooks
|
||||
)
|
||||
)
|
||||
for group in groups
|
||||
for group in conditioning_hook_groups(branch.base_conditioning)
|
||||
)
|
||||
if model_hook_count:
|
||||
if not signatures:
|
||||
return ()
|
||||
authority = signatures[0]
|
||||
if any(signature != authority for signature in signatures[1:]):
|
||||
raise ValueError(
|
||||
f"Attention Coupling {branch_name} global conditioning contains "
|
||||
"model hooks. Apply global LoRAs to the input MODEL; reserve "
|
||||
"conditioning hooks for masked regional entries."
|
||||
f"Attention Coupling {branch_name} global conditioning uses "
|
||||
"different model HookGroups across text schedule entries. Keep "
|
||||
"model LoRA scheduling on one shared WeightHook schedule."
|
||||
)
|
||||
return authority
|
||||
|
||||
def _uniform_hooks(
|
||||
self,
|
||||
|
||||
@@ -20,11 +20,13 @@ from ..domain.regional_model_capabilities import (
|
||||
RegionalModelFamily,
|
||||
RegionalPatchConflict,
|
||||
)
|
||||
from .ppm_negpip_interop import (
|
||||
PPM_NEGPIP_INTEROP_VALIDATOR,
|
||||
PpmNegpipInterop,
|
||||
)
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_NEGPIP_MODEL_OPTION = "ppm_negpip"
|
||||
_NEGPIP_ANIMA_WRAPPER_KEY = "ppm_negpip_anima"
|
||||
_EASYCACHE_OPTION = "easycache"
|
||||
_ATTN2_PATCH_CONFLICTS = {
|
||||
RegionalPatchConflict.ATTN2_INPUT_PATCH: "attn2_patch",
|
||||
@@ -49,6 +51,7 @@ class RegionalModelPatchInteropReport:
|
||||
|
||||
model_family: RegionalModelFamily
|
||||
preserved_modifiers: tuple[RegionalPreservedModelModifier, ...]
|
||||
negpip: PpmNegpipInterop | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Require a typed family and canonical unique modifier order."""
|
||||
@@ -62,6 +65,8 @@ class RegionalModelPatchInteropReport:
|
||||
raise TypeError("Regional interop report modifiers have invalid types.")
|
||||
if len(set(self.preserved_modifiers)) != len(self.preserved_modifiers):
|
||||
raise ValueError("Regional interop report modifiers must be unique.")
|
||||
if self.negpip is not None and not isinstance(self.negpip, PpmNegpipInterop):
|
||||
raise TypeError("Regional interop report NegPiP state has an invalid type.")
|
||||
|
||||
@property
|
||||
def cache_modifier(self) -> RegionalPreservedModelModifier | None:
|
||||
@@ -99,12 +104,22 @@ class RegionalModelPatchInteropValidator:
|
||||
model_weight_patches = _require_dictionary_attribute(model, "patches")
|
||||
patches = _require_optional_patch_state(transformer_options)
|
||||
|
||||
self._reject_negpip(model_options, wrappers)
|
||||
negpip = PPM_NEGPIP_INTEROP_VALIDATOR.validate(
|
||||
capabilities.model_family,
|
||||
model_options=model_options,
|
||||
wrappers=wrappers,
|
||||
object_patches=object_patches,
|
||||
transformer_patches=patches,
|
||||
)
|
||||
cache_modifier = self._validate_cache_state(
|
||||
transformer_options,
|
||||
wrappers,
|
||||
)
|
||||
self._reject_attention_collisions(patches, capabilities)
|
||||
self._reject_attention_collisions(
|
||||
patches,
|
||||
capabilities,
|
||||
admitted_negpip=negpip,
|
||||
)
|
||||
|
||||
modifiers: list[RegionalPreservedModelModifier] = []
|
||||
model_wrapper = model_options.get("model_function_wrapper")
|
||||
@@ -135,6 +150,7 @@ class RegionalModelPatchInteropValidator:
|
||||
report = RegionalModelPatchInteropReport(
|
||||
capabilities.model_family,
|
||||
tuple(modifiers),
|
||||
negpip,
|
||||
)
|
||||
LOGGER.info(
|
||||
"Regional MODEL patch interoperability admitted",
|
||||
@@ -188,30 +204,6 @@ class RegionalModelPatchInteropValidator:
|
||||
},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _reject_negpip(
|
||||
model_options: dict[object, object],
|
||||
wrappers: dict[str, dict[object, list[object]]],
|
||||
) -> None:
|
||||
"""Reject installed NegPiP before its mask can enter branch packing."""
|
||||
|
||||
marker = model_options.get(_NEGPIP_MODEL_OPTION, False)
|
||||
if not isinstance(marker, bool):
|
||||
raise TypeError("MODEL ppm_negpip marker must be boolean.")
|
||||
negpip_wrapper = bool(
|
||||
wrappers.get(WrappersMP.DIFFUSION_MODEL, {}).get(
|
||||
_NEGPIP_ANIMA_WRAPPER_KEY,
|
||||
(),
|
||||
)
|
||||
)
|
||||
if marker or negpip_wrapper:
|
||||
raise ValueError(
|
||||
"Attention Coupling does not support NegPiP because its attention "
|
||||
"mask is aligned to the ordinary conditioning batch rather than "
|
||||
"SimpleSyrup's regional branch batch. Remove CLIP NegPip before "
|
||||
"the Attention Coupling sampler."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _validate_cache_state(
|
||||
transformer_options: dict[object, object],
|
||||
@@ -260,6 +252,8 @@ class RegionalModelPatchInteropValidator:
|
||||
def _reject_attention_collisions(
|
||||
patches: dict[str, list[object]],
|
||||
capabilities: RegionalModelCapabilities,
|
||||
*,
|
||||
admitted_negpip: PpmNegpipInterop | None,
|
||||
) -> None:
|
||||
"""Reject every populated attention surface owned by the backend."""
|
||||
|
||||
@@ -268,6 +262,11 @@ class RegionalModelPatchInteropValidator:
|
||||
for conflict, patch_name in _ATTN2_PATCH_CONFLICTS.items()
|
||||
if conflict in capabilities.known_patch_conflicts
|
||||
and patches.get(patch_name)
|
||||
and not (
|
||||
patch_name == "attn2_patch"
|
||||
and admitted_negpip is not None
|
||||
and patches[patch_name] == [admitted_negpip.attention_patch]
|
||||
)
|
||||
)
|
||||
if conflicts:
|
||||
raise ValueError(
|
||||
|
||||
@@ -34,8 +34,9 @@ def make_tiled_model_args(
|
||||
input_batch_size: int,
|
||||
latent_height: int,
|
||||
latent_width: int,
|
||||
project_canvas_reference_latents: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Create apply-model args for one spatial tile batch."""
|
||||
"""Create tile arguments with optional canvas-reference projection."""
|
||||
|
||||
layout = tiled_batch_layout(
|
||||
tiles=tiles,
|
||||
@@ -63,6 +64,7 @@ def make_tiled_model_args(
|
||||
conditioning=conditioning,
|
||||
layout=layout,
|
||||
view_timestep=tiled_timestep,
|
||||
project_canvas_reference_latents=project_canvas_reference_latents,
|
||||
)
|
||||
tiled_args = args.copy()
|
||||
tiled_args["input"] = tiled_x
|
||||
@@ -114,8 +116,9 @@ def make_spatial_view_model_args(
|
||||
*,
|
||||
args: dict[str, Any],
|
||||
layout: SpatialBatchLayout,
|
||||
project_canvas_reference_latents: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Create apply-model arguments for equally shaped spatial views."""
|
||||
"""Create equal-view arguments with optional canvas-reference projection."""
|
||||
|
||||
target_shape = (layout.views[0].model_height, layout.views[0].model_width)
|
||||
if any(
|
||||
@@ -149,6 +152,7 @@ def make_spatial_view_model_args(
|
||||
conditioning=conditioning,
|
||||
layout=layout,
|
||||
view_timestep=view_timestep,
|
||||
project_canvas_reference_latents=project_canvas_reference_latents,
|
||||
)
|
||||
view_args = args.copy()
|
||||
view_args["input"] = view_x
|
||||
@@ -172,14 +176,18 @@ def spatial_view_conditioning(
|
||||
conditioning: dict[str, Any],
|
||||
layout: SpatialBatchLayout,
|
||||
view_timestep: torch.Tensor,
|
||||
project_canvas_reference_latents: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Resize spatial conditioning alongside arbitrary latent views."""
|
||||
"""Project spatial conditioning and optionally canvas-aligned references."""
|
||||
|
||||
transformed: dict[str, Any] = {}
|
||||
for key, value in conditioning.items():
|
||||
if key == "transformer_options":
|
||||
continue
|
||||
if key in SPATIAL_INVARIANT_CONDITIONING_KEYS:
|
||||
if (
|
||||
key in SPATIAL_INVARIANT_CONDITIONING_KEYS
|
||||
and not project_canvas_reference_latents
|
||||
):
|
||||
transformed[key] = repeat_spatial_invariant_value(
|
||||
value,
|
||||
view_count=layout.view_count,
|
||||
|
||||
@@ -158,11 +158,18 @@ class TileBlendWeightCache:
|
||||
class TilePredictionAccumulator:
|
||||
"""Evaluate tiled model views and combine them with one selected policy."""
|
||||
|
||||
def __init__(self, plan: TiledDiffusionPlan, *, diffusion_mode: str) -> None:
|
||||
"""Bind an immutable plan to its overlap weighting policy."""
|
||||
def __init__(
|
||||
self,
|
||||
plan: TiledDiffusionPlan,
|
||||
*,
|
||||
diffusion_mode: str,
|
||||
project_canvas_reference_latents: bool = False,
|
||||
) -> None:
|
||||
"""Bind a plan to its weighting and reference-projection policies."""
|
||||
|
||||
self._plan = plan
|
||||
self._blend_weights = TileBlendWeightCache(plan, diffusion_mode)
|
||||
self._project_canvas_reference_latents = project_canvas_reference_latents
|
||||
|
||||
def predict(
|
||||
self,
|
||||
@@ -183,6 +190,9 @@ class TilePredictionAccumulator:
|
||||
input_batch_size=input_batch_size,
|
||||
latent_height=self._plan.latent_height,
|
||||
latent_width=self._plan.latent_width,
|
||||
project_canvas_reference_latents=(
|
||||
self._project_canvas_reference_latents
|
||||
),
|
||||
)
|
||||
tile_output = evaluate(tiled_args)
|
||||
for index, tile in enumerate(batch):
|
||||
|
||||
@@ -14,7 +14,14 @@ from types import ModuleType
|
||||
from typing import Any, TypeAlias, cast
|
||||
|
||||
from ..shared.logging import get_logger
|
||||
from .model_folders import SUPPORTED_MODEL_EXTENSIONS
|
||||
from .model_catalog import ULTRALYTICS_ENTRIES, ModelEntry
|
||||
from .model_choices import ModelChoiceService
|
||||
from .model_downloads import DownloadRequest, ModelDownloader, ProgressReporter
|
||||
from .model_folders import (
|
||||
SUPPORTED_MODEL_EXTENSIONS,
|
||||
expected_model_file,
|
||||
resolve_model_file,
|
||||
)
|
||||
from .model_instance_cache import ModelInstanceCache
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
@@ -52,7 +59,6 @@ class LoadedUltralyticsDetector:
|
||||
class UltralyticsModelCacheKey:
|
||||
"""Identify a loaded Ultralytics detector for process-level reuse."""
|
||||
|
||||
model_name: str
|
||||
model_path: Path
|
||||
|
||||
|
||||
@@ -68,6 +74,8 @@ class UltralyticsLoaderService:
|
||||
self,
|
||||
folder_paths_module: ModuleType | None = None,
|
||||
ultralytics_module: ModuleType | None = None,
|
||||
downloader: ModelDownloader | None = None,
|
||||
choice_service: ModelChoiceService | None = None,
|
||||
cache: (
|
||||
MutableMapping[UltralyticsModelCacheKey, LoadedUltralyticsDetector] | None
|
||||
) = None,
|
||||
@@ -76,6 +84,8 @@ class UltralyticsLoaderService:
|
||||
|
||||
self._folder_paths_module = folder_paths_module
|
||||
self._ultralytics_module = ultralytics_module
|
||||
self._downloader = downloader or ModelDownloader()
|
||||
self._choice_service = choice_service or ModelChoiceService()
|
||||
self._cache: ModelInstanceCache[
|
||||
UltralyticsModelCacheKey, LoadedUltralyticsDetector
|
||||
] = ModelInstanceCache(
|
||||
@@ -83,9 +93,39 @@ class UltralyticsLoaderService:
|
||||
)
|
||||
|
||||
def model_choices(self) -> list[str]:
|
||||
"""Return local Ultralytics model choices for ComfyUI dropdowns."""
|
||||
"""Return installed choices first, followed by downloadable catalog choices."""
|
||||
|
||||
choices = self.available_models()
|
||||
self._register_model_folders()
|
||||
curated_choices = self._choice_service.ultralytics_choices()
|
||||
catalog_choice_labels = {
|
||||
_catalog_selection(entry): entry.display_name
|
||||
for entry in ULTRALYTICS_ENTRIES
|
||||
}
|
||||
available_choices = self.available_models()
|
||||
visible_catalog_choices = set(curated_choices)
|
||||
installed_catalog_choices = [
|
||||
entry.display_name
|
||||
for entry in ULTRALYTICS_ENTRIES
|
||||
if (
|
||||
entry.display_name in visible_catalog_choices
|
||||
and _catalog_selection(entry) in available_choices
|
||||
)
|
||||
]
|
||||
installed_non_catalog_choices = [
|
||||
choice
|
||||
for choice in available_choices
|
||||
if choice not in catalog_choice_labels
|
||||
]
|
||||
downloadable_choices = [
|
||||
choice
|
||||
for choice in curated_choices
|
||||
if choice not in installed_catalog_choices
|
||||
]
|
||||
choices = (
|
||||
installed_non_catalog_choices
|
||||
+ installed_catalog_choices
|
||||
+ downloadable_choices
|
||||
)
|
||||
return choices or [NO_LOCAL_ULTRALYTICS_MODELS]
|
||||
|
||||
def available_models(self) -> list[str]:
|
||||
@@ -133,16 +173,23 @@ class UltralyticsLoaderService:
|
||||
|
||||
return sorted(choices)
|
||||
|
||||
def load(self, model_name: str) -> LoadedUltralyticsDetector:
|
||||
def load(
|
||||
self,
|
||||
model_name: str,
|
||||
progress: ProgressReporter | None = None,
|
||||
) -> LoadedUltralyticsDetector:
|
||||
"""Load one Ultralytics model and create compatibility facades."""
|
||||
|
||||
self.reject_sentinel(model_name)
|
||||
model_path = self.resolve_model_path(model_name)
|
||||
normalized_name = _normalized_model_name(model_name)
|
||||
key = UltralyticsModelCacheKey(
|
||||
model_name=normalized_name,
|
||||
model_path=model_path.resolve(),
|
||||
)
|
||||
entry = _catalog_entry_or_none(model_name)
|
||||
if entry is None:
|
||||
model_path = self.resolve_model_path(model_name)
|
||||
normalized_name = _normalized_model_name(model_name)
|
||||
else:
|
||||
model_path = self._resolve_catalog_entry(entry, progress)
|
||||
normalized_name = _catalog_selection(entry)
|
||||
|
||||
key = UltralyticsModelCacheKey(model_path=model_path.resolve())
|
||||
already_loaded = key in self._cache.entries
|
||||
loaded = self._cache.get_or_load(
|
||||
key,
|
||||
@@ -160,6 +207,40 @@ class UltralyticsLoaderService:
|
||||
)
|
||||
return loaded
|
||||
|
||||
def _resolve_catalog_entry(
|
||||
self,
|
||||
entry: ModelEntry,
|
||||
progress: ProgressReporter | None,
|
||||
) -> Path:
|
||||
"""Resolve or securely download one curated Ultralytics checkpoint."""
|
||||
|
||||
if len(entry.artifacts) != 1:
|
||||
raise RuntimeError(
|
||||
f"Ultralytics catalog entry '{entry.entry_id}' must have one artifact."
|
||||
)
|
||||
|
||||
self._register_model_folders()
|
||||
artifact = entry.artifacts[0]
|
||||
existing = resolve_model_file(
|
||||
artifact.folder_name,
|
||||
artifact.filename,
|
||||
self._folder_paths_module,
|
||||
)
|
||||
destination = existing or expected_model_file(
|
||||
artifact.folder_name, artifact.filename, self._folder_paths_module
|
||||
)
|
||||
result = self._downloader.download(
|
||||
DownloadRequest(
|
||||
source_url=artifact.source_url,
|
||||
destination_path=destination,
|
||||
expected_folder=destination.parent,
|
||||
description=artifact.description,
|
||||
expected_sha256=artifact.sha256,
|
||||
),
|
||||
progress,
|
||||
)
|
||||
return result.path
|
||||
|
||||
def _load_uncached_detector(
|
||||
self,
|
||||
model_name: str,
|
||||
@@ -227,9 +308,10 @@ class UltralyticsLoaderService:
|
||||
|
||||
if model_name == NO_LOCAL_ULTRALYTICS_MODELS:
|
||||
raise ValueError(
|
||||
"No local Ultralytics models are available. Install a model in "
|
||||
"models\\ultralytics, models\\ultralytics\\bbox, or "
|
||||
"models\\ultralytics\\segm."
|
||||
"No local Ultralytics models are available. Enable 'Show "
|
||||
"downloadable models in loader dropdowns' in SimpleSyrup settings "
|
||||
"or install a model in models\\ultralytics, "
|
||||
"models\\ultralytics\\bbox, or models\\ultralytics\\segm."
|
||||
)
|
||||
|
||||
def resolve_model_path(self, model_name: str) -> Path:
|
||||
@@ -387,6 +469,42 @@ def _normalized_model_name(model_name: str) -> str:
|
||||
return model_name.replace("\\", "/")
|
||||
|
||||
|
||||
def _catalog_entry_or_none(selection: str) -> ModelEntry | None:
|
||||
"""Return a curated Ultralytics entry when a dropdown label matches it."""
|
||||
|
||||
return next(
|
||||
(
|
||||
entry
|
||||
for entry in ULTRALYTICS_ENTRIES
|
||||
if selection in (entry.entry_id, entry.display_name)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _catalog_selection(entry: ModelEntry) -> str:
|
||||
"""Return the local conventional selection path for one catalog entry."""
|
||||
|
||||
if len(entry.artifacts) != 1:
|
||||
raise ValueError(
|
||||
f"Ultralytics catalog entry '{entry.entry_id}' must have one artifact."
|
||||
)
|
||||
|
||||
artifact = entry.artifacts[0]
|
||||
prefix_by_folder = {
|
||||
ULTRALYTICS_BBOX_FOLDER: "bbox",
|
||||
ULTRALYTICS_SEGM_FOLDER: "segm",
|
||||
}
|
||||
try:
|
||||
prefix = prefix_by_folder[artifact.folder_name]
|
||||
except KeyError as error:
|
||||
raise ValueError(
|
||||
f"Ultralytics catalog entry '{entry.entry_id}' has unsupported folder "
|
||||
f"'{artifact.folder_name}'."
|
||||
) from error
|
||||
return f"{prefix}/{artifact.filename}"
|
||||
|
||||
|
||||
def _model_task(model_name: str, raw_model: object) -> str:
|
||||
"""Infer detector task from choice prefix or model metadata."""
|
||||
|
||||
|
||||
@@ -107,5 +107,6 @@ class AnimaAttentionCouplingModelFamily:
|
||||
adaptation=admission.adaptation,
|
||||
region_strengths=region_strengths,
|
||||
latent_batch_size=latent_batch_size,
|
||||
negpip=interop_report.negpip,
|
||||
)
|
||||
return built.model
|
||||
|
||||
@@ -13,11 +13,12 @@ from typing import Any, Protocol
|
||||
|
||||
import torch
|
||||
|
||||
from ..runtime.anima_artifacts import ANIMA_QWEN_TEXT_ENCODER, ANIMA_QWEN_VAE
|
||||
from ..runtime.anima_artifacts import ANIMA_QWEN_TEXT_ENCODER
|
||||
from ..runtime.auto_model_artifact import AutoModelArtifact
|
||||
from ..runtime.auto_model_resolver import AutoModelResolution, AutoModelResolver
|
||||
from ..runtime.model_downloads import ProgressReporter
|
||||
from ..runtime.quantization_progress import QuantizationProgressReporter
|
||||
from ..runtime.qwen_artifacts import QWEN_IMAGE_VAE
|
||||
from ..runtime.vae_loader import VaeLoaderService, load_vae_path
|
||||
from .anima_diffusion_model_service import AnimaDiffusionModelService
|
||||
|
||||
@@ -125,7 +126,7 @@ class AnimaLoaderService:
|
||||
"""Load a VAE using ComfyUI's VAE loader policy."""
|
||||
|
||||
if vae == AUTO_CHOICE:
|
||||
vae_path = self._resolver.resolve(ANIMA_QWEN_VAE, progress).path
|
||||
vae_path = self._resolver.resolve(QWEN_IMAGE_VAE, progress).path
|
||||
return load_vae_path(vae_path)
|
||||
|
||||
return self._vae_loader.load_vae(vae)
|
||||
|
||||
@@ -26,6 +26,7 @@ from ..runtime.comfy_conditioning_processing import (
|
||||
ComfyRegionalConditioningProcessor,
|
||||
)
|
||||
from ..runtime.comfy_latent_normalization import ComfyLatentNormalizer
|
||||
from ..runtime.global_hook_model_resolver import GlobalHookModelResolver
|
||||
from ..runtime.regional_lora_conditioning_adapter import (
|
||||
RegionalLoraConditioningAdapter,
|
||||
)
|
||||
@@ -82,6 +83,9 @@ class AttentionCouplingModelPreparationService:
|
||||
latent_normalizer_class: ClassVar[type[ComfyLatentNormalizer]] = (
|
||||
ComfyLatentNormalizer
|
||||
)
|
||||
global_hook_model_resolver_class: ClassVar[type[GlobalHookModelResolver]] = (
|
||||
GlobalHookModelResolver
|
||||
)
|
||||
model_family_selector_class: ClassVar[
|
||||
type[AttentionCouplingModelFamilySelector]
|
||||
] = AttentionCouplingModelFamilySelector
|
||||
@@ -116,6 +120,11 @@ class AttentionCouplingModelPreparationService:
|
||||
)
|
||||
interop_validator = self.interop_validator_class()
|
||||
interop_report = interop_validator.validate(model, capabilities)
|
||||
model = self.global_hook_model_resolver_class().resolve(
|
||||
model,
|
||||
positive=positive,
|
||||
negative=negative,
|
||||
)
|
||||
model_family = self.model_family_selector_class().select(capabilities)
|
||||
samples = self.latent_normalizer_class().normalize(
|
||||
model=model,
|
||||
@@ -218,6 +227,7 @@ class AttentionCouplingModelPreparationService:
|
||||
noise=samples.to(device),
|
||||
device=device,
|
||||
context_validator=model_family.context_validator,
|
||||
negpip=interop_report.negpip,
|
||||
)
|
||||
interop_validator.validate_execution(
|
||||
interop_report,
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Load and validate the diffusion, text encoder, and VAE for Krea 2."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Any, Protocol
|
||||
|
||||
from ..runtime.auto_model_artifact import AutoModelArtifact
|
||||
from ..runtime.auto_model_resolver import AutoModelResolution, AutoModelResolver
|
||||
from ..runtime.clip_type_support import ComfyClipTypeSupport
|
||||
from ..runtime.diffusion_model_loader import DiffusionModelLoader
|
||||
from ..runtime.diffusion_model_metadata import (
|
||||
DiffusionModelMetadata,
|
||||
DiffusionModelMetadataInspector,
|
||||
)
|
||||
from ..runtime.krea2_artifacts import (
|
||||
KREA2_AUTO_TEXT_ENCODER,
|
||||
KREA2_QWEN3_VL_4B_FP8,
|
||||
KREA2_TEXT_ENCODER_ARTIFACTS,
|
||||
)
|
||||
from ..runtime.model_downloads import ProgressReporter
|
||||
from ..runtime.qwen_artifacts import QWEN_IMAGE_VAE
|
||||
from ..runtime.text_encoder_loader import TextEncoderLoader
|
||||
from ..runtime.vae_loader import VaeLoaderService, load_vae_path
|
||||
|
||||
AUTO_CHOICE = "auto"
|
||||
KREA2_CLIP_TYPE = "KREA2"
|
||||
KREA2_IMAGE_MODEL = "krea2"
|
||||
|
||||
|
||||
class Krea2LoaderService:
|
||||
"""Orchestrate structurally validated Krea 2 component loading."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
diffusion_loader: DiffusionModelLoaderBoundary | None = None,
|
||||
text_encoder_loader: TextEncoderLoaderBoundary | None = None,
|
||||
model_inspector: DiffusionModelInspectorBoundary | None = None,
|
||||
clip_type_support: ClipTypeSupportBoundary | None = None,
|
||||
resolver: AutoModelResolverBoundary | None = None,
|
||||
vae_loader: VaeLoaderBoundary | None = None,
|
||||
folder_paths_module: ModuleType | None = None,
|
||||
) -> None:
|
||||
"""Create a loader with injectable host and artifact boundaries."""
|
||||
|
||||
self._folder_paths_module = folder_paths_module
|
||||
self._diffusion_loader = diffusion_loader or DiffusionModelLoader(
|
||||
folder_paths_module
|
||||
)
|
||||
self._text_encoder_loader = text_encoder_loader or TextEncoderLoader(
|
||||
folder_paths_module
|
||||
)
|
||||
self._model_inspector = model_inspector or DiffusionModelMetadataInspector()
|
||||
self._clip_type_support = clip_type_support or ComfyClipTypeSupport()
|
||||
self._resolver = resolver or AutoModelResolver(
|
||||
folder_paths_module=folder_paths_module
|
||||
)
|
||||
self._vae_loader = vae_loader or VaeLoaderService(folder_paths_module)
|
||||
|
||||
def load_models(
|
||||
self,
|
||||
diffusion_model: str,
|
||||
diffusion_weight_dtype: str,
|
||||
text_encoder: str,
|
||||
text_encoder_device: str,
|
||||
vae: str,
|
||||
progress: ProgressReporter | None = None,
|
||||
) -> tuple[object, object, object]:
|
||||
"""Return a validated Krea 2 MODEL, CLIP, and VAE tuple."""
|
||||
|
||||
model = self._diffusion_loader.load(
|
||||
diffusion_model,
|
||||
diffusion_weight_dtype,
|
||||
)
|
||||
self._require_krea2_model(model)
|
||||
self._clip_type_support.require(KREA2_CLIP_TYPE)
|
||||
|
||||
encoder_path = self._resolve_text_encoder(text_encoder, progress)
|
||||
clip = self._text_encoder_loader.load(
|
||||
(encoder_path,),
|
||||
KREA2_CLIP_TYPE,
|
||||
text_encoder_device,
|
||||
)
|
||||
loaded_vae = self._load_vae(vae, progress)
|
||||
return model, clip, loaded_vae
|
||||
|
||||
def _require_krea2_model(self, model: object) -> None:
|
||||
"""Reject non-Krea architectures before resolving large support files."""
|
||||
|
||||
metadata = self._model_inspector.inspect(model)
|
||||
if metadata is not None and metadata.image_model == KREA2_IMAGE_MODEL:
|
||||
return
|
||||
raise ValueError(
|
||||
"Simple Load Krea 2 requires a diffusion model ComfyUI recognizes "
|
||||
"as Krea 2. Select a Krea 2 Raw or Turbo diffusion model."
|
||||
)
|
||||
|
||||
def _resolve_text_encoder(
|
||||
self,
|
||||
selection: str,
|
||||
progress: ProgressReporter | None,
|
||||
) -> Path:
|
||||
"""Resolve auto and official selections or a local manual encoder."""
|
||||
|
||||
artifact = (
|
||||
KREA2_QWEN3_VL_4B_FP8
|
||||
if selection == KREA2_AUTO_TEXT_ENCODER
|
||||
else KREA2_TEXT_ENCODER_ARTIFACTS.get(selection)
|
||||
)
|
||||
if artifact is not None:
|
||||
return self._resolver.resolve(artifact, progress).path
|
||||
path = self._folder_paths().get_full_path_or_raise(
|
||||
"text_encoders",
|
||||
selection,
|
||||
)
|
||||
return Path(str(path))
|
||||
|
||||
def _load_vae(
|
||||
self,
|
||||
selection: str,
|
||||
progress: ProgressReporter | None,
|
||||
) -> object:
|
||||
"""Load the shared Qwen Image VAE automatically or a manual VAE."""
|
||||
|
||||
if selection == AUTO_CHOICE:
|
||||
path = self._resolver.resolve(QWEN_IMAGE_VAE, progress).path
|
||||
return load_vae_path(path)
|
||||
return self._vae_loader.load_vae(selection)
|
||||
|
||||
def _folder_paths(self) -> ModuleType:
|
||||
"""Return the configured ComfyUI folder-path registry."""
|
||||
|
||||
if self._folder_paths_module is not None:
|
||||
return self._folder_paths_module
|
||||
module: Any = importlib.import_module("folder_paths")
|
||||
if not isinstance(module, ModuleType):
|
||||
raise TypeError("folder_paths import did not return a module.")
|
||||
self._folder_paths_module = module
|
||||
return module
|
||||
|
||||
|
||||
class DiffusionModelLoaderBoundary(Protocol):
|
||||
"""Load one selected standalone diffusion model."""
|
||||
|
||||
def load(self, diffusion_model: str, weight_dtype: str) -> object:
|
||||
"""Return a loaded ComfyUI model patcher."""
|
||||
|
||||
|
||||
class TextEncoderLoaderBoundary(Protocol):
|
||||
"""Load one or more text-encoder files for a named Comfy CLIP type."""
|
||||
|
||||
def load(
|
||||
self,
|
||||
paths: tuple[Path, ...],
|
||||
clip_type_name: str,
|
||||
device: str,
|
||||
) -> object:
|
||||
"""Return a loaded ComfyUI CLIP object."""
|
||||
|
||||
|
||||
class DiffusionModelInspectorBoundary(Protocol):
|
||||
"""Inspect architecture metadata from a loaded diffusion model."""
|
||||
|
||||
def inspect(self, model: object) -> DiffusionModelMetadata | None:
|
||||
"""Return normalized metadata when ComfyUI exposes it."""
|
||||
|
||||
|
||||
class ClipTypeSupportBoundary(Protocol):
|
||||
"""Validate that the host supports a required Comfy CLIP type."""
|
||||
|
||||
def require(self, clip_type_name: str) -> None:
|
||||
"""Raise when a required CLIP type is unavailable."""
|
||||
|
||||
|
||||
class AutoModelResolverBoundary(Protocol):
|
||||
"""Resolve a trusted catalog artifact to a verified local file."""
|
||||
|
||||
def resolve(
|
||||
self,
|
||||
artifact: AutoModelArtifact,
|
||||
progress: ProgressReporter | None = None,
|
||||
) -> AutoModelResolution:
|
||||
"""Return a verified local artifact path."""
|
||||
|
||||
|
||||
class VaeLoaderBoundary(Protocol):
|
||||
"""Load one manually selected ComfyUI VAE."""
|
||||
|
||||
def load_vae(self, vae_name: str) -> object:
|
||||
"""Return a loaded ComfyUI VAE object."""
|
||||
@@ -0,0 +1,213 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Clone and patch supported MODEL/CLIP pairs for automatic NegPiP."""
|
||||
|
||||
# NegPiP behavior is adapted from ComfyUI-ppm and its credited predecessors.
|
||||
# See third_party/manifest.toml and third_party/NOTICE.md.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from functools import partial
|
||||
|
||||
from comfy.model_base import SDXL, Anima, BaseModel, Krea2, SDXLRefiner
|
||||
from comfy.model_patcher import ModelPatcher
|
||||
from comfy.sd import CLIP
|
||||
|
||||
from ..runtime.clip_patcher_mutations import (
|
||||
ClipBooleanOptionMutation,
|
||||
ClipCallableObjectPatchMutation,
|
||||
ClipTokenizerMutation,
|
||||
)
|
||||
from ..runtime.model_patcher_mutations import (
|
||||
ModelAttentionPatchMutation,
|
||||
ModelBooleanOptionMutation,
|
||||
ModelCallableObjectPatchMutation,
|
||||
ModelDiffusionWrapperMutation,
|
||||
ModelInteropDiffusionWrapperMutation,
|
||||
)
|
||||
from ..runtime.negpip.anima import (
|
||||
WRAPPER_KEY as ANIMA_WRAPPER_KEY,
|
||||
)
|
||||
from ..runtime.negpip.anima import (
|
||||
anima_attn2_negpip,
|
||||
anima_diffusion_negpip_wrapper,
|
||||
anima_extra_conds_negpip_wrapper,
|
||||
)
|
||||
from ..runtime.negpip.krea2 import (
|
||||
CLIP_MARKER,
|
||||
KREA_TOKEN_KEY,
|
||||
Krea2NegpipTokenizer,
|
||||
encode_krea2_token_weights_negpip,
|
||||
krea2_attn1_negpip,
|
||||
krea2_diffusion_negpip_wrapper,
|
||||
krea2_extra_conds_negpip_wrapper,
|
||||
)
|
||||
from ..runtime.negpip.krea2 import (
|
||||
WRAPPER_KEY as KREA_WRAPPER_KEY,
|
||||
)
|
||||
from ..runtime.negpip.standard import (
|
||||
encode_token_weights_negpip,
|
||||
standard_attn2_negpip,
|
||||
)
|
||||
from ..runtime.patcher_lifecycle import PATCHER_LIFECYCLE
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
MODEL_MARKER = "ppm_negpip"
|
||||
SUPPORTED_STANDARD_ENCODERS = ("clip_g", "clip_l", "t5xxl", "llama", "qwen3_06b")
|
||||
|
||||
|
||||
class NegpipModelService:
|
||||
"""Apply exactly one family-specific NegPiP patch set when supported."""
|
||||
|
||||
def prepare(self, model: object, clip: object) -> tuple[object, object]:
|
||||
"""Return a patched clone pair or the original unsupported pair unchanged."""
|
||||
|
||||
if not isinstance(model, ModelPatcher) or not isinstance(clip, CLIP):
|
||||
raise TypeError("Automatic NegPiP requires Comfy MODEL and CLIP objects.")
|
||||
marker = model.model_options.get(MODEL_MARKER, False)
|
||||
if not isinstance(marker, bool):
|
||||
raise TypeError("MODEL ppm_negpip marker must be boolean.")
|
||||
if marker:
|
||||
LOGGER.debug("Automatic NegPiP reused an already-patched MODEL")
|
||||
return model, clip
|
||||
|
||||
model_type = type(model.model)
|
||||
if model_type is Krea2:
|
||||
return self._prepare_krea2(model, clip)
|
||||
if model_type is Anima:
|
||||
return self._prepare_anima(model, clip)
|
||||
if model_type is BaseModel or issubclass(model_type, (SDXL, SDXLRefiner)):
|
||||
return self._prepare_standard(model, clip)
|
||||
LOGGER.debug(
|
||||
"Automatic NegPiP skipped unsupported model family",
|
||||
extra={"model_type": model_type.__qualname__},
|
||||
)
|
||||
return model, clip
|
||||
|
||||
def _prepare_standard(
|
||||
self,
|
||||
model: ModelPatcher,
|
||||
clip: CLIP,
|
||||
) -> tuple[ModelPatcher, CLIP]:
|
||||
"""Install PPM-compatible interleaved key/value encoding on SD1 or SDXL."""
|
||||
|
||||
encoders = [
|
||||
name
|
||||
for name in SUPPORTED_STANDARD_ENCODERS
|
||||
if hasattr(clip.patcher.model, name)
|
||||
]
|
||||
if not encoders:
|
||||
LOGGER.warning("Automatic NegPiP found no supported standard text encoder")
|
||||
return model, clip
|
||||
prepared_clip = PATCHER_LIFECYCLE.derive_clip(
|
||||
clip,
|
||||
(
|
||||
*(
|
||||
ClipCallableObjectPatchMutation(
|
||||
f"{encoder_name}.encode_token_weights",
|
||||
partial(
|
||||
encode_token_weights_negpip,
|
||||
getattr(clip.patcher.model, encoder_name),
|
||||
),
|
||||
)
|
||||
for encoder_name in encoders
|
||||
),
|
||||
ClipBooleanOptionMutation(MODEL_MARKER, True),
|
||||
),
|
||||
operation="automatic standard NegPiP CLIP preparation",
|
||||
)
|
||||
prepared_model = PATCHER_LIFECYCLE.derive_model(
|
||||
model,
|
||||
(
|
||||
ModelAttentionPatchMutation("attn2", standard_attn2_negpip),
|
||||
ModelBooleanOptionMutation(MODEL_MARKER, True),
|
||||
),
|
||||
operation="automatic standard NegPiP MODEL preparation",
|
||||
)
|
||||
return prepared_model, prepared_clip
|
||||
|
||||
def _prepare_anima(
|
||||
self,
|
||||
model: ModelPatcher,
|
||||
clip: CLIP,
|
||||
) -> tuple[ModelPatcher, CLIP]:
|
||||
"""Install PPM-compatible Anima weight-mask conditions and attention."""
|
||||
|
||||
previous = model.get_model_object("extra_conds")
|
||||
prepared_model = PATCHER_LIFECYCLE.derive_model(
|
||||
model,
|
||||
(
|
||||
ModelCallableObjectPatchMutation(
|
||||
"extra_conds",
|
||||
anima_extra_conds_negpip_wrapper(previous),
|
||||
),
|
||||
ModelInteropDiffusionWrapperMutation(
|
||||
ANIMA_WRAPPER_KEY,
|
||||
anima_diffusion_negpip_wrapper,
|
||||
),
|
||||
ModelAttentionPatchMutation("attn2", anima_attn2_negpip),
|
||||
ModelBooleanOptionMutation(MODEL_MARKER, True),
|
||||
),
|
||||
operation="automatic Anima NegPiP MODEL preparation",
|
||||
)
|
||||
prepared_clip = PATCHER_LIFECYCLE.derive_clip(
|
||||
clip,
|
||||
(ClipBooleanOptionMutation(MODEL_MARKER, True),),
|
||||
operation="automatic Anima NegPiP CLIP preparation",
|
||||
)
|
||||
return prepared_model, prepared_clip
|
||||
|
||||
def _prepare_krea2(
|
||||
self,
|
||||
model: ModelPatcher,
|
||||
clip: CLIP,
|
||||
) -> tuple[ModelPatcher, CLIP]:
|
||||
"""Install Krea's shape-preserving sign-mask encoder and attention patch."""
|
||||
|
||||
if not hasattr(clip.patcher.model, KREA_TOKEN_KEY):
|
||||
LOGGER.warning("Automatic NegPiP found no Krea Qwen3-VL text encoder")
|
||||
return model, clip
|
||||
outer_encoder = clip.patcher.get_model_object("encode_token_weights")
|
||||
prepared_clip = PATCHER_LIFECYCLE.derive_clip(
|
||||
clip,
|
||||
(
|
||||
ClipTokenizerMutation(
|
||||
clip.tokenizer,
|
||||
Krea2NegpipTokenizer(clip.tokenizer),
|
||||
),
|
||||
ClipCallableObjectPatchMutation(
|
||||
"encode_token_weights",
|
||||
partial(encode_krea2_token_weights_negpip, outer_encoder),
|
||||
),
|
||||
ClipBooleanOptionMutation(CLIP_MARKER, True),
|
||||
),
|
||||
operation="automatic Krea 2 NegPiP CLIP preparation",
|
||||
)
|
||||
previous = model.get_model_object("extra_conds")
|
||||
prepared_model = PATCHER_LIFECYCLE.derive_model(
|
||||
model,
|
||||
(
|
||||
ModelCallableObjectPatchMutation(
|
||||
"extra_conds",
|
||||
krea2_extra_conds_negpip_wrapper(previous),
|
||||
),
|
||||
ModelDiffusionWrapperMutation(
|
||||
KREA_WRAPPER_KEY,
|
||||
krea2_diffusion_negpip_wrapper,
|
||||
),
|
||||
ModelAttentionPatchMutation("attn1", krea2_attn1_negpip),
|
||||
ModelBooleanOptionMutation(MODEL_MARKER, True),
|
||||
),
|
||||
operation="automatic Krea 2 NegPiP MODEL preparation",
|
||||
)
|
||||
LOGGER.info(
|
||||
"Automatic NegPiP enabled",
|
||||
extra={"model_family": "krea2", "encoder": KREA_TOKEN_KEY},
|
||||
)
|
||||
return prepared_model, prepared_clip
|
||||
|
||||
|
||||
NEGPIP_MODEL_SERVICE = NegpipModelService()
|
||||
@@ -9,6 +9,7 @@ from __future__ import annotations
|
||||
from typing import Any, TypeAlias
|
||||
|
||||
import torch
|
||||
from comfy.hooks import HookGroup
|
||||
|
||||
from ..domain.conditioning_batch import ConditioningBatch
|
||||
from ..domain.regional_prompting import (
|
||||
@@ -19,6 +20,9 @@ from ..masking.regional_prompt_masks import (
|
||||
prepare_regional_mask_batch,
|
||||
regional_mask,
|
||||
)
|
||||
from ..runtime.global_first_conditioning_hooks import (
|
||||
GLOBAL_FIRST_CONDITIONING_HOOK_COMPOSER,
|
||||
)
|
||||
from ..runtime.regional_conditioning_companion import detach_global_companion
|
||||
from ..shared.logging import get_logger
|
||||
|
||||
@@ -114,6 +118,11 @@ class RegionalConditioningService:
|
||||
if not plan.pairs:
|
||||
return self._copy_conditioning(global_conditioning)
|
||||
|
||||
global_hooks = GLOBAL_FIRST_CONDITIONING_HOOK_COMPOSER.global_hooks(
|
||||
global_conditioning,
|
||||
source_label=f"{input_name} global conditioning",
|
||||
)
|
||||
hook_cache: dict[tuple[HookGroup, HookGroup], HookGroup] = {}
|
||||
assembled = self._as_default(global_conditioning)
|
||||
for pair in plan.pairs:
|
||||
conditioning = self._validate_conditioning(
|
||||
@@ -121,6 +130,22 @@ class RegionalConditioningService:
|
||||
input_name=(f"{input_name} regional entry {pair.conditioning_index}"),
|
||||
)
|
||||
conditioning, global_companion = detach_global_companion(conditioning)
|
||||
conditioning = GLOBAL_FIRST_CONDITIONING_HOOK_COMPOSER.compose(
|
||||
conditioning,
|
||||
global_hooks,
|
||||
source_label=(f"{input_name} regional entry {pair.conditioning_index}"),
|
||||
cache=hook_cache,
|
||||
)
|
||||
if global_companion is not None:
|
||||
global_companion = GLOBAL_FIRST_CONDITIONING_HOOK_COMPOSER.compose(
|
||||
global_companion,
|
||||
global_hooks,
|
||||
source_label=(
|
||||
f"{input_name} regional entry {pair.conditioning_index} "
|
||||
"global companion"
|
||||
),
|
||||
cache=hook_cache,
|
||||
)
|
||||
mask = regional_mask(mask_batch, pair.mask_index)
|
||||
if global_companion is not None and regional_prompt_weight < 1.0:
|
||||
assembled.extend(
|
||||
|
||||
@@ -27,9 +27,9 @@ from ..runtime.attention_coupling.unet_context import (
|
||||
from ..runtime.regional_attention_diagnostics import (
|
||||
RegionalAttentionDiagnosticsBuilder,
|
||||
)
|
||||
from ..runtime.regional_lora.standard_unet_native_admission import (
|
||||
StandardUnetNativeLoraAdmission,
|
||||
StandardUnetNativeLoraAdmissionService,
|
||||
from ..runtime.regional_lora.standard_unet_operation_preparation import (
|
||||
StandardUnetOperationAdmission,
|
||||
StandardUnetOperationPreparation,
|
||||
)
|
||||
from ..runtime.regional_lora_plan_adapter import RegionalLoraPlanAdaptation
|
||||
from ..runtime.regional_model_patch_interop import RegionalModelPatchInteropReport
|
||||
@@ -47,8 +47,8 @@ class StandardUnetAttentionCouplingModelFamily:
|
||||
backend_class: ClassVar[type[StandardUnetAttentionBackend]] = (
|
||||
StandardUnetAttentionBackend
|
||||
)
|
||||
native_admission_class: ClassVar[type[StandardUnetNativeLoraAdmissionService]] = (
|
||||
StandardUnetNativeLoraAdmissionService
|
||||
operation_preparation_class: ClassVar[type[StandardUnetOperationPreparation]] = (
|
||||
StandardUnetOperationPreparation
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -84,7 +84,7 @@ class StandardUnetAttentionCouplingModelFamily:
|
||||
raise TypeError(
|
||||
"Standard UNet Attention Coupling requires regional adaptation."
|
||||
)
|
||||
return self.native_admission_class().admit(model, adaptation)
|
||||
return self.operation_preparation_class().admit(model, adaptation)
|
||||
|
||||
def prepare_sampler_conditioning(
|
||||
self,
|
||||
@@ -113,8 +113,8 @@ class StandardUnetAttentionCouplingModelFamily:
|
||||
) -> object:
|
||||
"""Build shared diagnostics state and derive the paired attn2 backend."""
|
||||
|
||||
if not isinstance(admission, StandardUnetNativeLoraAdmission):
|
||||
raise TypeError("Standard UNet derivation requires native admission.")
|
||||
if not isinstance(admission, StandardUnetOperationAdmission):
|
||||
raise TypeError("Standard UNet derivation requires operation admission.")
|
||||
if not isinstance(interop_report, RegionalModelPatchInteropReport):
|
||||
raise TypeError("Standard UNet derivation requires interop evidence.")
|
||||
if admission.adaptation.plan != processed_plan.lora_plan:
|
||||
@@ -142,6 +142,7 @@ class StandardUnetAttentionCouplingModelFamily:
|
||||
model=model,
|
||||
state=state,
|
||||
admission=admission,
|
||||
negpip=interop_report.negpip,
|
||||
)
|
||||
.model
|
||||
)
|
||||
|
||||
@@ -76,6 +76,7 @@ def test_anima_family_retains_single_frame_context_and_backend_policy() -> None:
|
||||
"adaptation": adaptation,
|
||||
"region_strengths": (0.75,),
|
||||
"latent_batch_size": 2,
|
||||
"negpip": None,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -31,6 +31,10 @@ from simple_syrup.domain.spatial_views import (
|
||||
SpatialViewKind,
|
||||
)
|
||||
from simple_syrup.runtime.patcher_lifecycle import PATCHER_LIFECYCLE
|
||||
from simple_syrup.runtime.ppm_negpip_interop import (
|
||||
PpmNegpipInterop,
|
||||
PpmNegpipSemantics,
|
||||
)
|
||||
from simple_syrup.runtime.regional_lora.anima_activation_context import (
|
||||
AnimaActivationContext,
|
||||
AnimaActivationGeometry,
|
||||
@@ -258,6 +262,79 @@ def test_patch_batches_complete_branches_and_blends_expected_outputs(
|
||||
assert invocation_context.current_or_none() is None
|
||||
|
||||
|
||||
def test_patch_packs_anima_negpip_masks_with_the_same_branch_segments() -> None:
|
||||
"""Align each compact regional context with its own NegPiP value mask."""
|
||||
|
||||
activation_context = AnimaActivationContext()
|
||||
invocation_context = AnimaCrossAttentionInvocationContext()
|
||||
original = _DeterministicCrossAttention(invocation_context)
|
||||
base = torch.zeros((1, 2, 1))
|
||||
region = torch.ones_like(base)
|
||||
base_multiplier = torch.tensor([[[1.0], [-1.0]]])
|
||||
region_multiplier = torch.tensor([[[-1.0], [1.0]]])
|
||||
contexts = BatchedRegionalAttentionContexts(
|
||||
latent_batch_size=1,
|
||||
chunks=(
|
||||
RegionalAttentionChunkBatch(
|
||||
0,
|
||||
RegionalAttentionBranch.POSITIVE,
|
||||
0,
|
||||
1,
|
||||
),
|
||||
),
|
||||
base_context=base,
|
||||
regions=(
|
||||
BatchedRegionalAttentionRegion(
|
||||
0,
|
||||
(
|
||||
BatchedRegionalAttentionEntry(
|
||||
0,
|
||||
region,
|
||||
(1.0,),
|
||||
region_multiplier,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
base_value_multiplier=base_multiplier,
|
||||
)
|
||||
execution = AnimaRegionalAttentionExecution(
|
||||
contexts,
|
||||
_bank(torch.full((1, 1, 1), 0.5)),
|
||||
(1.0,),
|
||||
)
|
||||
negpip = PpmNegpipInterop(
|
||||
PpmNegpipSemantics.ANIMA_VALUE_MASK,
|
||||
lambda *args, **kwargs: (args, kwargs),
|
||||
)
|
||||
patch = AnimaRegionalCrossAttentionPatch(
|
||||
original,
|
||||
execution,
|
||||
activation_context=activation_context,
|
||||
invocation_context=invocation_context,
|
||||
phase_context=_FullRegionalPhaseContext(),
|
||||
negpip=negpip,
|
||||
)
|
||||
old_mask = torch.ones_like(base_multiplier)
|
||||
options: dict[str, object] = {"ppm_negpip_mask": old_mask}
|
||||
|
||||
with activation_context.activate(_geometry(batch=1, height=1, width=1)):
|
||||
patch(
|
||||
torch.zeros((1, 1, 1)),
|
||||
base,
|
||||
transformer_options=options,
|
||||
)
|
||||
|
||||
observed_options = original.calls[0][3]
|
||||
assert isinstance(observed_options, dict)
|
||||
assert observed_options is not options
|
||||
assert torch.equal(
|
||||
observed_options["ppm_negpip_mask"],
|
||||
torch.cat((base_multiplier, region_multiplier)),
|
||||
)
|
||||
assert options["ppm_negpip_mask"] is old_mask
|
||||
|
||||
|
||||
def test_cross_attention_backing_module_does_not_leak_a_host_weight_namespace() -> None:
|
||||
"""Keep the retained installed attention outside PyTorch child discovery."""
|
||||
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Verify exact static-global and regional Anima LoRA overlap rejection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from comfy.weight_adapter.lora import LoRAAdapter
|
||||
|
||||
from simple_syrup.domain.regional_lora_plan import (
|
||||
RegionalLoraAdapterIdentity,
|
||||
RegionalLoraAdapterPlan,
|
||||
RegionalLoraBranch,
|
||||
RegionalLoraPlan,
|
||||
RegionalLoraScheduleBoundary,
|
||||
)
|
||||
from simple_syrup.runtime.regional_lora.anima_global_lora_overlap import (
|
||||
AnimaGlobalRegionalLoraOverlapError,
|
||||
AnimaGlobalRegionalLoraOverlapValidator,
|
||||
)
|
||||
from simple_syrup.runtime.regional_lora.anima_plan_admission import (
|
||||
AnimaRegionalLoraAdapterAdmission,
|
||||
AnimaRegionalLoraPlanAdmission,
|
||||
)
|
||||
from simple_syrup.runtime.regional_lora.anima_targets import (
|
||||
AnimaLoraAdmission,
|
||||
AnimaLoraTarget,
|
||||
AnimaLoraTargetFamily,
|
||||
anima_lora_target_name,
|
||||
expected_anima_lora_features,
|
||||
)
|
||||
from simple_syrup.runtime.regional_lora.standard_adapter import StandardLoraTarget
|
||||
|
||||
|
||||
def test_overlap_validator_accepts_empty_distinct_and_partial_global_state() -> None:
|
||||
"""Preserve unpatched and content-distinct global MODEL LoRAs."""
|
||||
|
||||
admission, targets = _admission(target_count=2)
|
||||
validator = AnimaGlobalRegionalLoraOverlapValidator()
|
||||
|
||||
validator.validate(SimpleNamespace(patches={}), admission)
|
||||
validator.validate(
|
||||
SimpleNamespace(patches={_key(targets[0]): [_patch(targets[0])]}),
|
||||
admission,
|
||||
)
|
||||
changed = targets[0].up.clone()
|
||||
changed[0, 0] += 1.0
|
||||
validator.validate(
|
||||
SimpleNamespace(
|
||||
patches={
|
||||
_key(targets[0]): [_patch(targets[0], up=changed)],
|
||||
_key(targets[1]): [_patch(targets[1])],
|
||||
}
|
||||
),
|
||||
admission,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("clone_tensors", [False, True], ids=("identity", "content"))
|
||||
def test_overlap_validator_rejects_complete_exact_global_content(
|
||||
clone_tensors: bool,
|
||||
) -> None:
|
||||
"""Reject exact adapter content with identity and cloned-tensor paths."""
|
||||
|
||||
admission, targets = _admission(target_count=2)
|
||||
patches = {
|
||||
_key(target): [
|
||||
_patch(
|
||||
target,
|
||||
down=target.down.clone() if clone_tensors else target.down,
|
||||
up=target.up.clone() if clone_tensors else target.up,
|
||||
)
|
||||
]
|
||||
for target in targets
|
||||
}
|
||||
|
||||
with pytest.raises(
|
||||
AnimaGlobalRegionalLoraOverlapError,
|
||||
match="already applied globally.*regional.safetensors",
|
||||
):
|
||||
AnimaGlobalRegionalLoraOverlapValidator().validate(
|
||||
SimpleNamespace(patches=patches),
|
||||
admission,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"patch_factory",
|
||||
(
|
||||
lambda target: _patch(target, strength=0.0),
|
||||
lambda target: (1.0, ("diff", (target.up,)), 1.0, None, None),
|
||||
lambda target: _patch(target, alpha=1.0),
|
||||
),
|
||||
ids=("zero-strength", "non-lora", "alpha-form"),
|
||||
)
|
||||
def test_overlap_validator_preserves_noncomparable_global_patches(
|
||||
patch_factory: object,
|
||||
) -> None:
|
||||
"""Keep inactive and other global patch formats unchanged."""
|
||||
|
||||
admission, targets = _admission(target_count=1)
|
||||
factory = patch_factory
|
||||
assert callable(factory)
|
||||
|
||||
AnimaGlobalRegionalLoraOverlapValidator().validate(
|
||||
SimpleNamespace(patches={_key(targets[0]): [factory(targets[0])]}),
|
||||
admission,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("patches", "message"),
|
||||
(
|
||||
(None, "requires MODEL patches"),
|
||||
({"diffusion_model.blocks.0.self_attn.q_proj.weight": object()}, "list"),
|
||||
({"diffusion_model.blocks.0.self_attn.q_proj.weight": [object()]}, "tuple"),
|
||||
(
|
||||
{
|
||||
"diffusion_model.blocks.0.self_attn.q_proj.weight": [
|
||||
(float("nan"), object(), 1.0)
|
||||
]
|
||||
},
|
||||
"finite",
|
||||
),
|
||||
),
|
||||
)
|
||||
def test_overlap_validator_fails_closed_on_malformed_model_patch_state(
|
||||
patches: object,
|
||||
message: str,
|
||||
) -> None:
|
||||
"""Reject installed-host patch drift before regional execution setup."""
|
||||
|
||||
admission, _ = _admission(target_count=1)
|
||||
|
||||
with pytest.raises((TypeError, ValueError), match=message):
|
||||
AnimaGlobalRegionalLoraOverlapValidator().validate(
|
||||
SimpleNamespace(patches=patches),
|
||||
admission,
|
||||
)
|
||||
|
||||
|
||||
def _admission(
|
||||
*, target_count: int
|
||||
) -> tuple[AnimaRegionalLoraPlanAdmission, tuple[StandardLoraTarget, ...]]:
|
||||
"""Build one admitted regional adapter with small valid Anima targets."""
|
||||
|
||||
families = tuple(AnimaLoraTargetFamily)[:target_count]
|
||||
targets = tuple(_target(family) for family in families)
|
||||
plan_entry = RegionalLoraAdapterPlan(
|
||||
adapter_identity=RegionalLoraAdapterIdentity("regional.safetensors"),
|
||||
composition_index=0,
|
||||
region_index=0,
|
||||
branch=RegionalLoraBranch.POSITIVE,
|
||||
model_strength=0.8,
|
||||
schedule=(RegionalLoraScheduleBoundary(0.0, 1.0, 1.0, 0),),
|
||||
)
|
||||
plan = RegionalLoraPlan((plan_entry,))
|
||||
admission = AnimaLoraAdmission(
|
||||
tuple(
|
||||
AnimaLoraTarget(0, family, target)
|
||||
for family, target in zip(families, targets, strict=True)
|
||||
)
|
||||
)
|
||||
return (
|
||||
AnimaRegionalLoraPlanAdmission(
|
||||
plan,
|
||||
(AnimaRegionalLoraAdapterAdmission(plan_entry, admission),),
|
||||
),
|
||||
targets,
|
||||
)
|
||||
|
||||
|
||||
def _target(family: AnimaLoraTargetFamily) -> StandardLoraTarget:
|
||||
"""Return one rank-one target with installed Anima feature dimensions."""
|
||||
|
||||
input_features, output_features = expected_anima_lora_features(family)
|
||||
return StandardLoraTarget(
|
||||
target=anima_lora_target_name(0, family),
|
||||
down=torch.arange(input_features, dtype=torch.float32).reshape(1, -1),
|
||||
up=torch.arange(output_features, dtype=torch.float32).reshape(-1, 1),
|
||||
rank=1,
|
||||
input_features=input_features,
|
||||
output_features=output_features,
|
||||
)
|
||||
|
||||
|
||||
def _key(target: StandardLoraTarget) -> str:
|
||||
"""Return the installed Comfy MODEL patch key for one target."""
|
||||
|
||||
return f"{target.target}.weight"
|
||||
|
||||
|
||||
def _patch(
|
||||
target: StandardLoraTarget,
|
||||
*,
|
||||
strength: float = 1.0,
|
||||
down: torch.Tensor | None = None,
|
||||
up: torch.Tensor | None = None,
|
||||
alpha: float | None = None,
|
||||
) -> tuple[object, ...]:
|
||||
"""Return one installed-Comfy standard static LoRA patch entry."""
|
||||
|
||||
adapter = LoRAAdapter(
|
||||
set(),
|
||||
(
|
||||
target.up if up is None else up,
|
||||
target.down if down is None else down,
|
||||
alpha,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
)
|
||||
return (strength, adapter, 1.0, None, None)
|
||||
@@ -232,7 +232,7 @@ def test_loader_uses_auto_resolver_for_auto_choices(
|
||||
progress,
|
||||
)
|
||||
|
||||
assert resolver.requests == ["anima_qwen_text_encoder", "anima_qwen_vae"]
|
||||
assert resolver.requests == ["anima_qwen_text_encoder", "qwen_image_vae"]
|
||||
assert resolver.progress_reporters == [progress, progress]
|
||||
assert comfy_state.clip_calls[0]["ckpt_paths"] == [str(resolver.text_encoder_path)]
|
||||
assert comfy_state.vae_paths == [str(resolver.vae_path)]
|
||||
@@ -265,7 +265,7 @@ def test_anima_auto_downloads_emit_comfy_node_progress_end_to_end(
|
||||
"ANIMA_QWEN_TEXT_ENCODER",
|
||||
text_artifact,
|
||||
)
|
||||
monkeypatch.setattr(anima_loader_module, "ANIMA_QWEN_VAE", vae_artifact)
|
||||
monkeypatch.setattr(anima_loader_module, "QWEN_IMAGE_VAE", vae_artifact)
|
||||
|
||||
content_by_url = {
|
||||
text_artifact.source_url: text_content,
|
||||
@@ -494,4 +494,5 @@ def _small_artifact(
|
||||
source_repo="example/progress",
|
||||
description=f"progress test {filename}",
|
||||
sha256=hashlib.sha256(content).hexdigest(),
|
||||
file_size_bytes=len(content),
|
||||
)
|
||||
|
||||
@@ -25,10 +25,14 @@ from simple_syrup.domain.regional_attention_execution import (
|
||||
RegionalAttentionExecutionMode,
|
||||
)
|
||||
from simple_syrup.domain.regional_lora_plan import EMPTY_REGIONAL_LORA_PLAN
|
||||
from simple_syrup.domain.regional_model_capabilities import RegionalModelFamily
|
||||
from simple_syrup.runtime.attention_coupling.family_admission import (
|
||||
AttentionCouplingFamilyAdmission,
|
||||
)
|
||||
from simple_syrup.runtime.regional_lora_plan_adapter import RegionalLoraPlanAdaptation
|
||||
from simple_syrup.runtime.regional_model_patch_interop import (
|
||||
RegionalModelPatchInteropReport,
|
||||
)
|
||||
from simple_syrup.services.attention_coupling_model_family import (
|
||||
AttentionCouplingPreparedModelReuse,
|
||||
AttentionCouplingSamplerConditioning,
|
||||
@@ -59,10 +63,16 @@ class _CapabilityService:
|
||||
class _InteropValidator:
|
||||
"""Record centralized modifier admission without requiring a real patcher."""
|
||||
|
||||
report: ClassVar[object] = object()
|
||||
report: ClassVar[RegionalModelPatchInteropReport] = RegionalModelPatchInteropReport(
|
||||
RegionalModelFamily.ANIMA, ()
|
||||
)
|
||||
calls: ClassVar[list[tuple[object, ...]]] = []
|
||||
|
||||
def validate(self, model: object, capabilities: object) -> object:
|
||||
def validate(
|
||||
self,
|
||||
model: object,
|
||||
capabilities: object,
|
||||
) -> RegionalModelPatchInteropReport:
|
||||
"""Record exact orchestration inputs without changing them."""
|
||||
|
||||
type(self).calls.append((model, capabilities))
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Tests for artifact-aware automatic component dropdown choices."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import pytest
|
||||
|
||||
from simple_syrup.runtime.auto_model_artifact import AutoModelArtifact
|
||||
from simple_syrup.runtime.auto_model_choices import automatic_component_choices
|
||||
|
||||
|
||||
class _FolderPaths(ModuleType):
|
||||
"""Resolve ComfyUI-relative test model choices from one models root."""
|
||||
|
||||
def __init__(self, models_root: Path) -> None:
|
||||
"""Create a model-path fake rooted at the temporary directory."""
|
||||
|
||||
super().__init__("folder_paths")
|
||||
self._models_root = models_root
|
||||
|
||||
def get_full_path(self, folder_name: str, choice: str) -> str | None:
|
||||
"""Return an existing test model path or None."""
|
||||
|
||||
path = self._models_root / folder_name / choice
|
||||
return str(path) if path.is_file() else None
|
||||
|
||||
|
||||
def test_choices_hide_official_and_renamed_automatic_files(tmp_path: Path) -> None:
|
||||
"""Known local artifacts appear only through their automatic leading choice."""
|
||||
|
||||
folder_paths = _FolderPaths(tmp_path / "models")
|
||||
artifact = _artifact("official.safetensors", b"trusted")
|
||||
folder = tmp_path / "models" / "text_encoders"
|
||||
folder.mkdir(parents=True)
|
||||
(folder / "renamed.safetensors").write_bytes(b"trusted")
|
||||
(folder / "manual.safetensors").write_bytes(b"manual model")
|
||||
|
||||
choices = automatic_component_choices(
|
||||
installed=(
|
||||
artifact.filename,
|
||||
"renamed.safetensors",
|
||||
"manual.safetensors",
|
||||
),
|
||||
artifacts=(artifact,),
|
||||
leading_choices=("auto", artifact.filename),
|
||||
folder_paths_module=folder_paths,
|
||||
)
|
||||
|
||||
assert choices == ["auto", artifact.filename, "manual.safetensors"]
|
||||
|
||||
|
||||
def test_choices_keep_same_category_files_with_different_sizes(tmp_path: Path) -> None:
|
||||
"""Manual files remain selectable when they cannot be the automatic artifact."""
|
||||
|
||||
folder_paths = _FolderPaths(tmp_path / "models")
|
||||
artifact = _artifact("official.safetensors", b"trusted")
|
||||
folder = tmp_path / "models" / "text_encoders"
|
||||
folder.mkdir(parents=True)
|
||||
(folder / "custom.safetensors").write_bytes(b"different size")
|
||||
|
||||
choices = automatic_component_choices(
|
||||
installed=("custom.safetensors",),
|
||||
artifacts=(artifact,),
|
||||
leading_choices=("auto",),
|
||||
folder_paths_module=folder_paths,
|
||||
)
|
||||
|
||||
assert choices == ["auto", "custom.safetensors"]
|
||||
|
||||
|
||||
def test_choices_require_artifacts_from_one_model_category() -> None:
|
||||
"""Dropdown filtering cannot accidentally combine unrelated model categories."""
|
||||
|
||||
folder_paths = _FolderPaths(Path("models"))
|
||||
|
||||
with pytest.raises(ValueError, match="share one model category"):
|
||||
automatic_component_choices(
|
||||
installed=(),
|
||||
artifacts=(
|
||||
_artifact("encoder.safetensors", b"encoder", "text_encoders"),
|
||||
_artifact("vae.safetensors", b"vae", "vae"),
|
||||
),
|
||||
leading_choices=("auto",),
|
||||
folder_paths_module=folder_paths,
|
||||
)
|
||||
|
||||
|
||||
def _artifact(
|
||||
filename: str,
|
||||
content: bytes,
|
||||
folder_name: str = "text_encoders",
|
||||
) -> AutoModelArtifact:
|
||||
"""Create a small trusted artifact for dropdown tests."""
|
||||
|
||||
return AutoModelArtifact(
|
||||
cache_id=filename,
|
||||
filename=filename,
|
||||
folder_name=folder_name,
|
||||
canonical_subfolder="test",
|
||||
source_url=f"https://example.invalid/{filename}",
|
||||
source_repo="example/models",
|
||||
description=filename,
|
||||
sha256=hashlib.sha256(content).hexdigest(),
|
||||
file_size_bytes=len(content),
|
||||
)
|
||||
@@ -16,6 +16,7 @@ from simple_syrup.runtime.auto_model_cache import AutoModelCache, AutoModelCache
|
||||
from simple_syrup.runtime.auto_model_resolver import (
|
||||
AutoModelResolver,
|
||||
canonical_auto_destination,
|
||||
find_model_artifact,
|
||||
find_model_by_basename,
|
||||
relative_model_name,
|
||||
)
|
||||
@@ -158,6 +159,112 @@ def test_resolver_ignores_same_named_file_with_wrong_checksum(tmp_path: Path) ->
|
||||
assert len(downloader.requests) == 1
|
||||
|
||||
|
||||
def test_resolver_finds_renamed_artifact_by_size_and_checksum(tmp_path: Path) -> None:
|
||||
"""A renamed official artifact is reused from its registered model category."""
|
||||
|
||||
fake = FakeFolderPaths(tmp_path / "models")
|
||||
artifact = _artifact("text_encoders", "model.safetensors")
|
||||
renamed_path = (
|
||||
tmp_path / "models" / "text_encoders" / "custom" / "my-qwen.safetensors"
|
||||
)
|
||||
renamed_path.parent.mkdir(parents=True)
|
||||
renamed_path.write_bytes(b"model")
|
||||
cache = AutoModelCache(fake)
|
||||
downloader = RecordingDownloader()
|
||||
|
||||
resolved = AutoModelResolver(cache, downloader, fake).resolve(artifact)
|
||||
cached = AutoModelResolver(cache, downloader, fake).resolve(artifact)
|
||||
|
||||
assert resolved.path == renamed_path
|
||||
assert resolved.source == "found"
|
||||
assert cached.path == renamed_path
|
||||
assert cached.source == "cached"
|
||||
assert cache.load()[artifact.cache_id].path == renamed_path
|
||||
assert downloader.requests == []
|
||||
|
||||
|
||||
def test_resolver_does_not_scan_unrelated_model_categories(tmp_path: Path) -> None:
|
||||
"""Checksum discovery stays inside the artifact's registered category."""
|
||||
|
||||
fake = FakeFolderPaths(tmp_path / "models")
|
||||
artifact = _artifact("text_encoders", "model.safetensors")
|
||||
unrelated_path = tmp_path / "models" / "vae" / "renamed.safetensors"
|
||||
unrelated_path.parent.mkdir(parents=True)
|
||||
unrelated_path.write_bytes(b"model")
|
||||
downloader = RecordingDownloader()
|
||||
|
||||
resolved = AutoModelResolver(
|
||||
AutoModelCache(fake),
|
||||
downloader,
|
||||
fake,
|
||||
).resolve(artifact)
|
||||
|
||||
assert resolved.source == "downloaded"
|
||||
assert resolved.path != unrelated_path
|
||||
assert len(downloader.requests) == 1
|
||||
|
||||
|
||||
def test_resolver_prefers_canonical_filename_before_renamed_match(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""The direct canonical lookup wins before the broader size-based scan."""
|
||||
|
||||
fake = FakeFolderPaths(tmp_path / "models")
|
||||
artifact = _artifact("text_encoders", "model.safetensors")
|
||||
canonical = canonical_auto_destination(artifact, fake)
|
||||
canonical.parent.mkdir(parents=True)
|
||||
canonical.write_bytes(b"model")
|
||||
renamed = tmp_path / "models" / "text_encoders" / "renamed.safetensors"
|
||||
renamed.write_bytes(b"model")
|
||||
|
||||
assert find_model_artifact(artifact, fake) == canonical
|
||||
|
||||
|
||||
def test_resolver_prefers_recursive_official_filename_before_renamed_match(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Official filenames are searched recursively before alternate names."""
|
||||
|
||||
fake = FakeFolderPaths(tmp_path / "models")
|
||||
artifact = _artifact("text_encoders", "model.safetensors")
|
||||
root = tmp_path / "models" / "text_encoders"
|
||||
renamed = root / "a-renamed.safetensors"
|
||||
official = root / "nested" / artifact.filename
|
||||
official.parent.mkdir(parents=True)
|
||||
renamed.write_bytes(b"model")
|
||||
official.write_bytes(b"model")
|
||||
|
||||
assert find_model_artifact(artifact, fake) == official
|
||||
|
||||
|
||||
def test_artifact_discovery_hashes_only_size_matches(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The broad category scan avoids hashing files with a different byte size."""
|
||||
|
||||
fake = FakeFolderPaths(tmp_path / "models")
|
||||
artifact = _artifact("text_encoders", "model.safetensors")
|
||||
wrong_size = tmp_path / "models" / "text_encoders" / "other.safetensors"
|
||||
wrong_size.parent.mkdir(parents=True)
|
||||
wrong_size.write_bytes(b"different size")
|
||||
hashed_paths: list[Path] = []
|
||||
|
||||
def record_hash(path: Path) -> str:
|
||||
"""Record unexpected hashing while retaining a valid callable shape."""
|
||||
|
||||
hashed_paths.append(path)
|
||||
return artifact.sha256
|
||||
|
||||
monkeypatch.setattr(
|
||||
"simple_syrup.runtime.auto_model_resolver.sha256_file",
|
||||
record_hash,
|
||||
)
|
||||
|
||||
assert find_model_artifact(artifact, fake) is None
|
||||
assert hashed_paths == []
|
||||
|
||||
|
||||
def test_find_model_by_basename_respects_folder_priority(tmp_path: Path) -> None:
|
||||
"""Recursive search prefers earlier ComfyUI model roots."""
|
||||
|
||||
@@ -212,6 +319,7 @@ def test_canonical_destination_rejects_unsafe_subfolder(tmp_path: Path) -> None:
|
||||
source_repo="example/model",
|
||||
description="bad",
|
||||
sha256="abc",
|
||||
file_size_bytes=1,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="not safe"):
|
||||
@@ -274,4 +382,5 @@ def _artifact(folder_name: str, filename: str) -> AutoModelArtifact:
|
||||
source_repo="example/model",
|
||||
description=f"test {filename}",
|
||||
sha256=hashlib.sha256(b"model").hexdigest(),
|
||||
file_size_bytes=len(b"model"),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Tests for ComfyUI CLIP-type compatibility validation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from simple_syrup.runtime.clip_type_support import ComfyClipTypeSupport
|
||||
|
||||
|
||||
def test_clip_type_support_accepts_installed_krea2(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The current Comfy KREA2 enum satisfies loader preflight."""
|
||||
|
||||
comfy_sd = ModuleType("comfy.sd")
|
||||
comfy_sd.CLIPType = SimpleNamespace(KREA2=object()) # type: ignore[attr-defined]
|
||||
monkeypatch.setitem(sys.modules, "comfy.sd", comfy_sd)
|
||||
|
||||
ComfyClipTypeSupport().require("KREA2")
|
||||
|
||||
|
||||
def test_clip_type_support_reports_actionable_update_error(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Older Comfy builds fail explicitly before any artifact download."""
|
||||
|
||||
comfy_sd = ModuleType("comfy.sd")
|
||||
comfy_sd.CLIPType = SimpleNamespace() # type: ignore[attr-defined]
|
||||
monkeypatch.setitem(sys.modules, "comfy.sd", comfy_sd)
|
||||
|
||||
with pytest.raises(RuntimeError, match="Update ComfyUI"):
|
||||
ComfyClipTypeSupport().require("KREA2")
|
||||
@@ -14,7 +14,10 @@ from typing import Any, cast
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from simple_syrup.runtime.patcher_lifecycle import ComfyPatcherLifecycle
|
||||
from simple_syrup.runtime.patcher_lifecycle import (
|
||||
PATCHER_LIFECYCLE,
|
||||
ComfyPatcherLifecycle,
|
||||
)
|
||||
from simple_syrup.runtime.regional_lora.execution_cache import ModelCloneLineage
|
||||
|
||||
|
||||
@@ -64,6 +67,46 @@ def test_real_comfy_anima_lifecycle_regression(
|
||||
_assert_supported_model_mutations_share_one_clone()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("derivation_count", (2, 3, 5))
|
||||
def test_stacked_model_derivations_survive_simultaneous_cyclic_release(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
derivation_count: int,
|
||||
) -> None:
|
||||
"""Keep Comfy on a foreign boundary when any Syrup stack dies together."""
|
||||
|
||||
import comfy.model_management
|
||||
from comfy.model_management import LoadedModel
|
||||
|
||||
encoder = AnimaTEModel_()
|
||||
loader = _patcher(encoder)
|
||||
foreign_boundary = loader.clone()
|
||||
derived_models: list[object] = []
|
||||
current = foreign_boundary
|
||||
for stage in range(derivation_count):
|
||||
current = PATCHER_LIFECYCLE.derive_model(
|
||||
current,
|
||||
(),
|
||||
operation=f"stacked lifecycle regression stage {stage}",
|
||||
)
|
||||
derived_models.append(current)
|
||||
loaded = LoadedModel(current)
|
||||
loaded.real_model = weakref.ref(encoder)
|
||||
monkeypatch.setattr(comfy.model_management, "current_loaded_models", [loaded])
|
||||
|
||||
execution_cycle: list[object] = [*derived_models]
|
||||
execution_cycle.append(execution_cycle)
|
||||
del current, derived_models, execution_cycle
|
||||
gc.collect()
|
||||
with caplog.at_level(logging.INFO):
|
||||
comfy.model_management.cleanup_models_gc()
|
||||
|
||||
assert loaded.model is foreign_boundary
|
||||
assert loaded.is_dead() is False
|
||||
assert "Potential memory leak detected" not in caplog.text
|
||||
assert "WARNING, memory leak" not in caplog.text
|
||||
|
||||
|
||||
def test_clip_alignment_precedes_mutations_after_dynamic_to_static_clone() -> None:
|
||||
"""Mutate the same independently reloaded encoder the returned CLIP executes."""
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
from uuid import UUID
|
||||
|
||||
import comfy.conds
|
||||
@@ -31,6 +31,10 @@ from simple_syrup.runtime.attention_coupling.unet_context import (
|
||||
from simple_syrup.runtime.comfy_conditioning_processing import (
|
||||
COMFY_REGIONAL_CONDITIONING_PROCESSOR,
|
||||
)
|
||||
from simple_syrup.runtime.ppm_negpip_interop import (
|
||||
PpmNegpipInterop,
|
||||
PpmNegpipSemantics,
|
||||
)
|
||||
from simple_syrup.services.attention_coupling_preparation_service import (
|
||||
ATTENTION_COUPLING_PREPARATION_SERVICE,
|
||||
AttentionCouplingPreparation,
|
||||
@@ -89,6 +93,26 @@ class _LinearModelSampling:
|
||||
return 100.0 * (1.0 - float(percent))
|
||||
|
||||
|
||||
class _NegpipRecordingAnimaModel(_RecordingAnimaModel):
|
||||
"""Return a distinct PPM-style value mask for every processed context."""
|
||||
|
||||
def extra_conds(self, **kwargs: Any) -> dict[str, object]:
|
||||
"""Add a binary value mask beside the ordinary cross-attention output."""
|
||||
|
||||
result = super().extra_conds(**kwargs)
|
||||
output = self.outputs[-1]
|
||||
value = int(kwargs["negpip_value"])
|
||||
result["c_ppm_negpip_mask"] = comfy.conds.CONDRegular(
|
||||
torch.full(
|
||||
(*output.shape[:2], 1),
|
||||
value,
|
||||
dtype=torch.int32,
|
||||
device=output.device,
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def test_processor_uses_comfy_conversion_and_model_post_adapter_contexts() -> None:
|
||||
"""Retain weighted padded model outputs in exact positive/negative order."""
|
||||
|
||||
@@ -146,6 +170,47 @@ def test_processor_uses_comfy_conversion_and_model_post_adapter_contexts() -> No
|
||||
assert source_positive_context.shape == (1, 3, 1024)
|
||||
|
||||
|
||||
def test_processor_retains_each_anima_negpip_mask_with_its_scheduled_entry() -> None:
|
||||
"""Keep value semantics attached through Comfy conversion and UUID ownership."""
|
||||
|
||||
model = _NegpipRecordingAnimaModel()
|
||||
preparation = _preparation(
|
||||
positive=(
|
||||
_conditioning(1.0, negpip_value=1),
|
||||
_conditioning(2.0, negpip_value=-1),
|
||||
),
|
||||
negative=(
|
||||
_conditioning(-1.0, negpip_value=-1),
|
||||
_conditioning(-2.0, negpip_value=1),
|
||||
),
|
||||
)
|
||||
negpip = PpmNegpipInterop(
|
||||
PpmNegpipSemantics.ANIMA_VALUE_MASK,
|
||||
lambda *args, **kwargs: (args, kwargs),
|
||||
)
|
||||
|
||||
processed = COMFY_REGIONAL_CONDITIONING_PROCESSOR.process(
|
||||
preparation,
|
||||
model=SimpleNamespace(model=model),
|
||||
noise=torch.zeros((1, 16, 8, 8)),
|
||||
device=torch.device("cpu"),
|
||||
context_validator=ANIMA_REGIONAL_CONTEXT_VALIDATOR,
|
||||
negpip=negpip,
|
||||
)
|
||||
|
||||
entries = (
|
||||
processed.positive.base_context.entries[0],
|
||||
processed.positive.regional_contexts[0].entries[0],
|
||||
processed.negative.base_context.entries[0],
|
||||
processed.negative.regional_contexts[0].entries[0],
|
||||
)
|
||||
assert all(entry.cross_attention_value_multiplier is not None for entry in entries)
|
||||
assert [
|
||||
int(cast(torch.Tensor, entry.cross_attention_value_multiplier)[0, 0, 0].item())
|
||||
for entry in entries
|
||||
] == [1, -1, -1, 1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("sequence_length", "feature_width", "message"),
|
||||
[
|
||||
@@ -347,6 +412,7 @@ def _conditioning(
|
||||
strength: float | None = None,
|
||||
start_percent: float | None = None,
|
||||
end_percent: float | None = None,
|
||||
negpip_value: int | None = None,
|
||||
) -> list[list[object]]:
|
||||
"""Build one small standard conditioning with model-consumed metadata."""
|
||||
|
||||
@@ -357,6 +423,8 @@ def _conditioning(
|
||||
metadata["start_percent"] = start_percent
|
||||
if end_percent is not None:
|
||||
metadata["end_percent"] = end_percent
|
||||
if negpip_value is not None:
|
||||
metadata["negpip_value"] = negpip_value
|
||||
return [
|
||||
[
|
||||
torch.full((1, 3, ANIMA_CONTEXT_FEATURE_WIDTH), value),
|
||||
|
||||
@@ -182,11 +182,16 @@ def test_global_call_uses_one_full_source_reduced_model_layout(
|
||||
*,
|
||||
args: dict[str, Any],
|
||||
layout: SpatialBatchLayout,
|
||||
project_canvas_reference_latents: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Capture and apply the global model-argument layout."""
|
||||
|
||||
layouts.append(layout)
|
||||
return transform(args=args, layout=layout)
|
||||
return transform(
|
||||
args=args,
|
||||
layout=layout,
|
||||
project_canvas_reference_latents=project_canvas_reference_latents,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
wrapper_module,
|
||||
@@ -389,8 +394,8 @@ def test_weighted_correction_formula_is_exact_for_both_local_fusion_modes(
|
||||
assert torch.allclose(output[:, :, 1::2], torch.full((1, 1, 8, 32), 0.5))
|
||||
|
||||
|
||||
def test_local_and_global_calls_receive_complete_reference_latents() -> None:
|
||||
"""Keep independent reference images intact through both spatial views."""
|
||||
def test_local_and_global_calls_project_canvas_reference_latents() -> None:
|
||||
"""Give every Contextual Diffusion view its spatially aligned reference."""
|
||||
|
||||
reference = torch.arange(1 * 4 * 16 * 32, dtype=torch.float32).reshape(
|
||||
(1, 4, 16, 32)
|
||||
@@ -419,8 +424,16 @@ def test_local_and_global_calls_receive_complete_reference_latents() -> None:
|
||||
)
|
||||
|
||||
assert len(received) == 2
|
||||
assert torch.equal(received[0], torch.cat((reference, reference), dim=0))
|
||||
assert torch.equal(received[1], reference)
|
||||
assert torch.equal(
|
||||
received[0],
|
||||
torch.cat((reference[..., :16], reference[..., 16:]), dim=0),
|
||||
)
|
||||
expected_global = torch.nn.functional.interpolate(
|
||||
reference.reshape(-1, 1, 16, 32),
|
||||
size=(8, 16),
|
||||
mode="nearest-exact",
|
||||
).reshape(1, 4, 8, 16)
|
||||
assert torch.equal(received[1], expected_global)
|
||||
|
||||
|
||||
def test_one_tile_plan_delegates_to_one_original_evaluation() -> None:
|
||||
|
||||
@@ -140,6 +140,40 @@ def test_positive_conditioning_batch_selects_by_segment_index() -> None:
|
||||
assert [call.negative for call in sampler.sample_calls] == [negative, negative]
|
||||
|
||||
|
||||
def test_detailer_keeps_prompt_control_hooks_peer_scoped_by_segment() -> None:
|
||||
"""Preserve each scheduled LoRA hook on only its selected face conditioning."""
|
||||
|
||||
sampler = _FakeSampler()
|
||||
first = _segment(CropRegion(0, 0, 4, 4), BoundingBox(1, 1, 3, 3))
|
||||
second = _segment(CropRegion(4, 4, 8, 8), BoundingBox(5, 5, 7, 7))
|
||||
first_hooks = object()
|
||||
second_hooks = object()
|
||||
first_conditioning = [["first", {"hooks": first_hooks}]]
|
||||
second_conditioning = [["second", {"hooks": second_hooks}]]
|
||||
service = _service(sampler)
|
||||
|
||||
service.detail(
|
||||
_image(),
|
||||
_segs(first, second),
|
||||
object(),
|
||||
object(),
|
||||
ConditioningBatch((first_conditioning, second_conditioning)),
|
||||
[],
|
||||
**_settings(),
|
||||
)
|
||||
|
||||
assert sampler.sample_calls[0].positive is first_conditioning
|
||||
assert sampler.sample_calls[1].positive is second_conditioning
|
||||
selected_first = cast(list[list[object]], sampler.sample_calls[0].positive)
|
||||
selected_second = cast(list[list[object]], sampler.sample_calls[1].positive)
|
||||
first_metadata = selected_first[0][1]
|
||||
second_metadata = selected_second[0][1]
|
||||
assert isinstance(first_metadata, dict)
|
||||
assert isinstance(second_metadata, dict)
|
||||
assert first_metadata["hooks"] is first_hooks
|
||||
assert second_metadata["hooks"] is second_hooks
|
||||
|
||||
|
||||
def test_negative_conditioning_batch_selects_by_segment_index() -> None:
|
||||
"""A negative batch varies by SEG while normal positive broadcasts."""
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Tests for shared loaded diffusion-model metadata inspection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from simple_syrup.runtime.diffusion_model_metadata import (
|
||||
DiffusionModelMetadata,
|
||||
DiffusionModelMetadataInspector,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _ModelConfig:
|
||||
"""Expose one fake tensor-derived UNet configuration."""
|
||||
|
||||
unet_config: object
|
||||
|
||||
|
||||
class _ModelPatcher:
|
||||
"""Expose a model config through ComfyUI's model-patcher surface."""
|
||||
|
||||
def __init__(self, unet_config: object) -> None:
|
||||
"""Store the fake UNet configuration."""
|
||||
|
||||
self._config = _ModelConfig(unet_config)
|
||||
|
||||
def get_model_object(self, name: str) -> object:
|
||||
"""Return only the requested model configuration."""
|
||||
|
||||
assert name == "model_config"
|
||||
return self._config
|
||||
|
||||
|
||||
def test_metadata_inspector_normalizes_krea_architecture() -> None:
|
||||
"""Krea detection uses loaded tensor metadata rather than its filename."""
|
||||
|
||||
result = DiffusionModelMetadataInspector().inspect(
|
||||
_ModelPatcher({"image_model": "krea2", "context_in_dim": 30_720})
|
||||
)
|
||||
|
||||
assert result == DiffusionModelMetadata("krea2", 30_720)
|
||||
|
||||
|
||||
def test_metadata_inspector_rejects_unavailable_and_malformed_surfaces() -> None:
|
||||
"""Dynamic host values fail closed when structural metadata is unavailable."""
|
||||
|
||||
inspector = DiffusionModelMetadataInspector()
|
||||
|
||||
assert inspector.inspect(object()) is None
|
||||
assert inspector.inspect(_ModelPatcher("not a mapping")) is None
|
||||
@@ -290,4 +290,5 @@ def _artifact() -> AutoModelArtifact:
|
||||
source_repo="example/auto",
|
||||
description="test encoder",
|
||||
sha256="0" * 64,
|
||||
file_size_bytes=0,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Verify pre-derivation Comfy MODEL selection for global prompt hooks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from comfy.hooks import HookGroup
|
||||
|
||||
from simple_syrup.domain.conditioning_batch import ConditioningBatch
|
||||
from simple_syrup.runtime.global_hook_model_resolver import GlobalHookModelResolver
|
||||
|
||||
|
||||
class _Model:
|
||||
"""Expose the dynamic-model boundary used by Comfy's CFG guider."""
|
||||
|
||||
def __init__(self, *, dynamic: bool, delegate: object | None = None) -> None:
|
||||
"""Retain configured dynamic state and delegate result."""
|
||||
|
||||
self.dynamic = dynamic
|
||||
self.delegate = delegate
|
||||
self.delegate_calls = 0
|
||||
|
||||
def is_dynamic(self) -> bool:
|
||||
"""Return the configured Comfy model mode."""
|
||||
|
||||
return self.dynamic
|
||||
|
||||
def get_non_dynamic_delegate(self) -> object:
|
||||
"""Return and record the configured static delegate."""
|
||||
|
||||
self.delegate_calls += 1
|
||||
return self.delegate
|
||||
|
||||
|
||||
def test_unhooked_global_entry_preserves_dynamic_model() -> None:
|
||||
"""Leave regional-only hooks to the existing custom regional runtime."""
|
||||
|
||||
model = _Model(dynamic=True)
|
||||
conditioning = ConditioningBatch((_conditioning(), _conditioning(HookGroup())))
|
||||
|
||||
resolved = GlobalHookModelResolver().resolve(
|
||||
model,
|
||||
positive=conditioning,
|
||||
negative=conditioning,
|
||||
)
|
||||
|
||||
assert resolved is model
|
||||
assert model.delegate_calls == 0
|
||||
|
||||
|
||||
def test_global_hook_preserves_already_static_model() -> None:
|
||||
"""Avoid unnecessary model replacement when hook execution is already static."""
|
||||
|
||||
model = _Model(dynamic=False)
|
||||
|
||||
resolved = GlobalHookModelResolver().resolve(
|
||||
model,
|
||||
positive=_conditioning(HookGroup()),
|
||||
negative=_conditioning(HookGroup()),
|
||||
)
|
||||
|
||||
assert resolved is model
|
||||
assert model.delegate_calls == 0
|
||||
|
||||
|
||||
def test_global_hook_selects_static_delegate_before_regional_derivation() -> None:
|
||||
"""Bind regional wrappers to the same static graph Comfy samples with hooks."""
|
||||
|
||||
delegate = _Model(dynamic=False)
|
||||
model = _Model(dynamic=True, delegate=delegate)
|
||||
|
||||
resolved = GlobalHookModelResolver().resolve(
|
||||
model,
|
||||
positive=ConditioningBatch(
|
||||
(_conditioning(HookGroup()), _conditioning(HookGroup()))
|
||||
),
|
||||
negative=ConditioningBatch(
|
||||
(_conditioning(HookGroup()), _conditioning(HookGroup()))
|
||||
),
|
||||
)
|
||||
|
||||
assert resolved is delegate
|
||||
assert model.delegate_calls == 1
|
||||
|
||||
|
||||
def _conditioning(hooks: HookGroup | None = None) -> list[list[object]]:
|
||||
"""Return one standard conditioning with optional model hooks."""
|
||||
|
||||
metadata: dict[str, object] = {}
|
||||
if hooks is not None:
|
||||
metadata["hooks"] = hooks
|
||||
return [["embedding", metadata]]
|
||||
@@ -29,13 +29,6 @@ def test_matrix_covers_global_strength_regional_and_duplicate_placement() -> Non
|
||||
1.0,
|
||||
1.0,
|
||||
]
|
||||
assert [case.expect_overlap_rejection for case in definitions] == [
|
||||
False,
|
||||
False,
|
||||
False,
|
||||
False,
|
||||
True,
|
||||
]
|
||||
|
||||
|
||||
def test_prompt_renderer_places_primary_adapter_only_in_declared_segments() -> None:
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Verify exact user-prompt global LoRA proof graph mutations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tools.run_global_prompt_lora_proof import (
|
||||
ProofCase,
|
||||
build_case_graph,
|
||||
cases,
|
||||
render_global_first_prompt,
|
||||
)
|
||||
|
||||
|
||||
def test_prompt_renderer_preserves_named_separators_and_places_both_scopes() -> None:
|
||||
"""Keep global-first layout while preserving the user's named regions."""
|
||||
|
||||
rendered = render_global_first_prompt(
|
||||
"global text[SEP|Taffy]left text[SEP|Anise]right text",
|
||||
global_tag="<lora:shared:0.5>",
|
||||
regional_tag="<lora:shared:0.8>",
|
||||
)
|
||||
|
||||
assert rendered == (
|
||||
"<lora:shared:0.5>\nglobal text"
|
||||
"[SEP|Taffy]<lora:shared:0.8>\nleft text"
|
||||
"[SEP|Anise]right text"
|
||||
)
|
||||
|
||||
|
||||
def test_matrix_covers_same_lora_turbo_tiled_and_contextual() -> None:
|
||||
"""Keep all requested managed proof variants explicit and ordered."""
|
||||
|
||||
definitions = cases()
|
||||
|
||||
assert [case.case_id for case in definitions] == [
|
||||
"sdxl-global-and-regional-same-lora",
|
||||
"anima-global-and-regional-same-lora",
|
||||
"anima-turbo-global-arcane-regional-tiled",
|
||||
"anima-turbo-global-arcane-regional-contextual",
|
||||
]
|
||||
assert definitions[0].global_tag == definitions[0].regional_tag
|
||||
assert "ArcaneViolet" in definitions[1].global_tag
|
||||
assert "ArcaneViolet" in definitions[1].regional_tag
|
||||
assert [case.turbo for case in definitions] == [False, False, True, True]
|
||||
assert [case.contextual for case in definitions] == [False, False, False, True]
|
||||
assert definitions[0].region_mask_feather == 10
|
||||
assert {case.region_mask_feather for case in definitions[1:]} == {64}
|
||||
|
||||
|
||||
def test_turbo_contextual_graph_uses_appropriate_sampling_contract() -> None:
|
||||
"""Apply Turbo's low-step CFG-one contract to full and contextual stages."""
|
||||
|
||||
template = _anima_template()
|
||||
case = ProofCase(
|
||||
"fixture",
|
||||
"anima",
|
||||
"<lora:turbo:0.7>",
|
||||
"<lora:regional:0.8>",
|
||||
turbo=True,
|
||||
contextual=True,
|
||||
)
|
||||
|
||||
graph, save_ids = build_case_graph(template, case, run_id="run")
|
||||
|
||||
assert save_ids == ("proof:source", "proof:refinement")
|
||||
for node_id in (
|
||||
"anima-prompt-region:ksampler",
|
||||
"anima-diffusion-upscale:ksampler",
|
||||
):
|
||||
inputs = graph[node_id]["inputs"]
|
||||
assert isinstance(inputs, dict)
|
||||
assert inputs["steps"] == 10
|
||||
assert inputs["cfg"] == 1.0
|
||||
assert inputs["sampler_name"] == "euler"
|
||||
assert inputs["scheduler"] == "simple"
|
||||
assert inputs["region_mask_feather"] == 64
|
||||
refinement = graph["anima-diffusion-upscale:ksampler"]
|
||||
assert refinement["class_type"] == "SimpleSyrup.KSamplerAttentionCouplingContextual"
|
||||
refinement_inputs = refinement["inputs"]
|
||||
assert isinstance(refinement_inputs, dict)
|
||||
assert "latent_context_size" in refinement_inputs
|
||||
assert "latent_tile_width" not in refinement_inputs
|
||||
|
||||
|
||||
def test_replayed_multiselect_mask_values_are_literal_wrapped() -> None:
|
||||
"""Keep executed multiselect lists from being reinterpreted as graph links."""
|
||||
|
||||
template = _anima_template()
|
||||
template["mask-loader"] = {
|
||||
"class_type": "SimpleSyrup.LoadMaskBatch",
|
||||
"inputs": {"image": ["left.png", "right.png"], "channel": "red"},
|
||||
}
|
||||
case = ProofCase("fixture", "anima", "<lora:g:1>", "<lora:r:1>")
|
||||
|
||||
graph, _save_ids = build_case_graph(template, case, run_id="run")
|
||||
|
||||
assert graph["mask-loader"]["inputs"] == {
|
||||
"image": {"__value__": ["left.png", "right.png"]},
|
||||
"channel": "red",
|
||||
}
|
||||
|
||||
|
||||
def _anima_template() -> dict[str, dict[str, object]]:
|
||||
"""Return one minimal expanded Anima graph accepted by the mutator."""
|
||||
|
||||
return {
|
||||
"anima-prompt-region:positive_prompt": {
|
||||
"class_type": "PrimitiveStringMultiline",
|
||||
"inputs": {"value": "global[SEP|Taffy]left[SEP|Anise]right"},
|
||||
},
|
||||
"anima-diffusion-upscale:positive_prompt": {
|
||||
"class_type": "PrimitiveStringMultiline",
|
||||
"inputs": {"value": "global[SEP|Taffy]left[SEP|Anise]right"},
|
||||
},
|
||||
"anima-prompt-region:ksampler": {
|
||||
"class_type": "SimpleSyrup.KSamplerAttentionCoupling",
|
||||
"inputs": {},
|
||||
},
|
||||
"anima-diffusion-upscale:ksampler": {
|
||||
"class_type": "SimpleSyrup.KSamplerAttentionCouplingTiled",
|
||||
"inputs": {
|
||||
"latent_tile_width": 128,
|
||||
"latent_tile_height": 128,
|
||||
"latent_tile_overlap": 16,
|
||||
"latent_tile_batch_size": 4,
|
||||
},
|
||||
},
|
||||
"anima-prompt-region:vae_decode": {
|
||||
"class_type": "VAEDecode",
|
||||
"inputs": {},
|
||||
},
|
||||
"anima-diffusion-upscale:vae_decode": {
|
||||
"class_type": "VAEDecode",
|
||||
"inputs": {},
|
||||
},
|
||||
"__sugarcubes_cube_output__:fixture": {
|
||||
"class_type": "SugarCubes.CubeOutput",
|
||||
"inputs": {},
|
||||
},
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user