biegen / tools_sd15.py
Pixelkram's picture
Deploy app
2fd30a7 verified
Raw History Blame Contribute Delete
29.7 kB
"""The bending tools of the Biegen Space (once Tab 4 of the workshop): presets from the Neural_Bending lab
(~/ai/neural_nodes), ported to the SD 1.5 engine.
Each tool takes one of Neural_Bending's presets and reduces it to one knob, a place where it applies
and a window in the schedule. The presets' targets and numbers are the starting points; the defaults
here come from the calibration sheets in bench_out_sd15/tools/.
apply(engine, s) installs everything for one render call and removes it on any exit:
forward hooks, attention processors, weight edits, steps run after every sampler step, and the
engine's text encoding wrapped for this call.
"""
from __future__ import annotations
import math
from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
import torch
import torch.nn.functional as F
SEED_TOOLS = 11 # offset from the seed for the tools' own noise
@dataclass(frozen=True)
class ToolUse:
"""One tool in one slot of Tab 4."""
key: str
value: float # the tool's knob
place: str = "" # where it applies, one of the tool's places
start: float = 0.0 # window as fraction of the schedule
end: float = 1.0
word: str = "" # "excise" only
@dataclass(frozen=True)
class Tool:
key: str
label: str
group: str
what: str # one or two sentences for the participants
knob: str # the knob's label
lo: float # slider range; typed values may go beyond it
hi: float
default: float
step: float
neutral: float # the knob value that changes nothing
rule: str # the rule this tool breaks
places: tuple = () # (label, value)
window: tuple | None = (0.0, 1.0) # default window, None = the tool has no window
preset: str = "" # the Neural_Bending preset it comes from
place_defaults: tuple = () # (place, knob, start, end) where a place needs other values
def defaults_for(self, place: str) -> tuple[float, float, float]:
"""Knob and window that suit a place (the calibration sheets in bench_out_sd15/tools/)."""
for p, value, start, end in self.place_defaults:
if p == place:
return value, start, end
start, end = self.window or (0.0, 1.0)
return self.default, start, end
TOOLS = {t.key: t for t in [
# ------------------------------------------------ Semantik
Tool("excise", "Wort herausschneiden", "Semantik",
"Nimmt ein Wort aus dem Prompt heraus, aber erst im Bildnetz: Die Quer-Aufmerksamkeit darf es nicht "
"mehr ansehen. CLIP hat das Wort schon in die Füllpositionen nach dem Prompt kopiert, deshalb wirkt "
"es erst ganz, wenn auch das Polster maskiert ist. Negative Werte betonen das Wort.",
"Stärke", -2.0, 1.0, 1.0, 0.05, 0.0, "R8",
places=(("Wort und Polster", "word_pad"), ("Nur das Wort", "word")), preset="word-excision"),
Tool("layered", "Zweiter Prompt für die Oberfläche", "Semantik",
"Prompt A entscheidet, was das Bild zeigt und wo es steht. Einzelne Schichten des Bildnetzes hören "
"stattdessen Prompt B: im Aufwärtsweg entscheidet B, woraus das Ding gemacht ist.",
"Anteil von Prompt B", 0.0, 1.0, 1.0, 0.05, 0.0, "R4",
places=(("Aufwärtsweg (Material)", "up"), ("Abwärtsweg", "down"),
("Nur die Mitte (Identität)", "mid")), preset="layered-prompt"),
Tool("positions", "Wortreihenfolge vergessen", "Semantik",
"Löscht CLIPs Positionstabelle: Der Prompt kommt als Wortsack an. Die Dinge bleiben, aber die "
"Eigenschaften wandern zu den falschen Wörtern (der rote Hut wird blau).",
"Stärke", 0.0, 1.0, 1.0, 0.05, 0.0, "R9", window=None, preset="positional-amnesia"),
Tool("blind", "Prompt weg ab …", "Semantik",
"Ab diesem Punkt hört das Bildnetz den Prompt nicht mehr. Bildausschnitt, Pose und Licht stehen "
"dann schon fest, den Rest malt das Modell aus seinem Gedächtnis.",
"Ab (%)", 0.0, 100.0, 25.0, 5.0, 100.0, "R8",
places=(("Aufwärtsweg", "up"), ("Überall", "all")), window=None, preset="prompt-blind-late"),
Tool("erosion", "Spektrale Erosion", "Semantik",
"Schneidet jede Abbildung von Wörtern auf Bildmerkmale auf ihre stärksten Richtungen zurück. Das Bild "
"bleibt fotografisch, wird aber allgemein: Eigenschaften rutschen zum nächsten Nachbarn.",
"Behaltener Anteil (%)", 2.0, 100.0, 12.0, 1.0, 100.0, "R9", window=None, preset="spectral-erosion"),
Tool("aphasia", "CLIP-Aphasie", "Semantik",
"Der Text wird ein paar Schichten vor dem Ende aus CLIP ausgelesen. Erst in den letzten Schichten "
"werden Wörter zu Dingen: Das Bildnetz bekommt die Stimmung des Satzes, aber keine Hauptwörter, und "
"malt ein ordentliches Foto von etwas Benachbartem. Das geleerte Polster nimmt ihm die letzte "
"Zusammenfassung des Prompts.",
"Schichten früher", 0.0, 12.0, 7.0, 1.0, 0.0, "R5",
places=(("Früher auslesen und Polster leeren", "pad"), ("Nur früher auslesen", "skip")), window=None,
preset="clip-aphasia"),
Tool("guidance", "Guidance umkehren", "Semantik",
"Guidance zeigt vom Bild ohne Prompt zum Bild mit Prompt und verstärkt diesen Unterschied. Umgedreht "
"arbeitet jeder Schritt mit voller Kraft daran, dem Prompt weniger zu gleichen. Heraus kommt kein "
"Zufall, sondern sein Gegenteil. Bei 0,5 heben sich beide auf: das Bild ganz ohne Guidance, bei "
"jedem Prompt dasselbe. Beginnt das Fenster später, bleibt der Bildaufbau und nur das Motiv wechselt.",
"Umkehr", 0.0, 1.0, 1.0, 0.05, 0.0, "R3", preset="guidance-inverted"),
# ------------------------------------------------ Komposition
Tool("temperature", "Aufmerksamkeit: Nebel und Messer", "Komposition",
"Die Temperatur der Aufmerksamkeit. Über 1 schaut jede Stelle überallhin, das Bild löst sich in Nebel "
"auf, der die alte Pose hält. Unter 1 kopiert jede Stelle nur noch ihren besten Treffer: in den groben "
"Blöcken flache, harte Flächen wie ausgeschnitten, überall angewandt nur Konfetti.",
"Temperatur", 0.1, 8.0, 4.0, 0.05, 1.0, "R8",
places=(("Selbst-Aufmerksamkeit überall", "self"), ("Grobe Blöcke (Messer)", "coarse"),
("Quer-Aufmerksamkeit (Text)", "cross")), window=(0.2, 1.0), preset="attention-fog",
place_defaults=(("coarse", 0.25, 0.0, 1.0), ("cross", 3.0, 0.0, 1.0))),
Tool("skips", "Skip-Verbindungen", "Komposition",
"Die Abkürzungen der U-Form tragen das Gedächtnis des Abwärtswegs zum Aufwärtsweg. Verstärkt wachsen "
"überall geätzte Strukturen, gekappt erfindet das Netz Oberflächen aus der Bedeutung allein.",
"Verstärkung", 0.0, 3.0, 2.5, 0.05, 1.0, "R8",
places=(("Mittlere Auflösung (Aufwärts 2 und 3)", "mid_res"), ("Grob (Aufwärts 1 und 2)", "coarse")),
preset="skip-flood"),
Tool("mirror", "Symmetrie-Gefängnis", "Komposition",
"Nach jedem Schritt wird eine Hälfte des Bildes mit dem Spiegelbild der anderen überschrieben. Das "
"Modell will die Symmetrie brechen und darf nicht.",
"Stärke", 0.0, 1.0, 0.3, 0.05, 0.0, "R8",
places=(("Links und rechts", "h"), ("Oben und unten", "v"), ("Vierfach", "both")),
preset="symmetry-prison", place_defaults=(("v", 0.1, 0.0, 1.0), ("both", 0.2, 0.0, 1.0))),
Tool("freeze", "Eingefroren", "Komposition",
"Die groben Blöcke entscheiden früh und dürfen danach nicht mehr umdenken, während die feinen weiter "
"arbeiten: liebevoll gemalte Details auf einem unfertigen Entwurf.",
"Eingefroren ab (%)", 0.0, 100.0, 8.0, 1.0, 100.0, "R8",
places=(("Mitte und Aufwärts 2", "mid_up1"), ("Nur die Mitte", "mid")), window=None,
preset="frozen-in-thought"),
Tool("bypass", "Ohne Mitte", "Komposition",
"Die Mitte des U, wo das ganze Bild auf 8 × 8 Stellen zusammenkommt, wird zum Draht: Ihr Eingang "
"geht unverändert weiter. Allein ändert das fast nichts. Werden auch die groben Aufwärtsblöcke "
"überbrückt, kann das Netz nichts mehr anordnen: Das Motiv zerfällt in Fasern und Nebel, ab 0,8 "
"bleibt nur Textur.",
"Überbrückt", 0.0, 1.0, 0.6, 0.05, 0.0, "R8",
places=(("Mitte und Aufwärts 1 und 2", "mid_up"), ("Nur die Mitte", "mid")), preset="bottleneck-removed",
place_defaults=(("mid", 1.0, 0.0, 1.0),)),
Tool("shakes", "Zittern", "Komposition",
"Rauschen in den Gewichten der Aufmerksamkeit, aber nur eine Weile: Das Zittern schwillt an, ist am "
"stärksten, während das Bild entscheidet, was es wird, und klingt ab, bevor die Details kommen. In "
"der Selbst-Aufmerksamkeit wird das Bild weich und verschliert wie hinter beschlagenem Glas, in der "
"Quer-Aufmerksamkeit körnig wie eine Radierung. Zittert es den ganzen Lauf, bleibt kein Bild übrig.",
"Zittern", 0.0, 2.0, 1.0, 0.05, 0.0, "R9",
places=(("Selbst-Aufmerksamkeit", "self"), ("Quer-Aufmerksamkeit", "cross")), window=(0.1, 0.65),
preset="the-shakes"),
# ------------------------------------------------ Oberfläche
Tool("boil", "Kochen", "Oberfläche",
"Rauschen im ganzen Abwärtsweg, bei jedem Schritt neu: Nichts setzt sich, die Oberflächen köcheln.",
"Rauschen", 0.0, 1.0, 0.3, 0.01, 0.0, "R8", preset="boiling"),
Tool("norm", "Norm-Kollaps", "Oberfläche",
"Schaltet die Normalisierung in einer Schicht ab: Kontrast und Farbe laufen davon, das Motiv bleibt "
"lesbar.",
"Stärke", 0.0, 1.0, 1.0, 0.05, 0.0, "R8",
places=(("Aufwärts 4 (grün)", "up3"), ("Aufwärts 3 (orange)", "up2")), preset="norm-collapse"),
Tool("time", "Zeitlüge", "Oberfläche",
"Das UNet bekommt gesagt, das Bild sei viel verrauschter, als es ist. Also korrigiert es mutig weiter "
"an einem fast fertigen Bild und malt über seine eigene Arbeit: Pinselstriche statt Fell und Korn. "
"Negative Werte machen es glauben, es sei schon fertig: harte, überschärfte Bilder, bei −400 nur "
"noch Muster.",
"Verschiebung (von 1000)", -400.0, 800.0, 400.0, 25.0, 0.0, "R6", preset="time-displaced"),
Tool("ghost", "Auflösungsgeist", "Oberfläche",
"Die feinen Blöcke des Abwärtswegs müssen in halber Auflösung denken, der Aufwärtsweg malt in voller "
"Größe weiter. Wie ein Foto, das aus einem Vorschaubild wieder aufgebaut wurde: Treppen an den "
"Kanten, Matsch dazwischen, die Szene hält trotzdem. Verkleinert ihr nur den Weg nach unten, tragen "
"die Skips die scharfe Fassung hinüber, und der Schaden verschwindet fast.",
"Verkleinerung (Faktor)", 1.0, 4.0, 2.0, 1.0, 1.0, "R8",
places=(("ResNets von Abwärts 1 und 2", "resnets"), ("Nur der Weg nach unten", "path")),
window=(0.3, 1.0), preset="resolution-ghost"),
Tool("vae", "VAE-Fieber", "Oberfläche",
"Das Entrauschen läuft sauber, nur der Decoder, der das Ergebnis in Pixel übersetzt, rechnet mit "
"groben Gewichten. Gleiche Szene, falsche Farben.",
"Bits (weniger = gröber)", 2.0, 8.0, 3.0, 1.0, 16.0, "R9", window=None, preset="vae-fever"),
]}
TOOL_CHOICES = [("Kein Eingriff", "none")] + [(f"{t.group} · {t.label}", t.key) for t in TOOLS.values()]
def active(u: ToolUse) -> bool:
return u.key in TOOLS and u.value != TOOLS[u.key].neutral
def place_of(u: ToolUse) -> str:
"""The tool's place, its first place when none or an unknown one is given."""
places = [v for _, v in TOOLS[u.key].places]
return u.place if u.place in places else (places[0] if places else "")
def place_label(u: ToolUse) -> str:
return dict((v, k) for k, v in TOOLS[u.key].places).get(place_of(u), "")
# ---------------------------------------------------------------- attention
class ToolAttnProcessor:
"""SD 1.5's attention with the tools' changes, on PyTorch's fused attention (no maps in memory).
mods: dicts with a window "on" and any of: "temperature", "bias" (additive key bias for the
cond half, cross-attention only), "context" (replacement context for the cond half, with
weight "mix"), "gain" (factor on the output).
"""
def __init__(self, mods: list, clock):
self.mods, self.clock = mods, clock
def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None,
*args, **kwargs):
cross = encoder_hidden_states is not None
live = [m for m in self.mods if m["on"](self.clock.progress)]
ctx = encoder_hidden_states if cross else hidden_states
b = hidden_states.shape[0]
half = b // 2 # the batch is [cond; uncond]
temperature, bias, gain = 1.0, None, 1.0
for m in live:
temperature *= m.get("temperature", 1.0)
gain *= m.get("gain", 1.0)
if cross and "context" in m:
ctx = ctx.clone()
alt = m["context"].to(ctx.dtype).expand(half, -1, -1)
ctx[:half] = torch.lerp(ctx[:half], alt, m["mix"]) if m["mix"] != 1.0 else alt
if cross and "bias" in m:
bias = m["bias"] if bias is None else bias + m["bias"]
q, k, v = attn.to_q(hidden_states), attn.to_k(ctx), attn.to_v(ctx)
heads = attn.heads
d = k.shape[-1] // heads
q, k, v = (t.view(b, -1, heads, d).transpose(1, 2) for t in (q, k, v))
mask = None
if bias is not None: # (Lk,) on the cond half, nothing on uncond
mask = torch.zeros(b, 1, 1, k.shape[2], device=q.device, dtype=q.dtype)
mask[:half, 0, 0] = bias.to(q.dtype)
scale = attn.scale / _safe_temperature(temperature)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=scale)
out = out.transpose(1, 2).reshape(b, -1, heads * d).to(q.dtype)
out = attn.to_out[1](attn.to_out[0](out))
return out * gain if gain != 1.0 else out
def _safe_temperature(t: float) -> float:
"""Typed temperatures may be negative (attend to the least similar), but never zero."""
return math.copysign(max(abs(t), 0.02), t if t != 0 else 1.0)
def _attention_modules(unet, kind: str, blocks: list) -> list:
"""kind "attn1" (self) or "attn2" (cross), inside the given UNet blocks."""
return [m for blk in blocks for name, m in blk.named_modules() if name.endswith(kind)]
# ---------------------------------------------------------------- the tools
@contextmanager
def apply(engine, s):
"""Every active tool of s.tools for one render call. Removes all of it on any exit."""
uses = [u for u in getattr(s, "tools", ()) if active(u)]
if not uses:
yield []
return
unet = engine.pipe.unet
notes: list[str] = []
attn_mods: dict = {} # Attention module -> list of mods
with ExitStack() as stack:
# Tools that change how CLIP is read go first, so the others' encodings (prompt B) see it too.
for i, u in sorted(enumerate(uses), key=lambda iu: iu[1].key != "aphasia"):
_install(engine, s, u, i, stack, attn_mods, notes)
originals = {}
for module, mods in attn_mods.items():
originals[module] = module.processor
module.set_processor(ToolAttnProcessor(mods, engine.clock))
stack.callback(_restore_processors, originals)
yield notes
def _restore_processors(originals: dict) -> None:
for module, proc in originals.items():
module.set_processor(proc)
def _window(u: ToolUse):
tool = TOOLS[u.key]
if tool.window is None:
return lambda p: True
return lambda p: u.start <= p <= u.end
def _install(engine, s, u: ToolUse, i: int, stack: ExitStack, attn_mods: dict, notes: list) -> None:
unet, place, on = engine.pipe.unet, place_of(u), _window(u)
ups, downs = list(unet.up_blocks), list(unet.down_blocks)
def add_attn(modules, mod):
for m in modules:
attn_mods.setdefault(m, []).append(mod)
def hook(module, fn, pre=False):
h = (module.register_forward_pre_hook(fn, with_kwargs=True) if pre
else module.register_forward_hook(fn))
stack.callback(h.remove)
if u.key == "excise":
positions = word_positions(engine, s.prompt_a, u.word)
if not positions:
notes.append(f"„{u.word.strip()}“ kommt in Prompt A nicht vor, „Wort herausschneiden“ ändert nichts."
if u.word.strip() else "Für „Wort herausschneiden“ fehlt das Wort.")
return
if place == "word_pad": # CLIP copied the word into the end token and padding
n = len(engine.pipe.tokenizer(s.prompt_a, add_special_tokens=False).input_ids)
positions = positions + list(range(1 + n, engine.pipe.tokenizer.model_max_length))
keep = 1.0 - u.value # 0 removes, above 1 emphasises
bias = torch.zeros(engine.pipe.tokenizer.model_max_length, device=engine.device)
bias[positions] = math.log(keep) if keep > 0 else float("-inf")
add_attn(_attention_modules(unet, "attn2", [unet]), {"on": on, "bias": bias})
elif u.key == "layered":
alt = engine.encode(s.prompt_b, s.te_layers, 77).to(engine.device)
blocks = ups if place == "up" else downs if place == "down" else [unet.mid_block]
add_attn(_attention_modules(unet, "attn2", blocks), {"on": on, "context": alt, "mix": float(u.value)})
elif u.key == "positions":
emb = engine.pipe.text_encoder
emb = (emb.embeddings if hasattr(emb, "embeddings") else emb.text_model.embeddings).position_embedding
_edit_weight(stack, emb.weight, lambda w: w * (1.0 - u.value))
_tag_encodings(engine, stack, f"positions={u.value}")
elif u.key == "blind":
start = u.value / 100.0
blocks = ups if place == "up" else [unet]
add_attn(_attention_modules(unet, "attn2", blocks), {"on": lambda p: p >= start, "gain": 0.0})
elif u.key == "erosion":
keep = min(max(u.value / 100.0, 0.0), 1.0)
for m in _attention_modules(unet, "attn2", [unet]):
for lin in (m.to_q, m.to_k, m.to_v, m.to_out[0]):
_edit_weight(stack, lin.weight, lambda w: _svd_keep(w, keep))
elif u.key == "temperature":
if place == "self":
modules = _attention_modules(unet, "attn1", [unet])
elif place == "coarse": # Neural_Bending's attention-knife blocks
blocks = [downs[2], unet.mid_block, ups[1]]
modules = _attention_modules(unet, "attn1", blocks) + _attention_modules(unet, "attn2", blocks)
else:
modules = _attention_modules(unet, "attn2", [unet])
add_attn(modules, {"on": on, "temperature": float(u.value)})
elif u.key == "skips":
blocks = [ups[1], ups[2]] if place == "mid_res" else [ups[0], ups[1]]
g = float(u.value)
def scale_skips(module, args, kwargs):
if not on(engine.clock.progress) or "res_hidden_states_tuple" not in kwargs:
return None
return args, {**kwargs, "res_hidden_states_tuple": tuple(r * g for r in kwargs["res_hidden_states_tuple"])}
for blk in blocks:
hook(blk, scale_skips, pre=True)
elif u.key == "mirror":
w = float(u.value)
def mirror(lat):
if not on(engine.clock.progress):
return lat
out = lat.clone()
h, wd = lat.shape[-2:]
if place in ("h", "both"):
out[..., wd - wd // 2:] = torch.flip(out[..., : wd // 2], dims=[-1])
if place in ("v", "both"):
out[..., h - h // 2:, :] = torch.flip(out[..., : h // 2, :], dims=[-2])
return torch.lerp(lat, out, w) if w != 1.0 else out
engine.post_step.append(mirror)
stack.callback(engine.post_step.remove, mirror)
elif u.key == "freeze":
at = u.value / 100.0
blocks = [unet.mid_block, ups[1]] if place == "mid_up1" else [unet.mid_block]
for blk in blocks:
memo: dict = {}
def fossil(module, args, output, memo=memo):
t = output[0] if isinstance(output, tuple) else output
if engine.clock.progress <= at or "t" not in memo or memo["t"].shape != t.shape:
memo["t"] = t.detach().clone() # still live: the cache ends at the freezing step
return None
return (memo["t"],) + tuple(output[1:]) if isinstance(output, tuple) else memo["t"]
hook(blk, fossil)
elif u.key == "boil":
sigma = float(u.value)
gen = torch.Generator(engine.device).manual_seed(s.seed + SEED_TOOLS + i)
def simmer(module, args, output):
if not on(engine.clock.progress):
return None
t = output[0] if isinstance(output, tuple) else output
half = t.shape[0] // 2 # cond only, so guidance amplifies it
z = torch.randn(t[:half].shape, generator=gen, device=t.device, dtype=torch.float32)
t = t.clone()
t[:half] = t[:half] + (sigma * t[:half].float().std() * z).to(t.dtype)
return (t,) + tuple(output[1:]) if isinstance(output, tuple) else t
for blk in downs:
for m in list(blk.resnets) + list(getattr(blk, "attentions", None) or []):
hook(m, simmer)
elif u.key == "norm":
blk = ups[3] if place == "up3" else ups[2]
w = float(u.value)
def unnormed(module, args, output):
if not on(engine.clock.progress):
return None
return torch.lerp(output, args[0], w) if w != 1.0 else args[0].clone()
for res in blk.resnets:
hook(res.norm1, unnormed)
elif u.key == "vae":
bits = max(1, round(u.value))
if bits < 16:
for m in engine.pipe.vae.decoder.modules():
if isinstance(m, torch.nn.Conv2d):
_edit_weight(stack, m.weight, lambda w: _quantize(w, bits))
elif u.key == "aphasia":
k = min(max(round(u.value), 0), engine.pipe.text_encoder.config.num_hidden_layers)
def early(encode):
def read_early(prompt, layers=(12,), *args, **kwargs): # cached under the layer it reads
return encode(prompt, tuple(max(0, n - k) for n in layers), *args, **kwargs)
return read_early
_wrap(stack, engine, "encode", early)
if place == "pad":
n = len(engine.pipe.tokenizer(s.prompt_a, add_special_tokens=False).input_ids)
def blank(conditioning):
def blank_padding(s_, ts, max_len): # prompt A only, the negative stays as it is
cond, uncond = conditioning(s_, ts, max_len)
cond = cond.clone()
cond[:, 2 + min(n, max_len - 2):] = 0 # after the end token
return cond, uncond
return blank_padding
_wrap(stack, engine, "conditioning", blank)
elif u.key == "guidance":
w = float(u.value)
def invert(module, args, output):
if not on(engine.clock.progress):
return None
eps = (output[0] if isinstance(output, tuple) else output).float()
e_c, e_u = eps.chunk(2) # the batch is [cond; uncond]
# The engine combines e_u + g (e_c - e_u). Handed e_u + (1 - 2w)(e_c - e_u) as the prompt's
# prediction, it computes e_u + g (1 - 2w)(e_c - e_u): w = 1 reverses the guidance.
new = torch.cat([e_u + (1.0 - 2.0 * w) * (e_c - e_u), e_u])
return (new,) + tuple(output[1:]) if isinstance(output, tuple) else new
hook(unet, invert)
elif u.key == "time":
delta = float(u.value)
def lie(module, args, kwargs):
if not on(engine.clock.progress) or not args:
return None
return ((args[0].float() + delta).clamp(0.0, 999.0),) + tuple(args[1:]), kwargs
hook(unet.time_proj, lie, pre=True)
elif u.key == "bypass":
w = float(u.value)
def wire(module, args, kwargs, output):
if not on(engine.clock.progress):
return None
x = args[0] if args else kwargs.get("hidden_states")
t = output[0] if isinstance(output, tuple) else output
if x.shape[-2:] != t.shape[-2:]: # the up blocks double the resolution
x = F.interpolate(x.float(), size=t.shape[-2:], mode="nearest")
if x.shape[1] != t.shape[1]:
return None # never in the mid block and the first two up blocks
new = torch.lerp(t, x.to(t.dtype), w)
return (new,) + tuple(output[1:]) if isinstance(output, tuple) else new
for blk in [unet.mid_block] + ([ups[0], ups[1]] if place == "mid_up" else []):
h = blk.register_forward_hook(wire, with_kwargs=True)
stack.callback(h.remove)
elif u.key == "ghost":
f = max(1, round(u.value))
def coarse(t):
h, wd = t.shape[-2:]
small = F.interpolate(t.float(), size=(max(1, h // f), max(1, wd // f)), mode="area")
return F.interpolate(small, size=(h, wd), mode="nearest").to(t.dtype)
def ghost(module, args, output):
if not on(engine.clock.progress) or f == 1:
return None
if isinstance(output, tuple): # a down block: its skips leave unchanged
return (coarse(output[0]),) + tuple(output[1:])
return coarse(output)
for m in [r for blk in downs[:2] for r in blk.resnets] if place == "resnets" else downs[:2]:
hook(m, ghost)
elif u.key == "shakes":
sigma = float(u.value)
gen = torch.Generator(engine.device).manual_seed(s.seed + SEED_TOOLS + i)
def swell(p: float) -> float: # half a sine over the window, 0 at both ends
if not u.start <= p <= u.end or u.end <= u.start:
return 0.0
return math.sin(math.pi * (p - u.start) / (u.end - u.start))
for m in _attention_modules(unet, "attn1" if place == "self" else "attn2", [unet]):
for lin in (m.to_q, m.to_k, m.to_v, m.to_out[0]):
wt = lin.weight
z = torch.randn(wt.shape, generator=gen, device=wt.device, dtype=torch.float32)
noise = (z * (sigma * wt.float().std())).to(wt.dtype)
def shake(module, args, output, noise=noise):
a = swell(engine.clock.progress) # W + a * noise, without touching W
return None if a == 0.0 else output + a * F.linear(args[0], noise)
hook(lin, shake)
def _wrap(stack: ExitStack, obj, name: str, make) -> None:
"""Wrap a method of obj for this call: make(current method) -> replacement. Restored on exit."""
had, previous = name in vars(obj), vars(obj).get(name)
setattr(obj, name, make(getattr(obj, name)))
stack.callback(lambda: setattr(obj, name, previous) if had else delattr(obj, name))
def _edit_weight(stack: ExitStack, p: torch.Tensor, fn) -> None:
"""Replace a weight for this call, restore the exact original afterwards."""
original = p.detach().clone()
with torch.no_grad():
p.copy_(fn(original.float()).to(p.dtype))
def restore():
with torch.no_grad():
p.copy_(original)
stack.callback(restore)
def _tag_encodings(engine, stack: ExitStack, tag: str) -> None:
"""Encodings made with a changed CLIP must not land in, or come from, the plain cache."""
previous = engine.encode_tag
engine.encode_tag = f"{previous}|{tag}"
stack.callback(setattr, engine, "encode_tag", previous)
def _svd_keep(w: torch.Tensor, keep: float) -> torch.Tensor:
u, sv, vh = torch.linalg.svd(w, full_matrices=False)
r = max(1, round(keep * sv.numel()))
return (u[:, :r] * sv[:r]) @ vh[:r]
def _quantize(w: torch.Tensor, bits: int) -> torch.Tensor:
"""Uniform quantisation over the tensor's own range, as in Neural_Bending's weight_quantize."""
levels = float((1 << bits) - 1)
lo, hi = w.min(), w.max()
span = (hi - lo).clamp_min(1e-12)
return ((w - lo) / span * levels).round() / levels * span + lo
def word_positions(engine, prompt: str, word: str) -> list[int]:
"""Token positions of `word` in the prompt (start token = position 0). Every occurrence."""
word = (word or "").strip()
if not word:
return []
tok = engine.pipe.tokenizer
ids = tok(prompt, add_special_tokens=False).input_ids
target = tok(word, add_special_tokens=False).input_ids
hits = []
for k in range(len(ids) - len(target) + 1):
if ids[k:k + len(target)] == target:
hits += [1 + k + j for j in range(len(target))]
return [p for p in hits if p < tok.model_max_length - 1]