Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,45 @@
|
||||
## [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)
|
||||
|
||||
|
||||
|
||||
@@ -189,6 +189,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.9.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "simple-syrup-comfyui",
|
||||
"version": "1.7.0",
|
||||
"version": "1.9.2",
|
||||
"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.9.2",
|
||||
"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.9.2"
|
||||
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.9.2"
|
||||
|
||||
__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
|
||||
|
||||
@@ -135,6 +135,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 +150,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)
|
||||
@@ -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",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from dataclasses import dataclass
|
||||
|
||||
from ..model_attention_patch_mutations import ModelAttn2PatchesMutation
|
||||
from ..patcher_lifecycle import PATCHER_LIFECYCLE, ModelMutation
|
||||
from ..ppm_negpip_interop import PpmNegpipInterop
|
||||
from ..regional_lora.standard_unet_native_admission import (
|
||||
StandardUnetNativeLoraAdmission,
|
||||
)
|
||||
@@ -43,6 +44,7 @@ class StandardUnetAttentionBackend:
|
||||
model: object,
|
||||
state: StandardUnetAttentionState,
|
||||
admission: StandardUnetNativeLoraAdmission,
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> StandardUnetAttentionModel:
|
||||
"""Return a direct MODEL child containing only the paired UNet patches."""
|
||||
|
||||
@@ -55,6 +57,8 @@ class StandardUnetAttentionBackend:
|
||||
"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)
|
||||
@@ -68,6 +72,7 @@ class StandardUnetAttentionBackend:
|
||||
admission,
|
||||
attention_phase,
|
||||
template,
|
||||
negpip,
|
||||
),
|
||||
)
|
||||
if template is not None
|
||||
@@ -85,6 +90,7 @@ class StandardUnetAttentionBackend:
|
||||
ModelAttn2PatchesMutation(
|
||||
patches.input_patch,
|
||||
patches.output_patch,
|
||||
(() if negpip is None else (negpip.attention_patch,)),
|
||||
),
|
||||
)
|
||||
derived = PATCHER_LIFECYCLE.derive_model(
|
||||
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
*,
|
||||
|
||||
@@ -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 (
|
||||
@@ -44,6 +45,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,6 +53,8 @@ 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(
|
||||
@@ -89,6 +93,7 @@ class FullContextAnimaAttentionBackend:
|
||||
surface,
|
||||
attention,
|
||||
composition=composition,
|
||||
negpip=negpip,
|
||||
),
|
||||
)
|
||||
derived = PATCHER_LIFECYCLE.derive_model(
|
||||
|
||||
@@ -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}.")
|
||||
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -218,6 +218,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,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()
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from simple_syrup.nodes.grounded_sam_model_info import GroundedSAMModelInfo
|
||||
|
||||
@@ -20,9 +22,25 @@ def test_model_info_node_contract_constants() -> None:
|
||||
assert GroundedSAMModelInfo.CATEGORY == "SimpleSyrup/Masking"
|
||||
|
||||
|
||||
def test_model_info_node_declares_expected_inputs() -> None:
|
||||
def test_model_info_node_declares_expected_inputs(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Model info node exposes model selectors."""
|
||||
|
||||
class FakeChoices:
|
||||
"""Return the known downloadable selections for declaration tests."""
|
||||
|
||||
def sam_choices(self) -> list[str]:
|
||||
"""Return the expected SAM choice."""
|
||||
|
||||
return ["sam_hq_vit_b (379MB)"]
|
||||
|
||||
def grounding_dino_choices(self) -> list[str]:
|
||||
"""Return the expected GroundingDINO choice."""
|
||||
|
||||
return ["GroundingDINO_SwinT_OGC (694MB)"]
|
||||
|
||||
monkeypatch.setattr(GroundedSAMModelInfo, "_choices", cast(Any, FakeChoices()))
|
||||
input_types: dict[str, dict[str, tuple[Any, ...]]] = (
|
||||
GroundedSAMModelInfo.INPUT_TYPES()
|
||||
)
|
||||
@@ -33,6 +51,38 @@ def test_model_info_node_declares_expected_inputs() -> None:
|
||||
assert "GroundingDINO_SwinT_OGC (694MB)" in required["grounding_dino_model"][0]
|
||||
|
||||
|
||||
def test_model_info_node_uses_settings_aware_choices() -> None:
|
||||
"""Model metadata selectors follow the downloadable-models preference."""
|
||||
|
||||
class FakeChoices:
|
||||
"""Return the local-only choices supplied by settings policy."""
|
||||
|
||||
def sam_choices(self) -> list[str]:
|
||||
"""Return the available SAM choices."""
|
||||
|
||||
return ["local-sam"]
|
||||
|
||||
def grounding_dino_choices(self) -> list[str]:
|
||||
"""Return the available GroundingDINO choices."""
|
||||
|
||||
return ["local-dino"]
|
||||
|
||||
def reject_sentinel(self, selection: str) -> None:
|
||||
"""Accept the deterministic test selections."""
|
||||
|
||||
del selection
|
||||
|
||||
original = GroundedSAMModelInfo._choices
|
||||
GroundedSAMModelInfo._choices = cast(Any, FakeChoices())
|
||||
try:
|
||||
required = GroundedSAMModelInfo.INPUT_TYPES()["required"]
|
||||
finally:
|
||||
GroundedSAMModelInfo._choices = original
|
||||
|
||||
assert required["sam_model"][0] == ["local-sam"]
|
||||
assert required["grounding_dino_model"][0] == ["local-dino"]
|
||||
|
||||
|
||||
def test_model_info_node_delegates_to_metadata_provider() -> None:
|
||||
"""Node execution delegates metadata creation to its metadata provider."""
|
||||
|
||||
@@ -44,12 +94,23 @@ def test_model_info_node_delegates_to_metadata_provider() -> None:
|
||||
|
||||
return f"{sam_model}|{grounding_dino_model}"
|
||||
|
||||
class FakeChoices:
|
||||
"""Accept all model selections while exercising metadata delegation."""
|
||||
|
||||
def reject_sentinel(self, selection: str) -> None:
|
||||
"""Accept the deterministic test selections."""
|
||||
|
||||
del selection
|
||||
|
||||
node = GroundedSAMModelInfo()
|
||||
original = GroundedSAMModelInfo._metadata
|
||||
original_choices = GroundedSAMModelInfo._choices
|
||||
GroundedSAMModelInfo._metadata = FakeMetadata() # type: ignore[assignment]
|
||||
GroundedSAMModelInfo._choices = cast(Any, FakeChoices())
|
||||
try:
|
||||
result = node.describe("sam", "dino")
|
||||
finally:
|
||||
GroundedSAMModelInfo._metadata = original
|
||||
GroundedSAMModelInfo._choices = original_choices
|
||||
|
||||
assert result == ("sam|dino",)
|
||||
|
||||
@@ -28,9 +28,21 @@ def test_grounding_dino_model_loader_contract() -> None:
|
||||
assert GroundingDINOModelLoader.CATEGORY == "SimpleSyrup/Masking"
|
||||
|
||||
|
||||
def test_grounding_dino_model_loader_declares_expected_inputs() -> None:
|
||||
def test_grounding_dino_model_loader_declares_expected_inputs(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""GroundingDINO loader makes text encoder selection explicit."""
|
||||
|
||||
def catalog_choices() -> list[str]:
|
||||
"""Return the catalog choice expected by this declaration test."""
|
||||
|
||||
return ["GroundingDINO_SwinT_OGC (694MB)"]
|
||||
|
||||
monkeypatch.setattr(
|
||||
GroundingDINOModelLoader._choices,
|
||||
"grounding_dino_choices",
|
||||
catalog_choices,
|
||||
)
|
||||
input_types: dict[str, dict[str, tuple[Any, ...]]] = (
|
||||
GroundingDINOModelLoader.INPUT_TYPES()
|
||||
)
|
||||
|
||||
@@ -41,7 +41,10 @@ class _FakeLegacyNode:
|
||||
{"default": "hello", "tooltip": "Text to delegate."},
|
||||
),
|
||||
},
|
||||
"hidden": {"prompt": "PROMPT"},
|
||||
"hidden": {
|
||||
"prompt": "PROMPT",
|
||||
"ignored": "UNSUPPORTED_SECRET_SENTINEL",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, text: str, prompt: object | None = None) -> tuple[str]:
|
||||
@@ -70,6 +73,7 @@ def test_legacy_node_v3_adapter_builds_schema() -> None:
|
||||
assert schema.category == "SimpleSyrup/Test"
|
||||
assert schema.inputs[0].id == "text"
|
||||
assert schema.inputs[0].tooltip == "Text to delegate."
|
||||
assert len(schema.hidden) == 1
|
||||
assert schema.hidden[0].value == "PROMPT"
|
||||
assert schema.outputs[0].id == "result"
|
||||
assert schema.outputs[0].tooltip == "Delegated result."
|
||||
|
||||
@@ -11,6 +11,7 @@ from typing import Any, cast
|
||||
import pytest
|
||||
|
||||
from simple_syrup.nodes.load_ultralytics_model import LoadUltralyticsModel
|
||||
from simple_syrup.runtime.model_downloads import ProgressReporter
|
||||
from simple_syrup.runtime.ultralytics_loader import LoadedUltralyticsDetector
|
||||
|
||||
|
||||
@@ -50,8 +51,13 @@ class _FakeLoaderService:
|
||||
|
||||
return ["model.pt"]
|
||||
|
||||
def load(self, model_name: str) -> LoadedUltralyticsDetector:
|
||||
def load(
|
||||
self,
|
||||
model_name: str,
|
||||
progress: ProgressReporter | None = None,
|
||||
) -> LoadedUltralyticsDetector:
|
||||
"""Return deterministic loaded outputs."""
|
||||
|
||||
del progress
|
||||
assert model_name == "model.pt"
|
||||
return LoadedUltralyticsDetector(cast(Any, "native"), "bbox", "segm")
|
||||
|
||||
@@ -16,10 +16,13 @@ from simple_syrup.runtime.model_catalog import (
|
||||
BERT_ENTRY,
|
||||
GROUNDING_DINO_ENTRIES,
|
||||
SAM_ENTRIES,
|
||||
ULTRALYTICS_ENTRIES,
|
||||
get_grounding_dino_entry,
|
||||
get_sam_entry,
|
||||
get_ultralytics_entry,
|
||||
grounding_dino_choices,
|
||||
sam_choices,
|
||||
ultralytics_choices,
|
||||
)
|
||||
|
||||
|
||||
@@ -54,6 +57,77 @@ def test_catalog_choices_are_deterministic() -> None:
|
||||
assert grounding_dino_choices() == [
|
||||
entry.display_name for entry in GROUNDING_DINO_ENTRIES
|
||||
]
|
||||
assert ultralytics_choices() == [
|
||||
entry.display_name for entry in ULTRALYTICS_ENTRIES
|
||||
]
|
||||
|
||||
|
||||
def test_ultralytics_catalog_has_pinned_verified_anzhc_checkpoints() -> None:
|
||||
"""Curated Anzhc models are revision-pinned, verified, and task-foldered."""
|
||||
|
||||
anzhc_entries = tuple(
|
||||
entry
|
||||
for entry in ULTRALYTICS_ENTRIES
|
||||
if entry.source_repo == "Anzhc/Anzhcs_YOLOs"
|
||||
)
|
||||
|
||||
assert len(anzhc_entries) == 15
|
||||
assert all(entry.source_repo == "Anzhc/Anzhcs_YOLOs" for entry in anzhc_entries)
|
||||
assert all(len(entry.artifacts) == 1 for entry in anzhc_entries)
|
||||
assert all(
|
||||
artifact.source_url.startswith(
|
||||
"https://huggingface.co/Anzhc/Anzhcs_YOLOs/resolve/"
|
||||
"f5a2306d7fed4f3cfc26c25ff1ab2e3f3cfce855/"
|
||||
)
|
||||
for entry in anzhc_entries
|
||||
for artifact in entry.artifacts
|
||||
)
|
||||
assert all(
|
||||
artifact.folder_name == "ultralytics_segm"
|
||||
and artifact.sha256 is not None
|
||||
and len(artifact.sha256) == 64
|
||||
for entry in anzhc_entries
|
||||
for artifact in entry.artifacts
|
||||
)
|
||||
assert all(
|
||||
"Drones" not in artifact.filename
|
||||
and "Score" not in artifact.filename
|
||||
and "Breast size" not in artifact.filename
|
||||
for entry in anzhc_entries
|
||||
for artifact in entry.artifacts
|
||||
)
|
||||
|
||||
|
||||
def test_ultralytics_catalog_has_verified_adetailer_and_anime_models() -> None:
|
||||
"""ADetailer and anime face checkpoints have compatible curated metadata."""
|
||||
|
||||
assert len(ULTRALYTICS_ENTRIES) == 22
|
||||
|
||||
face = get_ultralytics_entry("bingsu_face_yolov8n_v2")
|
||||
hand = get_ultralytics_entry("bingsu_hand_yolov8s")
|
||||
person = get_ultralytics_entry("bingsu_person_yolov8s_seg")
|
||||
anime_face = get_ultralytics_entry("fuyucchi_yolov8x6_animeface")
|
||||
|
||||
assert face.artifacts[0].folder_name == "ultralytics_bbox"
|
||||
assert hand.artifacts[0].folder_name == "ultralytics_bbox"
|
||||
assert person.artifacts[0].folder_name == "ultralytics_segm"
|
||||
assert anime_face.artifacts[0].folder_name == "ultralytics_bbox"
|
||||
assert face.source_repo == "Bingsu/adetailer"
|
||||
assert face.license_note == "Apache-2.0"
|
||||
assert (
|
||||
"/resolve/53cc19de382014514d9d4038601d261a7faa9b7b/"
|
||||
in face.artifacts[0].source_url
|
||||
)
|
||||
assert anime_face.source_repo == "Fuyucchi/yolov8_animeface"
|
||||
assert anime_face.license_note == "AGPL-3.0"
|
||||
assert "/resolve/b0841ce930453c0f23ceb8086d6554c17de5fe4a/" in (
|
||||
anime_face.artifacts[0].source_url
|
||||
)
|
||||
assert all(
|
||||
artifact.sha256 is not None and len(artifact.sha256) == 64
|
||||
for entry in (face, hand, person, anime_face)
|
||||
for artifact in entry.artifacts
|
||||
)
|
||||
|
||||
|
||||
def test_catalog_lookup_rejects_unknown_selection() -> None:
|
||||
|
||||
+23
-37
@@ -7,7 +7,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -40,13 +39,13 @@ def test_downloadable_mode_includes_catalog_entries(tmp_path: Path) -> None:
|
||||
|
||||
service = ModelChoiceService(
|
||||
FakeSettingsRepository(show_downloadable_models=True),
|
||||
fake_folder_paths(tmp_path),
|
||||
)
|
||||
|
||||
assert "sam_vit_b (375MB)" in service.sam_choices()
|
||||
assert "GroundingDINO_SwinT_OGC (694MB)" in service.grounding_dino_choices()
|
||||
assert "vitmatte-small-composition-1k" in service.vitmatte_choices()
|
||||
assert "wd-eva02-large-tagger-v3" in service.wd14_tagger_choices()
|
||||
assert "Bingsu Hand YOLOv8n (6.23MB)" in service.ultralytics_choices()
|
||||
|
||||
|
||||
def test_local_only_mode_returns_sentinels_when_no_models_exist(
|
||||
@@ -60,23 +59,22 @@ def test_local_only_mode_returns_sentinels_when_no_models_exist(
|
||||
assert service.grounding_dino_choices() == [NO_LOCAL_GROUNDING_DINO_MODELS]
|
||||
assert service.vitmatte_choices() == [NO_LOCAL_VITMATTE_MODELS]
|
||||
assert service.wd14_tagger_choices() == [NO_LOCAL_WD14_TAGGER_MODELS]
|
||||
assert service.ultralytics_choices() == []
|
||||
|
||||
|
||||
def test_sam_local_only_lists_installed_catalog_artifacts(tmp_path: Path) -> None:
|
||||
"""SAM local-only mode lists installed known checkpoint files."""
|
||||
def test_hidden_catalog_mode_excludes_installed_sam_artifacts(tmp_path: Path) -> None:
|
||||
"""Catalog mode hides installed SAM entries when disabled."""
|
||||
|
||||
(tmp_path / "models" / "sams").mkdir(parents=True)
|
||||
(tmp_path / "models" / "sams" / "sam_vit_b_01ec64.pth").write_bytes(b"sam")
|
||||
|
||||
choices = local_only_service(tmp_path).sam_choices()
|
||||
|
||||
assert choices == ["sam_vit_b (375MB)"]
|
||||
assert local_only_service(tmp_path).sam_choices() == [NO_LOCAL_SAM_MODELS]
|
||||
|
||||
|
||||
def test_grounding_dino_local_only_requires_complete_artifacts(
|
||||
def test_hidden_catalog_mode_excludes_installed_grounding_dino_artifacts(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""GroundingDINO local-only mode excludes partial config/checkpoint pairs."""
|
||||
"""Catalog mode hides installed GroundingDINO entries when disabled."""
|
||||
|
||||
model_dir = tmp_path / "models" / "grounding-dino"
|
||||
model_dir.mkdir(parents=True)
|
||||
@@ -84,37 +82,35 @@ def test_grounding_dino_local_only_requires_complete_artifacts(
|
||||
(model_dir / "groundingdino_swint_ogc.pth").write_bytes(b"dino")
|
||||
(model_dir / "GroundingDINO_SwinB.cfg.py").write_text("", encoding="utf-8")
|
||||
|
||||
choices = local_only_service(tmp_path).grounding_dino_choices()
|
||||
|
||||
assert choices == ["GroundingDINO_SwinT_OGC (694MB)"]
|
||||
assert local_only_service(tmp_path).grounding_dino_choices() == [
|
||||
NO_LOCAL_GROUNDING_DINO_MODELS
|
||||
]
|
||||
|
||||
|
||||
def test_vitmatte_local_only_lists_valid_canonical_directory(
|
||||
def test_hidden_catalog_mode_excludes_installed_vitmatte_directory(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""ViTMatte local-only mode accepts canonical SimpleSyrup directories."""
|
||||
"""Catalog mode hides installed ViTMatte entries when disabled."""
|
||||
|
||||
create_vitmatte_snapshot(
|
||||
tmp_path / "models" / "vitmatte" / "vitmatte-small-composition-1k"
|
||||
)
|
||||
|
||||
choices = local_only_service(tmp_path).vitmatte_choices()
|
||||
|
||||
assert choices == ["vitmatte-small-composition-1k"]
|
||||
assert local_only_service(tmp_path).vitmatte_choices() == [NO_LOCAL_VITMATTE_MODELS]
|
||||
|
||||
|
||||
def test_vitmatte_local_only_lists_layerstyle_directory(tmp_path: Path) -> None:
|
||||
"""ViTMatte local-only mode accepts LayerStyle-compatible directories."""
|
||||
def test_hidden_catalog_mode_excludes_layerstyle_vitmatte_directory(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Catalog mode hides LayerStyle-compatible entries when disabled."""
|
||||
|
||||
create_vitmatte_snapshot(tmp_path / "models" / "vitmatte-base-composition-1k")
|
||||
|
||||
choices = local_only_service(tmp_path).vitmatte_choices()
|
||||
|
||||
assert choices == ["vitmatte-base-composition-1k"]
|
||||
assert local_only_service(tmp_path).vitmatte_choices() == [NO_LOCAL_VITMATTE_MODELS]
|
||||
|
||||
|
||||
def test_wd14_local_only_requires_complete_artifacts(tmp_path: Path) -> None:
|
||||
"""WD14 local-only mode excludes partial ONNX/CSV pairs."""
|
||||
def test_hidden_catalog_mode_excludes_installed_wd14_artifacts(tmp_path: Path) -> None:
|
||||
"""Catalog mode hides installed WD14 entries when disabled."""
|
||||
|
||||
model_dir = tmp_path / "models" / "wd14_tagger"
|
||||
model_dir.mkdir(parents=True)
|
||||
@@ -125,9 +121,9 @@ def test_wd14_local_only_requires_complete_artifacts(tmp_path: Path) -> None:
|
||||
)
|
||||
(model_dir / "wd-vit-tagger-v3.onnx").write_bytes(b"onnx")
|
||||
|
||||
choices = local_only_service(tmp_path).wd14_tagger_choices()
|
||||
|
||||
assert choices == ["wd-eva02-large-tagger-v3"]
|
||||
assert local_only_service(tmp_path).wd14_tagger_choices() == [
|
||||
NO_LOCAL_WD14_TAGGER_MODELS
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -157,19 +153,9 @@ def local_only_service(tmp_path: Path) -> ModelChoiceService:
|
||||
|
||||
return ModelChoiceService(
|
||||
FakeSettingsRepository(show_downloadable_models=False),
|
||||
fake_folder_paths(tmp_path),
|
||||
)
|
||||
|
||||
|
||||
def fake_folder_paths(tmp_path: Path) -> ModuleType:
|
||||
"""Create a minimal fake Comfy folder_paths module."""
|
||||
|
||||
module = ModuleType("folder_paths")
|
||||
module.models_dir = str(tmp_path / "models") # type: ignore[attr-defined]
|
||||
module.folder_names_and_paths = {} # type: ignore[attr-defined]
|
||||
return module
|
||||
|
||||
|
||||
def create_vitmatte_snapshot(path: Path) -> None:
|
||||
"""Create the minimal file set required for a valid ViTMatte directory."""
|
||||
|
||||
|
||||
@@ -113,6 +113,41 @@ def test_comfy_progress_reporter_updates_the_active_node_progress(
|
||||
assert updates == [(-1, 6), (0, 6), (3, 6), (6, 6)]
|
||||
|
||||
|
||||
def test_comfy_progress_reporter_does_not_falsely_complete_unknown_downloads(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Unknown response lengths emit no misleading progress until completion."""
|
||||
|
||||
updates: list[tuple[int, int | None]] = []
|
||||
|
||||
class FakeProgressBar:
|
||||
"""Record ComfyUI absolute progress updates."""
|
||||
|
||||
def __init__(self, total: int) -> None:
|
||||
"""Record the total selected for the progress bar."""
|
||||
|
||||
updates.append((-1, total))
|
||||
|
||||
def update_absolute(self, value: int, total: int | None = None) -> None:
|
||||
"""Record one absolute progress update."""
|
||||
|
||||
updates.append((value, total))
|
||||
|
||||
comfy_module = ModuleType("comfy")
|
||||
comfy_utils = ModuleType("comfy.utils")
|
||||
comfy_utils.ProgressBar = FakeProgressBar # type: ignore[attr-defined]
|
||||
comfy_module.utils = comfy_utils # type: ignore[attr-defined]
|
||||
monkeypatch.setitem(sys.modules, "comfy", comfy_module)
|
||||
monkeypatch.setitem(sys.modules, "comfy.utils", comfy_utils)
|
||||
|
||||
reporter = ComfyProgressReporter()
|
||||
reporter.start("Downloading unknown-size model", None)
|
||||
reporter.advance(1024 * 1024, None)
|
||||
reporter.finish()
|
||||
|
||||
assert updates == [(-1, 1), (1, 1)]
|
||||
|
||||
|
||||
def test_downloader_streams_file_and_reports_progress(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
@@ -235,6 +235,35 @@ def test_collision_safe_mutations_integrate_through_one_real_comfy_clone() -> No
|
||||
assert ModelPatcher.set_model_attn2_patch is original_attn2_setter
|
||||
|
||||
|
||||
def test_attn2_mutation_prepends_before_exact_preserved_input_patch() -> None:
|
||||
"""Compose regional packing before an identity-admitted input transformer."""
|
||||
|
||||
model = _patcher(torch.nn.Linear(1, 1))
|
||||
|
||||
def preserved(*args: object) -> tuple[object, ...]:
|
||||
"""Return preserved callback arguments."""
|
||||
|
||||
return args
|
||||
|
||||
def regional(*args: object) -> tuple[object, ...]:
|
||||
"""Return regional callback arguments."""
|
||||
|
||||
return args
|
||||
|
||||
def output(*args: object) -> tuple[object, ...]:
|
||||
"""Return output callback arguments."""
|
||||
|
||||
return args
|
||||
|
||||
model.set_model_attn2_patch(preserved)
|
||||
|
||||
ModelAttn2PatchesMutation(regional, output, (preserved,)).apply(model)
|
||||
|
||||
patches = model.model_options["transformer_options"]["patches"]
|
||||
assert patches["attn2_patch"] == [regional, preserved]
|
||||
assert patches["attn2_output_patch"] == [output]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("wrapper_type", "key", "wrapper", "message"),
|
||||
[
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Verify automatic NegPiP trigger detection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from simple_syrup.domain.negative_prompt_weights import (
|
||||
contains_negative_prompt_weight,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
"(1girl:-2.00)",
|
||||
"portrait, (red jacket: -1.5)",
|
||||
"((nested):-0.25)",
|
||||
"[plain:(scheduled concept:-1.0):0.5]",
|
||||
"outer ((inner):-3.0)",
|
||||
],
|
||||
)
|
||||
def test_detector_admits_effective_negative_prompt_weights(text: str) -> None:
|
||||
"""Recognize valid negative emphasis wherever Prompt Control may schedule it."""
|
||||
|
||||
assert contains_negative_prompt_weight(text) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
"1girl:-2.00",
|
||||
"(1girl:2.00)",
|
||||
"(1girl)",
|
||||
"(1girl:not-a-number)",
|
||||
r"escaped \(1girl:-2.0\)",
|
||||
"unfinished (1girl:-2.0",
|
||||
"STYLE(A1111, length)",
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_detector_rejects_non_negative_weight_syntax(text: str) -> None:
|
||||
"""Do not activate for plain text, positive weights, escapes, or malformed input."""
|
||||
|
||||
assert contains_negative_prompt_weight(text) is False
|
||||
|
||||
|
||||
def test_detector_resolves_nested_effective_weight() -> None:
|
||||
"""An inner explicit positive weight overrides a negative outer emphasis."""
|
||||
|
||||
assert contains_negative_prompt_weight("((kept positive:2.0):-3.0)") is False
|
||||
|
||||
|
||||
def test_detector_requires_text() -> None:
|
||||
"""Reject dynamic non-text values before prompt planning."""
|
||||
|
||||
with pytest.raises(TypeError, match="requires text"):
|
||||
contains_negative_prompt_weight(object()) # type: ignore[arg-type]
|
||||
@@ -0,0 +1,188 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Verify isolated automatic NegPiP proof workflow construction."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import cast
|
||||
|
||||
import pytest
|
||||
|
||||
from tools.negpip_integration.workflow import (
|
||||
REFINER_BASE_PROMPT,
|
||||
REFINER_SWITCH_STEP,
|
||||
NegpipFixtureSelections,
|
||||
NegpipLiveFamily,
|
||||
NegpipLiveWorkflowBuilder,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def builder() -> NegpipLiveWorkflowBuilder:
|
||||
"""Return a builder with deterministic nested Comfy selections."""
|
||||
|
||||
return NegpipLiveWorkflowBuilder(
|
||||
NegpipFixtureSelections(
|
||||
sd1_checkpoint=r"proof\sd1.safetensors",
|
||||
sdxl_checkpoint=r"proof\sdxl.safetensors",
|
||||
sdxl_refiner_checkpoint=r"proof\sdxl-refiner.safetensors",
|
||||
anima_diffusion=r"proof\anima.safetensors",
|
||||
anima_text_encoder=r"proof\anima-te.safetensors",
|
||||
krea2_diffusion=r"proof\krea2.safetensors",
|
||||
krea2_text_encoder=r"proof\krea2-te.safetensors",
|
||||
qwen_image_vae=r"proof\qwen-image-vae.safetensors",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("family", tuple(NegpipLiveFamily))
|
||||
def test_triggered_workflow_samples_and_requires_runtime_evidence(
|
||||
builder: NegpipLiveWorkflowBuilder,
|
||||
family: NegpipLiveFamily,
|
||||
) -> None:
|
||||
"""Every family uses the public node and synchronized callback observer."""
|
||||
|
||||
built = builder.build(family, run_id=f"proof:{family.value}", trigger=True)
|
||||
class_types = [str(node["class_type"]) for node in built.prompt.values()]
|
||||
schedule = next(
|
||||
node
|
||||
for node in built.prompt.values()
|
||||
if node["class_type"] == "SimpleSyrup.ScheduleAndEncodePromptsWithPromptControl"
|
||||
)
|
||||
|
||||
inputs = cast(dict[str, object], schedule["inputs"])
|
||||
assert "bright (red:-1.0) jacket" in str(inputs["positive_prompt"])
|
||||
expected_sampler = (
|
||||
"KSamplerAdvanced" if family is NegpipLiveFamily.SDXL_REFINER else "KSampler"
|
||||
)
|
||||
assert expected_sampler in class_types
|
||||
assert "VAEDecode" in class_types
|
||||
assert "SaveImage" in class_types
|
||||
assert "SimpleSyrupBenchmark.InstrumentNegpipModel" in class_types
|
||||
assert "SimpleSyrupBenchmark.ReadNegpipRuntime" in class_types
|
||||
assert built.runtime_node_id is not None
|
||||
assert built.conditioning_node_id is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("family", tuple(NegpipLiveFamily))
|
||||
def test_control_workflow_proves_automatic_gate_stays_off(
|
||||
builder: NegpipLiveWorkflowBuilder,
|
||||
family: NegpipLiveFamily,
|
||||
) -> None:
|
||||
"""A no-negative-weight control saves a sampled unmodified image."""
|
||||
|
||||
built = builder.build(family, run_id=f"control:{family.value}", trigger=False)
|
||||
class_types = [str(node["class_type"]) for node in built.prompt.values()]
|
||||
|
||||
assert "SimpleSyrupBenchmark.SnapshotModelModifier" in class_types
|
||||
expected_sampler = (
|
||||
"KSamplerAdvanced" if family is NegpipLiveFamily.SDXL_REFINER else "KSampler"
|
||||
)
|
||||
assert expected_sampler in class_types
|
||||
assert "VAEDecode" in class_types
|
||||
assert "SaveImage" in class_types
|
||||
assert "SimpleSyrupBenchmark.InstrumentNegpipModel" not in class_types
|
||||
assert built.runtime_node_id is None
|
||||
assert built.conditioning_node_id is None
|
||||
|
||||
|
||||
def test_family_workflows_select_native_loaders_and_latents(
|
||||
builder: NegpipLiveWorkflowBuilder,
|
||||
) -> None:
|
||||
"""Use real family-specific loader and latent contracts."""
|
||||
|
||||
expected = {
|
||||
NegpipLiveFamily.SD1: {"CheckpointLoaderSimple", "EmptyLatentImage"},
|
||||
NegpipLiveFamily.SDXL: {"CheckpointLoaderSimple", "EmptyLatentImage"},
|
||||
NegpipLiveFamily.SDXL_REFINER: {
|
||||
"CheckpointLoaderSimple",
|
||||
"EmptyLatentImage",
|
||||
},
|
||||
NegpipLiveFamily.ANIMA: {
|
||||
"SimpleSyrup.SimpleLoadAnima",
|
||||
"EmptyCosmosLatentVideo",
|
||||
},
|
||||
NegpipLiveFamily.KREA2: {
|
||||
"UNETLoader",
|
||||
"CLIPLoader",
|
||||
"VAELoader",
|
||||
"EmptySD3LatentImage",
|
||||
},
|
||||
}
|
||||
|
||||
for family, required in expected.items():
|
||||
built = builder.build(family, run_id=family.value, trigger=True)
|
||||
class_types = {str(node["class_type"]) for node in built.prompt.values()}
|
||||
assert required.issubset(class_types)
|
||||
|
||||
|
||||
def test_refiner_workflow_runs_base_then_refiner_sampling(
|
||||
builder: NegpipLiveWorkflowBuilder,
|
||||
) -> None:
|
||||
"""Use SDXL base for high noise and the probed refiner for low noise."""
|
||||
|
||||
built = builder.build(
|
||||
NegpipLiveFamily.SDXL_REFINER,
|
||||
run_id="refiner",
|
||||
trigger=True,
|
||||
)
|
||||
samplers = [
|
||||
node
|
||||
for node in built.prompt.values()
|
||||
if node["class_type"] == "KSamplerAdvanced"
|
||||
]
|
||||
|
||||
assert len(samplers) == 2
|
||||
base_inputs = cast(dict[str, object], samplers[0]["inputs"])
|
||||
refiner_inputs = cast(dict[str, object], samplers[1]["inputs"])
|
||||
assert base_inputs["add_noise"] == "enable"
|
||||
assert base_inputs["end_at_step"] == REFINER_SWITCH_STEP
|
||||
assert base_inputs["return_with_leftover_noise"] == "enable"
|
||||
assert refiner_inputs["add_noise"] == "disable"
|
||||
assert refiner_inputs["start_at_step"] == REFINER_SWITCH_STEP
|
||||
assert refiner_inputs["end_at_step"] == 24
|
||||
base_positive = next(
|
||||
node
|
||||
for node in built.prompt.values()
|
||||
if node["class_type"] == "CLIPTextEncode"
|
||||
and cast(dict[str, object], node["inputs"])["text"] == REFINER_BASE_PROMPT
|
||||
)
|
||||
base_text = cast(dict[str, object], base_positive["inputs"])["text"]
|
||||
assert isinstance(base_text, str)
|
||||
assert "red" not in base_text
|
||||
|
||||
|
||||
def test_ppm_baseline_prepatches_the_same_schedule_path(
|
||||
builder: NegpipLiveWorkflowBuilder,
|
||||
) -> None:
|
||||
"""Put pinned PPM before Schedule & Encode as the behavioral oracle."""
|
||||
|
||||
built = builder.build(
|
||||
NegpipLiveFamily.SD1,
|
||||
run_id="ppm-baseline",
|
||||
trigger=True,
|
||||
baseline_ppm=True,
|
||||
)
|
||||
class_types = [str(node["class_type"]) for node in built.prompt.values()]
|
||||
|
||||
assert built.mode == "ppm_baseline"
|
||||
assert class_types.count("CLIPNegPip") == 1
|
||||
assert (
|
||||
class_types.count("SimpleSyrup.ScheduleAndEncodePromptsWithPromptControl") == 1
|
||||
)
|
||||
|
||||
|
||||
def test_ppm_baseline_rejects_an_untriggered_workflow(
|
||||
builder: NegpipLiveWorkflowBuilder,
|
||||
) -> None:
|
||||
"""Keep ordinary controls free from every NegPiP patch."""
|
||||
|
||||
with pytest.raises(ValueError, match="requires a negative weight"):
|
||||
builder.build(
|
||||
NegpipLiveFamily.SD1,
|
||||
run_id="invalid",
|
||||
trigger=False,
|
||||
baseline_ppm=True,
|
||||
)
|
||||
@@ -0,0 +1,192 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Verify automatic NegPiP dispatch on real Comfy patcher objects."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from comfy.model_base import SDXL, Anima, BaseModel, Krea2, SDXLRefiner
|
||||
from comfy.model_patcher import ModelPatcher
|
||||
from comfy.patcher_extension import WrappersMP
|
||||
from comfy.sd import CLIP
|
||||
|
||||
from simple_syrup.runtime.negpip.anima import (
|
||||
WRAPPER_KEY as ANIMA_WRAPPER_KEY,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.anima import (
|
||||
anima_attn2_negpip,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.krea2 import (
|
||||
CLIP_MARKER,
|
||||
KREA_TOKEN_KEY,
|
||||
Krea2NegpipTokenizer,
|
||||
krea2_attn1_negpip,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.krea2 import (
|
||||
WRAPPER_KEY as KREA_WRAPPER_KEY,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.standard import standard_attn2_negpip
|
||||
from simple_syrup.services.negpip_model_service import (
|
||||
MODEL_MARKER,
|
||||
NegpipModelService,
|
||||
)
|
||||
|
||||
|
||||
class _Encoder(torch.nn.Module):
|
||||
"""Expose the encoder method patched by the standard NegPiP path."""
|
||||
|
||||
def encode_token_weights(self, pairs: object) -> object:
|
||||
"""Return the supplied placeholder pairs."""
|
||||
|
||||
return pairs
|
||||
|
||||
|
||||
class _ClipRoot(torch.nn.Module):
|
||||
"""Provide the model object structure used by supported CLIP families."""
|
||||
|
||||
def __init__(self, *, krea: bool = False) -> None:
|
||||
"""Install either the standard or Krea encoder surface."""
|
||||
|
||||
super().__init__()
|
||||
if krea:
|
||||
setattr(self, KREA_TOKEN_KEY, _Encoder())
|
||||
else:
|
||||
self.clip_l = _Encoder()
|
||||
|
||||
def encode_token_weights(
|
||||
self,
|
||||
pairs: object,
|
||||
*,
|
||||
template_end: int = -1,
|
||||
) -> tuple[object, None, dict[str, object]]:
|
||||
"""Stand in for Krea's root shape-preserving encoder."""
|
||||
|
||||
del template_end
|
||||
return pairs, None, {}
|
||||
|
||||
|
||||
class _Tokenizer:
|
||||
"""Represent the installed tokenizer retained by a Krea proxy."""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_class", (BaseModel, SDXL, SDXLRefiner))
|
||||
def test_service_patches_every_standard_ppm_family(
|
||||
model_class: type[BaseModel],
|
||||
) -> None:
|
||||
"""SD1, SDXL, and SDXL Refiner receive one cloned PPM-equivalent path."""
|
||||
|
||||
model = _model_patcher(model_class)
|
||||
clip = _clip(krea=False)
|
||||
|
||||
prepared_model, prepared_clip = NegpipModelService().prepare(model, clip)
|
||||
|
||||
assert isinstance(prepared_model, ModelPatcher)
|
||||
assert isinstance(prepared_clip, CLIP)
|
||||
assert prepared_model is not model
|
||||
assert prepared_clip is not clip
|
||||
assert MODEL_MARKER not in model.model_options
|
||||
assert MODEL_MARKER not in clip.patcher.model_options
|
||||
assert prepared_model.model_options[MODEL_MARKER] is True
|
||||
assert prepared_clip.patcher.model_options[MODEL_MARKER] is True
|
||||
assert _attention_patch(prepared_model, "attn2_patch") is standard_attn2_negpip
|
||||
assert "clip_l.encode_token_weights" in prepared_clip.patcher.object_patches
|
||||
|
||||
|
||||
def test_service_patches_anima_with_mask_wrapper_and_attention() -> None:
|
||||
"""Anima receives its extra condition, diffusion wrapper, and V patch."""
|
||||
|
||||
prepared_model, prepared_clip = NegpipModelService().prepare(
|
||||
_model_patcher(Anima),
|
||||
_clip(krea=False),
|
||||
)
|
||||
|
||||
model = cast(ModelPatcher, prepared_model)
|
||||
clip = cast(CLIP, prepared_clip)
|
||||
assert model.model_options[MODEL_MARKER] is True
|
||||
assert clip.patcher.model_options[MODEL_MARKER] is True
|
||||
assert "extra_conds" in model.object_patches
|
||||
assert _attention_patch(model, "attn2_patch") is anima_attn2_negpip
|
||||
assert ANIMA_WRAPPER_KEY in model.wrappers[WrappersMP.DIFFUSION_MODEL]
|
||||
|
||||
|
||||
def test_service_patches_krea_without_claiming_ppm_clip_encoding() -> None:
|
||||
"""Krea uses its layered encoder proxy and joint attn1 value patch."""
|
||||
|
||||
source_clip = _clip(krea=True)
|
||||
prepared_model, prepared_clip = NegpipModelService().prepare(
|
||||
_model_patcher(Krea2),
|
||||
source_clip,
|
||||
)
|
||||
|
||||
model = cast(ModelPatcher, prepared_model)
|
||||
clip = cast(CLIP, prepared_clip)
|
||||
assert model.model_options[MODEL_MARKER] is True
|
||||
assert MODEL_MARKER not in clip.patcher.model_options
|
||||
assert clip.patcher.model_options[CLIP_MARKER] is True
|
||||
assert isinstance(clip.tokenizer, Krea2NegpipTokenizer)
|
||||
assert clip.tokenizer is not source_clip.tokenizer
|
||||
assert "encode_token_weights" in clip.patcher.object_patches
|
||||
assert "extra_conds" in model.object_patches
|
||||
assert _attention_patch(model, "attn1_patch") is krea2_attn1_negpip
|
||||
assert KREA_WRAPPER_KEY in model.wrappers[WrappersMP.DIFFUSION_MODEL]
|
||||
|
||||
|
||||
def test_service_reuses_already_patched_pair_without_double_patching() -> None:
|
||||
"""An existing PPM model marker makes automatic preparation idempotent."""
|
||||
|
||||
model = _model_patcher(BaseModel)
|
||||
clip = _clip(krea=False)
|
||||
model.model_options[MODEL_MARKER] = True
|
||||
|
||||
prepared_model, prepared_clip = NegpipModelService().prepare(model, clip)
|
||||
|
||||
assert prepared_model is model
|
||||
assert prepared_clip is clip
|
||||
prepared_model_typed = cast(ModelPatcher, prepared_model)
|
||||
transformer_options = cast(
|
||||
dict[str, object],
|
||||
prepared_model_typed.model_options["transformer_options"],
|
||||
)
|
||||
assert "patches" not in transformer_options
|
||||
|
||||
|
||||
def _model_patcher(model_class: type[BaseModel]) -> ModelPatcher:
|
||||
"""Construct an unloaded family instance behind Comfy's real patcher."""
|
||||
|
||||
model = object.__new__(model_class)
|
||||
torch.nn.Module.__init__(model)
|
||||
device = torch.device("cpu")
|
||||
return ModelPatcher(model, load_device=device, offload_device=device)
|
||||
|
||||
|
||||
def _clip(*, krea: bool) -> CLIP:
|
||||
"""Construct a cloneable unloaded CLIP around a real model patcher."""
|
||||
|
||||
clip = CLIP(no_init=True)
|
||||
root = _ClipRoot(krea=krea)
|
||||
device = torch.device("cpu")
|
||||
clip.patcher = ModelPatcher(root, load_device=device, offload_device=device)
|
||||
clip.cond_stage_model = root
|
||||
clip.tokenizer = _Tokenizer()
|
||||
clip.layer_idx = None
|
||||
clip.tokenizer_options = {}
|
||||
clip.use_clip_schedule = False
|
||||
clip.apply_hooks_to_conds = None
|
||||
return clip
|
||||
|
||||
|
||||
def _attention_patch(model: ModelPatcher, key: str) -> Callable[..., Any]:
|
||||
"""Return the single installed attention patch from model options."""
|
||||
|
||||
transformer_options = cast(
|
||||
dict[str, object], model.model_options["transformer_options"]
|
||||
)
|
||||
patches = cast(dict[str, list[Callable[..., Any]]], transformer_options["patches"])
|
||||
assert len(patches[key]) == 1
|
||||
return patches[key][0]
|
||||
@@ -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
|
||||
|
||||
"""Prove family-specific NegPiP tensor and wrapper invariants."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from simple_syrup.runtime.negpip.anima import (
|
||||
CONDITION_MASK_KEY as ANIMA_CONDITION_MASK_KEY,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.anima import (
|
||||
TRANSFORMER_MASK_KEY as ANIMA_TRANSFORMER_MASK_KEY,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.anima import (
|
||||
anima_attn2_negpip,
|
||||
anima_diffusion_negpip_wrapper,
|
||||
anima_extra_conds_negpip_wrapper,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.krea2 import (
|
||||
CONDITION_MASK_KEY as KREA_CONDITION_MASK_KEY,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.krea2 import (
|
||||
ENCODER_MASK_KEY,
|
||||
encode_krea2_token_weights_negpip,
|
||||
krea2_attn1_negpip,
|
||||
krea2_diffusion_negpip_wrapper,
|
||||
krea2_extra_conds_negpip_wrapper,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.krea2 import (
|
||||
TRANSFORMER_MASK_KEY as KREA_TRANSFORMER_MASK_KEY,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.standard import (
|
||||
encode_token_weights_negpip,
|
||||
standard_attn2_negpip,
|
||||
)
|
||||
|
||||
|
||||
class _StandardEncoder:
|
||||
"""Produce deterministic token and empty-prompt embeddings."""
|
||||
|
||||
special_tokens: dict[str, int] = {}
|
||||
|
||||
def gen_empty_tokens(
|
||||
self,
|
||||
special_tokens: dict[str, int],
|
||||
length: int,
|
||||
) -> list[int]:
|
||||
"""Return a fixed empty token row matching the requested length."""
|
||||
|
||||
del special_tokens
|
||||
return [0] * length
|
||||
|
||||
def encode(self, sections: list[list[object]]) -> tuple[torch.Tensor, None]:
|
||||
"""Map source tokens to scalar embeddings and empty tokens to one."""
|
||||
|
||||
rows = [
|
||||
[[1.0 if token == 0 else float(cast(int, token))] for token in section]
|
||||
for section in sections
|
||||
]
|
||||
return torch.tensor(rows), None
|
||||
|
||||
|
||||
def test_standard_negpip_interleaves_magnitude_keys_and_signed_values() -> None:
|
||||
"""Standard encoding doubles tokens and signs only the value positions."""
|
||||
|
||||
encoded, pooled = encode_token_weights_negpip(
|
||||
cast(Any, _StandardEncoder()),
|
||||
[[(3, -2.0), (5, 0.5)]],
|
||||
)
|
||||
|
||||
assert pooled is None
|
||||
assert isinstance(encoded, torch.Tensor)
|
||||
assert encoded.flatten().tolist() == [5.0, -5.0, 3.0, 3.0]
|
||||
|
||||
query = torch.tensor([[[9.0], [8.0]]])
|
||||
key = encoded.clone()
|
||||
value = encoded.clone()
|
||||
prepared_query, prepared_key, prepared_value = standard_attn2_negpip(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
{},
|
||||
)
|
||||
assert prepared_query is query
|
||||
assert prepared_key.flatten().tolist() == [5.0, 3.0]
|
||||
assert prepared_value.flatten().tolist() == [-5.0, 3.0]
|
||||
|
||||
|
||||
def test_anima_negpip_preserves_magnitude_and_propagates_value_mask() -> None:
|
||||
"""Anima moves signs through conditions and changes only attention values."""
|
||||
|
||||
observed_weights: list[torch.Tensor] = []
|
||||
|
||||
def base_extra_conds(**kwargs: object) -> dict[str, object]:
|
||||
weights = kwargs["t5xxl_weights"]
|
||||
assert isinstance(weights, torch.Tensor)
|
||||
observed_weights.append(weights)
|
||||
return {"base": "condition"}
|
||||
|
||||
wrapped = anima_extra_conds_negpip_wrapper(base_extra_conds)
|
||||
output = wrapped(t5xxl_weights=torch.tensor([-2.0, 0.5, 1.0]))
|
||||
|
||||
assert torch.equal(observed_weights[0], torch.tensor([2.0, 0.5, 1.0]))
|
||||
condition = output[ANIMA_CONDITION_MASK_KEY]
|
||||
multiplier = cast(Any, condition).cond
|
||||
assert multiplier.shape == (1, 512, 1)
|
||||
assert multiplier[0, :3, 0].tolist() == [-1.0, 1.0, 1.0]
|
||||
assert torch.all(multiplier[0, 3:, 0] == 1.0)
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def executor(*args: object, **kwargs: object) -> str:
|
||||
del args
|
||||
captured.update(kwargs)
|
||||
return "executed"
|
||||
|
||||
context = torch.zeros((1, 512, 4))
|
||||
result = anima_diffusion_negpip_wrapper(
|
||||
executor,
|
||||
object(),
|
||||
object(),
|
||||
context,
|
||||
transformer_options={"existing": True},
|
||||
**{ANIMA_CONDITION_MASK_KEY: multiplier},
|
||||
)
|
||||
assert result == "executed"
|
||||
options = cast(dict[str, object], captured["transformer_options"])
|
||||
assert options["existing"] is True
|
||||
assert torch.equal(
|
||||
cast(torch.Tensor, options[ANIMA_TRANSFORMER_MASK_KEY]), multiplier
|
||||
)
|
||||
|
||||
query = torch.ones((1, 1, 3, 1))
|
||||
key = torch.full_like(query, 2.0)
|
||||
value = torch.tensor([[[[3.0], [4.0], [5.0]]]])
|
||||
attention = anima_attn2_negpip(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
extra_options={ANIMA_TRANSFORMER_MASK_KEY: multiplier[:, :3]},
|
||||
)
|
||||
assert attention["q"] is query
|
||||
assert attention["k"] is key
|
||||
assert cast(torch.Tensor, attention["v"]).flatten().tolist() == [
|
||||
-3.0,
|
||||
4.0,
|
||||
5.0,
|
||||
]
|
||||
|
||||
|
||||
def test_krea2_negpip_preserves_shape_and_signs_only_text_values() -> None:
|
||||
"""Krea retains layered encoding and leaves Q, K, and image V untouched."""
|
||||
|
||||
tokens: dict[str, list[list[tuple[object, ...]]]] = {
|
||||
"qwen3vl_4b": [
|
||||
[
|
||||
(151644, 1.0),
|
||||
(0, 1.0),
|
||||
(198, 1.0),
|
||||
(151644, 1.0),
|
||||
(872, 1.0),
|
||||
(198, 1.0),
|
||||
(10, -2.0),
|
||||
(11, 0.5),
|
||||
]
|
||||
]
|
||||
}
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
def original(
|
||||
prepared: dict[str, list[list[tuple[object, ...]]]],
|
||||
*,
|
||||
template_end: int,
|
||||
) -> tuple[torch.Tensor, None, dict[str, object]]:
|
||||
observed["tokens"] = prepared
|
||||
observed["template_end"] = template_end
|
||||
return torch.ones((1, 2, 30_720)), None, {"source": True}
|
||||
|
||||
conditioning, pooled, extra = encode_krea2_token_weights_negpip(
|
||||
original,
|
||||
tokens,
|
||||
)
|
||||
|
||||
conditioning_tensor = cast(torch.Tensor, conditioning)
|
||||
assert conditioning_tensor.shape == (1, 2, 30_720)
|
||||
assert pooled is None
|
||||
absolute = cast(
|
||||
dict[str, list[list[tuple[object, ...]]]],
|
||||
observed["tokens"],
|
||||
)
|
||||
assert [pair[1] for pair in absolute["qwen3vl_4b"][0][-2:]] == [2.0, 0.5]
|
||||
metadata = cast(dict[str, object], extra)
|
||||
multiplier = cast(torch.Tensor, metadata[ENCODER_MASK_KEY])
|
||||
assert multiplier.flatten().tolist() == [-1.0, 1.0]
|
||||
|
||||
wrapped_extra = krea2_extra_conds_negpip_wrapper(lambda **kwargs: {})
|
||||
processed = wrapped_extra(**{ENCODER_MASK_KEY: multiplier})
|
||||
condition = processed[KREA_CONDITION_MASK_KEY]
|
||||
processed_multiplier = cast(Any, condition).cond
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def executor(*args: object, **kwargs: object) -> str:
|
||||
del args
|
||||
captured.update(kwargs)
|
||||
return "executed"
|
||||
|
||||
assert (
|
||||
krea2_diffusion_negpip_wrapper(
|
||||
executor,
|
||||
transformer_options={"img_slice": [2, 4]},
|
||||
**{KREA_CONDITION_MASK_KEY: processed_multiplier},
|
||||
)
|
||||
== "executed"
|
||||
)
|
||||
options = cast(dict[str, Any], captured["transformer_options"])
|
||||
assert options["img_slice"] == [2, 4]
|
||||
|
||||
positional_capture: dict[str, object] = {}
|
||||
|
||||
def positional_executor(*args: object, **kwargs: object) -> str:
|
||||
positional_capture["args"] = args
|
||||
positional_capture["kwargs"] = kwargs
|
||||
return "positional"
|
||||
|
||||
positional_options = {"img_slice": [2, 4]}
|
||||
assert (
|
||||
krea2_diffusion_negpip_wrapper(
|
||||
positional_executor,
|
||||
object(),
|
||||
object(),
|
||||
object(),
|
||||
None,
|
||||
None,
|
||||
positional_options,
|
||||
**{KREA_CONDITION_MASK_KEY: processed_multiplier},
|
||||
)
|
||||
== "positional"
|
||||
)
|
||||
positional_args = cast(tuple[object, ...], positional_capture["args"])
|
||||
prepared_positional = cast(dict[str, object], positional_args[5])
|
||||
assert prepared_positional is not positional_options
|
||||
assert prepared_positional[KREA_TRANSFORMER_MASK_KEY] is processed_multiplier
|
||||
assert "transformer_options" not in cast(
|
||||
dict[str, object], positional_capture["kwargs"]
|
||||
)
|
||||
|
||||
query = torch.arange(8.0).reshape(1, 1, 4, 2)
|
||||
key = query + 10.0
|
||||
value = query + 20.0
|
||||
attention = krea2_attn1_negpip(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
extra_options=options,
|
||||
)
|
||||
assert attention["q"] is query
|
||||
assert attention["k"] is key
|
||||
prepared_value = cast(torch.Tensor, attention["v"])
|
||||
assert prepared_value[0, 0, 0].tolist() == [-20.0, -21.0]
|
||||
assert prepared_value[0, 0, 1].tolist() == [22.0, 23.0]
|
||||
assert torch.equal(prepared_value[:, :, 2:], value[:, :, 2:])
|
||||
assert torch.equal(value, query + 20.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"image_slice",
|
||||
(None, [3, 4]),
|
||||
)
|
||||
def test_krea2_negpip_rejects_unprovable_text_boundaries(
|
||||
image_slice: object,
|
||||
) -> None:
|
||||
"""Krea fails closed when the model boundary cannot align to its sign mask."""
|
||||
|
||||
options: dict[str, object] = {KREA_TRANSFORMER_MASK_KEY: torch.ones((1, 2, 1))}
|
||||
if image_slice is not None:
|
||||
options["img_slice"] = image_slice
|
||||
|
||||
with pytest.raises(ValueError, match="boundary|does not match"):
|
||||
krea2_attn1_negpip(
|
||||
torch.ones((1, 1, 4, 1)),
|
||||
torch.ones((1, 1, 4, 1)),
|
||||
torch.ones((1, 1, 4, 1)),
|
||||
extra_options=options,
|
||||
)
|
||||
@@ -0,0 +1,133 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Verify benchmark-only live NegPiP callback introspection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
from simple_syrup.runtime.negpip.krea2 import TRANSFORMER_MASK_KEY
|
||||
from tools.attention_coupling_benchmark.comfy_probe.negpip_runtime import (
|
||||
InstrumentNegpipModelV3,
|
||||
ReadNegpipRuntimeV3,
|
||||
_NegpipProbeState,
|
||||
_observe_masked,
|
||||
_observe_standard,
|
||||
_owned_negpip_callback,
|
||||
)
|
||||
|
||||
|
||||
def test_negpip_runtime_probe_schemas_are_stable() -> None:
|
||||
"""Expose distinct instrument and synchronized evidence node IDs."""
|
||||
|
||||
instrument = InstrumentNegpipModelV3.define_schema()
|
||||
reader = ReadNegpipRuntimeV3.define_schema()
|
||||
|
||||
assert instrument.node_id == "SimpleSyrupBenchmark.InstrumentNegpipModel"
|
||||
assert reader.node_id == "SimpleSyrupBenchmark.ReadNegpipRuntime"
|
||||
|
||||
|
||||
def test_standard_probe_validates_live_interleaved_selection() -> None:
|
||||
"""Record one standard callback only after exact even/odd selection."""
|
||||
|
||||
state = _NegpipProbeState("standard", "attn2_patch", "callback")
|
||||
query = torch.ones((1, 2, 1))
|
||||
key = torch.tensor([[[1.0], [1.0], [2.0], [2.0]]])
|
||||
value = torch.tensor([[[1.0], [-1.0], [2.0], [2.0]]])
|
||||
|
||||
_observe_standard(
|
||||
state,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
(query, key[:, 0::2], value[:, 1::2]),
|
||||
)
|
||||
|
||||
assert state.attention_calls == 1
|
||||
assert state.negative_mask_calls == 1
|
||||
assert state.input_value_shape == [1, 4, 1]
|
||||
assert state.output_value_shape == [1, 2, 1]
|
||||
assert state.negative_token_count == 1
|
||||
assert state.negative_token_positions == [0]
|
||||
assert state.negative_token_locations == [[0, 0]]
|
||||
|
||||
|
||||
def test_standard_probe_finds_signed_tokens_outside_cfg_batch_zero() -> None:
|
||||
"""Inspect every CFG row rather than assuming the positive prompt is first."""
|
||||
|
||||
state = _NegpipProbeState("standard", "attn2_patch", "callback")
|
||||
query = torch.ones((2, 2, 1))
|
||||
key = torch.tensor(
|
||||
[
|
||||
[[1.0], [1.0], [2.0], [2.0]],
|
||||
[[1.0], [1.0], [2.0], [2.0]],
|
||||
]
|
||||
)
|
||||
value = torch.tensor(
|
||||
[
|
||||
[[1.0], [1.0], [2.0], [2.0]],
|
||||
[[1.0], [1.0], [2.0], [-2.0]],
|
||||
]
|
||||
)
|
||||
|
||||
_observe_standard(
|
||||
state,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
(query, key[:, 0::2], value[:, 1::2]),
|
||||
)
|
||||
|
||||
assert state.negative_mask_calls == 1
|
||||
assert state.negative_token_count == 1
|
||||
assert state.negative_token_positions == [1]
|
||||
assert state.negative_token_locations == [[1, 1]]
|
||||
|
||||
|
||||
def test_probe_admits_the_pinned_ppm_standard_callback_identity() -> None:
|
||||
"""Recognize PPM even when Comfy prefixes its module with a Windows path."""
|
||||
|
||||
def sdxl_attn2_negpip() -> None:
|
||||
"""Stand in for the identity-checked pinned PPM callback."""
|
||||
|
||||
sdxl_attn2_negpip.__module__ = "managed_comfyui_ppm.src.negpip.unet_negpip"
|
||||
sdxl_attn2_negpip.__qualname__ = "sdxl_attn2_negpip"
|
||||
|
||||
patch_name, family, callback = _owned_negpip_callback(
|
||||
{"attn2_patch": [sdxl_attn2_negpip]}
|
||||
)
|
||||
|
||||
assert patch_name == "attn2_patch"
|
||||
assert family == "standard"
|
||||
assert callback is sdxl_attn2_negpip
|
||||
|
||||
|
||||
def test_krea_probe_validates_text_only_value_signing() -> None:
|
||||
"""Record Krea only when its image suffix remains exact."""
|
||||
|
||||
state = _NegpipProbeState("krea2", "attn1_patch", "callback")
|
||||
query = torch.ones((1, 1, 4, 1))
|
||||
key = torch.ones((1, 1, 4, 1)) * 2
|
||||
value = torch.tensor([[[[3.0], [4.0], [5.0], [6.0]]]])
|
||||
multiplier = torch.tensor([[[-1.0], [1.0]]])
|
||||
output_value = value.clone()
|
||||
output_value[:, :, :2] *= multiplier.unsqueeze(1)
|
||||
|
||||
_observe_masked(
|
||||
state,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
{"q": query, "k": key, "v": output_value},
|
||||
{TRANSFORMER_MASK_KEY: multiplier, "img_slice": [2, 4]},
|
||||
)
|
||||
|
||||
assert state.attention_calls == 1
|
||||
assert state.negative_mask_calls == 1
|
||||
assert state.text_length == 2
|
||||
assert state.mask_shape == [1, 2, 1]
|
||||
assert state.negative_token_count == 1
|
||||
assert state.negative_token_positions == [0]
|
||||
assert state.negative_token_locations == [[0, 0]]
|
||||
@@ -0,0 +1,93 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Verify decoded NegPiP proof artifacts and contact-sheet evidence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from tools.comfy_api import JsonObject
|
||||
from tools.negpip_integration.visual_proof import NegpipVisualProofRecorder
|
||||
from tools.negpip_integration.workflow import NegpipLiveFamily
|
||||
|
||||
|
||||
def test_visual_recorder_persists_pairs_and_contact_sheet(tmp_path: Path) -> None:
|
||||
"""Every family receives originals, pixel deltas, and visible labels."""
|
||||
|
||||
recorder = NegpipVisualProofRecorder(tmp_path)
|
||||
families: JsonObject = {}
|
||||
for index, family in enumerate(NegpipLiveFamily):
|
||||
control = recorder.record(
|
||||
family,
|
||||
"control",
|
||||
_png_bytes((20 + index, 40, 60)),
|
||||
)
|
||||
negative = recorder.record(
|
||||
family,
|
||||
"negative",
|
||||
_png_bytes((120 + index, 40, 60)),
|
||||
)
|
||||
families[family.value] = {
|
||||
"control": {"image": control},
|
||||
"negative": {
|
||||
"image": negative,
|
||||
"runtime": {
|
||||
"family": family.value,
|
||||
"attention_calls": 3,
|
||||
"negative_mask_calls": 3,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
sheet = recorder.finalize(families)
|
||||
|
||||
assert (tmp_path / str(sheet["file"])).is_file()
|
||||
assert sheet["width"] == 1346
|
||||
assert sheet["height"] == 2528
|
||||
for family in NegpipLiveFamily:
|
||||
result = families[family.value]
|
||||
assert isinstance(result, dict)
|
||||
comparison = result["image_comparison"]
|
||||
assert isinstance(comparison, dict)
|
||||
assert comparison["changed_pixels"] == 512 * 512
|
||||
assert comparison["mean_absolute_rgb_delta"] > 0
|
||||
|
||||
|
||||
def test_visual_recorder_rejects_identical_pair(tmp_path: Path) -> None:
|
||||
"""A decoded image must visibly change in every supported family."""
|
||||
|
||||
recorder = NegpipVisualProofRecorder(tmp_path)
|
||||
image = _png_bytes((20, 40, 60))
|
||||
families: JsonObject = {}
|
||||
for family in NegpipLiveFamily:
|
||||
families[family.value] = {
|
||||
"control": {"image": recorder.record(family, "control", image)},
|
||||
"negative": {
|
||||
"image": recorder.record(family, "negative", image),
|
||||
"runtime": {
|
||||
"family": family.value,
|
||||
"attention_calls": 1,
|
||||
"negative_mask_calls": 1,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
recorder.finalize(families)
|
||||
except ValueError as error:
|
||||
assert "images are equal" in str(error)
|
||||
else:
|
||||
raise AssertionError("Identical NegPiP proof images must be rejected.")
|
||||
|
||||
|
||||
def _png_bytes(color: tuple[int, int, int]) -> bytes:
|
||||
"""Return one deterministic 512-square PNG."""
|
||||
|
||||
stream = io.BytesIO()
|
||||
Image.new("RGB", (512, 512), color).save(stream, format="PNG")
|
||||
return stream.getvalue()
|
||||
@@ -0,0 +1,140 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Prove Triton remains an optional CUDA acceleration dependency."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from simple_syrup.runtime.regional_lora.triton_runtime import (
|
||||
TritonRuntimeResolver,
|
||||
)
|
||||
|
||||
|
||||
def test_node_registration_and_cpu_accumulation_do_not_import_triton() -> None:
|
||||
"""Load public nodes and execute CPU accumulation with Triton blocked."""
|
||||
|
||||
script = """
|
||||
import importlib.abc
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path.cwd().parents[1]))
|
||||
sys.argv = [sys.argv[0], "--cpu"]
|
||||
import comfy.options
|
||||
comfy.options.enable_args_parsing()
|
||||
|
||||
class BlockTriton(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
if fullname == "triton" or fullname.startswith("triton."):
|
||||
raise ModuleNotFoundError("blocked optional Triton", name=fullname)
|
||||
return None
|
||||
|
||||
sys.meta_path.insert(0, BlockTriton())
|
||||
import torch
|
||||
from simple_syrup.nodes_v3 import get_nodes
|
||||
from simple_syrup.runtime.regional_lora import ordered_accumulation
|
||||
|
||||
assert get_nodes()
|
||||
base = torch.tensor([1.0, 2.0])
|
||||
result = ordered_accumulation.OrderedTensorAccumulator().accumulate(
|
||||
base,
|
||||
(torch.tensor([3.0, 4.0]), torch.tensor([5.0, 6.0])),
|
||||
)
|
||||
assert result.tolist() == [9.0, 12.0]
|
||||
assert not any(name == "triton" or name.startswith("triton.") for name in sys.modules)
|
||||
"""
|
||||
completed = subprocess.run(
|
||||
[sys.executable, "-c", script],
|
||||
cwd=Path(__file__).resolve().parents[1],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
check=False,
|
||||
)
|
||||
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
|
||||
|
||||
def test_resolver_caches_one_missing_result_and_warns_once(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Treat an absent Triton package as one observable optional miss."""
|
||||
|
||||
calls: list[str] = []
|
||||
|
||||
def missing_import(name: str) -> object:
|
||||
calls.append(name)
|
||||
raise ModuleNotFoundError("missing", name="triton")
|
||||
|
||||
resolver = TritonRuntimeResolver(import_module=missing_import)
|
||||
|
||||
with caplog.at_level("WARNING"):
|
||||
assert resolver.resolve("fake.backend") is None
|
||||
assert resolver.resolve("fake.backend") is None
|
||||
|
||||
assert calls == ["fake.backend"]
|
||||
assert [record.message for record in caplog.records] == [
|
||||
"Triton acceleration is unavailable; using the Torch execution path"
|
||||
]
|
||||
|
||||
|
||||
def test_resolver_exposes_broken_backend_import_with_original_cause() -> None:
|
||||
"""Fail visibly when a present backend cannot initialize correctly."""
|
||||
|
||||
failure = RuntimeError("JIT initialization failed")
|
||||
|
||||
def broken_import(_name: str) -> object:
|
||||
raise failure
|
||||
|
||||
resolver = TritonRuntimeResolver(import_module=broken_import)
|
||||
|
||||
with pytest.raises(RuntimeError, match="failed to initialize") as raised:
|
||||
resolver.resolve("fake.backend")
|
||||
|
||||
assert raised.value.__cause__ is failure
|
||||
|
||||
|
||||
def test_resolver_is_thread_safe_and_returns_one_cached_backend() -> None:
|
||||
"""Publish exactly one imported backend across concurrent callers."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
backend = object()
|
||||
calls: list[str] = []
|
||||
|
||||
def import_backend(name: str) -> object:
|
||||
calls.append(name)
|
||||
return backend
|
||||
|
||||
resolver = TritonRuntimeResolver(import_module=import_backend)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as executor:
|
||||
results = tuple(executor.map(resolver.resolve, ("fake.backend",) * 32))
|
||||
|
||||
assert all(result is backend for result in results)
|
||||
assert calls == ["fake.backend"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"missing_name",
|
||||
["fake.backend", "unrelated_dependency"],
|
||||
)
|
||||
def test_resolver_does_not_hide_non_triton_module_failures(missing_name: str) -> None:
|
||||
"""Reserve optional fallback exclusively for the Triton package family."""
|
||||
|
||||
def missing_import(_name: str) -> object:
|
||||
raise ModuleNotFoundError("missing", name=missing_name)
|
||||
|
||||
resolver = TritonRuntimeResolver(
|
||||
import_module=missing_import,
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="failed to initialize"):
|
||||
resolver.resolve("fake.backend")
|
||||
@@ -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 typed PPM NegPiP conditioning and call-local option adaptation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import comfy.conds
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from simple_syrup.runtime.ppm_negpip_interop import (
|
||||
PpmNegpipInterop,
|
||||
PpmNegpipSemantics,
|
||||
)
|
||||
|
||||
|
||||
def test_anima_adapter_extracts_exact_typed_value_multiplier() -> None:
|
||||
"""Convert PPM's model condition to context-aligned execution state."""
|
||||
|
||||
interop = _anima_interop()
|
||||
context = torch.zeros((1, 3, 4), dtype=torch.float16)
|
||||
source = torch.tensor([[[1], [-1], [1]]], dtype=torch.int32)
|
||||
|
||||
multiplier = interop.extract_value_multiplier(
|
||||
{"c_ppm_negpip_mask": comfy.conds.CONDRegular(source)},
|
||||
context,
|
||||
)
|
||||
|
||||
assert multiplier is not None
|
||||
assert multiplier.dtype is context.dtype
|
||||
assert multiplier.device == context.device
|
||||
assert multiplier.tolist() == [[[1.0], [-1.0], [1.0]]]
|
||||
|
||||
|
||||
def test_anima_adapter_uses_neutral_multiplier_when_condition_is_absent() -> None:
|
||||
"""Represent an all-positive prompt without leaving branch state partial."""
|
||||
|
||||
context = torch.zeros((2, 3, 4))
|
||||
|
||||
multiplier = _anima_interop().extract_value_multiplier({}, context)
|
||||
|
||||
assert multiplier is not None
|
||||
assert torch.equal(multiplier, torch.ones((2, 3, 1)))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source",
|
||||
[
|
||||
torch.ones((1, 2, 1)),
|
||||
torch.zeros((1, 3, 1)),
|
||||
torch.ones((1, 3, 2)),
|
||||
],
|
||||
)
|
||||
def test_anima_adapter_rejects_misaligned_or_nonbinary_masks(
|
||||
source: torch.Tensor,
|
||||
) -> None:
|
||||
"""Fail closed before malformed PPM state reaches regional packing."""
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
_anima_interop().extract_value_multiplier(
|
||||
{"c_ppm_negpip_mask": SimpleNamespace(cond=source)},
|
||||
torch.zeros((1, 3, 4)),
|
||||
)
|
||||
|
||||
|
||||
def test_anima_adapter_publishes_mask_on_an_isolated_option_copy() -> None:
|
||||
"""Keep the ordinary call options unchanged outside original cross-attention."""
|
||||
|
||||
old_mask = torch.ones((1, 2, 1))
|
||||
packed = torch.tensor([[[1.0], [-1.0]], [[-1.0], [1.0]]])
|
||||
source: dict[str, object] = {
|
||||
"ppm_negpip_mask": old_mask,
|
||||
"preserved": object(),
|
||||
}
|
||||
|
||||
prepared = _anima_interop().prepare_anima_transformer_options(source, packed)
|
||||
|
||||
assert prepared is not source
|
||||
assert prepared["preserved"] is source["preserved"]
|
||||
assert prepared["ppm_negpip_mask"] is packed
|
||||
assert source["ppm_negpip_mask"] is old_mask
|
||||
|
||||
|
||||
def _anima_interop() -> PpmNegpipInterop:
|
||||
"""Return one focused admitted Anima semantic adapter."""
|
||||
|
||||
return PpmNegpipInterop(
|
||||
PpmNegpipSemantics.ANIMA_VALUE_MASK,
|
||||
lambda *args, **kwargs: (args, kwargs),
|
||||
)
|
||||
@@ -26,6 +26,7 @@ from simple_syrup.runtime.comfy_conditioning_model_loader import (
|
||||
from simple_syrup.runtime.comfy_conditioning_processing import (
|
||||
ComfyRegionalConditioningProcessor,
|
||||
)
|
||||
from simple_syrup.runtime.ppm_negpip_interop import PpmNegpipInterop
|
||||
from simple_syrup.runtime.regional_lora_conditioning_adapter import (
|
||||
RegionalLoraConditioningAdapter,
|
||||
)
|
||||
@@ -135,6 +136,7 @@ def test_profiled_collaborators_preserve_arguments_results_and_stage_order(
|
||||
noise: torch.Tensor,
|
||||
device: torch.device,
|
||||
context_validator: RegionalContextValidator,
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> ProcessedRegionalAttentionPlan:
|
||||
calls.append(
|
||||
(
|
||||
@@ -145,6 +147,7 @@ def test_profiled_collaborators_preserve_arguments_results_and_stage_order(
|
||||
"noise": noise,
|
||||
"device": device,
|
||||
"context_validator": context_validator,
|
||||
"negpip": negpip,
|
||||
},
|
||||
)
|
||||
)
|
||||
@@ -190,6 +193,7 @@ def test_profiled_collaborators_preserve_arguments_results_and_stage_order(
|
||||
"noise": noise,
|
||||
"device": device,
|
||||
"context_validator": validator,
|
||||
"negpip": None,
|
||||
}
|
||||
assert _stages(caplog) == [
|
||||
"source_model_load",
|
||||
|
||||
@@ -60,6 +60,63 @@ def test_schedule_encode_graph_builds_single_conditioning_outputs(
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("positive_prompt", "negative_prompt"),
|
||||
[
|
||||
("portrait of (1girl:-2.0)", "blur"),
|
||||
("portrait", "(blur:-0.5)"),
|
||||
("portrait [SEP] (hands:-1.2)", "blur"),
|
||||
("portrait [0:(eyes:-1.5):0.5]", "blur"),
|
||||
],
|
||||
)
|
||||
def test_schedule_encode_graph_injects_negpip_for_negative_weights(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
positive_prompt: str,
|
||||
negative_prompt: str,
|
||||
) -> None:
|
||||
"""Any effective negative segment weight prepares MODEL and CLIP first."""
|
||||
|
||||
calls = _install_fake_prompt_control(monkeypatch)
|
||||
|
||||
output = PromptControlScheduleEncodeGraphBuilder().build(
|
||||
model=["model", 0],
|
||||
clip=["clip", 0],
|
||||
positive_prompt=positive_prompt,
|
||||
negative_prompt=negative_prompt,
|
||||
)
|
||||
|
||||
assert output.expand is not None
|
||||
preparation_nodes = [
|
||||
node
|
||||
for node in output.expand.values()
|
||||
if node["class_type"] == "SimpleSyrup.ApplyAutomaticNegpip"
|
||||
]
|
||||
assert len(preparation_nodes) == 1
|
||||
assert calls["encode"]
|
||||
assert all(call["clip"] != ["clip", 0] for call in calls["encode"])
|
||||
|
||||
|
||||
def test_schedule_encode_graph_does_not_inject_negpip_for_nonnegative_weights(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Ordinary and positive-weight prompts retain the existing graph path."""
|
||||
|
||||
_install_fake_prompt_control(monkeypatch)
|
||||
|
||||
output = PromptControlScheduleEncodeGraphBuilder().build(
|
||||
model=["model", 0],
|
||||
clip=["clip", 0],
|
||||
positive_prompt="portrait of (1girl:2.0)",
|
||||
negative_prompt="blur",
|
||||
)
|
||||
|
||||
assert output.expand is not None
|
||||
assert not any(
|
||||
node["class_type"] == "SimpleSyrup.ApplyAutomaticNegpip"
|
||||
for node in output.expand.values()
|
||||
)
|
||||
|
||||
|
||||
def test_schedule_encode_graph_packs_both_sides_to_matched_segment_counts(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
|
||||
@@ -108,6 +108,56 @@ def test_batching_builds_canonical_regions_with_base_fallback() -> None:
|
||||
]
|
||||
|
||||
|
||||
def test_batching_aligns_value_multipliers_with_cfg_regions_and_fallbacks() -> None:
|
||||
"""Keep each scheduled branch's value semantics in identical chunk order."""
|
||||
|
||||
source = _plan()
|
||||
plan = ProcessedRegionalAttentionPlan(
|
||||
ProcessedRegionalAttentionBranch(
|
||||
_context_with_multiplier(source.positive.base_context, 1.0),
|
||||
(
|
||||
_context_with_multiplier(
|
||||
source.positive.regional_contexts[0],
|
||||
-1.0,
|
||||
),
|
||||
_context_with_multiplier(
|
||||
source.positive.regional_contexts[1],
|
||||
1.0,
|
||||
),
|
||||
),
|
||||
),
|
||||
ProcessedRegionalAttentionBranch(
|
||||
_context_with_multiplier(source.negative.base_context, -1.0),
|
||||
(
|
||||
_context_with_multiplier(
|
||||
source.negative.regional_contexts[0],
|
||||
1.0,
|
||||
),
|
||||
),
|
||||
),
|
||||
source.mask_bank,
|
||||
source.lora_plan,
|
||||
)
|
||||
|
||||
aligned = REGIONAL_ATTENTION_BATCHING_SERVICE.align(
|
||||
plan,
|
||||
base_context=_runtime_base(plan, [1, 0], 2),
|
||||
cond_or_uncond=[1, 0],
|
||||
conditioning_uuids=_uuids_for_selectors(plan, [1, 0]),
|
||||
sigma=0.5,
|
||||
latent_batch_size=2,
|
||||
)
|
||||
|
||||
assert aligned.base_value_multiplier is not None
|
||||
assert aligned.base_value_multiplier[:, 0, 0].tolist() == [-1.0, -1.0, 1.0, 1.0]
|
||||
region_zero = aligned.regions[0].entries[0].cross_attention_value_multiplier
|
||||
region_one = aligned.regions[1].entries[0].cross_attention_value_multiplier
|
||||
assert region_zero is not None
|
||||
assert region_one is not None
|
||||
assert region_zero[:, 0, 0].tolist() == [1.0, 1.0, -1.0, -1.0]
|
||||
assert region_one[:, 0, 0].tolist() == [-1.0, -1.0, 1.0, 1.0]
|
||||
|
||||
|
||||
def test_batching_preserves_all_regional_entries_and_per_sample_strengths() -> None:
|
||||
"""Align simultaneous regional entries without collapsing their order."""
|
||||
|
||||
@@ -409,6 +459,34 @@ def _multi_entry_context(
|
||||
)
|
||||
|
||||
|
||||
def _context_with_multiplier(
|
||||
context: ProcessedRegionalAttentionContext,
|
||||
value: float,
|
||||
) -> ProcessedRegionalAttentionContext:
|
||||
"""Copy one context with a uniform sequence-aligned value multiplier."""
|
||||
|
||||
return ProcessedRegionalAttentionContext(
|
||||
context.conditioning_index,
|
||||
context.region_index,
|
||||
tuple(
|
||||
ProcessedRegionalAttentionEntry(
|
||||
entry.entry_index,
|
||||
entry.uuid,
|
||||
entry.schedule,
|
||||
entry.cross_attention,
|
||||
entry.strength,
|
||||
torch.full(
|
||||
(*entry.cross_attention.shape[:2], 1),
|
||||
value,
|
||||
dtype=entry.cross_attention.dtype,
|
||||
device=entry.cross_attention.device,
|
||||
),
|
||||
)
|
||||
for entry in context.entries
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _entry(
|
||||
entry_index: int,
|
||||
tensor: torch.Tensor,
|
||||
|
||||
@@ -30,6 +30,7 @@ from simple_syrup.domain.regional_model_capabilities import (
|
||||
RegionalReferenceLatentPolicy,
|
||||
RegionalSpatialPatchSupport,
|
||||
)
|
||||
from simple_syrup.runtime.ppm_negpip_interop import PpmNegpipSemantics
|
||||
from simple_syrup.runtime.regional_model_patch_interop import (
|
||||
REGIONAL_MODEL_PATCH_INTEROP_VALIDATOR,
|
||||
RegionalPreservedModelModifier,
|
||||
@@ -46,6 +47,11 @@ class _FixtureModel(torch.nn.Module):
|
||||
self.projection = torch.nn.Linear(1, 1)
|
||||
self.latent_format = SimpleNamespace(latent_channels=4)
|
||||
|
||||
def extra_conds(self, **_kwargs: object) -> dict[str, object]:
|
||||
"""Expose the object path patched by Anima NegPiP."""
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
def test_validator_preserves_easycache_and_unrelated_model_state() -> None:
|
||||
"""Accept EasyCache while retaining every collaborator-owned surface."""
|
||||
@@ -186,28 +192,152 @@ def test_validator_rejects_both_core_caches_without_mutating_them() -> None:
|
||||
assert combined.wrappers == before_wrappers
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"family",
|
||||
[RegionalModelFamily.ANIMA, RegionalModelFamily.STANDARD_UNET],
|
||||
)
|
||||
def test_validator_rejects_named_negpip_before_generic_attn2_collision(
|
||||
family: RegionalModelFamily,
|
||||
) -> None:
|
||||
"""Report the installed modifier and regional mask misalignment by name."""
|
||||
def test_validator_admits_exact_standard_unet_negpip_without_mutation() -> None:
|
||||
"""Retain PPM's exact split-K/V callback as typed interop evidence."""
|
||||
|
||||
model = _patcher()
|
||||
callback = _identity_callback(
|
||||
"custom_nodes.ComfyUI-ppm.src.negpip.unet_negpip",
|
||||
"sdxl_attn2_negpip",
|
||||
)
|
||||
model.model_options["ppm_negpip"] = True
|
||||
model.set_model_attn2_patch(callback)
|
||||
|
||||
report = REGIONAL_MODEL_PATCH_INTEROP_VALIDATOR.validate(
|
||||
model,
|
||||
_capabilities(RegionalModelFamily.STANDARD_UNET),
|
||||
)
|
||||
|
||||
assert report.negpip is not None
|
||||
assert report.negpip.semantics is PpmNegpipSemantics.STANDARD_UNET_SPLIT_KEY_VALUE
|
||||
assert report.negpip.attention_patch is callback
|
||||
assert model.model_options["transformer_options"]["patches"]["attn2_patch"] == [
|
||||
callback
|
||||
]
|
||||
|
||||
|
||||
def test_validator_admits_exact_anima_negpip_without_mutation() -> None:
|
||||
"""Retain PPM's complete Anima callback, wrapper, and object-patch family."""
|
||||
|
||||
model = _patcher()
|
||||
callback = _identity_callback(
|
||||
"custom_nodes.ComfyUI-ppm.src.negpip.anima_negpip",
|
||||
"cosmos_attn2_negpip",
|
||||
)
|
||||
wrapper = _identity_callback(
|
||||
"custom_nodes.ComfyUI-ppm.src.negpip.anima_negpip",
|
||||
"cosmos_diffusion_negpip_wrapper",
|
||||
)
|
||||
extra_conds = _identity_callback(
|
||||
"custom_nodes.ComfyUI-ppm.src.negpip.anima_negpip",
|
||||
("anima_extra_conds_negpip_wrapper.<locals>._anima_extra_conds_negpip_wrapper"),
|
||||
)
|
||||
model.model_options["ppm_negpip"] = True
|
||||
model.set_model_attn2_patch(callback)
|
||||
model.add_wrapper_with_key(
|
||||
WrappersMP.DIFFUSION_MODEL,
|
||||
"ppm_negpip_anima",
|
||||
lambda executor, *args, **kwargs: executor(*args, **kwargs),
|
||||
wrapper,
|
||||
)
|
||||
model.set_model_attn2_patch(lambda q, k, v, **kwargs: {"q": q, "k": k, "v": v})
|
||||
model.add_object_patch("extra_conds", extra_conds)
|
||||
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="NegPiP.*ordinary conditioning batch.*regional branch batch",
|
||||
):
|
||||
report = REGIONAL_MODEL_PATCH_INTEROP_VALIDATOR.validate(
|
||||
model,
|
||||
_capabilities(RegionalModelFamily.ANIMA),
|
||||
)
|
||||
|
||||
assert report.negpip is not None
|
||||
assert report.negpip.semantics is PpmNegpipSemantics.ANIMA_VALUE_MASK
|
||||
assert report.negpip.attention_patch is callback
|
||||
assert model.wrappers[WrappersMP.DIFFUSION_MODEL]["ppm_negpip_anima"] == [wrapper]
|
||||
assert model.object_patches["extra_conds"] is extra_conds
|
||||
|
||||
|
||||
def test_validator_admits_owned_standard_negpip_without_mutation() -> None:
|
||||
"""Retain the automatic node's owned split-K/V callback identity."""
|
||||
|
||||
from simple_syrup.runtime.negpip.standard import standard_attn2_negpip
|
||||
|
||||
model = _patcher()
|
||||
model.model_options["ppm_negpip"] = True
|
||||
model.set_model_attn2_patch(standard_attn2_negpip)
|
||||
|
||||
report = REGIONAL_MODEL_PATCH_INTEROP_VALIDATOR.validate(
|
||||
model,
|
||||
_capabilities(RegionalModelFamily.STANDARD_UNET),
|
||||
)
|
||||
|
||||
assert report.negpip is not None
|
||||
assert report.negpip.attention_patch is standard_attn2_negpip
|
||||
|
||||
|
||||
def test_validator_admits_owned_anima_negpip_without_mutation() -> None:
|
||||
"""Retain the automatic node's complete owned Anima callback family."""
|
||||
|
||||
from simple_syrup.runtime.negpip.anima import (
|
||||
anima_attn2_negpip,
|
||||
anima_diffusion_negpip_wrapper,
|
||||
anima_extra_conds_negpip_wrapper,
|
||||
)
|
||||
|
||||
model = _patcher()
|
||||
model.model_options["ppm_negpip"] = True
|
||||
model.set_model_attn2_patch(anima_attn2_negpip)
|
||||
model.add_wrapper_with_key(
|
||||
WrappersMP.DIFFUSION_MODEL,
|
||||
"ppm_negpip_anima",
|
||||
anima_diffusion_negpip_wrapper,
|
||||
)
|
||||
model.add_object_patch(
|
||||
"extra_conds",
|
||||
anima_extra_conds_negpip_wrapper(lambda **kwargs: {}),
|
||||
)
|
||||
|
||||
report = REGIONAL_MODEL_PATCH_INTEROP_VALIDATOR.validate(
|
||||
model,
|
||||
_capabilities(RegionalModelFamily.ANIMA),
|
||||
)
|
||||
|
||||
assert report.negpip is not None
|
||||
assert report.negpip.attention_patch is anima_attn2_negpip
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("family", "configure", "message"),
|
||||
[
|
||||
(
|
||||
RegionalModelFamily.STANDARD_UNET,
|
||||
lambda model: model.model_options.__setitem__("ppm_negpip", True),
|
||||
"requires exactly its PPM split-K/V",
|
||||
),
|
||||
(
|
||||
RegionalModelFamily.STANDARD_UNET,
|
||||
lambda model: model.set_model_attn2_patch(
|
||||
_identity_callback(
|
||||
"custom_nodes.ComfyUI-ppm.src.negpip.unet_negpip",
|
||||
"sdxl_attn2_negpip",
|
||||
)
|
||||
),
|
||||
"incomplete NegPiP patch family",
|
||||
),
|
||||
(
|
||||
RegionalModelFamily.ANIMA,
|
||||
lambda model: model.model_options.__setitem__("ppm_negpip", True),
|
||||
"requires exactly its PPM attention patch",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_validator_rejects_partial_or_foreign_negpip_families(
|
||||
family: RegionalModelFamily,
|
||||
configure: Callable[[ModelPatcher], object],
|
||||
message: str,
|
||||
) -> None:
|
||||
"""Fail closed before partial or identity-foreign NegPiP state is composed."""
|
||||
|
||||
model = _patcher()
|
||||
configure(model)
|
||||
|
||||
with pytest.raises(ValueError, match=message):
|
||||
REGIONAL_MODEL_PATCH_INTEROP_VALIDATOR.validate(
|
||||
model,
|
||||
_capabilities(family),
|
||||
@@ -313,6 +443,19 @@ def _patcher() -> ModelPatcher:
|
||||
)
|
||||
|
||||
|
||||
def _identity_callback(module: str, qualname: str) -> Callable[..., object]:
|
||||
"""Build one executable callback carrying a stable PPM definition identity."""
|
||||
|
||||
def callback(*args: object, **_kwargs: object) -> object:
|
||||
"""Return callback inputs for model-state-only admission tests."""
|
||||
|
||||
return args
|
||||
|
||||
callback.__module__ = module
|
||||
callback.__qualname__ = qualname
|
||||
return callback
|
||||
|
||||
|
||||
def _capabilities(family: RegionalModelFamily) -> RegionalModelCapabilities:
|
||||
"""Build the exact family contract consumed by modifier admission."""
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ def test_regional_patch_stack_preserves_state_lineage_and_runtime_nesting() -> N
|
||||
|
||||
assert stack.user_model is source
|
||||
assert stack.attention_model.parent is source
|
||||
assert stack.sampling_model.parent is stack.attention_model
|
||||
assert stack.sampling_model.parent is source
|
||||
assert stack.sampling_model.patches["weight"] == [global_lora_patch]
|
||||
assert (
|
||||
source.get_wrappers("diffusion_model", "simple_syrup.attention_coupling") == []
|
||||
|
||||
@@ -41,6 +41,9 @@ def test_every_matrix_case_requires_exact_modifier_and_terminal_evidence(
|
||||
observed: RegionalPatchInteropHistory
|
||||
if case.expect_success:
|
||||
model_call_count = STEPS
|
||||
diagnostic_record_count = model_call_count * (
|
||||
2 if case.model_family is PatchInteropModelFamily.SDXL else 1
|
||||
)
|
||||
observed = RegionalPatchInteropSuccess(
|
||||
snapshot,
|
||||
{
|
||||
@@ -49,7 +52,7 @@ def test_every_matrix_case_requires_exact_modifier_and_terminal_evidence(
|
||||
"runtime_ms": 10.0,
|
||||
"peak_vram_bytes": 1,
|
||||
},
|
||||
_diagnostics(case, workflow, record_count=model_call_count),
|
||||
_diagnostics(case, workflow, record_count=diagnostic_record_count),
|
||||
ImageReference("result.png", "", "output"),
|
||||
None,
|
||||
)
|
||||
@@ -69,7 +72,7 @@ def test_every_matrix_case_requires_exact_modifier_and_terminal_evidence(
|
||||
assert validated.model_call_count == (STEPS if case.expect_success else 0)
|
||||
|
||||
|
||||
def test_success_requires_one_diagnostic_record_per_actual_model_call() -> None:
|
||||
def test_success_requires_family_specific_diagnostic_records_per_model_call() -> None:
|
||||
"""Reject cache evidence whose diagnostics omit an executed model call."""
|
||||
|
||||
case = next(
|
||||
@@ -89,7 +92,7 @@ def test_success_requires_one_diagnostic_record_per_actual_model_call() -> None:
|
||||
None,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="one diagnostic record per model call"):
|
||||
with pytest.raises(ValueError, match="model-family execution shape"):
|
||||
validate_case(case, workflow, observed)
|
||||
|
||||
|
||||
@@ -216,7 +219,8 @@ def _diagnostics(
|
||||
PatchInteropSpatialMode.CONTEXTUAL: ("tile", "contextual_global"),
|
||||
}[case.spatial_mode]
|
||||
snapshots = [
|
||||
_diagnostic_snapshot(modes[index % len(modes)]) for index in range(record_count)
|
||||
_diagnostic_snapshot(case, modes[index % len(modes)])
|
||||
for index in range(record_count)
|
||||
]
|
||||
return {
|
||||
"run_id": workflow.diagnostics_run_id,
|
||||
@@ -225,8 +229,25 @@ def _diagnostics(
|
||||
}
|
||||
|
||||
|
||||
def _diagnostic_snapshot(mode: str) -> JsonObject:
|
||||
"""Return one exact static-PRIMARY_ADAPTER diagnostic record."""
|
||||
def _diagnostic_snapshot(
|
||||
case: RegionalPatchInteropCase,
|
||||
mode: str,
|
||||
) -> JsonObject:
|
||||
"""Return one exact family-specific regional diagnostic record."""
|
||||
|
||||
if case.model_family is PatchInteropModelFamily.SDXL:
|
||||
return {
|
||||
"strategy": "attention_coupling",
|
||||
"backend": "comfy.ldm.modules.diffusionmodules.openaimodel.UNetModel",
|
||||
"spatial_mode": mode,
|
||||
"region_count": 2,
|
||||
"active_region_indices": [0, 1],
|
||||
"estimated_work": {
|
||||
"cross_attention_branch_multiplier": 3.0,
|
||||
"cross_attention_formula": "base_plus_region_count",
|
||||
"denoiser_call_multiplier": 1.0,
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
"strategy": "attention_coupling",
|
||||
|
||||
@@ -23,13 +23,13 @@ from tools.regional_patch_interop_integration.workflow import (
|
||||
)
|
||||
|
||||
|
||||
def test_matrix_contains_five_acceptances_and_six_exact_rejections() -> None:
|
||||
def test_matrix_contains_seven_acceptances_and_four_exact_rejections() -> None:
|
||||
"""Keep every required modifier, spatial, scheduled, and family case."""
|
||||
|
||||
definitions = cases()
|
||||
|
||||
assert len(definitions) == 11
|
||||
assert sum(case.expect_success for case in definitions) == 5
|
||||
assert sum(case.expect_success for case in definitions) == 7
|
||||
assert {case.modifier for case in definitions} == set(PatchInteropModifier)
|
||||
assert {case.spatial_mode for case in definitions} == set(PatchInteropSpatialMode)
|
||||
assert {case.model_family for case in definitions} == set(PatchInteropModelFamily)
|
||||
@@ -154,11 +154,9 @@ def test_scheduled_cache_graph_authors_the_exact_regional_adapter_interval() ->
|
||||
|
||||
|
||||
def test_sdxl_negpip_graph_uses_public_modifier_snapshot_and_sampler() -> None:
|
||||
"""Submit SDXL NegPiP through the same evidence and rejection boundary."""
|
||||
"""Submit SDXL NegPiP through the same evidence and execution boundary."""
|
||||
|
||||
definition = next(
|
||||
case for case in cases() if case.case_id == "sdxl-negpip-rejected"
|
||||
)
|
||||
definition = next(case for case in cases() if case.case_id == "sdxl-negpip")
|
||||
workflow = RegionalPatchInteropWorkflowBuilder().build(
|
||||
definition,
|
||||
run_id="run",
|
||||
|
||||
@@ -75,6 +75,7 @@ BASE_NODE_IDS = [
|
||||
]
|
||||
|
||||
PROMPT_CONTROL_NODE_IDS = [
|
||||
"SimpleSyrup.ApplyAutomaticNegpip",
|
||||
"SimpleSyrup.AttachRegionalGlobalConditioning",
|
||||
"SimpleSyrup.EncodePromptBatchWithPromptControl",
|
||||
"SimpleSyrup.LabelRegionalLoraHooks",
|
||||
|
||||
@@ -23,9 +23,17 @@ def test_sam_model_loader_contract() -> None:
|
||||
assert SAMModelLoader.CATEGORY == "SimpleSyrup/Masking"
|
||||
|
||||
|
||||
def test_sam_model_loader_declares_expected_inputs() -> None:
|
||||
def test_sam_model_loader_declares_expected_inputs(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""SAM loader inputs are deterministic and loader-owned."""
|
||||
|
||||
def catalog_choices() -> list[str]:
|
||||
"""Return the catalog choices expected by this declaration test."""
|
||||
|
||||
return ["sam_vit_b (375MB)", "FastSAM-s (23MB)"]
|
||||
|
||||
monkeypatch.setattr(SAMModelLoader._choices, "sam_choices", catalog_choices)
|
||||
input_types: dict[str, dict[str, tuple[Any, ...]]] = SAMModelLoader.INPUT_TYPES()
|
||||
required = input_types["required"]
|
||||
|
||||
|
||||
@@ -144,6 +144,37 @@ def test_spatial_args_preserve_batch_metadata_references_and_source_args() -> No
|
||||
assert "spatial_batch_layout" not in existing_namespace
|
||||
|
||||
|
||||
def test_spatial_args_project_canvas_reference_latents_when_requested() -> None:
|
||||
"""Crop canvas-aligned references while preserving independent references."""
|
||||
|
||||
canvas_reference = torch.arange(1 * 2 * 4 * 8, dtype=torch.float32).reshape(
|
||||
(1, 2, 4, 8)
|
||||
)
|
||||
independent_reference = torch.full((1, 2, 3, 5), 7.0)
|
||||
layout = _layout(_left_right_views(), input_batch_size=1)
|
||||
|
||||
transformed = make_spatial_view_model_args(
|
||||
args={
|
||||
"input": torch.zeros((1, 1, 4, 8)),
|
||||
"timestep": torch.ones((1,)),
|
||||
"c": {"ref_latents": [canvas_reference, independent_reference]},
|
||||
},
|
||||
layout=layout,
|
||||
project_canvas_reference_latents=True,
|
||||
)
|
||||
|
||||
references = transformed["c"]["ref_latents"]
|
||||
assert isinstance(references, list)
|
||||
assert torch.equal(
|
||||
references[0],
|
||||
torch.cat((canvas_reference[..., :4], canvas_reference[..., 4:]), dim=0),
|
||||
)
|
||||
assert torch.equal(
|
||||
references[1],
|
||||
torch.cat((independent_reference, independent_reference), dim=0),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("transformer_options", "message"),
|
||||
[
|
||||
|
||||
@@ -14,6 +14,10 @@ import torch
|
||||
from simple_syrup.runtime.attention_coupling.unet_attn2_execution import (
|
||||
UnetAttn2Execution,
|
||||
)
|
||||
from simple_syrup.runtime.ppm_negpip_interop import (
|
||||
PpmNegpipInterop,
|
||||
PpmNegpipSemantics,
|
||||
)
|
||||
from simple_syrup.runtime.regional_lora.standard_unet_variant_base_attention import (
|
||||
StandardUnetVariantBaseAttention,
|
||||
)
|
||||
@@ -67,3 +71,32 @@ def test_prepare_rejects_any_preexisting_attn2_callback_surface(key: str) -> Non
|
||||
|
||||
with pytest.raises(ValueError, match="already contains"):
|
||||
StandardUnetVariantBaseAttention(_Resolver()).prepare({"patches": {key: []}})
|
||||
|
||||
|
||||
def test_prepare_places_coupling_before_exact_preserved_negpip_callback() -> None:
|
||||
"""Pack regional alternating tokens before PPM selects K and V views."""
|
||||
|
||||
def negpip(*args: object, **_kwargs: object) -> tuple[object, ...]:
|
||||
"""Represent the identity-validated PPM split callback."""
|
||||
|
||||
return args
|
||||
|
||||
interop = PpmNegpipInterop(
|
||||
PpmNegpipSemantics.STANDARD_UNET_SPLIT_KEY_VALUE,
|
||||
negpip,
|
||||
)
|
||||
source: dict[str, object] = {"patches": {"attn2_patch": [negpip]}}
|
||||
|
||||
prepared = StandardUnetVariantBaseAttention(
|
||||
_Resolver(),
|
||||
negpip=interop,
|
||||
).prepare(source)
|
||||
|
||||
patches = prepared["patches"]
|
||||
assert isinstance(patches, dict)
|
||||
installed = patches["attn2_patch"]
|
||||
assert isinstance(installed, list)
|
||||
assert len(installed) == 2
|
||||
assert installed[1] is negpip
|
||||
assert callable(installed[0])
|
||||
assert source == {"patches": {"attn2_patch": [negpip]}}
|
||||
|
||||
@@ -192,3 +192,32 @@ def test_notice_records_sampler_and_tiled_diffusion_provenance() -> None:
|
||||
assert "k-diffusion Euler ancestral sampler" in notice
|
||||
assert "Mixture of Diffusers and MultiDiffusion tiled diffusion behavior" in notice
|
||||
assert "regional prompt mask blending" in notice
|
||||
|
||||
|
||||
def test_negpip_provenance_records_baseline_and_original_implementations() -> None:
|
||||
"""NegPiP should trace through PPM to both credited original projects."""
|
||||
|
||||
manifest = tomllib.loads(
|
||||
(REPO_ROOT / "third_party" / "manifest.toml").read_text(encoding="utf-8")
|
||||
)
|
||||
components = {component["name"]: component for component in manifest["component"]}
|
||||
|
||||
negpip = components["NegPiP prompt weighting"]
|
||||
license_path = REPO_ROOT / negpip["license_file"]
|
||||
|
||||
assert negpip["license"] == "AGPL-3.0"
|
||||
assert "GNU AFFERO GENERAL PUBLIC" in license_path.read_text(encoding="utf-8")
|
||||
assert negpip["source"] == "https://github.com/pamparamm/ComfyUI-ppm"
|
||||
assert negpip["revision"] == "6c6c360155cace9d7091306c1b8e26d9c7438620"
|
||||
assert negpip["origin_sources"] == [
|
||||
"https://github.com/laksjdjf/cd-tuner_negpip-ComfyUI@"
|
||||
"938b838546cf774dc8841000996552cef52cccf3",
|
||||
"https://github.com/hako-mikan/sd-webui-negpip@"
|
||||
"fb7151f327ae56195f08b30b70d459493dadedbb",
|
||||
]
|
||||
assert negpip["vendored_files"] == [
|
||||
"simple_syrup/runtime/negpip/standard.py",
|
||||
"simple_syrup/runtime/negpip/anima.py",
|
||||
"simple_syrup/runtime/negpip/krea2.py",
|
||||
"simple_syrup/services/negpip_model_service.py",
|
||||
]
|
||||
|
||||
@@ -13,6 +13,15 @@ from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from simple_syrup.runtime.model_catalog import get_ultralytics_entry
|
||||
from simple_syrup.runtime.model_choices import ModelChoiceService
|
||||
from simple_syrup.runtime.model_downloads import (
|
||||
DownloadRequest,
|
||||
DownloadResult,
|
||||
ModelDownloader,
|
||||
ProgressReporter,
|
||||
)
|
||||
from simple_syrup.runtime.settings import SimpleSyrupSettings
|
||||
from simple_syrup.runtime.ultralytics_loader import (
|
||||
NO_LOCAL_ULTRALYTICS_MODELS,
|
||||
LoadedUltralyticsDetector,
|
||||
@@ -32,7 +41,11 @@ def test_model_choices_list_conventional_folders(tmp_path: Path) -> None:
|
||||
(models_dir / "ultralytics" / "bbox" / "face.pt").write_bytes(b"")
|
||||
(models_dir / "ultralytics" / "segm" / "person.pt").write_bytes(b"")
|
||||
|
||||
service = UltralyticsLoaderService(folder_paths_module=_folder_paths(models_dir))
|
||||
folder_paths = _folder_paths(models_dir)
|
||||
service = UltralyticsLoaderService(
|
||||
folder_paths_module=folder_paths,
|
||||
choice_service=_choice_service(show_downloadable_models=False),
|
||||
)
|
||||
|
||||
assert service.model_choices() == ["bbox/face.pt", "root.pt", "segm/person.pt"]
|
||||
|
||||
@@ -43,7 +56,75 @@ def test_model_choices_returns_sentinel_when_no_models(tmp_path: Path) -> None:
|
||||
models_dir = tmp_path / "models"
|
||||
models_dir.mkdir()
|
||||
|
||||
service = UltralyticsLoaderService(folder_paths_module=_folder_paths(models_dir))
|
||||
folder_paths = _folder_paths(models_dir)
|
||||
service = UltralyticsLoaderService(
|
||||
folder_paths_module=folder_paths,
|
||||
choice_service=_choice_service(show_downloadable_models=False),
|
||||
)
|
||||
|
||||
assert service.model_choices() == [NO_LOCAL_ULTRALYTICS_MODELS]
|
||||
|
||||
|
||||
def test_model_choices_include_curated_downloadable_models(tmp_path: Path) -> None:
|
||||
"""Downloadable mode exposes the complete curated Anzhc model selection."""
|
||||
|
||||
folder_paths = _folder_paths(tmp_path / "models")
|
||||
service = UltralyticsLoaderService(
|
||||
folder_paths_module=folder_paths,
|
||||
choice_service=_choice_service(show_downloadable_models=True),
|
||||
)
|
||||
|
||||
choices = service.model_choices()
|
||||
|
||||
assert len(choices) == 22
|
||||
assert "Anzhc Face -seg (6.52MB)" in choices
|
||||
assert "Bingsu Hand YOLOv8n (6.23MB)" in choices
|
||||
assert "Fuyucchi YOLOv8x6 Anime Face (195MB)" in choices
|
||||
assert "Anzhcs Breast size det cls v8 640 y11m (38.70MB)" not in choices
|
||||
assert not any("Drone" in choice for choice in choices)
|
||||
assert not any("Score" in choice for choice in choices)
|
||||
|
||||
|
||||
def test_model_choices_list_installed_models_before_downloadable_entries(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Installed choices precede curated models that still require a download."""
|
||||
|
||||
models_dir = tmp_path / "models"
|
||||
bbox_dir = models_dir / "ultralytics" / "bbox"
|
||||
bbox_dir.mkdir(parents=True)
|
||||
(bbox_dir / "face_yolov8n_v2.pt").write_bytes(b"checkpoint")
|
||||
(bbox_dir / "local-detector.pt").write_bytes(b"checkpoint")
|
||||
folder_paths = _folder_paths(models_dir)
|
||||
service = UltralyticsLoaderService(
|
||||
folder_paths_module=folder_paths,
|
||||
choice_service=_choice_service(show_downloadable_models=True),
|
||||
)
|
||||
|
||||
choices = service.model_choices()
|
||||
|
||||
assert choices[:2] == [
|
||||
"bbox/local-detector.pt",
|
||||
"Bingsu Face YOLOv8n v2 (6.23MB)",
|
||||
]
|
||||
assert choices[2] == "Anzhc Face -seg (6.52MB)"
|
||||
assert "bbox/face_yolov8n_v2.pt" not in choices
|
||||
|
||||
|
||||
def test_hidden_catalog_choices_exclude_installed_curated_model(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Hidden catalog mode excludes installed curated model files."""
|
||||
|
||||
models_dir = tmp_path / "models"
|
||||
checkpoint = models_dir / "ultralytics" / "segm" / "Anzhc Face -seg.pt"
|
||||
checkpoint.parent.mkdir(parents=True)
|
||||
checkpoint.write_bytes(b"checkpoint")
|
||||
folder_paths = _folder_paths(models_dir)
|
||||
service = UltralyticsLoaderService(
|
||||
folder_paths_module=folder_paths,
|
||||
choice_service=_choice_service(show_downloadable_models=False),
|
||||
)
|
||||
|
||||
assert service.model_choices() == [NO_LOCAL_ULTRALYTICS_MODELS]
|
||||
|
||||
@@ -102,6 +183,112 @@ def test_loader_returns_native_and_compatibility_outputs(tmp_path: Path) -> None
|
||||
assert loaded.bbox_detector is cast(Any, loaded.segm_detector).bbox_detector
|
||||
|
||||
|
||||
def test_curated_model_downloads_to_impact_pack_compatible_folder(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A curated selection downloads with checksum verification into segm."""
|
||||
|
||||
models_dir = tmp_path / "models"
|
||||
folder_paths = _folder_paths(models_dir)
|
||||
downloader = _RecordingDownloader()
|
||||
ultralytics_module = ModuleType("ultralytics")
|
||||
cast(Any, ultralytics_module).YOLO = _FakeYOLO
|
||||
entry = get_ultralytics_entry("anzhc_face_seg")
|
||||
service = UltralyticsLoaderService(
|
||||
folder_paths_module=folder_paths,
|
||||
ultralytics_module=ultralytics_module,
|
||||
downloader=downloader,
|
||||
choice_service=_choice_service(show_downloadable_models=True),
|
||||
cache={},
|
||||
)
|
||||
|
||||
loaded = service.load(entry.display_name)
|
||||
|
||||
expected_path = models_dir / "ultralytics" / "segm" / "Anzhc Face -seg.pt"
|
||||
assert loaded.detector_model.model_path == expected_path
|
||||
assert loaded.detector_model.model_name == "segm/Anzhc Face -seg.pt"
|
||||
assert loaded.detector_model.supports_segmentation is True
|
||||
assert downloader.requests[0].destination_path == expected_path
|
||||
assert downloader.requests[0].expected_folder == expected_path.parent
|
||||
assert downloader.requests[0].expected_sha256 == entry.artifacts[0].sha256
|
||||
|
||||
|
||||
def test_curated_bbox_model_downloads_to_impact_pack_compatible_folder(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A curated bbox selection downloads into the conventional bbox folder."""
|
||||
|
||||
models_dir = tmp_path / "models"
|
||||
folder_paths = _folder_paths(models_dir)
|
||||
downloader = _RecordingDownloader()
|
||||
ultralytics_module = ModuleType("ultralytics")
|
||||
cast(Any, ultralytics_module).YOLO = _FakeYOLO
|
||||
entry = get_ultralytics_entry("bingsu_hand_yolov8n")
|
||||
service = UltralyticsLoaderService(
|
||||
folder_paths_module=folder_paths,
|
||||
ultralytics_module=ultralytics_module,
|
||||
downloader=downloader,
|
||||
choice_service=_choice_service(show_downloadable_models=True),
|
||||
cache={},
|
||||
)
|
||||
|
||||
loaded = service.load(entry.display_name)
|
||||
|
||||
expected_path = models_dir / "ultralytics" / "bbox" / "hand_yolov8n.pt"
|
||||
assert loaded.detector_model.model_path == expected_path
|
||||
assert loaded.detector_model.supports_segmentation is False
|
||||
assert downloader.requests[0].destination_path == expected_path
|
||||
assert downloader.requests[0].expected_sha256 == entry.artifacts[0].sha256
|
||||
|
||||
|
||||
def test_curated_existing_model_must_match_its_catalog_checksum(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A pre-existing curated checkpoint cannot bypass checksum verification."""
|
||||
|
||||
models_dir = tmp_path / "models"
|
||||
checkpoint = models_dir / "ultralytics" / "segm" / "Anzhc Face -seg.pt"
|
||||
checkpoint.parent.mkdir(parents=True)
|
||||
checkpoint.write_bytes(b"wrong checkpoint")
|
||||
folder_paths = _folder_paths(models_dir)
|
||||
service = UltralyticsLoaderService(
|
||||
folder_paths_module=folder_paths,
|
||||
choice_service=_choice_service(show_downloadable_models=True),
|
||||
cache={},
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="checksum mismatch"):
|
||||
service.load("Anzhc Face -seg (6.52MB)")
|
||||
|
||||
|
||||
def test_catalog_and_local_selection_share_one_loaded_model(tmp_path: Path) -> None:
|
||||
"""Catalog and conventional-path selections share the loaded model instance."""
|
||||
|
||||
models_dir = tmp_path / "models"
|
||||
folder_paths = _folder_paths(models_dir)
|
||||
downloader = _RecordingDownloader()
|
||||
ultralytics_module = ModuleType("ultralytics")
|
||||
yolo_factory = _RecordingYOLOFactory()
|
||||
cast(Any, ultralytics_module).YOLO = yolo_factory
|
||||
entry = get_ultralytics_entry("anzhc_face_seg")
|
||||
cache: dict[UltralyticsModelCacheKey, LoadedUltralyticsDetector] = {}
|
||||
service = UltralyticsLoaderService(
|
||||
folder_paths_module=folder_paths,
|
||||
ultralytics_module=ultralytics_module,
|
||||
downloader=downloader,
|
||||
choice_service=_choice_service(show_downloadable_models=True),
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
catalog_loaded = service.load(entry.display_name)
|
||||
local_loaded = service.load("segm/Anzhc Face -seg.pt")
|
||||
|
||||
assert local_loaded is catalog_loaded
|
||||
assert len(downloader.requests) == 1
|
||||
assert len(yolo_factory.paths) == 1
|
||||
assert len(cache) == 1
|
||||
|
||||
|
||||
def test_bbox_prefix_marks_model_as_bbox_only(tmp_path: Path) -> None:
|
||||
"""BBox-prefixed models do not claim segmentation support."""
|
||||
|
||||
@@ -233,6 +420,57 @@ class _RecordingYOLOFactory:
|
||||
return _FakeYOLO(path)
|
||||
|
||||
|
||||
class _RecordingDownloader(ModelDownloader):
|
||||
"""Download boundary double that records verified catalog requests."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialize the recorded request collection."""
|
||||
|
||||
self.requests: list[DownloadRequest] = []
|
||||
|
||||
def download(
|
||||
self,
|
||||
request: DownloadRequest,
|
||||
progress: ProgressReporter | None = None,
|
||||
) -> DownloadResult:
|
||||
"""Materialize a placeholder checkpoint at the requested destination."""
|
||||
|
||||
del progress
|
||||
self.requests.append(request)
|
||||
request.destination_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
request.destination_path.write_bytes(b"checkpoint")
|
||||
return DownloadResult(
|
||||
path=request.destination_path,
|
||||
bytes_downloaded=len(b"checkpoint"),
|
||||
skipped_existing=False,
|
||||
)
|
||||
|
||||
|
||||
class _FakeSettingsRepository:
|
||||
"""Settings boundary double for Ultralytics dropdown tests."""
|
||||
|
||||
def __init__(self, show_downloadable_models: bool) -> None:
|
||||
"""Store the configured dropdown visibility preference."""
|
||||
|
||||
self._settings = SimpleSyrupSettings(
|
||||
show_downloadable_models=show_downloadable_models
|
||||
)
|
||||
|
||||
def load(self) -> SimpleSyrupSettings:
|
||||
"""Return the configured settings value."""
|
||||
|
||||
return self._settings
|
||||
|
||||
|
||||
def _choice_service(
|
||||
*,
|
||||
show_downloadable_models: bool,
|
||||
) -> ModelChoiceService:
|
||||
"""Build an Ultralytics choice service with deterministic settings."""
|
||||
|
||||
return ModelChoiceService(_FakeSettingsRepository(show_downloadable_models))
|
||||
|
||||
|
||||
def _folder_paths(models_dir: Path) -> ModuleType:
|
||||
"""Build a minimal fake ComfyUI folder_paths module."""
|
||||
|
||||
|
||||
@@ -29,6 +29,13 @@ from simple_syrup.runtime.attention_coupling.unet_attn2_execution_resolver impor
|
||||
from simple_syrup.runtime.attention_coupling.unet_attn2_patch import (
|
||||
UnetAttn2PatchPair,
|
||||
)
|
||||
from simple_syrup.runtime.ppm_negpip_interop import (
|
||||
PpmNegpipInterop,
|
||||
PpmNegpipSemantics,
|
||||
)
|
||||
from simple_syrup.runtime.regional_lora.standard_unet_variant_base_attention import (
|
||||
StandardUnetVariantBaseAttention,
|
||||
)
|
||||
|
||||
|
||||
class _ZeroAttention(nn.Module):
|
||||
@@ -81,6 +88,32 @@ class _RegionalAttention(nn.Module):
|
||||
return query + context.mean(dim=1, keepdim=True)
|
||||
|
||||
|
||||
class _RecordingKeyValueAttention(nn.Module):
|
||||
"""Record exact post-patch key/value inputs and return packed zeros."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialize an empty invocation record."""
|
||||
|
||||
super().__init__()
|
||||
self.calls: list[tuple[torch.Tensor, torch.Tensor]] = []
|
||||
|
||||
def forward(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
*,
|
||||
context: torch.Tensor | None,
|
||||
value: torch.Tensor | None,
|
||||
transformer_options: dict[str, Any],
|
||||
) -> torch.Tensor:
|
||||
"""Retain post-patch K/V sources without performing attention."""
|
||||
|
||||
del transformer_options
|
||||
if context is None or value is None:
|
||||
raise AssertionError("NegPiP test requires explicit K and V tensors.")
|
||||
self.calls.append((context, value))
|
||||
return torch.zeros_like(query)
|
||||
|
||||
|
||||
class _CountingZeroFeedForward(nn.Module):
|
||||
"""Return zero while counting the retained feed-forward trajectory."""
|
||||
|
||||
@@ -165,6 +198,149 @@ def test_unet_patch_clears_callback_state_after_output_failure() -> None:
|
||||
patches.input_patch(query, context, context, options)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("persistent_base_graph", [False, True])
|
||||
def test_negpip_splits_exact_packed_regional_key_and_value_views(
|
||||
persistent_base_graph: bool,
|
||||
) -> None:
|
||||
"""Select even K and odd V tokens after packing in both UNet base routes."""
|
||||
|
||||
contexts = _negpip_contexts()
|
||||
execution = UnetAttn2Execution(
|
||||
contexts,
|
||||
torch.tensor([[[1.0, 0.0]], [[0.0, 1.0]]]),
|
||||
(1.0, 1.0),
|
||||
1,
|
||||
2,
|
||||
)
|
||||
pair = UnetAttn2PatchPair(StaticUnetAttn2ExecutionResolver(execution))
|
||||
|
||||
def split_negpip(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
_extra_options: dict[str, Any],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Apply PPM's public alternating-token UNet semantics exactly."""
|
||||
|
||||
return query, key[:, 0::2], value[:, 1::2]
|
||||
|
||||
if persistent_base_graph:
|
||||
interop = PpmNegpipInterop(
|
||||
PpmNegpipSemantics.STANDARD_UNET_SPLIT_KEY_VALUE,
|
||||
split_negpip,
|
||||
)
|
||||
options = StandardUnetVariantBaseAttention(
|
||||
StaticUnetAttn2ExecutionResolver(execution),
|
||||
negpip=interop,
|
||||
).prepare({"patches": {"attn2_patch": [split_negpip]}})
|
||||
else:
|
||||
options = {
|
||||
"patches": {
|
||||
"attn2_patch": [pair.input_patch, split_negpip],
|
||||
"attn2_output_patch": [pair.output_patch],
|
||||
}
|
||||
}
|
||||
recording = _RecordingKeyValueAttention()
|
||||
block = _block(recording)
|
||||
|
||||
block(
|
||||
torch.zeros((1, 2, 1)),
|
||||
context=contexts.base_context,
|
||||
transformer_options=options,
|
||||
)
|
||||
|
||||
assert len(recording.calls) == 1
|
||||
key, value = recording.calls[0]
|
||||
assert key[:, :, 0].tolist() == [[30.0, 40.0], [70.0, 80.0]]
|
||||
assert value[:, :, 0].tolist() == [[31.0, 41.0], [71.0, 81.0]]
|
||||
|
||||
|
||||
def test_persistent_regional_graph_keeps_native_negpip_split_semantics() -> None:
|
||||
"""Split one manually selected regional graph without adding branch packing."""
|
||||
|
||||
recording = _RecordingKeyValueAttention()
|
||||
block = _block(recording)
|
||||
context = torch.tensor([[[30.0], [31.0], [40.0], [41.0]]])
|
||||
|
||||
def split_negpip(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
_extra_options: dict[str, Any],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Apply PPM's public alternating-token UNet semantics exactly."""
|
||||
|
||||
return query, key[:, 0::2], value[:, 1::2]
|
||||
|
||||
block(
|
||||
torch.zeros((1, 2, 1)),
|
||||
context=context,
|
||||
transformer_options={"patches": {"attn2_patch": [split_negpip]}},
|
||||
)
|
||||
|
||||
key, value = recording.calls[0]
|
||||
assert key[:, :, 0].tolist() == [[30.0, 40.0]]
|
||||
assert value[:, :, 0].tolist() == [[31.0, 41.0]]
|
||||
|
||||
|
||||
def _block(cross_attention: nn.Module) -> BasicTransformerBlock:
|
||||
"""Build one deterministic block around a supplied cross-attention owner."""
|
||||
|
||||
block = BasicTransformerBlock(
|
||||
dim=1,
|
||||
n_heads=1,
|
||||
d_head=1,
|
||||
context_dim=1,
|
||||
checkpoint=False,
|
||||
)
|
||||
block.norm1 = nn.Identity()
|
||||
block.attn1 = _ZeroAttention()
|
||||
block.norm2 = nn.Identity()
|
||||
block.attn2 = cross_attention
|
||||
block.norm3 = nn.Identity()
|
||||
block.ff = _CountingZeroFeedForward()
|
||||
return block
|
||||
|
||||
|
||||
def _negpip_contexts() -> BatchedRegionalAttentionContexts:
|
||||
"""Return alternating K/V token pairs for base and two regions."""
|
||||
|
||||
return BatchedRegionalAttentionContexts(
|
||||
latent_batch_size=1,
|
||||
chunks=(
|
||||
RegionalAttentionChunkBatch(
|
||||
0,
|
||||
RegionalAttentionBranch.POSITIVE,
|
||||
0,
|
||||
1,
|
||||
),
|
||||
),
|
||||
base_context=torch.tensor([[[10.0], [11.0], [20.0], [21.0]]]),
|
||||
regions=(
|
||||
BatchedRegionalAttentionRegion(
|
||||
0,
|
||||
(
|
||||
BatchedRegionalAttentionEntry(
|
||||
0,
|
||||
torch.tensor([[[30.0], [31.0], [40.0], [41.0]]]),
|
||||
(1.0,),
|
||||
),
|
||||
),
|
||||
),
|
||||
BatchedRegionalAttentionRegion(
|
||||
1,
|
||||
(
|
||||
BatchedRegionalAttentionEntry(
|
||||
0,
|
||||
torch.tensor([[[70.0], [71.0], [80.0], [81.0]]]),
|
||||
(1.0,),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _contexts() -> BatchedRegionalAttentionContexts:
|
||||
"""Return one base and two single-entry regional contexts."""
|
||||
|
||||
|
||||
@@ -23,9 +23,24 @@ def test_vitmatte_model_loader_contract() -> None:
|
||||
assert ViTMatteModelLoader.CATEGORY == "SimpleSyrup/Masking"
|
||||
|
||||
|
||||
def test_vitmatte_model_loader_declares_expected_inputs() -> None:
|
||||
def test_vitmatte_model_loader_declares_expected_inputs(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""ViTMatte loader inputs are asset-only and deterministic."""
|
||||
|
||||
def catalog_choices() -> list[str]:
|
||||
"""Return the catalog choices expected by this declaration test."""
|
||||
|
||||
return [
|
||||
"vitmatte-small-composition-1k",
|
||||
"vitmatte-base-composition-1k",
|
||||
]
|
||||
|
||||
monkeypatch.setattr(
|
||||
ViTMatteModelLoader._choices,
|
||||
"vitmatte_choices",
|
||||
catalog_choices,
|
||||
)
|
||||
input_types: dict[str, dict[str, tuple[Any, ...]]] = (
|
||||
ViTMatteModelLoader.INPUT_TYPES()
|
||||
)
|
||||
|
||||
@@ -23,9 +23,21 @@ def test_wd14_tagger_loader_contract() -> None:
|
||||
assert WD14TaggerLoader.CATEGORY == "SimpleSyrup/Tagging"
|
||||
|
||||
|
||||
def test_wd14_tagger_loader_declares_expected_inputs() -> None:
|
||||
def test_wd14_tagger_loader_declares_expected_inputs(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""WD14 loader inputs are asset-only and deterministic."""
|
||||
|
||||
def catalog_choices() -> list[str]:
|
||||
"""Return the catalog choice expected by this declaration test."""
|
||||
|
||||
return ["wd-eva02-large-tagger-v3"]
|
||||
|
||||
monkeypatch.setattr(
|
||||
WD14TaggerLoader._choices,
|
||||
"wd14_tagger_choices",
|
||||
catalog_choices,
|
||||
)
|
||||
input_types: dict[str, dict[str, tuple[Any, ...]]] = WD14TaggerLoader.INPUT_TYPES()
|
||||
required = input_types["required"]
|
||||
|
||||
|
||||
@@ -8,13 +8,25 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from simple_syrup.nodes.wd14_tagger_loader import WD14TaggerLoader
|
||||
from simple_syrup.nodes_v3 import wd14_tagger_loader as wd14_tagger_loader_v3
|
||||
from simple_syrup.nodes_v3.wd14_tagger_loader import WD14TaggerLoaderV3
|
||||
|
||||
|
||||
def test_wd14_tagger_loader_v3_schema() -> None:
|
||||
def test_wd14_tagger_loader_v3_schema(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""The v3 loader schema exposes the WD14 tagger loader contract."""
|
||||
|
||||
class FakeChoices:
|
||||
"""Return the catalog choice expected by this schema test."""
|
||||
|
||||
def wd14_tagger_choices(self) -> list[str]:
|
||||
"""Return the expected WD14 tagger choice."""
|
||||
|
||||
return ["wd-eva02-large-tagger-v3"]
|
||||
|
||||
monkeypatch.setattr(wd14_tagger_loader_v3, "ModelChoiceService", FakeChoices)
|
||||
schema = WD14TaggerLoaderV3.define_schema()
|
||||
|
||||
assert schema.node_id == "SimpleSyrup.WD14TaggerLoader"
|
||||
|
||||
Vendored
+17
@@ -56,3 +56,20 @@ tagger ONNX models and `selected_tags.csv` files at runtime from Hugging Face.
|
||||
These model files are not vendored in this repository. The runtime catalog
|
||||
points to the corresponding `SmilingWolf/*` repositories and stores downloaded
|
||||
files in the user's ComfyUI model directory.
|
||||
|
||||
## NegPiP prompt weighting
|
||||
|
||||
SimpleSyrup adapts the AGPL-3.0 NegPiP implementation from
|
||||
`pamparamm/ComfyUI-ppm` at revision
|
||||
`6c6c360155cace9d7091306c1b8e26d9c7438620`. The standard SD1/SDXL and Anima
|
||||
paths preserve PPM's ModelPatcher-based magnitude-key and signed-value
|
||||
behavior. The Krea 2 path extends the same signed-value rule to Krea's layered
|
||||
Qwen conditioning and joint text/image attention while preserving its native
|
||||
conditioning shape.
|
||||
|
||||
PPM credits the original ComfyUI port to
|
||||
`laksjdjf/cd-tuner_negpip-ComfyUI`; SimpleSyrup records revision
|
||||
`938b838546cf774dc8841000996552cef52cccf3`. That port credits the original
|
||||
Automatic1111 WebUI implementation in `hako-mikan/sd-webui-negpip`;
|
||||
SimpleSyrup records revision
|
||||
`fb7151f327ae56195f08b30b70d459493dadedbb`.
|
||||
|
||||
+661
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) 2024 <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
Vendored
+22
@@ -133,3 +133,25 @@ vendored_files = [
|
||||
"simple_syrup/runtime/tiled_sampling_validation.py",
|
||||
"simple_syrup/services/detail_segs_as_regions_service.py",
|
||||
]
|
||||
|
||||
[[component]]
|
||||
name = "NegPiP prompt weighting"
|
||||
license = "AGPL-3.0"
|
||||
license_file = "third_party/licenses/negpip.LICENSE.txt"
|
||||
source = "https://github.com/pamparamm/ComfyUI-ppm"
|
||||
revision = "6c6c360155cace9d7091306c1b8e26d9c7438620"
|
||||
source_paths = [
|
||||
"src/nodes_ppm/clip_negpip.py",
|
||||
"src/negpip/unet_negpip.py",
|
||||
"src/negpip/anima_negpip.py",
|
||||
]
|
||||
origin_sources = [
|
||||
"https://github.com/laksjdjf/cd-tuner_negpip-ComfyUI@938b838546cf774dc8841000996552cef52cccf3",
|
||||
"https://github.com/hako-mikan/sd-webui-negpip@fb7151f327ae56195f08b30b70d459493dadedbb",
|
||||
]
|
||||
vendored_files = [
|
||||
"simple_syrup/runtime/negpip/standard.py",
|
||||
"simple_syrup/runtime/negpip/anima.py",
|
||||
"simple_syrup/runtime/negpip/krea2.py",
|
||||
"simple_syrup/services/negpip_model_service.py",
|
||||
]
|
||||
|
||||
@@ -21,6 +21,7 @@ from .latent_completion import CompleteLatentV3
|
||||
from .lora_execution_probe import InstrumentLoraModelV3, ReadLoraMetricsV3
|
||||
from .materialization_parity_node import CompareMaterializationParityV3
|
||||
from .model_modifier_snapshot import SnapshotModelModifierV3
|
||||
from .negpip_runtime import InstrumentNegpipModelV3, ReadNegpipRuntimeV3
|
||||
from .operator_profile import ProfileIndexedModelCallV3, ReadOperatorProfileV3
|
||||
from .prompt_control_expansion import SnapshotPromptControlExpansionV3
|
||||
from .prompt_control_runtime import (
|
||||
@@ -70,6 +71,8 @@ class BenchmarkProbeExtension(_ComfyExtensionBase):
|
||||
ReadLoraMetricsV3,
|
||||
CompareMaterializationParityV3,
|
||||
SnapshotModelModifierV3,
|
||||
InstrumentNegpipModelV3,
|
||||
ReadNegpipRuntimeV3,
|
||||
SnapshotPromptControlV3,
|
||||
SnapshotPromptControlExpansionV3,
|
||||
InstrumentPromptControlModelV3,
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
# SimpleSyrup - workflow-focused ComfyUI extensions for image generation
|
||||
# Copyright (C) 2026 Artificial Sweetener and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
"""Instrument live NegPiP attention callbacks without changing their results."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from importlib import import_module
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
from comfy.model_patcher import ModelPatcher
|
||||
|
||||
from simple_syrup.runtime.negpip.anima import (
|
||||
TRANSFORMER_MASK_KEY as ANIMA_MASK_KEY,
|
||||
)
|
||||
from simple_syrup.runtime.negpip.krea2 import (
|
||||
TRANSFORMER_MASK_KEY as KREA_MASK_KEY,
|
||||
)
|
||||
|
||||
_comfy_api: Any = None
|
||||
if TYPE_CHECKING:
|
||||
|
||||
class _ComfyNodeBase:
|
||||
"""Type-checking base for benchmark-only Comfy v3 nodes."""
|
||||
|
||||
pass
|
||||
|
||||
else:
|
||||
_comfy_api = import_module("comfy_api.latest")
|
||||
_ComfyNodeBase = _comfy_api.io.ComfyNode
|
||||
|
||||
_comfy_io: Any = None if TYPE_CHECKING else _comfy_api.io
|
||||
|
||||
|
||||
@dataclass
|
||||
class _NegpipProbeState:
|
||||
"""Accumulate live callback evidence for one managed workflow."""
|
||||
|
||||
family: str
|
||||
patch_name: str
|
||||
callback_name: str
|
||||
attention_calls: int = 0
|
||||
negative_mask_calls: int = 0
|
||||
invariant_failures: list[str] = field(default_factory=list)
|
||||
input_value_shape: list[int] | None = None
|
||||
output_value_shape: list[int] | None = None
|
||||
mask_shape: list[int] | None = None
|
||||
text_length: int | None = None
|
||||
negative_token_count: int = 0
|
||||
negative_token_positions: list[int] = field(default_factory=list)
|
||||
negative_token_locations: list[list[int]] = field(default_factory=list)
|
||||
|
||||
|
||||
_STATES: dict[str, _NegpipProbeState] = {}
|
||||
_STATE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class InstrumentNegpipModelV3(_ComfyNodeBase):
|
||||
"""Wrap one installed NegPiP callback and validate live tensor semantics."""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls) -> Any:
|
||||
"""Declare benchmark-only MODEL instrumentation."""
|
||||
|
||||
return _comfy_io.Schema(
|
||||
node_id="SimpleSyrupBenchmark.InstrumentNegpipModel",
|
||||
display_name="Benchmark Instrument NegPiP Model",
|
||||
category="SimpleSyrup/Benchmark",
|
||||
inputs=[
|
||||
_comfy_io.Model.Input("model"),
|
||||
_comfy_io.String.Input("run_id"),
|
||||
],
|
||||
outputs=[_comfy_io.Model.Output("model")],
|
||||
is_dev_only=True,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, model: object, run_id: str) -> Any:
|
||||
"""Clone MODEL and replace its owned callback with an observing delegate."""
|
||||
|
||||
if not isinstance(model, ModelPatcher):
|
||||
raise TypeError("NegPiP instrumentation requires a Comfy MODEL.")
|
||||
if not isinstance(run_id, str) or not run_id:
|
||||
raise ValueError("NegPiP instrumentation run ID must not be empty.")
|
||||
if model.model_options.get("ppm_negpip") is not True:
|
||||
raise ValueError("NegPiP instrumentation requires a patched MODEL.")
|
||||
cloned = model.clone()
|
||||
patches = _transformer_patches(cloned)
|
||||
patch_name, family, callback = _owned_negpip_callback(patches)
|
||||
state = _NegpipProbeState(
|
||||
family=family,
|
||||
patch_name=patch_name,
|
||||
callback_name=f"{callback.__module__}.{callback.__qualname__}",
|
||||
)
|
||||
with _STATE_LOCK:
|
||||
if run_id in _STATES:
|
||||
raise ValueError(f"NegPiP probe run is already active: {run_id!r}.")
|
||||
_STATES[run_id] = state
|
||||
|
||||
def observe(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
*args: object,
|
||||
**kwargs: object,
|
||||
) -> object:
|
||||
"""Delegate one callback and record its exact family invariant."""
|
||||
|
||||
result = callback(query, key, value, *args, **kwargs)
|
||||
options = _extra_options(args, kwargs)
|
||||
try:
|
||||
_observe_result(
|
||||
state,
|
||||
query=query,
|
||||
key=key,
|
||||
value=value,
|
||||
result=result,
|
||||
options=options,
|
||||
)
|
||||
except (TypeError, ValueError) as error:
|
||||
with _STATE_LOCK:
|
||||
state.invariant_failures.append(str(error))
|
||||
return result
|
||||
|
||||
replacement = list(patches[patch_name])
|
||||
replacement[replacement.index(callback)] = observe
|
||||
patches[patch_name] = replacement
|
||||
return _comfy_io.NodeOutput(cloned)
|
||||
|
||||
|
||||
class ReadNegpipRuntimeV3(_ComfyNodeBase):
|
||||
"""Publish and enforce completed live NegPiP callback evidence."""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls) -> Any:
|
||||
"""Declare a latent-synchronized evidence output."""
|
||||
|
||||
return _comfy_io.Schema(
|
||||
node_id="SimpleSyrupBenchmark.ReadNegpipRuntime",
|
||||
display_name="Benchmark Read NegPiP Runtime",
|
||||
category="SimpleSyrup/Benchmark",
|
||||
inputs=[
|
||||
_comfy_io.Latent.Input("latent"),
|
||||
_comfy_io.String.Input("run_id"),
|
||||
],
|
||||
outputs=[
|
||||
_comfy_io.Latent.Output("latent"),
|
||||
_comfy_io.String.Output("evidence_json"),
|
||||
],
|
||||
is_output_node=True,
|
||||
is_dev_only=True,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, latent: dict[str, Any], run_id: str) -> Any:
|
||||
"""Require observed negative-mask execution and return stable evidence."""
|
||||
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.synchronize()
|
||||
with _STATE_LOCK:
|
||||
state = _STATES.pop(run_id, None)
|
||||
if state is None:
|
||||
raise ValueError(f"NegPiP probe run was not instrumented: {run_id!r}.")
|
||||
if state.attention_calls < 1:
|
||||
raise ValueError("NegPiP attention callback was not executed.")
|
||||
if state.negative_mask_calls < 1:
|
||||
raise ValueError("NegPiP callback never observed a negative token.")
|
||||
if state.invariant_failures:
|
||||
raise ValueError(
|
||||
"NegPiP live tensor invariants failed: "
|
||||
+ "; ".join(state.invariant_failures[:3])
|
||||
)
|
||||
evidence = {
|
||||
"run_id": run_id,
|
||||
"family": state.family,
|
||||
"patch_name": state.patch_name,
|
||||
"callback_name": state.callback_name,
|
||||
"attention_calls": state.attention_calls,
|
||||
"negative_mask_calls": state.negative_mask_calls,
|
||||
"input_value_shape": state.input_value_shape,
|
||||
"output_value_shape": state.output_value_shape,
|
||||
"mask_shape": state.mask_shape,
|
||||
"text_length": state.text_length,
|
||||
"negative_token_count": state.negative_token_count,
|
||||
"negative_token_positions": state.negative_token_positions,
|
||||
"negative_token_locations": state.negative_token_locations,
|
||||
"invariant_failures": state.invariant_failures,
|
||||
}
|
||||
encoded = json.dumps(evidence, sort_keys=True, separators=(",", ":"))
|
||||
return _comfy_io.NodeOutput(
|
||||
latent,
|
||||
encoded,
|
||||
ui={"negpip_runtime_evidence": [evidence]},
|
||||
)
|
||||
|
||||
|
||||
def _transformer_patches(model: ModelPatcher) -> dict[str, list[object]]:
|
||||
"""Return the cloned MODEL's mutable transformer patch mapping."""
|
||||
|
||||
options = model.model_options.get("transformer_options")
|
||||
if not isinstance(options, dict):
|
||||
raise TypeError("NegPiP MODEL transformer_options must be a dictionary.")
|
||||
patches = options.get("patches")
|
||||
if not isinstance(patches, dict):
|
||||
raise TypeError("NegPiP MODEL patches must be a dictionary.")
|
||||
return cast(dict[str, list[object]], patches)
|
||||
|
||||
|
||||
def _owned_negpip_callback(
|
||||
patches: dict[str, list[object]],
|
||||
) -> tuple[str, str, Any]:
|
||||
"""Resolve exactly one owned family callback from a patch list."""
|
||||
|
||||
identities = {
|
||||
("src.negpip.unet_negpip", "sdxl_attn2_negpip"): (
|
||||
"attn2_patch",
|
||||
"standard",
|
||||
),
|
||||
("simple_syrup.runtime.negpip.standard", "standard_attn2_negpip"): (
|
||||
"attn2_patch",
|
||||
"standard",
|
||||
),
|
||||
("src.negpip.anima_negpip", "cosmos_attn2_negpip"): (
|
||||
"attn2_patch",
|
||||
"anima",
|
||||
),
|
||||
("simple_syrup.runtime.negpip.anima", "anima_attn2_negpip"): (
|
||||
"attn2_patch",
|
||||
"anima",
|
||||
),
|
||||
("simple_syrup.runtime.negpip.krea2", "krea2_attn1_negpip"): (
|
||||
"attn1_patch",
|
||||
"krea2",
|
||||
),
|
||||
}
|
||||
matches: list[tuple[str, str, Any]] = []
|
||||
observed: list[str] = []
|
||||
for patch_name, callbacks in patches.items():
|
||||
if not isinstance(callbacks, list):
|
||||
raise TypeError("NegPiP transformer patches must be callback lists.")
|
||||
for callback in callbacks:
|
||||
module = getattr(callback, "__module__", None)
|
||||
qualname = getattr(callback, "__qualname__", None)
|
||||
observed.append(f"{patch_name}:{module}.{qualname}")
|
||||
resolved = None
|
||||
if isinstance(module, str) and isinstance(qualname, str):
|
||||
resolved = next(
|
||||
(
|
||||
value
|
||||
for (
|
||||
module_suffix,
|
||||
expected_qualname,
|
||||
), value in identities.items()
|
||||
if (
|
||||
module == module_suffix
|
||||
or module.endswith(f".{module_suffix}")
|
||||
)
|
||||
and qualname == expected_qualname
|
||||
),
|
||||
None,
|
||||
)
|
||||
if resolved is not None:
|
||||
matches.append((*resolved, callback))
|
||||
if len(matches) != 1:
|
||||
raise ValueError(
|
||||
"NegPiP instrumentation requires exactly one owned family callback; "
|
||||
f"observed {observed!r}."
|
||||
)
|
||||
return matches[0]
|
||||
|
||||
|
||||
def _extra_options(
|
||||
args: tuple[object, ...],
|
||||
kwargs: dict[str, object],
|
||||
) -> dict[str, Any]:
|
||||
"""Read Comfy's positional or keyword attention option mapping."""
|
||||
|
||||
options = kwargs.get("extra_options")
|
||||
if options is None and args:
|
||||
options = args[-1]
|
||||
if not isinstance(options, dict):
|
||||
return {}
|
||||
return cast(dict[str, Any], options)
|
||||
|
||||
|
||||
def _observe_result(
|
||||
state: _NegpipProbeState,
|
||||
*,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
result: object,
|
||||
options: dict[str, Any],
|
||||
) -> None:
|
||||
"""Validate one family-specific callback result against its live inputs."""
|
||||
|
||||
if state.family == "standard":
|
||||
_observe_standard(state, query, key, value, result)
|
||||
return
|
||||
_observe_masked(state, query, key, value, result, options)
|
||||
|
||||
|
||||
def _observe_standard(
|
||||
state: _NegpipProbeState,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
result: object,
|
||||
) -> None:
|
||||
"""Verify the standard interleaved split and count signed value pairs."""
|
||||
|
||||
if not isinstance(result, tuple) or len(result) != 3:
|
||||
raise TypeError("Standard NegPiP must return a Q/K/V tuple.")
|
||||
output_query, output_key, output_value = result
|
||||
if output_query is not query:
|
||||
raise ValueError("Standard NegPiP changed attention queries.")
|
||||
if not isinstance(output_key, torch.Tensor) or not isinstance(
|
||||
output_value, torch.Tensor
|
||||
):
|
||||
raise TypeError("Standard NegPiP must return tensor keys and values.")
|
||||
if not torch.equal(output_key, key[:, 0::2]):
|
||||
raise ValueError("Standard NegPiP did not select magnitude key positions.")
|
||||
if not torch.equal(output_value, value[:, 1::2]):
|
||||
raise ValueError("Standard NegPiP did not select signed value positions.")
|
||||
pair_delta = value[:, 0::2] - value[:, 1::2]
|
||||
signed_pairs = torch.any(pair_delta != 0, dim=-1)
|
||||
negative_locations = signed_pairs.nonzero().tolist()
|
||||
negative_positions = sorted({int(location[1]) for location in negative_locations})
|
||||
_record_observation(
|
||||
state,
|
||||
value,
|
||||
output_value,
|
||||
negative=bool(negative_locations),
|
||||
negative_positions=negative_positions,
|
||||
negative_locations=negative_locations,
|
||||
)
|
||||
|
||||
|
||||
def _observe_masked(
|
||||
state: _NegpipProbeState,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
result: object,
|
||||
options: dict[str, Any],
|
||||
) -> None:
|
||||
"""Verify Anima or Krea applies a binary sign mask only to values."""
|
||||
|
||||
if not isinstance(result, dict):
|
||||
raise TypeError("Masked NegPiP must return an attention tensor dictionary.")
|
||||
if result.get("q") is not query or result.get("k") is not key:
|
||||
raise ValueError("Masked NegPiP changed attention queries or keys.")
|
||||
output_value = result.get("v")
|
||||
if not isinstance(output_value, torch.Tensor):
|
||||
raise TypeError("Masked NegPiP must return tensor values.")
|
||||
mask_key = ANIMA_MASK_KEY if state.family == "anima" else KREA_MASK_KEY
|
||||
multiplier = options.get(mask_key)
|
||||
if not isinstance(multiplier, torch.Tensor):
|
||||
raise TypeError("Masked NegPiP callback did not receive its sign tensor.")
|
||||
negative_mask = multiplier[:, :, 0] < 0
|
||||
negative_locations = negative_mask.nonzero().tolist()
|
||||
negative = bool(negative_locations)
|
||||
negative_positions = sorted({int(location[1]) for location in negative_locations})
|
||||
state.mask_shape = list(multiplier.shape)
|
||||
if state.family == "anima":
|
||||
expected = value * multiplier
|
||||
else:
|
||||
image_slice = options.get("img_slice")
|
||||
if not isinstance(image_slice, (list, tuple)) or len(image_slice) != 2:
|
||||
raise ValueError("Krea NegPiP did not receive its text/image boundary.")
|
||||
text_length = image_slice[0]
|
||||
if not isinstance(text_length, int):
|
||||
raise TypeError("Krea NegPiP text boundary must be an integer.")
|
||||
state.text_length = text_length
|
||||
expected = value.clone()
|
||||
expected[:, :, :text_length] *= multiplier.to(value).unsqueeze(1)
|
||||
if not torch.equal(output_value[:, :, text_length:], value[:, :, text_length:]):
|
||||
raise ValueError("Krea NegPiP changed image or reference values.")
|
||||
if not torch.equal(output_value, expected):
|
||||
raise ValueError("Masked NegPiP values do not match the live sign tensor.")
|
||||
_record_observation(
|
||||
state,
|
||||
value,
|
||||
output_value,
|
||||
negative=negative,
|
||||
negative_positions=negative_positions,
|
||||
negative_locations=negative_locations,
|
||||
)
|
||||
|
||||
|
||||
def _record_observation(
|
||||
state: _NegpipProbeState,
|
||||
source: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
*,
|
||||
negative: bool,
|
||||
negative_positions: list[int],
|
||||
negative_locations: list[list[int]],
|
||||
) -> None:
|
||||
"""Record one proven callback execution under the process-local lock."""
|
||||
|
||||
with _STATE_LOCK:
|
||||
state.attention_calls += 1
|
||||
state.negative_mask_calls += int(negative)
|
||||
if len(negative_positions) > state.negative_token_count:
|
||||
state.negative_token_count = len(negative_positions)
|
||||
state.negative_token_positions = negative_positions
|
||||
state.negative_token_locations = negative_locations
|
||||
if state.input_value_shape is None:
|
||||
state.input_value_shape = list(source.shape)
|
||||
state.output_value_shape = list(output.shape)
|
||||
@@ -23,6 +23,7 @@ from simple_syrup.runtime.comfy_conditioning_model_loader import (
|
||||
from simple_syrup.runtime.comfy_conditioning_processing import (
|
||||
ComfyRegionalConditioningProcessor,
|
||||
)
|
||||
from simple_syrup.runtime.ppm_negpip_interop import PpmNegpipInterop
|
||||
from simple_syrup.runtime.regional_lora_conditioning_adapter import (
|
||||
RegionalLoraConditioningAdapter,
|
||||
)
|
||||
@@ -101,6 +102,7 @@ class ProfiledComfyRegionalConditioningProcessor(ComfyRegionalConditioningProces
|
||||
noise: torch.Tensor,
|
||||
device: torch.device,
|
||||
context_validator: RegionalContextValidator,
|
||||
negpip: PpmNegpipInterop | None = None,
|
||||
) -> ProcessedRegionalAttentionPlan:
|
||||
"""Delegate conditioning processing with synchronized device timing."""
|
||||
|
||||
@@ -114,6 +116,7 @@ class ProfiledComfyRegionalConditioningProcessor(ComfyRegionalConditioningProces
|
||||
noise=noise,
|
||||
device=device,
|
||||
context_validator=context_validator,
|
||||
negpip=negpip,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
"""Build and execute isolated automatic NegPiP integration proofs."""
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user