Pixelkram commited on
Commit
1624300
·
verified ·
1 Parent(s): 4f6efe5

Deploy app

Browse files
Files changed (14) hide show
  1. README.md +111 -5
  2. app.py +490 -0
  3. bendmap.css +122 -0
  4. bendmap.js +703 -0
  5. compare.js +37 -0
  6. engine.py +541 -0
  7. engine_sd15.py +255 -0
  8. family.py +101 -0
  9. measure.py +115 -0
  10. packages.txt +1 -0
  11. requirements.txt +7 -0
  12. safety.py +63 -0
  13. sites.py +108 -0
  14. tools_sd15.py +427 -0
README.md CHANGED
@@ -1,13 +1,119 @@
1
  ---
2
  title: Biegen
3
- emoji: 🌍
4
- colorFrom: green
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.31.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Biegen
3
+ emoji: 🪢
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 6.31.0
8
+ python_version: "3.12"
9
  app_file: app.py
10
  pinned: false
11
+ suggested_hardware: l4x1
12
+ models:
13
+ - stable-diffusion-v1-5/stable-diffusion-v1-5
14
+ short_description: Stable Diffusion 1.5 von innen biegen, auf einer Karte
15
  ---
16
 
17
+ # Biegen
18
+
19
+ Twelve model-bending tools for Stable Diffusion 1.5, controlled from a map of the network. The tools
20
+ come from the Neural_Bending lab (`~/ai/neural_nodes`) and used to be Tab 4 of the workshop Space
21
+ "Erkunden, biegen, brechen". Here they get a Space of their own, built around one question: where in
22
+ the network does a tool act, and what does it change there?
23
+
24
+ ## The map
25
+
26
+ The map (`bendmap.js`, a `gr.HTML` component with its own script) is the control surface.
27
+
28
+ - **Text lane, left:** Prompt A, the token and position tables, CLIP's 12 layers, and the context:
29
+ 77 vectors, shown as the prompt's actual CLIP tokens plus the end token and the padding. Prompt B
30
+ appears below it, lit up only when a tool uses it.
31
+ - **UNet, middle:** the U shape with its real layout: Abwärts 1 to 4 (64 x 64 down to 8 x 8 positions),
32
+ Mitte, Aufwärts 1 to 4, and the skip connections across. Each block shows what it contains: Res
33
+ (convolutions), Selbst (self-attention) and Quer (cross-attention, the only place where text enters the
34
+ image). Abwärts 4 and Aufwärts 1 contain convolutions only.
35
+ - **Loop, top:** latent x_t, UNet, noise prediction, sampler step, back to x_t. After the last step the
36
+ VAE decoder turns the latent into pixels; the first image of the last run is shown there.
37
+ - **Timeline, bottom:** each tool's window from noise (0 %) to image (100 %), with handles you drag.
38
+ For "Prompt weg ab …" and "Eingefroren" the knob itself is a moment, so the handle sets the knob.
39
+
40
+ Picking a tool from the palette lights up its sites in the slot's colour (up to three tools: orange,
41
+ blue, green). Hovering a tool in the palette shows every place it can act, as dashed outlines. The selected
42
+ tool's other places are drawn dashed too; clicking one on the map moves the tool there. Every element
43
+ explains itself in a tooltip and lists the tools acting on it.
44
+
45
+ The sites come from `sites.py`. `tests/test_sites.py` installs every tool at every place on a tiny UNet
46
+ with SD 1.5's layout, collects the hooks, attention processors, weight edits and sampler steps it really
47
+ installs, maps the module names to sites, and checks the result against the table. A site on the map
48
+ therefore names exactly the modules the code changes.
49
+
50
+ ## What is measured
51
+
52
+ Every run renders the same seeds without tools too (kept in memory, so changing only the tools reuses
53
+ them). `measure.py` records, for the first image and every step, a strided sample of each UNet block's
54
+ output (at most 320 channels on a 16 x 16 grid) and of the latent, in both runs, and compares them as a
55
+ relative change |bent - plain| / |plain|.
56
+
57
+ - **Block fill:** the change in the first step where anything changed. The latent going into that step
58
+ is still identical, so only the block where the tool enters, and everything after it, light up. On the
59
+ real model: Norm-Kollaps on Aufwärts 4 fills Aufwärts 4 alone, the second prompt on the up path starts
60
+ at Aufwärts 2 (Aufwärts 1 has no cross-attention), the skip tool at the first up block it feeds.
61
+ - **Line in each block:** the same change over all steps.
62
+ - **Line above the timeline:** the change of the latent over the steps.
63
+ - **Images:** each result is shown bent, with the unbent image under a wipe that follows the pointer,
64
+ and the mean pixel change ("Δ 14 %").
65
+
66
+ The recorder is installed inside the engine's interventions, after the tools, so it sees what they leave
67
+ behind (a frozen block's cached output, the mirrored latent). The map greys the measurement out as soon as
68
+ the tools change after a run.
69
+
70
+ ## The tools
71
+
72
+ Each tool takes a Neural_Bending preset and reduces it to one knob, a place and a window. The defaults come
73
+ from the calibration sheets of the workshop project (`python bench.py tools` in `~/ai/boden_workshop_space`).
74
+
75
+ | Tool | Preset | Knob, default | Places | What the sheets showed |
76
+ |---|---|---|---|---|
77
+ | Wort herausschneiden | word-excision | Stärke 1 (negative emphasises) | word and padding, word only | the horse leaves the picture only when the padding is masked too |
78
+ | Zweiter Prompt für die Oberfläche | layered-prompt | share of prompt B 1 | up path, down path, mid only | up path: same horse in marble; down path: a marble statue |
79
+ | Wortreihenfolge vergessen | positional-amnesia | Stärke 1 | | painterly, colours move to other objects already at 0.25 |
80
+ | Prompt weg ab … | prompt-blind-late | from 25 % | up path, everywhere | the astronaut becomes an ordinary rider in the same pose |
81
+ | Spektrale Erosion | spectral-erosion | 12 % of the singular values | | generic people and objects; texture below 6 % |
82
+ | Aufmerksamkeit: Nebel und Messer | attention-fog / attention-knife | temperature 4 from 20 % (coarse: 0.25, text: 3) | self-attention, coarse blocks, cross-attention | fog above 1, cut-paper collage below 1 on the coarse blocks, confetti below 1 everywhere |
83
+ | Skip-Verbindungen | skip-flood / skip-severed | gain 2.5 | mid resolution, coarse | 0 invents texture, 2.5 over-resolves into colour blotches |
84
+ | Symmetrie-Gefängnis | symmetry-prison | 0.3 (top/bottom 0.1, four-fold 0.2) | left/right, top/bottom, four-fold | full strength collapses into ornament on this sampler |
85
+ | Eingefroren | frozen-in-thought | from 8 % | mid and up 2, mid only | early freezing leaves a soft fossil of the noise |
86
+ | Kochen | boiling | noise 0.3 | | surfaces simmer, dissolves from 0.6 |
87
+ | Norm-Kollaps | norm-collapse | Stärke 1 | up 4 (green), up 3 (orange) | woven high-contrast colour, subject readable |
88
+ | VAE-Fieber | vae-fever | 3 bits | | invisible at 5 bits, fever colours at 3, abstract at 2 |
89
+
90
+ Temperature, word masking and the second prompt run in one attention processor on PyTorch's fused
91
+
92
+ Every number may go past its slider (the knob's number box, steps, guidance), the seed may be negative.
93
+ Windows are clamped to 0 to 100 % with a note. One job may cost at most a 4 x 4 grid at the default steps,
94
+ rendered with and without tools; bigger requests are refused with a message, the outputs stay as they were.
95
+
96
+ ## Files
97
+
98
+ | File | |
99
+ |---|---|
100
+ | `app.py` | the Gradio app: prompts, map, settings, results, status with one recipe line per tool |
101
+ | `bendmap.js`, `bendmap.css` | the map, the palette and the tool cards |
102
+ | `compare.js` | the before/after wipe |
103
+ | `sites.py` | where each tool acts, and module names to sites |
104
+ | `measure.py` | the activation recorder and the effect |
105
+ | `engine.py`, `engine_sd15.py`, `family.py`, `tools_sd15.py`, `safety.py` | symlinks to `~/ai/boden_workshop_space`, one engine for both Spaces |
106
+
107
+ The NSFW output filter (`safety.py`) is on, as in the workshop Space. With the secret `WORKSHOP_PASSWORD`
108
+ set, the Space asks for the user name `workshop` and that password.
109
+
110
+ ## Development
111
+
112
+ ```
113
+ .venv/bin/python -m pytest # CPU: sites, measurement, app (tiny model)
114
+ BIEGEN_GPU_TESTS=1 .venv/bin/python -m pytest -m gpu # every tool at every place on the real model
115
+ GRADIO_SERVER_PORT=7870 .venv/bin/python app.py
116
+ python deploy_space.py Pixelkram/biegen --token-name claude_write
117
+ ```
118
+
119
+ `.venv` is the workshop project's environment (Gradio 6.31, torch 2.10, diffusers 0.42.1).
app.py ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio app "Biegen": Neural_Bending's tools for Stable Diffusion 1.5, on a map of the network.
2
+
3
+ The map (bendmap.js) is the control surface: pick tools, choose where they act by clicking the
4
+ network, drag their time windows. Every run renders the same seeds without tools too (cached), shows
5
+ both images with a wipe, and draws on the map how much each block of the UNet changed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import html
11
+ import json
12
+ import math
13
+ import os
14
+ import shutil
15
+ import tempfile
16
+ import threading
17
+ from collections import OrderedDict
18
+ from dataclasses import replace
19
+
20
+ os.environ.setdefault("MODEL_FAMILY", "sd15")
21
+
22
+ import gradio as gr # noqa: E402
23
+
24
+ import engine as E # noqa: E402
25
+ import measure as M # noqa: E402
26
+ import safety as S # noqa: E402
27
+ import sites as W # noqa: E402
28
+ import tools_sd15 as T # noqa: E402
29
+ from family import ACTIVE as FAM # noqa: E402
30
+
31
+ if FAM.key != "sd15":
32
+ raise SystemExit("Biegen runs on Stable Diffusion 1.5 only (MODEL_FAMILY=sd15).")
33
+
34
+ HERE = os.path.dirname(os.path.abspath(__file__))
35
+ WORKSHOP_PASSWORD = os.environ.get("WORKSHOP_PASSWORD")
36
+ OUT_DIR = os.environ.get("BIEGEN_OUT") or tempfile.mkdtemp(prefix="biegen-")
37
+ KEEP_RUNS = 40 # result folders kept on disk, older ones are deleted
38
+ PLAIN_CACHE = 12 # renders without tools kept in memory
39
+
40
+ PROMPT_A = "a photograph of a horse standing in a field"
41
+ PROMPT_B = "carved from cracked white marble, veined stone, museum lighting"
42
+ GRID_CHOICES = [(f"{k} × {k}", k * k) for k in range(1, 5)]
43
+ GRID_DEFAULT = 4
44
+ N_SLOTS = 3
45
+ SLOT_COLORS = ("#e8590c", "#1c7ed6", "#2f9e44") # orange, blue, green: tell apart in light and dark mode
46
+ ICONS = {"excise": "✂", "layered": "◫", "positions": "⇄", "blind": "◐", "erosion": "≋", "temperature": "✱",
47
+ "skips": "⤳", "mirror": "⧉", "freeze": "❄", "boil": "♨", "norm": "◩", "vae": "▦"}
48
+ TIME_KNOB = ("blind", "freeze") # tools whose knob is a moment in the schedule
49
+ # Typed numbers may go past every slider. These limits stay.
50
+ HARD_LIMITS = {"seed": ("Seed", -2 ** 62, 2 ** 62), "steps": ("Schritte", 1, 250)}
51
+ # One job: the largest grid at the default steps, with and without tools. Nobody holds the queue longer.
52
+ MAX_WORK = 2 * max(n for _, n in GRID_CHOICES)
53
+
54
+ THEME = gr.themes.Soft(
55
+ primary_hue="indigo", neutral_hue="slate",
56
+ font=[gr.themes.GoogleFont("Atkinson Hyperlegible"), "system-ui", "sans-serif"],
57
+ font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"])
58
+
59
+ # Gradio's slider snaps a typed value back into its range when the number box loses focus.
60
+ FREE_SLIDER_JS = """<script>
61
+ window.addEventListener("blur", (e) => {
62
+ const box = e.target;
63
+ if (box instanceof HTMLInputElement && box.type === "number" && box.closest(".free-slider")) {
64
+ e.stopImmediatePropagation();
65
+ }
66
+ }, true);
67
+ </script>"""
68
+
69
+
70
+ class FreeSlider(gr.Slider):
71
+ """A slider whose number box takes values beyond the slider's range (with FREE_SLIDER_JS).
72
+ No __init__ of its own: Gradio reads the component's settings from the __init__ signature."""
73
+
74
+ is_template = True
75
+
76
+ def preprocess(self, payload: float) -> float:
77
+ return gr.Number.round_to_precision(payload, self.precision)
78
+
79
+
80
+ def free_slider(minimum: float, maximum: float, **kwargs) -> FreeSlider:
81
+ return FreeSlider(minimum, maximum, elem_classes=["free-slider"], **kwargs)
82
+
83
+
84
+ def read(name: str) -> str:
85
+ with open(os.path.join(HERE, name), encoding="utf-8") as f:
86
+ return f.read()
87
+
88
+
89
+ # ---------------------------------------------------------------- engine
90
+
91
+ _engine = None
92
+ _engine_lock = threading.Lock()
93
+ _sec_per_image = None
94
+ _tokenizer = None
95
+
96
+
97
+ def get_engine():
98
+ global _engine, _sec_per_image
99
+ with _engine_lock:
100
+ if _engine is None:
101
+ _engine = E.load_engine()
102
+ print(f"[app] warm-up {_engine.warmup():.1f} s", flush=True)
103
+ seconds = _engine.warmup(n=GRID_DEFAULT, steps=E.DEFAULT_STEPS)
104
+ _sec_per_image = seconds / GRID_DEFAULT
105
+ print(f"[app] {GRID_DEFAULT} images at the defaults in {seconds:.1f} s", flush=True)
106
+ return _engine
107
+
108
+
109
+ def tokenizer():
110
+ """CLIP's tokenizer on its own, so the map can show tokens before the model has loaded."""
111
+ global _tokenizer
112
+ if _tokenizer is None:
113
+ from transformers import CLIPTokenizer
114
+
115
+ _tokenizer = CLIPTokenizer.from_pretrained(E.MODEL_ID, subfolder="tokenizer")
116
+ return _tokenizer
117
+
118
+
119
+ def sec_per_image() -> float:
120
+ return _sec_per_image or FAM.sec_per_image
121
+
122
+
123
+ def duration(seconds: float) -> str:
124
+ return f"etwa {round(seconds / 60)} Minuten" if seconds >= 90 else f"etwa {round(seconds)} Sekunden"
125
+
126
+
127
+ # ---------------------------------------------------------------- the map's catalogue and state
128
+
129
+ def catalog() -> dict:
130
+ """Everything bendmap.js needs to know about the tools and the network."""
131
+ tools = []
132
+ for t in T.TOOLS.values():
133
+ places = []
134
+ for label, value in (t.places or (("", ""),)):
135
+ v, start, end = t.defaults_for(value)
136
+ places.append({"value": value, "label": label, "sites": list(W.sites(t.key, value)),
137
+ "default": v, "start": round(start * 100), "end": round(end * 100)})
138
+ tools.append({"key": t.key, "label": t.label, "group": t.group, "what": t.what, "knob": t.knob,
139
+ "lo": t.lo, "hi": t.hi, "step": t.step, "neutral": t.neutral, "preset": t.preset,
140
+ "window": t.window is not None, "time_knob": t.key in TIME_KNOB,
141
+ "after_loop": t.key == "vae", "icon": ICONS.get(t.key, "•"), "places": places})
142
+ return {"tools": tools, "groups": list(dict.fromkeys(t.group for t in T.TOOLS.values())),
143
+ "colors": list(SLOT_COLORS), "max_slots": N_SLOTS}
144
+
145
+
146
+ def default_slot(key: str, place: str = "", word: str = "") -> dict:
147
+ t = T.TOOLS[key]
148
+ place = place or W.places(key)[0]
149
+ value, start, end = t.defaults_for(place)
150
+ return {"tool": key, "place": place, "value": value, "start": round(start * 100), "end": round(end * 100),
151
+ "word": word}
152
+
153
+
154
+ DEFAULT_STATE = {"slots": [default_slot("layered", "up")], "rev": 0}
155
+
156
+
157
+ def tokens(prompt: str) -> list[str]:
158
+ """CLIP's tokens of a prompt as the map shows them, without start, end and padding."""
159
+ tok = tokenizer()
160
+ ids = tok(prompt or "", add_special_tokens=False, truncation=True,
161
+ max_length=tok.model_max_length - 2).input_ids
162
+ return [tok.convert_ids_to_tokens(i).replace("</w>", "") for i in ids]
163
+
164
+
165
+ def server_part(prompt_a: str, prompt_b: str) -> dict:
166
+ return {"prompt": prompt_a or "", "prompt_b": prompt_b or "", "tokens": tokens(prompt_a),
167
+ "tokens_b": tokens(prompt_b), "max_len": tokenizer().model_max_length}
168
+
169
+
170
+ def map_value(server: dict, state: dict | None = None) -> str:
171
+ out = {"server": server}
172
+ if state is not None:
173
+ out["state"] = state
174
+ return json.dumps(out, ensure_ascii=False)
175
+
176
+
177
+ def parse_state(value: str | None) -> dict:
178
+ """The map's state from its JSON value. Anything malformed counts as no tools."""
179
+ try:
180
+ data = json.loads(value) if value else {}
181
+ except (TypeError, ValueError):
182
+ data = {}
183
+ state = data.get("state") if isinstance(data, dict) else None
184
+ if not isinstance(state, dict):
185
+ return {"slots": [], "rev": 0}
186
+ slots = [s for s in state.get("slots") or [] if isinstance(s, dict)][:N_SLOTS]
187
+ rev = state.get("rev", 0)
188
+ return {"slots": slots, "rev": rev if isinstance(rev, int) else 0}
189
+
190
+
191
+ def number(x, default: float) -> float:
192
+ try:
193
+ x = float(x)
194
+ except (TypeError, ValueError):
195
+ return default
196
+ return x if math.isfinite(x) else default
197
+
198
+
199
+ def tool_uses(slots: list[dict]) -> tuple[tuple, list[str]]:
200
+ """ToolUse entries from the map's slots. Windows are clamped to 0..100 % with a note."""
201
+ uses, notes = [], []
202
+ for k, v in enumerate(slots):
203
+ key = v.get("tool")
204
+ if key not in T.TOOLS:
205
+ continue
206
+ t = T.TOOLS[key]
207
+ start, end = number(v.get("start"), 0.0) / 100, number(v.get("end"), 100.0) / 100
208
+ if t.window is not None and not (0 <= start <= 1 and 0 <= end <= 1):
209
+ notes.append(f"Eingriff {k + 1}: das Zeitfenster geht nur von 0 % bis 100 %, "
210
+ "gerechnet wird mit dem Teil darin.")
211
+ start, end = min(max(start, 0.0), 1.0), min(max(end, 0.0), 1.0)
212
+ place = v.get("place") if v.get("place") in W.places(key) else W.places(key)[0]
213
+ uses.append(T.ToolUse(key, number(v.get("value"), t.neutral), place, start, end,
214
+ str(v.get("word") or "")[:80]))
215
+ return tuple(uses), notes
216
+
217
+
218
+ def recipe(u: T.ToolUse) -> str:
219
+ """One line per tool, to copy and to compare runs."""
220
+ t = T.TOOLS[u.key]
221
+ parts = [f'"{t.label}"']
222
+ if T.place_label(u):
223
+ parts.append(f'ort="{T.place_label(u)}"')
224
+ if u.key == "excise":
225
+ parts.append(f'wort="{u.word.strip()}"')
226
+ parts.append(f"{t.knob.split(' (')[0].lower()}={E.fmt_num(u.value, 2).rstrip('0').rstrip(',')}")
227
+ if t.window is not None:
228
+ parts.append(f"wirkt={round(u.start * 100)}–{round(u.end * 100)} %")
229
+ return f"biegen({', '.join(parts)})"
230
+
231
+
232
+ # ---------------------------------------------------------------- settings and budget
233
+
234
+ def settings(prompt_a, prompt_b, seed, steps, guidance, grid, uses) -> E.Settings:
235
+ return E.Settings(prompt_a or "", prompt_b or "", "seed_grid", seed=int(number(seed, 42)),
236
+ steps=int(round(number(steps, E.DEFAULT_STEPS))), guidance=number(guidance, FAM.g_default),
237
+ grid=int(grid or GRID_DEFAULT), te_layers=(12,), tools=uses)
238
+
239
+
240
+ def within_limits(s: E.Settings) -> tuple[E.Settings, list[str]]:
241
+ changes, notes = {}, []
242
+ for name, (label, lo, hi) in HARD_LIMITS.items():
243
+ value = getattr(s, name)
244
+ if not lo <= value <= hi:
245
+ changes[name] = min(max(value, lo), hi)
246
+ notes.append(f"{label}: möglich sind {lo} bis {hi}, gerechnet wird mit {changes[name]}.")
247
+ return replace(s, **changes), notes
248
+
249
+
250
+ def work(s: E.Settings) -> float:
251
+ """GPU work of one render in images at the default steps."""
252
+ return (s.grid or GRID_DEFAULT) * s.steps / E.DEFAULT_STEPS
253
+
254
+
255
+ def too_much_work(s: E.Settings, renders: int) -> str | None:
256
+ w = work(s) * renders
257
+ if w <= MAX_WORK:
258
+ return None
259
+ return (f"Das ist zu viel auf einmal: Es würde {duration(w * sec_per_image())} dauern, und alle anderen "
260
+ "müssten warten. Nehmt ein kleineres Raster oder weniger Schritte.")
261
+
262
+
263
+ def plain_key(s: E.Settings) -> E.Settings:
264
+ """Renders without tools do not depend on prompt B."""
265
+ return replace(s, tools=(), prompt_b="")
266
+
267
+
268
+ # ---------------------------------------------------------------- rendering
269
+
270
+ class Shot:
271
+ """One render: image files, captions and the recorded activations."""
272
+
273
+ def __init__(self, paths: list[str], captions: list[str], images: list, acts: dict, seconds: float,
274
+ warnings: list[str]):
275
+ self.paths, self.captions, self.images, self.acts = paths, captions, images, acts
276
+ self.seconds, self.warnings = seconds, warnings
277
+
278
+
279
+ _plain: OrderedDict = OrderedDict()
280
+ _run_counter = 0
281
+ _run_lock = threading.Lock()
282
+
283
+
284
+ def run_dir() -> str:
285
+ """A fresh folder for one run's images. Old folders go."""
286
+ global _run_counter
287
+ with _run_lock:
288
+ _run_counter += 1
289
+ path = os.path.join(OUT_DIR, f"run-{_run_counter:05d}")
290
+ os.makedirs(path, exist_ok=True)
291
+ stale = sorted(d for d in os.listdir(OUT_DIR) if d.startswith("run-"))[:-KEEP_RUNS]
292
+ keep = {os.path.dirname(p) for shot in _plain.values() for p in shot.paths[:1]}
293
+ for d in stale:
294
+ if os.path.join(OUT_DIR, d) not in keep:
295
+ shutil.rmtree(os.path.join(OUT_DIR, d), ignore_errors=True)
296
+ return path
297
+
298
+
299
+ def shoot(s: E.Settings, folder: str, tag: str, report) -> Shot:
300
+ eng = get_engine()
301
+ rec = M.Recorder(s.steps)
302
+ try:
303
+ with M.recording(eng, rec):
304
+ res = eng.render(s, E.sample_specs(s), max_seq=77, progress=report)
305
+ except gr.Error:
306
+ raise
307
+ except ValueError as exc:
308
+ raise gr.Error(f"Diese Einstellung geht nicht: {exc}")
309
+ items, hidden = S.filter_items(res.items)
310
+ if hidden:
311
+ res.warnings.append(f"Der Filter hat {hidden} von {len(items)} Bildern ausgeblendet.")
312
+ paths = []
313
+ for k, (im, _) in enumerate(items):
314
+ p = os.path.join(folder, f"{tag}-{k:02d}.jpg")
315
+ im.convert("RGB").save(p, quality=90)
316
+ paths.append(p)
317
+ return Shot(paths, [c for _, c in items], [im for im, _ in items], rec.tensors(), res.seconds, res.warnings)
318
+
319
+
320
+ def image_change(a, b) -> float:
321
+ """Mean absolute pixel difference, 0 (same) to 1 (black against white)."""
322
+ import numpy as np
323
+
324
+ x = np.asarray(a.convert("RGB"), dtype=np.float32)
325
+ y = np.asarray(b.convert("RGB"), dtype=np.float32)
326
+ return float(np.abs(x - y).mean() / 255.0) if x.shape == y.shape else 1.0
327
+
328
+
329
+ def file_url(path: str) -> str:
330
+ return "/gradio_api/file=" + path
331
+
332
+
333
+ def compare_html(plain: Shot, bent: Shot | None, changes: list[float]) -> str:
334
+ cols = math.ceil(math.sqrt(len(plain.paths)))
335
+ cards = []
336
+ for k, p in enumerate(plain.paths):
337
+ cap = html.escape(plain.captions[k])
338
+ if bent is None:
339
+ cards.append(f'<figure class="bc-card"><img src="{file_url(p)}" alt="{cap}" loading="lazy">'
340
+ f"<figcaption>{cap}</figcaption></figure>")
341
+ continue
342
+ d = f"Δ {round(changes[k] * 100)} %"
343
+ cards.append(
344
+ f'<figure class="bc-card" data-both="1"><div class="bc-frame">'
345
+ f'<img class="bc-bent" src="{file_url(bent.paths[k])}" alt="{cap}, gebogen">'
346
+ f'<img class="bc-plain" src="{file_url(p)}" alt="{cap}, ohne Eingriff">'
347
+ f'<div class="bc-line"></div><span class="bc-tag bc-tag-plain">ohne</span>'
348
+ f'<span class="bc-tag bc-tag-bent">gebogen</span></div>'
349
+ f'<figcaption>{cap} <b title="mittlere Pixeländerung gegenüber dem Bild ohne Eingriff">{d}</b>'
350
+ f"</figcaption></figure>")
351
+ hint = ("Fahrt mit der Maus über ein Bild: links vom Strich seht ihr dasselbe Bild ohne Eingriff."
352
+ if bent is not None else "Kein Eingriff aktiv: das sind die Bilder ohne Eingriff.")
353
+ toggle = '<button type="button" class="bc-toggle">Alle ohne Eingriff zeigen</button>' if bent else ""
354
+ return (f'<div class="bc"><div class="bc-bar"><span>{hint}</span>{toggle}</div>'
355
+ f'<div class="bc-grid" style="grid-template-columns: repeat({cols}, minmax(0, 1fr))">'
356
+ f'{"".join(cards)}</div></div>')
357
+
358
+
359
+ EMPTY_RESULT = ('<div class="bc bc-empty">Hier erscheinen die Bilder: jedes einmal gebogen und einmal ohne '
360
+ "Eingriff, zum Vergleichen.</div>")
361
+
362
+
363
+ def run(prompt_a, prompt_b, seed, steps, guidance, grid, map_json, progress=gr.Progress()):
364
+ state = parse_state(map_json)
365
+ print(f"[run] rev {state['rev']}, tools {[v.get('tool') for v in state['slots']]}", flush=True)
366
+ uses, notes = tool_uses(state["slots"])
367
+ s, limit_notes = within_limits(settings(prompt_a, prompt_b, seed, steps, guidance, grid, uses))
368
+ notes = limit_notes + notes
369
+ live = [u for u in uses if T.active(u)]
370
+ key = plain_key(s)
371
+ cached = _plain.get(key)
372
+ renders = (cached is None) + bool(live)
373
+ refusal = too_much_work(s, renders)
374
+ if refusal:
375
+ gr.Warning(refusal)
376
+ return gr.update(), gr.update(), refusal
377
+
378
+ total = renders * s.steps * math.ceil(len(E.sample_specs(s)) / max(1, E.MAX_BATCH))
379
+ done = [0]
380
+
381
+ def report(i: int, n: int) -> None:
382
+ done[0] += 1
383
+ progress(min(done[0] / max(1, total), 1.0), desc="ohne Eingriff" if cached is None and done[0] <= total / renders
384
+ else "gebogen")
385
+
386
+ folder = run_dir()
387
+ if cached is None:
388
+ cached = shoot(key, folder, "plain", report)
389
+ _plain[key] = cached
390
+ while len(_plain) > PLAIN_CACHE:
391
+ _plain.popitem(last=False)
392
+ else:
393
+ _plain.move_to_end(key)
394
+ bent = shoot(s, folder, "bent", report) if live else None
395
+
396
+ server = server_part(prompt_a, prompt_b)
397
+ if bent is not None:
398
+ changes = [image_change(a, b) for a, b in zip(cached.images, bent.images)]
399
+ eff = M.effect(cached.acts, bent.acts)
400
+ eff.update(image=changes, thumb=file_url(bent.paths[0]), plain_thumb=file_url(cached.paths[0]),
401
+ rev=state["rev"])
402
+ server["effect"] = eff
403
+ seconds = bent.seconds + (cached.seconds if renders == 2 else 0.0)
404
+ lines = [f"{len(bent.paths)} Bilder gebogen in {E.fmt_num(seconds, 1)} s"
405
+ + ("." if renders == 2 else ", die Bilder ohne Eingriff kamen aus dem Speicher.")]
406
+ lines += notes + bent.warnings
407
+ lines.append("```\n" + "\n".join(recipe(u) for u in live) + "\n```")
408
+ else:
409
+ changes = []
410
+ server["effect"] = {"rev": state["rev"], "steps": 0, "blocks": {}, "latent": [], "impact": {},
411
+ "first": None, "image": [], "thumb": file_url(cached.paths[0]), "none": True}
412
+ lines = [f"{len(cached.paths)} Bilder ohne Eingriff"
413
+ + (f" in {E.fmt_num(cached.seconds, 1)} s." if renders else " aus dem Speicher.")]
414
+ lines += notes + cached.warnings
415
+ if uses:
416
+ lines.append("Die Werkzeuge stehen auf dem Wert, bei dem sie nichts ändern.")
417
+ return map_value(server), compare_html(cached, bent, changes), "\n\n".join(lines)
418
+
419
+
420
+ def show_tokens(prompt_a, prompt_b):
421
+ return map_value(server_part(prompt_a, prompt_b))
422
+
423
+
424
+ # ---------------------------------------------------------------- the app
425
+
426
+ INTRO = """# Biegen
427
+ Stable Diffusion 1.5 von innen. Wählt oben ein Werkzeug: Auf der Karte leuchtet auf, wo es im Netz eingreift.
428
+ Klickt auf die Karte, um den Ort zu wechseln, und zieht auf der Zeitleiste, wann es wirkt. Nach jedem Lauf zeigt
429
+ die Karte, wie stark sich jeder Block gegenüber dem Lauf ohne Eingriff verändert hat."""
430
+
431
+ LEGEND = """**So liest man die Karte.** Links wird der Text zu 77 Vektoren (Kontext). In der Mitte das UNet in seiner
432
+ U-Form: der Abwärtsweg verkleinert das Bild von 64 × 64 auf 8 × 8 Stellen, der Aufwärtsweg baut es wieder auf, die
433
+ Skip-Verbindungen tragen Einzelheiten quer hinüber. In jedem Block rechnen **Res** (Faltungen, hier hört das Netz
434
+ auch die Zeit), **Selbst** (jede Bildstelle schaut auf alle anderen) und **Quer** (jede Bildstelle schaut auf den
435
+ Kontext; nur hier kommt der Text ins Bild). Oben läuft die Schleife: das UNet sagt das Rauschen voraus, der Sampler
436
+ zieht es ab, nach dem letzten Schritt übersetzt der VAE-Decoder das Latent in Pixel.
437
+
438
+ **Was gemessen wird.** Jeder Lauf rechnet dieselben Seeds auch ohne Eingriff. Die Füllung eines Blocks zeigt, wie
439
+ stark sich sein Ausgang im ersten veränderten Schritt unterscheidet: Dort ist das Latent noch gleich, also ändern
440
+ sich nur der Ort des Eingriffs und alles danach. Die Linie im Block zeigt dieselbe Änderung über alle Schritte, die
441
+ Linie über der Zeitleiste die Änderung des Latents. Gemessen wird am ersten Bild, als relative Änderung."""
442
+
443
+
444
+ def biegen_app() -> gr.Blocks:
445
+ js = read("bendmap.js").replace("__CATALOG__", json.dumps(catalog(), ensure_ascii=False))
446
+ with gr.Blocks(title="Biegen") as demo:
447
+ gr.Markdown(INTRO, elem_id="intro")
448
+ with gr.Row():
449
+ prompt_a = gr.Textbox(PROMPT_A, label="Prompt A", max_lines=2, elem_id="prompt-a",
450
+ info="CLIP liest Englisch.")
451
+ prompt_b = gr.Textbox(PROMPT_B, label="Prompt B", max_lines=2, elem_id="prompt-b",
452
+ info="Nur für „Zweiter Prompt für die Oberfläche“.")
453
+ bendmap = gr.HTML(map_value(server_part(PROMPT_A, PROMPT_B), DEFAULT_STATE),
454
+ html_template='<div class="bm-host"></div>', js_on_load=js, apply_default_css=False,
455
+ elem_id="bendmap")
456
+ with gr.Row():
457
+ seed = gr.Number(value=42, precision=0, label="Seed", scale=1, min_width=120)
458
+ steps = free_slider(4, 50, value=E.DEFAULT_STEPS, step=1, label="Schritte", scale=2)
459
+ guidance = free_slider(1.0, 15.0, value=FAM.g_default, step=0.1, label="Guidance", scale=2)
460
+ grid = gr.Radio(GRID_CHOICES, value=GRID_DEFAULT, label="Raster", scale=3)
461
+ with gr.Column(scale=1, min_width=160):
462
+ go = gr.Button("Biegen", variant="primary", size="lg", elem_id="go")
463
+ status = gr.Markdown(elem_id="status")
464
+ result = gr.HTML(EMPTY_RESULT, js_on_load=read("compare.js"), apply_default_css=False, elem_id="result")
465
+ with gr.Accordion("So liest man die Karte", open=False):
466
+ gr.Markdown(LEGEND)
467
+
468
+ for box in (prompt_a, prompt_b):
469
+ box.change(show_tokens, [prompt_a, prompt_b], bendmap, queue=False, show_progress="hidden",
470
+ trigger_mode="always_last", api_visibility="private")
471
+ go.click(run, [prompt_a, prompt_b, seed, steps, guidance, grid, bendmap], [bendmap, result, status],
472
+ api_name="biegen", show_progress_on=[result])
473
+ return demo
474
+
475
+
476
+ def launch(**kwargs) -> gr.Blocks:
477
+ get_engine()
478
+ if S.SAFETY_FILTER:
479
+ S.classifier()
480
+ demo = biegen_app()
481
+ demo.queue(max_size=64)
482
+ demo.launch(theme=THEME, css=read("bendmap.css"), head=FREE_SLIDER_JS, allowed_paths=[OUT_DIR],
483
+ auth=("workshop", WORKSHOP_PASSWORD) if WORKSHOP_PASSWORD else None,
484
+ auth_message="Meldet euch mit dem Benutzernamen workshop an. Das Passwort steht an der Tafel.",
485
+ **kwargs)
486
+ return demo
487
+
488
+
489
+ if __name__ == "__main__":
490
+ launch()
bendmap.css ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .gradio-container { max-width: 1440px !important; font-size: 16px; }
2
+ #intro p { font-size: 1.05rem; max-width: 72rem; }
3
+
4
+ /* ---------------------------------------------------------------- the map */
5
+ .bm { --bm-ink: var(--body-text-color); --bm-soft: var(--body-text-color-subdued); --bm-line: var(--border-color-primary);
6
+ --bm-panel: var(--background-fill-secondary); --bm-card: var(--block-background-fill);
7
+ --bm-heat: #7048e8; display: flex; flex-direction: column; gap: 10px; color: var(--bm-ink); }
8
+ .bm-palette { display: flex; flex-wrap: wrap; gap: 8px 18px; align-items: flex-start; }
9
+ .bm-group { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
10
+ .bm-group-label { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--bm-soft);
11
+ margin-right: 2px; }
12
+ .bm-tile { display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 999px;
13
+ border: 1px solid var(--bm-line); background: var(--bm-card); color: var(--bm-ink); cursor: pointer;
14
+ font: inherit; font-size: 0.92rem; line-height: 1.2; }
15
+ .bm-tile:hover { border-color: var(--color-accent); box-shadow: 0 0 0 2px color-mix(in srgb, var(--color-accent) 25%, transparent); }
16
+ .bm-tile.bm-used { font-weight: 600; }
17
+ .bm-ico { font-size: 1.05rem; width: 1.2em; text-align: center; }
18
+ .bm-dot { width: 9px; height: 9px; border-radius: 50%; display: inline-block; }
19
+ .bm-pal-hint { flex-basis: 100%; font-size: 0.85rem; color: var(--bm-soft); }
20
+
21
+ .bm-stage { position: relative; border: 1px solid var(--bm-line); border-radius: 12px; background: var(--bm-panel);
22
+ padding: 6px; }
23
+ .bm-svg { width: 100%; height: auto; display: block; font-family: inherit; user-select: none; touch-action: pan-y; }
24
+ .bm-svg text { fill: var(--bm-ink); font-size: 13px; }
25
+ .bm-svg .bm-t { font-weight: 600; font-size: 13px; }
26
+ .bm-svg .bm-s { fill: var(--bm-soft); font-size: 11px; }
27
+ .bm-svg .bm-h { font-size: 15px; font-weight: 700; }
28
+ .bm-svg .bm-strong { font-weight: 700; fill: var(--bm-ink); }
29
+ .bm-svg .bm-val { fill: var(--bm-ink); font-weight: 600; }
30
+ .bm-node rect, .bm-block-bg { fill: var(--bm-card); stroke: var(--bm-line); stroke-width: 1.2; }
31
+ .bm-node, .bm-block, .bm-glyph, .bm-skip, .bm-chip-svg { cursor: pointer; }
32
+ .bm-node:hover rect, .bm-block:hover .bm-block-bg { stroke: var(--bm-soft); }
33
+ .bm-heatfill { fill: var(--bm-heat); pointer-events: none; }
34
+ .bm-glyph rect { stroke: var(--bm-line); stroke-width: 1; }
35
+ .bm-gR rect { fill: color-mix(in srgb, var(--bm-card) 80%, #868e96); }
36
+ .bm-gS rect { fill: color-mix(in srgb, var(--bm-card) 78%, #4dabf7); }
37
+ .bm-gX rect { fill: color-mix(in srgb, var(--bm-card) 78%, #f783ac); }
38
+ .bm-glyph text { font-size: 11px; font-weight: 600; }
39
+ .bm-glyph:hover rect { stroke: var(--bm-ink); }
40
+ .bm-stripe { fill: color-mix(in srgb, var(--bm-card) 70%, #868e96); stroke: none; }
41
+ .bm-chip-svg rect { fill: color-mix(in srgb, var(--bm-card) 85%, #f783ac); stroke: var(--bm-line); }
42
+ .bm-chip-svg.bm-special rect { fill: var(--bm-panel); stroke-dasharray: 3 2; }
43
+ .bm-chip-svg text { font-size: 11px; }
44
+ .bm-arrow { stroke: var(--bm-soft); stroke-width: 1.4; fill: none; }
45
+ .bm-headpath { fill: var(--bm-soft); }
46
+ .bm-after { stroke-dasharray: 5 4; }
47
+ .bm-skipline { stroke-dasharray: 2 3; }
48
+ .bm-hit { stroke: transparent; stroke-width: 14; }
49
+ .bm-skip:hover .bm-skipline { stroke: var(--bm-ink); }
50
+ .bm-thin rect { stroke-dasharray: 3 2; }
51
+ .bm-off { opacity: 0.35; }
52
+ .bm-hl { pointer-events: none; }
53
+ .bm-spark { fill: none; stroke: var(--bm-heat); stroke-width: 1.8; stroke-linejoin: round; }
54
+ .bm-latent { stroke-width: 2.2; }
55
+ .bm-base { stroke: var(--bm-line); stroke-width: 1; }
56
+ .bm-axis { stroke: var(--bm-soft); stroke-width: 1.2; }
57
+ .bm-base-lane { fill: var(--bm-line); }
58
+ .bm-band { cursor: grab; }
59
+ .bm-handle { fill: var(--bm-card); stroke-width: 2.5; cursor: ew-resize; }
60
+ .bm-hatch { fill: url(#bm-hatch); }
61
+ .bm-svg .bm-on-band { fill: #fff; font-size: 11px; font-weight: 700; paint-order: stroke; stroke: rgba(0,0,0,0.35); stroke-width: 2px; }
62
+ .bm-svg .bm-lane-sel { text-decoration: underline; }
63
+ .bm-stale { opacity: 0.45; }
64
+ .bm-tip { position: absolute; z-index: 20; max-width: 300px; padding: 7px 10px; border-radius: 8px; font-size: 0.85rem;
65
+ line-height: 1.35; white-space: pre-line; pointer-events: none; color: var(--bm-ink);
66
+ background: var(--bm-card); border: 1px solid var(--bm-line); box-shadow: 0 4px 14px rgba(0,0,0,0.15); }
67
+
68
+ /* ---------------------------------------------------------------- the slots */
69
+ .bm-slots { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
70
+ @media (max-width: 900px) { .bm-slots { grid-template-columns: 1fr; } }
71
+ .bm-card { --c: #868e96; border: 1px solid var(--bm-line); border-top: 5px solid var(--c); border-radius: 10px;
72
+ background: var(--bm-card); padding: 10px 12px; display: flex; flex-direction: column; gap: 7px; }
73
+ .bm-card.bm-sel { box-shadow: 0 0 0 2px var(--c); }
74
+ .bm-card.bm-empty { border-style: dashed; border-top-width: 1px; color: var(--bm-soft); flex-direction: row;
75
+ align-items: center; justify-content: center; min-height: 80px; font-size: 0.92rem; gap: 8px; }
76
+ .bm-card-head { display: flex; align-items: center; gap: 7px; }
77
+ .bm-card-head b { flex: 1; font-size: 1rem; }
78
+ .bm-badge { width: 22px; height: 22px; border-radius: 50%; background: var(--c); color: #fff; font-weight: 700;
79
+ display: inline-flex; align-items: center; justify-content: center; font-size: 0.85rem; flex: none; }
80
+ .bm-x { border: none; background: transparent; color: var(--bm-soft); cursor: pointer; font-size: 1rem; padding: 2px 6px; }
81
+ .bm-x:hover { color: var(--bm-ink); }
82
+ .bm-what { margin: 0; font-size: 0.88rem; line-height: 1.4; color: var(--bm-ink); }
83
+ .bm-places { display: flex; flex-wrap: wrap; gap: 5px; }
84
+ .bm-pchip { font: inherit; font-size: 0.82rem; padding: 4px 9px; border-radius: 999px; border: 1px dashed var(--c);
85
+ background: transparent; color: var(--bm-ink); cursor: pointer; }
86
+ .bm-pchip.bm-on { border-style: solid; background: color-mix(in srgb, var(--c) 18%, transparent); font-weight: 600; }
87
+ .bm-row { display: flex; align-items: center; gap: 8px; font-size: 0.88rem; flex-wrap: wrap; }
88
+ .bm-row input[type=text] { flex: 1; min-width: 6em; }
89
+ .bm-row input[type=text], .bm-row input[type=number] { font: inherit; padding: 4px 6px; border-radius: 6px;
90
+ border: 1px solid var(--bm-line); background: var(--input-background-fill); color: var(--bm-ink); }
91
+ .bm-row input[type=number] { width: 5.5em; }
92
+ .bm-knob span { min-width: 7em; }
93
+ .bm-knob input[type=range] { flex: 1; min-width: 6em; accent-color: var(--c); }
94
+ .bm-hint { font-size: 0.78rem; color: var(--bm-soft); }
95
+ .bm-foot { margin: 0; font-size: 0.75rem; color: var(--bm-soft); }
96
+
97
+ /* ---------------------------------------------------------------- results with a wipe */
98
+ .bc { display: flex; flex-direction: column; gap: 8px; }
99
+ .bc-empty { padding: 28px; text-align: center; color: var(--body-text-color-subdued);
100
+ border: 1px dashed var(--border-color-primary); border-radius: 12px; }
101
+ .bc-bar { display: flex; justify-content: space-between; align-items: center; gap: 12px; font-size: 0.9rem;
102
+ color: var(--body-text-color-subdued); }
103
+ .bc-toggle { font: inherit; font-size: 0.85rem; padding: 5px 12px; border-radius: 999px; cursor: pointer;
104
+ border: 1px solid var(--border-color-primary); background: var(--block-background-fill);
105
+ color: var(--body-text-color); }
106
+ .bc-toggle.bc-on { background: var(--color-accent); color: #fff; border-color: var(--color-accent); }
107
+ .bc-grid { display: grid; gap: 8px; max-width: 980px; margin: 0 auto; width: 100%; }
108
+ .bc-card { margin: 0; display: flex; flex-direction: column; gap: 4px; }
109
+ .bc-card img { width: 100%; display: block; border-radius: 8px; }
110
+ .bc-frame { position: relative; --cut: 0%; cursor: ew-resize; touch-action: pan-y; }
111
+ .bc-plain { position: absolute; inset: 0; clip-path: inset(0 calc(100% - var(--cut)) 0 0); }
112
+ .bc-line { position: absolute; top: 0; bottom: 0; left: var(--cut); width: 2px; background: #fff;
113
+ box-shadow: 0 0 0 1px rgba(0,0,0,0.35); opacity: 0; pointer-events: none; }
114
+ .bc-frame.bc-wiping .bc-line { opacity: 1; }
115
+ .bc-tag { position: absolute; top: 6px; font-size: 0.72rem; font-weight: 700; padding: 2px 7px; border-radius: 999px;
116
+ background: rgba(0,0,0,0.55); color: #fff; opacity: 0; transition: opacity 0.15s; pointer-events: none; }
117
+ .bc-tag-plain { left: 6px; }
118
+ .bc-tag-bent { right: 6px; }
119
+ .bc-frame.bc-wiping .bc-tag { opacity: 1; }
120
+ .bc-card figcaption { font-size: 0.82rem; color: var(--body-text-color-subdued); display: flex;
121
+ justify-content: space-between; }
122
+ #go { min-height: 64px; font-size: 1.15rem; margin-top: 18px; }
bendmap.js ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The map of Stable Diffusion 1.5 and the tool slots. Runs as js_on_load of a gr.HTML component:
2
+ // `element`, `props` and `watch` come from Gradio. app.py replaces __CATALOG__ with the tools.
3
+ //
4
+ // props.value is JSON. This script owns {"state": {slots, rev}}; Python sends {"server": {...}} with
5
+ // the prompt's tokens and, after a run, the measured effect. Python never sends state back, so a
6
+ // change made while a run is going is kept.
7
+
8
+ const CAT = __CATALOG__;
9
+ const TOOLS = Object.fromEntries(CAT.tools.map((t) => [t.key, t]));
10
+ const COLORS = CAT.colors;
11
+ const W = 1200, H = 800, BW = 150, BH = 96;
12
+ const X0 = 336, X1 = 1016; // the UNet's width = the timeline's 0 .. 100 %
13
+ const TL_AXIS = 696, TL_LANE = 712, LANE_H = 18, LANE_GAP = 28;
14
+
15
+ const BLK = {};
16
+ ["d0", "d1", "d2", "d3"].forEach((b, i) => { BLK[b] = { x: 336 + 52 * i, y: 78 + 116 * i }; });
17
+ BLK.mid = { x: 601, y: 542 };
18
+ ["u0", "u1", "u2", "u3"].forEach((b, j) => { BLK[b] = { x: 866 - 52 * (3 - j), y: 78 + 116 * (3 - j) }; });
19
+ const META = {
20
+ d0: { label: "Abwärts 1", res: "64 × 64", ch: 320, R: 2, A: 2 },
21
+ d1: { label: "Abwärts 2", res: "32 × 32", ch: 640, R: 2, A: 2 },
22
+ d2: { label: "Abwärts 3", res: "16 × 16", ch: 1280, R: 2, A: 2 },
23
+ d3: { label: "Abwärts 4", res: "8 × 8", ch: 1280, R: 2, A: 0 },
24
+ mid: { label: "Mitte", res: "8 × 8", ch: 1280, R: 2, A: 1 },
25
+ u0: { label: "Aufwärts 1", res: "8 × 8", ch: 1280, R: 3, A: 0 },
26
+ u1: { label: "Aufwärts 2", res: "16 × 16", ch: 1280, R: 3, A: 3 },
27
+ u2: { label: "Aufwärts 3", res: "32 × 32", ch: 640, R: 3, A: 3 },
28
+ u3: { label: "Aufwärts 4", res: "64 × 64", ch: 320, R: 3, A: 3 },
29
+ };
30
+ const BLOCKS = Object.keys(META);
31
+ const SKIP_FROM = { u0: "d3", u1: "d2", u2: "d1", u3: "d0" };
32
+ const GLYPH = {
33
+ R: { dx: 6, w: 34, text: "Res" },
34
+ S: { dx: 44, w: 48, text: "Selbst" },
35
+ X: { dx: 96, w: 46, text: "Quer" },
36
+ };
37
+ const BOX = { // fixed boxes outside the UNet
38
+ prompt: { x: 16, y: 54, w: 280, h: 40 },
39
+ tok: { x: 16, y: 118, w: 132, h: 34 },
40
+ pos: { x: 164, y: 118, w: 132, h: 34 },
41
+ clip: { x: 16, y: 176, w: 280, h: 46 },
42
+ ctx: { x: 16, y: 246, w: 280, h: 150 },
43
+ promptB: { x: 16, y: 440, w: 280, h: 36 },
44
+ clipB: { x: 16, y: 488, w: 280, h: 24 },
45
+ ctxB: { x: 16, y: 524, w: 280, h: 40 },
46
+ latent: { x: 336, y: 14, w: 150, h: 42 },
47
+ sampler: { x: 601, y: 14, w: 150, h: 42 },
48
+ eps: { x: 866, y: 14, w: 150, h: 42 },
49
+ vae: { x: 1036, y: 118, w: 150, h: 52 },
50
+ image: { x: 1036, y: 192, w: 150, h: 150 },
51
+ };
52
+ const TIPS = {
53
+ R: "Res: Faltungsschichten, die das Bild an jeder Stelle umrechnen. Hier hört das Netz auch die Zeit, also wie verrauscht das Bild noch ist.",
54
+ S: "Selbst-Aufmerksamkeit: jede Bildstelle schaut auf alle anderen Bildstellen und holt sich, was zu ihr passt.",
55
+ X: "Quer-Aufmerksamkeit: jede Bildstelle schaut auf die 77 Vektoren des Kontexts. Nur hier kommt der Text ins Bild.",
56
+ out: "Der Ausgang des Blocks, der an den nächsten Block weitergeht.",
57
+ prompt: "Prompt A, so wie ihr ihn oben eingebt.",
58
+ tok: "Wort-Tabelle: jedes Token wird zu einem Vektor mit 768 Zahlen.",
59
+ pos: "Positions-Tabelle: ein Vektor pro Platz 0 bis 76. Er sagt CLIP, an welcher Stelle ein Token steht.",
60
+ clip: "CLIP-Textencoder: 12 Transformer-Schichten mischen die Token-Vektoren miteinander.",
61
+ ctx: "Kontext: 77 Vektoren, einer pro Platz. Nach dem Prompt folgen das Ende-Token und Polster, die CLIP mit dem Sinn des ganzen Prompts füllt.",
62
+ promptB: "Prompt B wird genauso zu 77 Vektoren und ersetzt in einzelnen Blöcken den Kontext von Prompt A.",
63
+ latent: "Das Latent x_t: 4 Kanäle auf 64 × 64 Stellen. Es beginnt als Rauschen aus dem Seed, jeder Sampler-Schritt nimmt Rauschen weg.",
64
+ sampler: "Sampler-Schritt (Euler): zieht das vorhergesagte Rauschen ein Stück weit vom Latent ab. Das wiederholt sich für jeden Schritt.",
65
+ eps: "Das UNet sagt das Rauschen im Latent voraus, einmal mit und einmal ohne Prompt. Guidance verstärkt den Unterschied.",
66
+ vae: "VAE-Decoder: übersetzt das fertige Latent (64 × 64) in Pixel (512 × 512). Er läuft einmal, nach dem letzten Schritt.",
67
+ image: "Das erste Bild des letzten Laufs.",
68
+ };
69
+
70
+ let st = { slots: [], sel: 0, rev: 0 };
71
+ let srv = { prompt: "", prompt_b: "", tokens: [], tokens_b: [], max_len: 77, effect: null };
72
+ let hoverTool = null, hoverSlot = null, drag = null, chipBoxes = {}, root = null;
73
+
74
+ // ---------------------------------------------------------------- state
75
+
76
+ function parse(v) {
77
+ if (!v) return {};
78
+ if (typeof v !== "string") return v;
79
+ try { return JSON.parse(v); } catch (e) { return {}; }
80
+ }
81
+
82
+ function cleanSlots(slots) {
83
+ return (Array.isArray(slots) ? slots : []).filter((s) => s && TOOLS[s.tool]).slice(0, CAT.max_slots);
84
+ }
85
+
86
+ function absorb(v, initial) {
87
+ const d = parse(v);
88
+ if (d.server) Object.assign(srv, d.server);
89
+ if (d.state && initial) {
90
+ st.slots = cleanSlots(d.state.slots);
91
+ st.rev = Number.isInteger(d.state.rev) ? d.state.rev : 0;
92
+ }
93
+ }
94
+
95
+ function publish(changed) {
96
+ if (changed) st.rev += 1;
97
+ props.value = JSON.stringify({ state: { slots: st.slots, rev: st.rev } });
98
+ if (root) root.dataset.rev = st.rev;
99
+ }
100
+
101
+ function placeOf(slot) {
102
+ const t = TOOLS[slot.tool];
103
+ return t.places.find((p) => p.value === slot.place) || t.places[0];
104
+ }
105
+
106
+ function guessWord(prompt) {
107
+ const words = (prompt || "").toLowerCase().match(/[a-zäöüß]+/g) || [];
108
+ const of = words.findIndex((w, i) => w === "of" && ["a", "an", "the"].includes(words[i + 1]));
109
+ if (of >= 0 && words[of + 2]) return words[of + 2];
110
+ const at = words.findIndex((w) => ["in", "on", "with", "at", "under"].includes(w));
111
+ if (at > 0) return words[at - 1];
112
+ return words[words.length - 1] || "";
113
+ }
114
+
115
+ function newSlot(key) {
116
+ const t = TOOLS[key], p = t.places[0];
117
+ return { tool: key, place: p.value, value: p.default, start: p.start, end: p.end,
118
+ word: key === "excise" ? guessWord(srv.prompt) : "" };
119
+ }
120
+
121
+ function addTool(key) {
122
+ if (st.slots.length < CAT.max_slots) {
123
+ st.slots.push(newSlot(key));
124
+ st.sel = st.slots.length - 1;
125
+ } else {
126
+ const i = Math.min(st.sel, st.slots.length - 1);
127
+ st.slots[i] = newSlot(key);
128
+ st.sel = i;
129
+ }
130
+ publish(true);
131
+ renderAll();
132
+ }
133
+
134
+ function setPlace(i, value) {
135
+ const s = st.slots[i], t = TOOLS[s.tool];
136
+ const p = t.places.find((q) => q.value === value);
137
+ if (!p || s.place === value) return;
138
+ Object.assign(s, { place: p.value, value: p.default, start: p.start, end: p.end });
139
+ publish(true);
140
+ renderAll();
141
+ }
142
+
143
+ function removeSlot(i) {
144
+ st.slots.splice(i, 1);
145
+ st.sel = Math.max(0, Math.min(st.sel, st.slots.length - 1));
146
+ hoverSlot = null;
147
+ publish(true);
148
+ renderAll();
149
+ }
150
+
151
+ function siteClick(site) {
152
+ const s = st.slots[st.sel];
153
+ if (!s) return;
154
+ const t = TOOLS[s.tool];
155
+ const hits = t.places.filter((p) => p.sites.includes(site));
156
+ if (!hits.length) {
157
+ const owner = st.slots.findIndex((q) => placeOf(q).sites.includes(site));
158
+ if (owner >= 0 && owner !== st.sel) { st.sel = owner; renderAll(); }
159
+ return;
160
+ }
161
+ const k = hits.findIndex((p) => p.value === s.place);
162
+ setPlace(st.sel, hits[(k + 1) % hits.length].value);
163
+ }
164
+
165
+ // ---------------------------------------------------------------- helpers
166
+
167
+ const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
168
+ const tx = (pct) => X0 + (X1 - X0) * Math.min(Math.max(pct, 0), 100) / 100;
169
+ const num = (x) => (Math.round(x * 1000) / 1000).toString().replace(".", ",");
170
+
171
+ function pct(v) {
172
+ if (!(v > 0)) return "0 %";
173
+ if (v < 0.01) return "<1 %";
174
+ if (v > 9.99) return ">999 %";
175
+ return Math.round(v * 100) + " %";
176
+ }
177
+
178
+ function glyphBox(b, k) {
179
+ const g = GLYPH[k], p = BLK[b];
180
+ return { x: p.x + g.dx, y: p.y + 23, w: g.w, h: 20 };
181
+ }
182
+
183
+ function wordChips(word) {
184
+ const target = (word || "").toLowerCase().replace(/\s+/g, "");
185
+ const toks = srv.tokens || [];
186
+ const hit = [];
187
+ if (!target) return hit;
188
+ for (let k = 0; k < toks.length; k++) {
189
+ let acc = "";
190
+ for (let j = k; j < toks.length && acc.length < target.length; j++) {
191
+ acc += toks[j].toLowerCase();
192
+ if (acc === target) { for (let m = k; m <= j; m++) hit.push(m); break; }
193
+ }
194
+ }
195
+ return hit;
196
+ }
197
+
198
+ // Box (or line) to draw a site's highlight around. Word and padding chips depend on the slot.
199
+ function siteShapes(site, slot) {
200
+ if (BOX[site]) return [BOX[site]];
201
+ if (site === "ctx_word") return wordChips(slot && slot.word).map((k) => chipBoxes["t" + k]).filter(Boolean);
202
+ if (site === "ctx_pad") return [chipBoxes.end, chipBoxes.pad].filter(Boolean);
203
+ if (site.startsWith("skip.")) {
204
+ const u = site.slice(5), d = SKIP_FROM[u];
205
+ const y = BLK[d].y + 46;
206
+ return [{ line: true, x1: BLK[d].x + BW, x2: BLK[u].x, y }];
207
+ }
208
+ const [b, k] = site.split(".");
209
+ if (!BLK[b]) return [];
210
+ if (k === "out") return [{ x: BLK[b].x, y: BLK[b].y, w: BW, h: BH }];
211
+ if ((k === "S" || k === "X") && META[b].A === 0) return [];
212
+ return [glyphBox(b, k)];
213
+ }
214
+
215
+ function ring(shape, color, layer, style) {
216
+ const o = 3 + 4 * layer;
217
+ if (shape.line) {
218
+ const y = shape.y + (layer % 2 ? 1 : -1) * Math.ceil(layer / 2) * 5;
219
+ return `<line x1="${shape.x1}" y1="${y}" x2="${shape.x2 - 8}" y2="${y}" stroke="${color}" stroke-width="${style === "dash" ? 3 : 5}"
220
+ ${style === "dash" ? 'stroke-dasharray="6 5"' : ""} marker-end="url(#bm-arrow-${color.slice(1)})" class="bm-hl"/>`;
221
+ }
222
+ const fill = style === "solid" && layer === 0 ? `fill="${color}" fill-opacity="0.16"` : 'fill="none"';
223
+ return `<rect x="${shape.x - o}" y="${shape.y - o}" width="${shape.w + 2 * o}" height="${shape.h + 2 * o}" rx="${6 + o}"
224
+ stroke="${color}" stroke-width="${style === "dash" ? 2 : 3}" ${style === "dash" ? 'stroke-dasharray="5 4"' : ""} ${fill} class="bm-hl"/>`;
225
+ }
226
+
227
+ function slotsAt(site) {
228
+ return st.slots.map((s, i) => [s, i]).filter(([s]) => placeOf(s).sites.includes(site));
229
+ }
230
+
231
+ function tipFor(base, site) {
232
+ const who = slotsAt(site).map(([s, i]) => `${i + 1} ${TOOLS[s.tool].label}`);
233
+ return esc(base + (who.length ? "\nHier greift ein: " + who.join(", ") : ""));
234
+ }
235
+
236
+ // ---------------------------------------------------------------- the map
237
+
238
+ function box(b, cls, label, sub, site, tip) {
239
+ return `<g class="bm-node ${cls}" data-site="${site}" data-tip="${tipFor(tip, site)}">
240
+ <rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="8"/>
241
+ <text x="${b.x + 10}" y="${b.y + (sub ? 17 : b.h / 2 + 5)}" class="bm-t">${esc(label)}</text>
242
+ ${sub ? `<text x="${b.x + 10}" y="${b.y + 33}" class="bm-s">${esc(sub)}</text>` : ""}</g>`;
243
+ }
244
+
245
+ function arrow(x1, y1, x2, y2, cls = "") {
246
+ return `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" class="bm-arrow ${cls}" marker-end="url(#bm-head)"/>`;
247
+ }
248
+
249
+ function chips(tokens, b, maxRows, withPad, fixedSite) {
250
+ const out = [], toks = tokens || [];
251
+ const items = [["start", "‹Start›"]].concat(toks.map((t, k) => ["t" + k, t.length > 12 ? t.slice(0, 11) + "…" : t]));
252
+ if (withPad) {
253
+ items.push(["end", "‹Ende›"]);
254
+ const pad = Math.max(0, (srv.max_len || 77) - 2 - toks.length);
255
+ if (pad) items.push(["pad", `‹Polster × ${pad}›`]);
256
+ }
257
+ let x = b.x + 8, y = b.y + 26, row = 0;
258
+ const boxes = {};
259
+ for (let n = 0; n < items.length; n++) {
260
+ const [id, text] = items[n];
261
+ const w = 10 + 6.1 * text.length;
262
+ if (x + w > b.x + b.w - 8) {
263
+ row += 1; x = b.x + 8; y += 23;
264
+ if (row >= maxRows) { out.push(`<text x="${x}" y="${y + 13}" class="bm-s">… und ${items.length - n} weitere</text>`); break; }
265
+ }
266
+ const special = id === "start" || id === "end" || id === "pad";
267
+ const site = fixedSite || (id === "end" || id === "pad" ? "ctx_pad" : id === "start" ? "ctx" : "ctx_word");
268
+ out.push(`<g class="bm-chip-svg ${special ? "bm-special" : ""}" data-site="${site}">
269
+ <rect x="${x}" y="${y}" width="${w}" height="19" rx="9"/><text x="${x + w / 2}" y="${y + 13.5}" text-anchor="middle">${esc(text)}</text></g>`);
270
+ boxes[id] = { x, y, w, h: 19 };
271
+ x += w + 4;
272
+ }
273
+ return [out.join(""), boxes];
274
+ }
275
+
276
+ function textLane() {
277
+ const usesB = st.slots.some((s) => s.tool === "layered");
278
+ const p = srv.prompt || "";
279
+ const short = p.length > 40 ? p.slice(0, 39) + "…" : p;
280
+ const [ctxChips, boxes] = chips(srv.tokens, BOX.ctx, 5, true);
281
+ chipBoxes = boxes;
282
+ const stripes = Array.from({ length: 12 }, (_, k) =>
283
+ `<rect x="${BOX.clip.x + 150 + k * 10}" y="${BOX.clip.y + 10}" width="6" height="26" rx="2" class="bm-stripe"/>`).join("");
284
+ const pb = srv.prompt_b || "";
285
+ const [bChips] = chips(srv.tokens_b, { ...BOX.ctxB, y: BOX.ctxB.y - 18 }, 1, false, "promptB");
286
+ return `
287
+ <text x="16" y="34" class="bm-h">Text</text>
288
+ ${box(BOX.prompt, "", "Prompt A", short, "prompt", TIPS.prompt)}
289
+ ${arrow(82, 94, 82, 116)} ${arrow(230, 94, 230, 116)}
290
+ ${box(BOX.tok, "", "Wort-Tabelle", "", "tok", TIPS.tok)}
291
+ ${box(BOX.pos, "", "Positionen", "", "pos", TIPS.pos)}
292
+ <text x="156" y="140" class="bm-t" text-anchor="middle">+</text>
293
+ ${arrow(156, 152, 156, 174)}
294
+ <g class="bm-node" data-site="clip" data-tip="${tipFor(TIPS.clip, "clip")}">
295
+ <rect x="${BOX.clip.x}" y="${BOX.clip.y}" width="${BOX.clip.w}" height="${BOX.clip.h}" rx="8"/>
296
+ <text x="${BOX.clip.x + 10}" y="${BOX.clip.y + 20}" class="bm-t">CLIP</text>
297
+ <text x="${BOX.clip.x + 10}" y="${BOX.clip.y + 36}" class="bm-s">12 Schichten</text>${stripes}</g>
298
+ ${arrow(156, 222, 156, 244)}
299
+ <g class="bm-node" data-site="ctx" data-tip="${tipFor(TIPS.ctx, "ctx")}">
300
+ <rect x="${BOX.ctx.x}" y="${BOX.ctx.y}" width="${BOX.ctx.w}" height="${BOX.ctx.h}" rx="8"/>
301
+ <text x="${BOX.ctx.x + 10}" y="${BOX.ctx.y + 17}" class="bm-t">Kontext · 77 Vektoren</text></g>
302
+ ${ctxChips}
303
+ <path d="M 296 330 C 316 330, 312 300, 330 300" class="bm-arrow bm-text-flow" marker-end="url(#bm-head)"/>
304
+ <text x="16" y="414" class="bm-s">Der Kontext geht in jede <tspan class="bm-strong">Quer</tspan>-Aufmerksamkeit.</text>
305
+ <g class="${usesB ? "" : "bm-off"}">
306
+ <text x="16" y="432" class="bm-s">Prompt B (nur für „Zweiter Prompt“)</text>
307
+ ${box(BOX.promptB, "", "Prompt B", pb.length > 40 ? pb.slice(0, 39) + "…" : pb, "promptB", TIPS.promptB)}
308
+ ${box(BOX.clipB, "bm-thin", "CLIP", "", "promptB", TIPS.promptB)}
309
+ ${bChips}
310
+ </g>`;
311
+ }
312
+
313
+ function heat(b) {
314
+ const e = srv.effect;
315
+ if (!e || e.none || !e.steps || !e.impact) return "";
316
+ const top = Math.max(1e-6, ...BLOCKS.map((k) => e.impact[k] || 0));
317
+ const a = 0.55 * (e.impact[b] || 0) / top * (e.rev !== st.rev ? 0.4 : 1);
318
+ return `<rect x="${BLK[b].x}" y="${BLK[b].y}" width="${BW}" height="${BH}" rx="10" class="bm-heatfill" fill-opacity="${a.toFixed(3)}"/>`;
319
+ }
320
+
321
+ function unetBlock(b) {
322
+ const p = BLK[b], m = META[b];
323
+ const glyphs = (m.A ? ["R", "S", "X"] : ["R"]).map((k) => {
324
+ const g = glyphBox(b, k), site = `${b}.${k}`;
325
+ const count = k === "R" ? m.R : m.A;
326
+ return `<g class="bm-glyph bm-g${k}" data-site="${site}" data-tip="${tipFor(`${m.label} · ${TIPS[k]} (${count} ×)`, site)}">
327
+ <rect x="${g.x}" y="${g.y}" width="${g.w}" height="${g.h}" rx="5"/>
328
+ <text x="${g.x + g.w / 2}" y="${g.y + 14}" text-anchor="middle">${GLYPH[k].text}</text></g>`;
329
+ }).join("");
330
+ const none = m.A ? "" : `<text x="${p.x + 48}" y="${p.y + 37}" class="bm-s">nur Faltungen</text>`;
331
+ return `<g class="bm-block" data-site="${b}.out" data-tip="${tipFor(`${m.label} · ${m.res} Stellen · ${m.ch} Kanäle. ${TIPS.out}`, `${b}.out`)}">
332
+ <rect x="${p.x}" y="${p.y}" width="${BW}" height="${BH}" rx="10" class="bm-block-bg"/>
333
+ ${heat(b)}
334
+ <text x="${p.x + 8}" y="${p.y + 17}" class="bm-t">${m.label}</text>
335
+ <text x="${p.x + BW - 8}" y="${p.y + 17}" class="bm-s" text-anchor="end">${m.res}</text></g>
336
+ ${glyphs}${none}`;
337
+ }
338
+
339
+ function unet() {
340
+ const parts = [];
341
+ // skips first, so blocks sit on top
342
+ for (const [u, d] of Object.entries(SKIP_FROM)) {
343
+ const y = BLK[d].y + 46, x1 = BLK[d].x + BW, x2 = BLK[u].x;
344
+ parts.push(`<g class="bm-skip" data-site="skip.${u}" data-tip="${tipFor(`Skip-Verbindung: trägt die Merkmale aus ${META[d].label} direkt zu ${META[u].label}.`, `skip.${u}`)}">
345
+ <line x1="${x1}" y1="${y}" x2="${x2}" y2="${y}" class="bm-hit"/>
346
+ <line x1="${x1}" y1="${y}" x2="${x2 - 4}" y2="${y}" class="bm-arrow bm-skipline" marker-end="url(#bm-head)"/>
347
+ <text x="${(x1 + x2) / 2}" y="${y - 5}" text-anchor="middle" class="bm-s">Skip</text></g>`);
348
+ }
349
+ ["d0", "d1", "d2"].forEach((b, i) => {
350
+ const p = BLK[b], q = BLK[["d1", "d2", "d3"][i]];
351
+ parts.push(arrow(p.x + 75, p.y + BH, q.x + 75, q.y - 2));
352
+ });
353
+ parts.push(arrow(BLK.d3.x + 75, BLK.d3.y + BH, BLK.mid.x + 30, BLK.mid.y - 2));
354
+ parts.push(arrow(BLK.mid.x + BW - 30, BLK.mid.y, BLK.u0.x + 75, BLK.u0.y + BH + 2));
355
+ ["u0", "u1", "u2"].forEach((b, i) => {
356
+ const p = BLK[b], q = BLK[["u1", "u2", "u3"][i]];
357
+ parts.push(arrow(p.x + 75, p.y, q.x + 75, q.y + BH + 2));
358
+ });
359
+ BLOCKS.forEach((b) => parts.push(unetBlock(b)));
360
+ // the loop
361
+ parts.push(box(BOX.latent, "", "Latent x_t", "Start: Rauschen (Seed)", "latent", TIPS.latent));
362
+ parts.push(box(BOX.sampler, "", "Sampler-Schritt", "× Schritte", "sampler", TIPS.sampler));
363
+ parts.push(box(BOX.eps, "", "Rausch-Vorhersage", "mit und ohne Prompt", "eps", TIPS.eps));
364
+ parts.push(arrow(BLK.d0.x + 75, BOX.latent.y + BOX.latent.h, BLK.d0.x + 75, BLK.d0.y - 2));
365
+ parts.push(arrow(BLK.u3.x + 75, BLK.u3.y, BLK.u3.x + 75, BOX.eps.y + BOX.eps.h + 2));
366
+ parts.push(arrow(BOX.eps.x, 35, BOX.sampler.x + BOX.sampler.w + 2, 35));
367
+ parts.push(arrow(BOX.sampler.x, 35, BOX.latent.x + BOX.latent.w + 2, 35));
368
+ parts.push(`<text x="${X0 + 340}" y="${BOX.latent.y + BOX.latent.h + 16}" text-anchor="middle" class="bm-s">UNet · einmal pro Schritt</text>`);
369
+ // after the loop
370
+ parts.push(`<path d="M ${BOX.sampler.x + 75} ${BOX.sampler.y} L ${BOX.sampler.x + 75} 6 L 1100 6 L 1100 ${BOX.vae.y - 2}" class="bm-arrow bm-after" marker-end="url(#bm-head)"/>`);
371
+ parts.push(`<text x="1106" y="62" class="bm-s">nach dem</text><text x="1106" y="76" class="bm-s">letzten Schritt</text>`);
372
+ parts.push(box(BOX.vae, "", "VAE-Decoder", "Latent → Pixel", "vae", TIPS.vae));
373
+ parts.push(arrow(1111, BOX.vae.y + BOX.vae.h, 1111, BOX.image.y - 2));
374
+ return parts.join("");
375
+ }
376
+
377
+ function imageNode() {
378
+ const e = srv.effect, b = BOX.image;
379
+ const inner = e && e.thumb
380
+ ? `<image href="${esc(e.thumb)}" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" preserveAspectRatio="xMidYMid slice" clip-path="url(#bm-img-clip)"/>`
381
+ : `<text x="${b.x + b.w / 2}" y="${b.y + b.h / 2 + 5}" text-anchor="middle" class="bm-s">Bild</text>`;
382
+ return `<g class="bm-node" data-site="image" data-tip="${esc(TIPS.image)}">
383
+ <clipPath id="bm-img-clip"><rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="8"/></clipPath>
384
+ <rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="8"/>${inner}</g>`;
385
+ }
386
+
387
+ function effectLayer() {
388
+ const e = srv.effect;
389
+ if (!e || e.none || !e.steps) {
390
+ const lines = e && e.none ? ["Letzter Lauf ohne Eingriff:", "nichts zu messen."]
391
+ : ["Nach dem ersten Lauf steht", "hier, wie stark sich jeder", "Block verändert hat."];
392
+ return lines.map((l, k) => `<text x="1036" y="${372 + 16 * k}" class="bm-s">${esc(l)}</text>`).join("");
393
+ }
394
+ const stale = e.rev !== st.rev;
395
+ const N = e.steps, parts = [];
396
+ const all = BLOCKS.flatMap((b) => e.blocks[b] || []);
397
+ const top = Math.max(1e-6, ...all);
398
+ for (const b of BLOCKS) {
399
+ const v = e.blocks[b] || [], p = BLK[b];
400
+ if (!v.length) continue;
401
+ const pts = v.map((y, i) => `${(p.x + 8 + 134 * (i + 0.5) / N).toFixed(1)},${(p.y + 89 - 20 * Math.min(1, y / top)).toFixed(1)}`).join(" ");
402
+ parts.push(`<line x1="${p.x + 8}" y1="${p.y + 89}" x2="${p.x + 142}" y2="${p.y + 89}" class="bm-base"/>`);
403
+ parts.push(`<polyline points="${pts}" class="bm-spark" pointer-events="none"/>`);
404
+ parts.push(`<text x="${p.x + 8}" y="${p.y + 66}" class="bm-s">Änderung</text>`);
405
+ parts.push(`<text x="${p.x + BW - 8}" y="${p.y + 66}" text-anchor="end" class="bm-s bm-val">bis ${pct(Math.max(...v))}</text>`);
406
+ }
407
+ // latent curve over the timeline
408
+ const lat = e.latent || [];
409
+ if (lat.length) {
410
+ const ltop = Math.max(1e-6, ...lat);
411
+ const pts = lat.map((y, i) => `${tx(100 * (i + 1) / N).toFixed(1)},${(684 - 30 * Math.min(1, y / ltop)).toFixed(1)}`).join(" ");
412
+ parts.push(`<polyline points="${tx(0)},684 ${pts}" class="bm-spark bm-latent" pointer-events="none"/>`);
413
+ parts.push(`<text x="${X1 + 6}" y="${684 - 30 * Math.min(1, lat[lat.length - 1] / ltop) + 4}" class="bm-s bm-val">${pct(lat[lat.length - 1])}</text>`);
414
+ }
415
+ const img = e.image || [];
416
+ const meanImg = img.length ? img.reduce((a, b) => a + b, 0) / img.length : 0;
417
+ const first = e.first === null || e.first === undefined ? "–" : `Schritt ${e.first + 1} von ${N}`;
418
+ parts.push(`<g class="bm-caption">
419
+ <text x="1036" y="364" class="bm-t">Gemessen${stale ? " (voriger Eingriff)" : ""}</text>
420
+ <text x="1036" y="382" class="bm-s">Bild: ${pct(meanImg)} anders</text>
421
+ <text x="1036" y="398" class="bm-s">Füllung: erster veränderter</text>
422
+ <text x="1036" y="412" class="bm-s">Schritt (${first})</text>
423
+ <text x="1036" y="428" class="bm-s">Linie: alle Schritte</text></g>`);
424
+ return `<g class="bm-effect ${stale ? "bm-stale" : ""}">${parts.join("")}</g>`;
425
+ }
426
+
427
+ function timeline() {
428
+ const parts = [];
429
+ parts.push(`<text x="16" y="${TL_AXIS + 4}" class="bm-h">Zeit</text>`);
430
+ parts.push(`<text x="16" y="670" class="bm-s">Latent: Abstand zum Lauf ohne Eingriff</text>`);
431
+ parts.push(`<line x1="${X0}" y1="684" x2="${X1}" y2="684" class="bm-base"/>`);
432
+ parts.push(`<line x1="${X0}" y1="${TL_AXIS}" x2="${X1}" y2="${TL_AXIS}" class="bm-axis"/>`);
433
+ for (const p of [0, 25, 50, 75, 100]) {
434
+ parts.push(`<line x1="${tx(p)}" y1="${TL_AXIS - 3}" x2="${tx(p)}" y2="${TL_AXIS + 3}" class="bm-axis"/>`);
435
+ parts.push(`<text x="${tx(p)}" y="${TL_AXIS + 15}" text-anchor="middle" class="bm-s bm-tick">${p} %</text>`);
436
+ }
437
+ parts.push(`<text x="${X0 - 8}" y="${TL_AXIS + 4}" text-anchor="end" class="bm-s">Rauschen</text>`);
438
+ parts.push(`<text x="${X1 + 8}" y="${TL_AXIS + 4}" class="bm-s">Bild</text>`);
439
+ st.slots.forEach((s, i) => {
440
+ const t = TOOLS[s.tool], c = COLORS[i], y = TL_LANE + 8 + LANE_GAP * i;
441
+ const sel = i === st.sel ? "bm-lane-sel" : "";
442
+ parts.push(`<text x="24" y="${y + 13}" class="bm-t bm-lane-label ${sel}" style="fill:${c}">${i + 1} ${esc(t.label)}</text>`);
443
+ if (t.after_loop) {
444
+ parts.push(`<rect x="${BOX.vae.x}" y="${y}" width="${BOX.vae.w}" height="${LANE_H}" rx="5" fill="${c}" fill-opacity="0.85"/>`);
445
+ parts.push(`<text x="${BOX.vae.x + 8}" y="${y + 13}" class="bm-on-band">nach der Schleife</text>`);
446
+ return;
447
+ }
448
+ if (t.time_knob) {
449
+ const a = tx(s.value);
450
+ parts.push(`<rect x="${a}" y="${y}" width="${Math.max(0, X1 - a)}" height="${LANE_H}" rx="5" fill="${c}" fill-opacity="0.85" data-handle="${i}:knob" class="bm-band"/>`);
451
+ parts.push(`<rect x="${a - 5}" y="${y - 3}" width="10" height="${LANE_H + 6}" rx="3" class="bm-handle" style="stroke:${c}" data-handle="${i}:knob" data-tip="${esc(t.knob + ": ziehen")}"/>`);
452
+ parts.push(`<text x="${Math.min(a + 8, X1 - 60)}" y="${y + 13}" class="bm-on-band" pointer-events="none">ab ${num(s.value)} %</text>`);
453
+ return;
454
+ }
455
+ if (!t.window) {
456
+ parts.push(`<rect x="${X0}" y="${y}" width="${X1 - X0}" height="${LANE_H}" rx="5" fill="${c}" fill-opacity="0.35" class="bm-hatch"/>`);
457
+ parts.push(`<text x="${X0 + 8}" y="${y + 13}" class="bm-s">ganzer Lauf (ändert Gewichte)</text>`);
458
+ return;
459
+ }
460
+ const a = tx(s.start), b = tx(s.end);
461
+ parts.push(`<rect x="${X0}" y="${y + LANE_H / 2 - 1}" width="${X1 - X0}" height="2" class="bm-base-lane"/>`);
462
+ if (b > a) parts.push(`<rect x="${a}" y="${y}" width="${b - a}" height="${LANE_H}" rx="5" fill="${c}" fill-opacity="0.85" data-handle="${i}:move" class="bm-band" data-tip="Fenster verschieben"/>`);
463
+ parts.push(`<rect x="${a - 5}" y="${y - 3}" width="10" height="${LANE_H + 6}" rx="3" class="bm-handle" style="stroke:${c}" data-handle="${i}:start" data-tip="Beginn ziehen"/>`);
464
+ parts.push(`<rect x="${b - 5}" y="${y - 3}" width="10" height="${LANE_H + 6}" rx="3" class="bm-handle" style="stroke:${c}" data-handle="${i}:end" data-tip="Ende ziehen"/>`);
465
+ parts.push(`<text x="${Math.min(Math.max(a, X0) + 10, X1 - 70)}" y="${y + 13}" class="bm-on-band" pointer-events="none">${num(s.start)}–${num(s.end)} %</text>`);
466
+ });
467
+ if (!st.slots.length) parts.push(`<text x="${X0}" y="${TL_LANE + 21}" class="bm-s">Noch kein Werkzeug gewählt.</text>`);
468
+ return parts.join("");
469
+ }
470
+
471
+ function highlights() {
472
+ const parts = [], layers = {};
473
+ const order = st.slots.map((s, i) => i).sort((a, b) => (a === st.sel) - (b === st.sel));
474
+ // other places of the selected slot: dashed, clickable on the map
475
+ const cur = st.slots[st.sel];
476
+ if (cur) {
477
+ const t = TOOLS[cur.tool], here = new Set(placeOf(cur).sites);
478
+ const other = new Set(t.places.filter((p) => p.value !== cur.place).flatMap((p) => p.sites).filter((x) => !here.has(x)));
479
+ other.forEach((site) => siteShapes(site, cur).forEach((sh) => parts.push(ring(sh, COLORS[st.sel], 0, "dash"))));
480
+ }
481
+ for (const i of order) {
482
+ const s = st.slots[i];
483
+ const dim = hoverSlot !== null && hoverSlot !== i;
484
+ if (dim) parts.push('<g opacity="0.25">');
485
+ for (const site of placeOf(s).sites) {
486
+ const n = layers[site] || 0;
487
+ layers[site] = n + 1;
488
+ siteShapes(site, s).forEach((sh) => parts.push(ring(sh, COLORS[i], n, "solid")));
489
+ }
490
+ if (dim) parts.push("</g>");
491
+ if (s.tool === "excise" && !wordChips(s.word).length) {
492
+ parts.push(`<text x="${BOX.ctx.x + 10}" y="${BOX.ctx.y + BOX.ctx.h - 8}" class="bm-s" style="fill:${COLORS[i]}">„${esc(s.word || "")}“ steht nicht in Prompt A</text>`);
493
+ }
494
+ }
495
+ if (hoverTool && TOOLS[hoverTool]) {
496
+ const seen = new Set();
497
+ TOOLS[hoverTool].places.forEach((p) => p.sites.forEach((site) => {
498
+ if (seen.has(site)) return;
499
+ seen.add(site);
500
+ siteShapes(site, { word: guessWord(srv.prompt) }).forEach((sh) => parts.push(ring(sh, "#868e96", 0, "dash")));
501
+ }));
502
+ }
503
+ return parts.join("");
504
+ }
505
+
506
+ function defs() {
507
+ const heads = COLORS.concat(["#868e96"]).map((c) =>
508
+ `<marker id="bm-arrow-${c.slice(1)}" viewBox="0 0 10 10" refX="6" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="${c}"/></marker>`).join("");
509
+ return `<defs><marker id="bm-head" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
510
+ <path d="M 0 0 L 10 5 L 0 10 z" class="bm-headpath"/></marker>${heads}
511
+ <pattern id="bm-hatch" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
512
+ <line x1="0" y1="0" x2="0" y2="8" stroke="currentColor" stroke-width="2" stroke-opacity="0.25"/></pattern></defs>`;
513
+ }
514
+
515
+ function paintMap() {
516
+ const svg = element.querySelector(".bm-svg");
517
+ if (!svg) return;
518
+ svg.innerHTML = defs() + textLane() + unet() + imageNode() + effectLayer() + highlights() + timeline();
519
+ }
520
+
521
+ // ---------------------------------------------------------------- palette and slots (HTML)
522
+
523
+ function renderPalette() {
524
+ const pal = element.querySelector(".bm-palette");
525
+ pal.innerHTML = CAT.groups.map((g) => `<div class="bm-group"><span class="bm-group-label">${esc(g)}</span>
526
+ ${CAT.tools.filter((t) => t.group === g).map((t) => {
527
+ const used = st.slots.map((s, i) => (s.tool === t.key ? i : -1)).filter((i) => i >= 0);
528
+ const dots = used.map((i) => `<span class="bm-dot" style="background:${COLORS[i]}"></span>`).join("");
529
+ return `<button type="button" class="bm-tile ${used.length ? "bm-used" : ""}" data-key="${t.key}" title="${esc(t.what)}">
530
+ <span class="bm-ico">${t.icon}</span><span>${esc(t.label)}</span>${dots}</button>`;
531
+ }).join("")}</div>`).join("") +
532
+ `<div class="bm-pal-hint">${st.slots.length >= CAT.max_slots
533
+ ? "Drei Werkzeuge sind das Maximum: ein weiteres ersetzt das markierte."
534
+ : "Klickt ein Werkzeug an, um es einzusetzen (bis zu drei). Mit der Maus darüber seht ihr, wo es wirken kann."}</div>`;
535
+ }
536
+
537
+ function slotCard(s, i) {
538
+ const t = TOOLS[s.tool], c = COLORS[i];
539
+ const places = t.places.length > 1
540
+ ? `<div class="bm-places">${t.places.map((p) => `<button type="button" class="bm-pchip ${p.value === s.place ? "bm-on" : ""}"
541
+ data-act="place" data-place="${p.value}">${esc(p.label)}</button>`).join("")}</div>
542
+ <div class="bm-hint">Ort: hier wählen oder auf die gestrichelten Stellen der Karte klicken.</div>` : "";
543
+ const word = s.tool === "excise"
544
+ ? `<label class="bm-row">Wort <input type="text" data-act="word" value="${esc(s.word || "")}" placeholder="Wort aus Prompt A"></label>` : "";
545
+ const lo = Math.min(t.lo, t.hi), hi = Math.max(t.lo, t.hi);
546
+ const knob = `<div class="bm-row bm-knob"><span>${esc(t.knob)}</span>
547
+ <input type="range" data-act="value" min="${lo}" max="${hi}" step="${t.step}" value="${s.value}">
548
+ <input type="number" data-act="value" step="any" value="${s.value}"></div>`;
549
+ const win = t.window
550
+ ? `<div class="bm-row bm-win"><span>Zeitfenster</span><input type="number" data-act="start" step="any" value="${s.start}">
551
+ <span>bis</span><input type="number" data-act="end" step="any" value="${s.end}"><span>%</span></div>
552
+ <div class="bm-hint">Oder auf der Zeitleiste unter der Karte ziehen.</div>`
553
+ : t.time_knob ? `<div class="bm-hint">Den Zeitpunkt könnt ihr auch auf der Zeitleiste ziehen.</div>`
554
+ : t.after_loop ? `<div class="bm-hint">Wirkt nach der Schleife, beim Übersetzen in Pixel.</div>`
555
+ : `<div class="bm-hint">Ändert Gewichte, wirkt also im ganzen Lauf.</div>`;
556
+ return `<div class="bm-card ${i === st.sel ? "bm-sel" : ""}" data-i="${i}" style="--c:${c}">
557
+ <div class="bm-card-head"><span class="bm-badge">${i + 1}</span><span class="bm-ico">${t.icon}</span>
558
+ <b>${esc(t.label)}</b><button type="button" class="bm-x" data-act="remove" title="Werkzeug entfernen">��</button></div>
559
+ <p class="bm-what">${esc(t.what)}</p>${places}${word}${knob}${win}
560
+ <p class="bm-foot">${esc(t.group)} · aus dem Neural-Bending-Rezept „${esc(t.preset)}“ · bei ${num(t.neutral)} keine Wirkung</p></div>`;
561
+ }
562
+
563
+ function renderSlots() {
564
+ const box = element.querySelector(".bm-slots");
565
+ const cards = st.slots.map(slotCard);
566
+ for (let i = st.slots.length; i < CAT.max_slots; i++) {
567
+ cards.push(`<div class="bm-card bm-empty" data-i="${i}"><span class="bm-badge" style="--c:${COLORS[i]}">${i + 1}</span>
568
+ Freier Platz: oben ein Werkzeug wählen.</div>`);
569
+ }
570
+ box.innerHTML = cards.join("");
571
+ }
572
+
573
+ function renderAll() {
574
+ renderPalette();
575
+ renderSlots();
576
+ paintMap();
577
+ }
578
+
579
+ // Keep the other input of a pair in step without re-rendering the card (that would steal the focus).
580
+ function syncCard(i, except) {
581
+ const card = element.querySelector(`.bm-card[data-i="${i}"]`);
582
+ if (!card) return;
583
+ const s = st.slots[i];
584
+ card.querySelectorAll("[data-act]").forEach((inp) => {
585
+ if (inp === except || inp.tagName !== "INPUT") return;
586
+ const a = inp.dataset.act;
587
+ if (a === "value" || a === "start" || a === "end") inp.value = s[a];
588
+ });
589
+ }
590
+
591
+ // ---------------------------------------------------------------- events
592
+
593
+ element.querySelector(".bm-host").innerHTML = `<div class="bm">
594
+ <div class="bm-palette"></div>
595
+ <div class="bm-stage"><svg class="bm-svg" viewBox="0 0 ${W} ${H}" role="img" aria-label="Karte von Stable Diffusion 1.5"></svg>
596
+ <div class="bm-tip" hidden></div></div>
597
+ <div class="bm-slots"></div></div>`;
598
+ root = element.querySelector(".bm");
599
+ const svg = element.querySelector(".bm-svg");
600
+ const tip = element.querySelector(".bm-tip");
601
+
602
+ root.addEventListener("click", (e) => {
603
+ const tile = e.target.closest(".bm-tile");
604
+ if (tile) { addTool(tile.dataset.key); return; }
605
+ const act = e.target.closest("[data-act]");
606
+ const card = e.target.closest(".bm-card");
607
+ if (act && card && act.dataset.act === "remove") { removeSlot(+card.dataset.i); return; }
608
+ if (act && card && act.dataset.act === "place") { st.sel = +card.dataset.i; setPlace(+card.dataset.i, act.dataset.place); return; }
609
+ if (card && !card.classList.contains("bm-empty") && +card.dataset.i !== st.sel && !e.target.closest("input")) {
610
+ st.sel = +card.dataset.i; renderAll(); return;
611
+ }
612
+ const site = e.target.closest("[data-site]");
613
+ if (site && svg.contains(site) && !e.target.closest("[data-handle]")) siteClick(site.dataset.site);
614
+ });
615
+
616
+ root.addEventListener("input", (e) => {
617
+ const inp = e.target, card = inp.closest(".bm-card");
618
+ if (!card || !inp.dataset.act) return;
619
+ const i = +card.dataset.i, s = st.slots[i], a = inp.dataset.act;
620
+ if (!s) return;
621
+ if (a === "word") s.word = inp.value;
622
+ else {
623
+ const v = parseFloat(String(inp.value).replace(",", "."));
624
+ if (!Number.isFinite(v)) return;
625
+ s[a] = v;
626
+ syncCard(i, inp);
627
+ }
628
+ publish(true);
629
+ paintMap();
630
+ });
631
+
632
+ root.addEventListener("pointerover", (e) => {
633
+ const tile = e.target.closest(".bm-tile"), card = e.target.closest(".bm-card:not(.bm-empty)");
634
+ const ht = tile ? tile.dataset.key : null, hs = card ? +card.dataset.i : null;
635
+ if (ht !== hoverTool || hs !== hoverSlot) { hoverTool = ht; hoverSlot = hs; paintMap(); }
636
+ });
637
+ root.addEventListener("pointerleave", () => { hoverTool = null; hoverSlot = null; paintMap(); });
638
+
639
+ function svgX(e) {
640
+ const pt = svg.createSVGPoint();
641
+ pt.x = e.clientX; pt.y = e.clientY;
642
+ return pt.matrixTransform(svg.getScreenCTM().inverse()).x;
643
+ }
644
+
645
+ svg.addEventListener("pointerdown", (e) => {
646
+ const h = e.target.closest("[data-handle]");
647
+ if (!h) return;
648
+ const [i, kind] = h.dataset.handle.split(":");
649
+ const s = st.slots[+i];
650
+ if (!s) return;
651
+ e.preventDefault();
652
+ st.sel = +i;
653
+ drag = { i: +i, kind, x0: svgX(e), start: s.start, end: s.end };
654
+ svg.setPointerCapture(e.pointerId);
655
+ renderPalette(); renderSlots();
656
+ });
657
+
658
+ svg.addEventListener("pointermove", (e) => {
659
+ if (drag) {
660
+ const s = st.slots[drag.i];
661
+ const d = (svgX(e) - drag.x0) / (X1 - X0) * 100;
662
+ const at = Math.round(Math.min(100, Math.max(0, (svgX(e) - X0) / (X1 - X0) * 100)));
663
+ if (drag.kind === "start") s.start = Math.min(at, s.end);
664
+ else if (drag.kind === "end") s.end = Math.max(at, s.start);
665
+ else if (drag.kind === "knob") s.value = at;
666
+ else {
667
+ const len = drag.end - drag.start;
668
+ const a = Math.round(Math.min(100 - len, Math.max(0, drag.start + d)));
669
+ s.start = a; s.end = a + len;
670
+ }
671
+ syncCard(drag.i, null);
672
+ paintMap();
673
+ return;
674
+ }
675
+ const t = e.target.closest("[data-tip]");
676
+ if (!t) { tip.hidden = true; return; }
677
+ const r = element.querySelector(".bm-stage").getBoundingClientRect();
678
+ tip.textContent = t.dataset.tip;
679
+ tip.hidden = false;
680
+ const x = e.clientX - r.left, y = e.clientY - r.top;
681
+ tip.style.left = Math.min(x + 14, r.width - 300) + "px";
682
+ tip.style.top = (y + 18) + "px";
683
+ });
684
+
685
+ function endDrag() {
686
+ if (!drag) return;
687
+ drag = null;
688
+ publish(true);
689
+ paintMap();
690
+ }
691
+ svg.addEventListener("pointerup", endDrag);
692
+ svg.addEventListener("pointercancel", endDrag);
693
+ svg.addEventListener("pointerleave", () => { tip.hidden = true; });
694
+
695
+ watch("value", () => {
696
+ absorb(props.value, false);
697
+ publish(false);
698
+ paintMap();
699
+ });
700
+
701
+ absorb(props.value, true);
702
+ publish(false);
703
+ renderAll();
compare.js ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The results: every image bent, the same seed without tools under a wipe that follows the pointer.
2
+ // Runs as js_on_load of a gr.HTML component. The listeners sit on `element`, so they survive new results.
3
+ let sticky = false;
4
+
5
+ function setCut(card, pct, wiping) {
6
+ const frame = card.querySelector(".bc-frame");
7
+ if (!frame) return;
8
+ frame.style.setProperty("--cut", pct + "%");
9
+ frame.classList.toggle("bc-wiping", wiping);
10
+ }
11
+
12
+ function reset() {
13
+ element.querySelectorAll(".bc-card[data-both]").forEach((c) => setCut(c, sticky ? 100 : 0, false));
14
+ }
15
+
16
+ element.addEventListener("pointermove", (e) => {
17
+ const frame = e.target.closest(".bc-frame");
18
+ if (!frame) return;
19
+ const r = frame.getBoundingClientRect();
20
+ const pct = Math.round(100 * Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)));
21
+ element.querySelectorAll(".bc-card[data-both]").forEach((c) => setCut(c, pct, true));
22
+ });
23
+
24
+ element.addEventListener("pointerout", (e) => {
25
+ if (e.target.closest(".bc-frame") && !(e.relatedTarget && e.relatedTarget.closest && e.relatedTarget.closest(".bc-frame"))) reset();
26
+ });
27
+
28
+ element.addEventListener("click", (e) => {
29
+ const btn = e.target.closest(".bc-toggle");
30
+ if (!btn) return;
31
+ sticky = !sticky;
32
+ btn.classList.toggle("bc-on", sticky);
33
+ btn.textContent = sticky ? "Gebogene Bilder zeigen" : "Alle ohne Eingriff zeigen";
34
+ reset();
35
+ });
36
+
37
+ watch("value", () => { sticky = false; reset(); });
engine.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model loading, Settings and the custom denoising loop.
2
+
3
+ Every rule the workshop talks about is a line in this file. The pipeline object
4
+ is only a container for the components and a few static helpers. We never call
5
+ pipe(...) during the workshop.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import os
12
+ import threading
13
+ import time
14
+ from collections import OrderedDict
15
+ from contextlib import contextmanager
16
+ from dataclasses import dataclass, field
17
+
18
+ import numpy as np
19
+ import torch
20
+ from PIL import Image
21
+
22
+ from family import ACTIVE as FAMILY
23
+
24
+ # Defaults come from the model family (family.py), environment variables override them.
25
+ MODEL_ID = os.environ.get("MODEL_ID", FAMILY.model_id)
26
+ DEFAULT_SIZE = int(os.environ.get("DEFAULT_SIZE", FAMILY.default_size))
27
+ DEFAULT_STEPS = int(os.environ.get("DEFAULT_STEPS", FAMILY.default_steps))
28
+ GRID_N = int(os.environ.get("GRID_N", FAMILY.grid_n)) # FLUX: 9 images take 30 s on the L40S, 4 take 13 s
29
+ MAX_BATCH = int(os.environ.get("MAX_BATCH", FAMILY.max_batch))
30
+ MAX_SEQ = int(os.environ.get("MAX_SEQ", FAMILY.max_seq))
31
+ GRID_SIZES = tuple(k * k for k in range(2, 9)) # 2 x 2 to 8 x 8, one choice for the whole app
32
+
33
+ STANDARD_LAYERS = FAMILY.standard_layers
34
+ EXPERIMENTS = ("seed_grid", "guidance_sweep", "interpolation")
35
+ # Pixels per VAE decode call. Decoding in float32 is memory hungry at 1024 px.
36
+ DECODE_PIXELS = int(os.environ.get("DECODE_PIXELS", str(4 * 512 * 512)))
37
+ EMB_CACHE_SIZE = 32
38
+
39
+ BEND_OPS = ("none", "amplify", "invert", "ablate", "rotate", "flip", "shift", "noise", "threshold")
40
+ SPATIAL_OPS = ("rotate", "flip", "shift") # image stream only
41
+ # Offsets from the seed, so each source of randomness has its own stream.
42
+ SEED_SHUFFLE, SEED_EMB_NOISE, SEED_ABLATE, SEED_BEND_NOISE, SEED_WEIGHTS = 3, 5, 7, 8, 9
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Settings:
47
+ prompt_a: str
48
+ prompt_b: str
49
+ experiment: str # "seed_grid" | "guidance_sweep" | "interpolation"
50
+ seed: int
51
+ steps: int
52
+ t: float = 0.0 # blend A -> B, used by seed_grid and guidance_sweep
53
+ guidance: float = 4.0 # used by seed_grid and interpolation
54
+ g_from: float = 1.5 # guidance_sweep
55
+ g_to: float = 7.0
56
+ t_from: float = 0.0 # interpolation
57
+ t_to: float = 1.0
58
+ width: int = DEFAULT_SIZE
59
+ height: int = DEFAULT_SIZE
60
+ emb_scale: float = 1.0 # R4
61
+ emb_noise: float = 0.0 # R4
62
+ emb_shuffle: bool = False # R4
63
+ te_layers: tuple = STANDARD_LAYERS # R5
64
+ sigma_mult: float = 1.0 # R6
65
+ sigma_offset: float = 0.0 # R6
66
+ stop_at: float = 1.0 # R7, fraction of steps actually run
67
+ show_x0: bool = False # R7, decode predicted clean image instead of x_t
68
+ bend_block: str | None = None # R8, "double.0".."double.4" | "single.0".."single.19"
69
+ bend_stream: str = "image" # "image" | "text"
70
+ bend_op: str = "none"
71
+ bend_strength: float = 0.0
72
+ bend_from: float = 0.0 # active window as fraction of the schedule
73
+ bend_to: float = 1.0
74
+ weight_block: str | None = None # R9
75
+ weight_noise: float = 0.0 # R9, relative to each weight tensor's std
76
+ grid: int | None = None # images in the grid, None = GRID_N
77
+ tools: tuple = () # Tab 4: tools_sd15.ToolUse entries, SD 1.5 only
78
+
79
+
80
+ @dataclass
81
+ class Result:
82
+ items: list # [(PIL.Image, caption)] for gr.Gallery
83
+ grid: Image.Image # composite for the board
84
+ warnings: list = field(default_factory=list)
85
+ seconds: float = 0.0
86
+ timings: dict = field(default_factory=dict)
87
+
88
+
89
+ class Clock:
90
+ """Progress through the schedule, read by the bending hooks."""
91
+
92
+ progress = 0.0
93
+
94
+
95
+ def fmt_num(x: float, decimals: int) -> str:
96
+ """German number formatting with a decimal comma."""
97
+ return f"{x:.{decimals}f}".replace(".", ",")
98
+
99
+
100
+ def clamp_size(x: int) -> int:
101
+ return max(16, int(round(x / 16)) * 16)
102
+
103
+
104
+ def sample_specs(s: Settings, n: int | None = None) -> list[tuple[int, float, float, str]]:
105
+ """One (seed, t, guidance, caption) tuple per image of the grid."""
106
+ n = n or s.grid or GRID_N
107
+ if s.experiment == "seed_grid":
108
+ return [(s.seed + i, s.t, s.guidance, f"Seed {s.seed + i}") for i in range(n)]
109
+ if s.experiment == "guidance_sweep":
110
+ gs = np.linspace(s.g_from, s.g_to, n)
111
+ return [(s.seed, s.t, float(g), f"Guidance {fmt_num(g, 1)}") for g in gs]
112
+ if s.experiment == "interpolation":
113
+ ts = np.linspace(s.t_from, s.t_to, n)
114
+ return [(s.seed, float(t), s.guidance, f"t = {fmt_num(t, 3)}") for t in ts]
115
+ raise ValueError(f"unknown experiment {s.experiment!r}")
116
+
117
+
118
+ def make_grid(images: list[Image.Image], cols: int | None = None, cell: int = 256,
119
+ gap: int = 4, bg=(255, 255, 255)) -> Image.Image:
120
+ """Composite of all images, the long side of each cell is `cell` px (smaller for wide grids)."""
121
+ n = len(images)
122
+ cols = cols or math.ceil(math.sqrt(n))
123
+ rows = math.ceil(n / cols)
124
+ cell = min(cell, 1040 // cols) # a 6 x 6 grid stays about as wide as a 4 x 4 one
125
+ w0, h0 = images[0].size
126
+ scale = cell / max(w0, h0)
127
+ cw, ch = max(1, round(w0 * scale)), max(1, round(h0 * scale))
128
+ grid = Image.new("RGB", (cols * cw + (cols - 1) * gap, rows * ch + (rows - 1) * gap), bg)
129
+ for i, im in enumerate(images):
130
+ r, c = divmod(i, cols)
131
+ grid.paste(im.convert("RGB").resize((cw, ch), Image.LANCZOS), (c * (cw + gap), r * (ch + gap)))
132
+ return grid
133
+
134
+
135
+ def block_ids(transformer) -> list[str]:
136
+ """"double.0".."double.4" (text and image still separate), then "single.0".."single.19"."""
137
+ return ([f"double.{k}" for k in range(len(transformer.transformer_blocks))]
138
+ + [f"single.{k}" for k in range(len(transformer.single_transformer_blocks))])
139
+
140
+
141
+ def get_block(transformer, block_id: str):
142
+ kind, k = block_id.split(".")
143
+ blocks = {"double": transformer.transformer_blocks, "single": transformer.single_transformer_blocks}[kind]
144
+ return blocks[int(k)]
145
+
146
+
147
+ def bend_tensor(h: torch.Tensor, op: str, s: float, lat_hw: tuple[int, int] | None = None,
148
+ mask: torch.Tensor | None = None, gen: torch.Generator | None = None) -> torch.Tensor:
149
+ """R8: one bending operation on tokens h (B, L, D). Spatial ops need lat_hw = (lat_h, lat_w)."""
150
+ if op == "amplify":
151
+ return h * (1 + 4 * s)
152
+ if op == "invert":
153
+ return h * (1 - 2 * s)
154
+ if op == "ablate":
155
+ return h * mask
156
+ if op == "noise":
157
+ z = torch.randn(h.shape, generator=gen, device=h.device, dtype=torch.float32)
158
+ return h + (2 * s * h.float().std() * z).to(h.dtype)
159
+ if op == "threshold":
160
+ return torch.where(h.abs() > 2 * s * h.float().std(), h, torch.zeros_like(h))
161
+ B, L, D = h.shape
162
+ lat_h, lat_w = lat_hw
163
+ x = h.reshape(B, lat_h, lat_w, D).permute(0, 3, 1, 2) # spatial view (B, D, h, w)
164
+ if op == "rotate":
165
+ # 90 degrees keeps the shape only for square latents, otherwise turn by 180.
166
+ x = torch.lerp(x, torch.rot90(x, 1 if lat_h == lat_w else 2, dims=(-2, -1)), s)
167
+ elif op == "flip":
168
+ x = torch.lerp(x, torch.flip(x, dims=(-1,)), s)
169
+ elif op == "shift":
170
+ x = torch.roll(x, shifts=round(s * lat_w / 2), dims=-1)
171
+ else:
172
+ raise ValueError(f"unknown bending op {op!r}")
173
+ return x.permute(0, 2, 3, 1).reshape(B, L, D)
174
+
175
+
176
+ class Engine:
177
+ """FLUX.2 [klein] engine. engine_sd15.SD15Engine reuses render, conditioning and the interventions."""
178
+
179
+ latent_factor = 16 # pixels per packed latent token: VAE scale 8 x patch 2
180
+ standard_layers = (9, 18, 27) # Qwen3 hidden states the pipeline reads
181
+
182
+ def __init__(self, pipe, device: str | torch.device = "cuda"):
183
+ from diffusers import FlowMatchEulerDiscreteScheduler
184
+ from diffusers.pipelines.flux2.pipeline_flux2_klein import (
185
+ Flux2KleinPipeline, compute_empirical_mu, retrieve_timesteps)
186
+
187
+ self.pipe = pipe
188
+ self.device = torch.device(device)
189
+ self.P = Flux2KleinPipeline
190
+ self._Scheduler = FlowMatchEulerDiscreteScheduler
191
+ self._mu = compute_empirical_mu
192
+ self._retrieve_timesteps = retrieve_timesteps
193
+ self.clock = Clock()
194
+ self._emb_cache: OrderedDict = OrderedDict()
195
+ self._lock = threading.Lock()
196
+ self.post_step: list = [] # functions latent -> latent after every sampler step (Tab 4)
197
+ self.encode_tag = "" # part of the encoding cache key while a tool changes the text encoder
198
+ self.run_notes: list = [] # notes for the status line from the current render call
199
+ for m in (pipe.transformer, pipe.text_encoder, pipe.vae):
200
+ m.requires_grad_(False)
201
+ m.eval()
202
+
203
+ @classmethod
204
+ def from_pretrained(cls, model_id: str = MODEL_ID, device: str = "cuda") -> "Engine":
205
+ from diffusers import Flux2KleinPipeline
206
+
207
+ pipe = Flux2KleinPipeline.from_pretrained(model_id, dtype=torch.bfloat16).to(device)
208
+ # Extreme latents overflow less in float32. The VAE config sets force_upcast anyway.
209
+ pipe.vae.to(torch.float32)
210
+ # Tiles only above the VAE's sample_size (1024 px), so smaller images are unchanged.
211
+ # Without it a float32 decode at 1536 px runs out of memory on a 24 GB card.
212
+ pipe.vae.enable_tiling()
213
+ return cls(pipe, device)
214
+
215
+ def block(self, block_id: str):
216
+ return get_block(self.pipe.transformer, block_id)
217
+
218
+ def text_bend_note(self, s: Settings) -> str | None:
219
+ """A status line when a text-stream bend cannot act, else None."""
220
+ if s.bend_stream == "text" and s.bend_block == block_ids(self.pipe.transformer)[-1]:
221
+ # The transformer drops the text tokens after its last block.
222
+ return ("Nach dem letzten Block liest das Netz den Text-Strom nicht mehr. "
223
+ "Dieser Eingriff ändert deshalb nichts. Wählt einen früheren Block.")
224
+ return None
225
+
226
+ def warmup(self, size: int = DEFAULT_SIZE, n: int = 2, steps: int = 2) -> float:
227
+ s = Settings("warm-up", "warm-up", "seed_grid", seed=0, steps=steps, width=size, height=size,
228
+ te_layers=self.standard_layers)
229
+ return self.render(s, sample_specs(s, n)).seconds
230
+
231
+ # ---------------------------------------------------------------- text
232
+
233
+ def encode(self, prompt: str, layers: tuple = STANDARD_LAYERS, max_len: int = MAX_SEQ) -> torch.Tensor:
234
+ """Stacked Qwen3 hidden states (1, max_len, 3 * 2560), cached."""
235
+ key = (prompt, tuple(layers), max_len)
236
+ with self._lock:
237
+ if key in self._emb_cache:
238
+ self._emb_cache.move_to_end(key)
239
+ return self._emb_cache[key]
240
+ with torch.inference_mode():
241
+ emb = self.P._get_qwen3_prompt_embeds(
242
+ self.pipe.text_encoder, self.pipe.tokenizer, prompt, dtype=torch.bfloat16,
243
+ device=self.device, max_sequence_length=max_len, hidden_states_layers=tuple(layers))
244
+ with self._lock:
245
+ self._emb_cache[key] = emb
246
+ while len(self._emb_cache) > EMB_CACHE_SIZE:
247
+ self._emb_cache.popitem(last=False)
248
+ return emb
249
+
250
+ def clear_cache(self) -> None:
251
+ with self._lock:
252
+ self._emb_cache.clear()
253
+
254
+ def conditioning(self, s: Settings, ts: list[float], max_len: int) -> tuple[torch.Tensor, torch.Tensor]:
255
+ """cond (n, L, D) and uncond (1, L, D), both bfloat16."""
256
+ n_layers = self.pipe.text_encoder.config.num_hidden_layers # hidden_states has n_layers + 1 entries
257
+ if any(not 0 <= k <= n_layers for k in s.te_layers):
258
+ raise ValueError(f"text encoder layers must lie in 0..{n_layers}, got {s.te_layers}")
259
+ emb_a, emb_b = self.prompt_embeddings(s, max_len)
260
+ uncond = self.encode("", s.te_layers, max_len)
261
+ # R2: a linear blend in the stacked hidden-state space, padding positions included.
262
+ t = torch.tensor(ts, device=self.device, dtype=torch.float32).view(-1, 1, 1)
263
+ cond = emb_a + t * (emb_b - emb_a)
264
+ # R4 acts on cond only, in this order: shuffle, scale, noise. uncond stays untouched.
265
+ if s.emb_shuffle:
266
+ cond = self.shuffle_cond(s, cond, max_len)
267
+ if s.emb_scale != 1.0:
268
+ cond = cond * s.emb_scale
269
+ if s.emb_noise != 0:
270
+ # The same noise for every sample, so a seed grid stays comparable.
271
+ z = torch.randn(cond.shape[1:], generator=torch.Generator("cpu").manual_seed(s.seed + SEED_EMB_NOISE))
272
+ cond = cond + s.emb_noise * z.to(self.device) * cond.std(dim=-1, keepdim=True)
273
+ return cond.to(torch.bfloat16), uncond
274
+
275
+ def prompt_embeddings(self, s: Settings, max_len: int) -> tuple[torch.Tensor, torch.Tensor]:
276
+ return (self.encode(s.prompt_a, s.te_layers, max_len).float(),
277
+ self.encode(s.prompt_b, s.te_layers, max_len).float())
278
+
279
+ def shuffle_cond(self, s: Settings, cond: torch.Tensor, max_len: int) -> torch.Tensor:
280
+ """R4: permute the hidden states at the prompt's token positions (template and padding stay)."""
281
+ pos = sorted(set(self.content_positions(s.prompt_a, max_len))
282
+ | set(self.content_positions(s.prompt_b, max_len)))
283
+ if len(pos) > 1:
284
+ perm = torch.randperm(len(pos), generator=torch.Generator("cpu").manual_seed(s.seed + SEED_SHUFFLE))
285
+ idx = torch.tensor(pos, device=self.device)
286
+ cond[:, idx] = cond[:, idx[perm.to(self.device)]]
287
+ return cond
288
+
289
+ def content_positions(self, prompt: str, max_len: int = MAX_SEQ) -> list[int]:
290
+ """Token positions of the user's prompt inside the chat template (no template tokens, no padding)."""
291
+ tok = self.pipe.tokenizer
292
+
293
+ def template(content: str) -> str:
294
+ return tok.apply_chat_template([{"role": "user", "content": content}], tokenize=False,
295
+ add_generation_prompt=True, enable_thinking=False)
296
+
297
+ text = template(prompt)
298
+ start = len(template("\x00").split("\x00")[0])
299
+ end = start + len(prompt)
300
+ if text[start:end] != prompt:
301
+ raise ValueError("chat template does not contain the prompt verbatim")
302
+ enc = tok(text, return_offsets_mapping=True, padding="max_length", truncation=True, max_length=max_len)
303
+ return [i for i, (a, b) in enumerate(enc["offset_mapping"]) if b > a and a >= start and b <= end]
304
+
305
+ # ---------------------------------------------------------------- loop
306
+
307
+ @contextmanager
308
+ def interventions(self, s: Settings, lat_h: int, lat_w: int, txt_len: int):
309
+ """Hooks (R8) and weight noise (R9) for exactly one render call, removed on any exit.
310
+
311
+ Safe only because the Space runs one GPU job at a time.
312
+ """
313
+ with self.weight_noise(s), self.bending(s, lat_h, lat_w, txt_len):
314
+ yield
315
+
316
+ @contextmanager
317
+ def bending(self, s: Settings, lat_h: int, lat_w: int, txt_len: int):
318
+ """R8: a forward hook on one block changes its image or text tokens inside a phase window."""
319
+ if not s.bend_block or s.bend_op == "none" or s.bend_strength == 0:
320
+ yield
321
+ return
322
+ op, st, image = s.bend_op, float(s.bend_strength), s.bend_stream == "image"
323
+ if op not in BEND_OPS:
324
+ raise ValueError(f"unknown bending op {op!r}")
325
+ if not image and op in SPATIAL_OPS:
326
+ raise ValueError(f"{op} works on the image stream only")
327
+ block = self.block(s.bend_block)
328
+ double = s.bend_block.startswith("double")
329
+ mask = gen = None
330
+ if op == "ablate":
331
+ dim = self.pipe.transformer.config.num_attention_heads * self.pipe.transformer.config.attention_head_dim
332
+ off = torch.randperm(dim, generator=torch.Generator("cpu").manual_seed(s.seed + SEED_ABLATE))
333
+ mask = torch.ones(dim)
334
+ mask[off[:round(min(max(st, 0.0), 1.0) * dim)]] = 0.0 # typed values may leave 0..1
335
+ mask = mask.to(self.device, torch.bfloat16)
336
+ elif op == "noise":
337
+ gen = torch.Generator(self.device).manual_seed(s.seed + SEED_BEND_NOISE)
338
+ clock = self.clock
339
+
340
+ def bend(h, spatial):
341
+ return bend_tensor(h, op, st, (lat_h, lat_w) if spatial else None, mask, gen)
342
+
343
+ def hook(module, args, output):
344
+ if not (s.bend_from <= clock.progress <= s.bend_to):
345
+ return None # outside the window: unchanged
346
+ if double: # (text, image)
347
+ txt, img = output
348
+ return (txt, bend(img, True)) if image else (bend(txt, False), img)
349
+ txt, img = output[:, :txt_len], output[:, txt_len:] # single stream: [text, image]
350
+ return torch.cat([txt, bend(img, True)] if image else [bend(txt, False), img], dim=1)
351
+
352
+ handle = block.register_forward_hook(hook)
353
+ try:
354
+ yield
355
+ finally:
356
+ handle.remove()
357
+
358
+ @contextmanager
359
+ def weight_noise(self, s: Settings):
360
+ """R9: add noise to one block's weight matrices, relative to each tensor's std. Restored on exit."""
361
+ if not s.weight_block or s.weight_noise == 0:
362
+ yield
363
+ return
364
+ block = self.block(s.weight_block)
365
+ gen = torch.Generator(self.device).manual_seed(s.seed + SEED_WEIGHTS)
366
+ saved = []
367
+ try:
368
+ with torch.no_grad():
369
+ for p in block.parameters():
370
+ if p.dim() < 2:
371
+ continue
372
+ saved.append((p, p.detach().clone()))
373
+ z = torch.randn(p.shape, generator=gen, device=p.device, dtype=torch.float32)
374
+ w = p.float()
375
+ p.copy_((w + s.weight_noise * w.std() * z).to(p.dtype))
376
+ yield
377
+ finally:
378
+ with torch.no_grad():
379
+ for p, orig in saved:
380
+ p.copy_(orig)
381
+
382
+ def denoise(self, s: Settings, cond: torch.Tensor, uncond: torch.Tensor, seeds: list[int],
383
+ guidances: list[float], on_step=None) -> torch.Tensor:
384
+ """Run the sampler for one chunk. Returns packed latents (n, h*w, 128) in float32."""
385
+ P, dev, N = self.P, self.device, s.steps
386
+ n = len(seeds)
387
+ lat_h, lat_w = s.height // 16, s.width // 16 # vae scale 8 x patch 2
388
+ noise = torch.stack([torch.randn((128, lat_h, lat_w), generator=torch.Generator("cpu").manual_seed(sd))
389
+ for sd in seeds]) # float32, device independent
390
+ img_ids = P._prepare_latent_ids(noise).to(dev)
391
+ lat = P._pack_latents(noise).to(dev) # (n, h*w, 128), stays float32
392
+
393
+ sched = self._Scheduler.from_config(self.pipe.scheduler.config) # fresh: the scheduler is stateful
394
+ sigmas = np.linspace(1.0, 1.0 / N, N)
395
+ mu = self._mu(image_seq_len=lat.shape[1], num_steps=N)
396
+ timesteps, _ = self._retrieve_timesteps(sched, N, dev, sigmas=sigmas, mu=mu)
397
+ sched.set_begin_index(0)
398
+ sig = sched.sigmas.float().cpu().tolist() # shifted sigmas, N + 1 values ending in 0
399
+ n_run = max(1, round(N * s.stop_at))
400
+
401
+ enc = torch.cat([cond, uncond.expand(n, -1, -1)]).to(torch.bfloat16)
402
+ txt_ids = P._prepare_text_ids(enc).to(dev)
403
+ ids2 = torch.cat([img_ids, img_ids])
404
+ g = torch.tensor(guidances, device=dev, dtype=torch.float32).view(-1, 1, 1)
405
+ x0_pred = None
406
+ for i, t in enumerate(timesteps[:n_run]):
407
+ self.clock.progress = i / N
408
+ sigma = sig[i]
409
+ t_model = sigma * s.sigma_mult + s.sigma_offset # R6: the model is told a different time
410
+ x = torch.cat([lat, lat]).to(torch.bfloat16)
411
+ v = self.pipe.transformer(
412
+ hidden_states=x, timestep=torch.full((2 * n,), t_model, device=dev), guidance=None,
413
+ encoder_hidden_states=enc, txt_ids=txt_ids, img_ids=ids2, return_dict=False)[0].float()
414
+ v_c, v_u = v.chunk(2)
415
+ v = v_u + g * (v_c - v_u) # R3: per-sample guidance
416
+ x0_pred = lat - sigma * v
417
+ lat = sched.step(v, t, lat, return_dict=False)[0] # float32 stays float32 because v is float32
418
+ if on_step is not None:
419
+ on_step()
420
+ return x0_pred if (s.show_x0 and n_run < N) else lat
421
+
422
+ def decode(self, final: torch.Tensor, lat_h: int, lat_w: int) -> tuple[list[Image.Image], list[bool]]:
423
+ vae = self.pipe.vae
424
+ n = final.shape[0]
425
+ finite = torch.isfinite(final).flatten(1).all(1).tolist()
426
+ final = torch.nan_to_num(final.float(), 0.0, 0.0, 0.0)
427
+ lat = final.view(n, lat_h, lat_w, 128).permute(0, 3, 1, 2) # row-major, as _prepare_latent_ids
428
+ mean = vae.bn.running_mean.view(1, -1, 1, 1).to(lat.device, torch.float32)
429
+ std = torch.sqrt(vae.bn.running_var.view(1, -1, 1, 1) + vae.config.batch_norm_eps).to(lat.device, torch.float32)
430
+ lat = self.P._unpatchify_latents(lat * std + mean)
431
+ per_call = max(1, DECODE_PIXELS // (lat_h * lat_w * 256))
432
+ images = []
433
+ for k in range(0, n, per_call):
434
+ img = vae.decode(lat[k:k + per_call].to(vae.dtype), return_dict=False)[0]
435
+ img = torch.nan_to_num(img.float(), 0.0, 0.0, 0.0)
436
+ images += self.pipe.image_processor.postprocess(img, output_type="pil")
437
+ return images, finite
438
+
439
+ # ---------------------------------------------------------------- entry points
440
+
441
+ def render(self, s: Settings, specs: list[tuple[int, float, float, str]], max_seq: int = MAX_SEQ,
442
+ per_chunk: int | None = None, progress=None) -> Result:
443
+ """Render explicit per-sample specs. `progress(done, total)` is called once per step.
444
+
445
+ Images per forward pass default to MAX_BATCH at DEFAULT_SIZE, scaled by pixel count.
446
+ """
447
+ s = _checked(s)
448
+ t0 = time.perf_counter()
449
+ lat_h, lat_w = s.height // self.latent_factor, s.width // self.latent_factor
450
+ n = len(specs)
451
+ per_chunk = per_chunk or max(1, math.floor(MAX_BATCH * DEFAULT_SIZE ** 2 / (s.width * s.height)))
452
+ chunks = [specs[k:k + per_chunk] for k in range(0, n, per_chunk)]
453
+ n_run = max(1, round(s.steps * s.stop_at))
454
+ total, done = len(chunks) * n_run, 0
455
+
456
+ def on_step():
457
+ nonlocal done
458
+ done += 1
459
+ if progress is not None:
460
+ progress(done, total)
461
+
462
+ timings = {}
463
+ self.run_notes = []
464
+ try:
465
+ with self.interventions(s, lat_h, lat_w, max_seq), torch.inference_mode():
466
+ _sync()
467
+ t1 = time.perf_counter()
468
+ finals = []
469
+ cond_all, uncond = self.conditioning(s, [sp[1] for sp in specs], max_seq)
470
+ _sync()
471
+ timings["encode"] = time.perf_counter() - t1
472
+ t1 = time.perf_counter()
473
+ for k, chunk in enumerate(chunks):
474
+ lo = k * per_chunk
475
+ finals.append(self.denoise(s, cond_all[lo:lo + len(chunk)], uncond,
476
+ [sp[0] for sp in chunk], [sp[2] for sp in chunk], on_step))
477
+ _sync()
478
+ timings["denoise"] = time.perf_counter() - t1
479
+ t1 = time.perf_counter()
480
+ images, finite = self.decode(torch.cat(finals), lat_h, lat_w)
481
+ _sync()
482
+ timings["decode"] = time.perf_counter() - t1
483
+ except torch.cuda.OutOfMemoryError:
484
+ torch.cuda.empty_cache()
485
+ import gradio as gr
486
+ raise gr.Error("Zu wenig GPU-Speicher. Wählt eine kleinere Bildgröße.")
487
+
488
+ items, warnings = [], []
489
+ for im, ok, sp in zip(images, finite, specs):
490
+ items.append((im, sp[3] if ok else f"{sp[3]} (numerischer Überlauf)"))
491
+ note = self.text_bend_note(s) if (s.bend_block and s.bend_op != "none" and s.bend_strength != 0) else None
492
+ if note:
493
+ warnings.append(note)
494
+ warnings += self.run_notes
495
+ n_bad = finite.count(False)
496
+ if n_bad:
497
+ warnings.append(f"Bei {n_bad} von {n} Bildern ist die Rechnung numerisch übergelaufen. "
498
+ "Diese Bilder zeigen nur einen Ersatz für die ungültigen Werte.")
499
+ cols = math.ceil(math.sqrt(n))
500
+ return Result(items=items, grid=make_grid(images, cols), warnings=warnings,
501
+ seconds=time.perf_counter() - t0, timings=timings)
502
+
503
+ def generate(self, s: Settings, progress=None) -> Result:
504
+ return self.render(s, sample_specs(s), progress=progress)
505
+
506
+
507
+ def load_engine(device: str = "cuda") -> Engine:
508
+ """The engine of the active model family."""
509
+ if FAMILY.key == "sd15":
510
+ from engine_sd15 import SD15Engine
511
+
512
+ return SD15Engine.from_pretrained(MODEL_ID, device)
513
+ return Engine.from_pretrained(MODEL_ID, device)
514
+
515
+
516
+ def _checked(s: Settings) -> Settings:
517
+ from dataclasses import replace
518
+
519
+ if s.experiment not in EXPERIMENTS:
520
+ raise ValueError(f"unknown experiment {s.experiment!r}")
521
+ if s.bend_op not in BEND_OPS:
522
+ raise ValueError(f"unknown bending op {s.bend_op!r}")
523
+ if s.bend_stream not in ("image", "text"):
524
+ raise ValueError(f"unknown stream {s.bend_stream!r}")
525
+ if s.tools:
526
+ from tools_sd15 import TOOLS
527
+
528
+ unknown = [u.key for u in s.tools if u.key not in TOOLS]
529
+ if unknown:
530
+ raise ValueError(f"unknown tools {unknown}")
531
+ return replace(s, prompt_a=s.prompt_a or "", prompt_b=s.prompt_b or "",
532
+ width=clamp_size(s.width), height=clamp_size(s.height),
533
+ steps=max(1, int(s.steps)), seed=int(s.seed),
534
+ te_layers=tuple(int(k) for k in s.te_layers),
535
+ stop_at=min(1.0, max(0.0, float(s.stop_at))),
536
+ grid=None if s.grid is None else max(1, min(max(GRID_SIZES), int(s.grid))))
537
+
538
+
539
+ def _sync() -> None:
540
+ if torch.cuda.is_available():
541
+ torch.cuda.synchronize()
engine_sd15.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable Diffusion 1.5 engine with the same interface and rules as the FLUX engine.
2
+
3
+ The loop runs Euler in sigma space, so the update reads like the FLUX one:
4
+ x = x + (sigma_next - sigma) * eps. The network is told the time as a timestep in [0, 1000).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import threading
10
+ from collections import OrderedDict
11
+ from contextlib import contextmanager
12
+
13
+ import torch
14
+ from PIL import Image
15
+
16
+ import engine as E
17
+ from engine import Clock, Settings
18
+
19
+ DECODE_PIXELS = E.DECODE_PIXELS
20
+
21
+
22
+ class SD15Engine(E.Engine):
23
+ latent_factor = 8 # VAE scale, no patching
24
+ standard_layers = (12,) # CLIP's last layer, as in the pipeline
25
+
26
+ def __init__(self, pipe, device: str | torch.device = "cuda"):
27
+ from diffusers import EulerDiscreteScheduler
28
+
29
+ self.pipe = pipe
30
+ self.device = torch.device(device)
31
+ self.clock = Clock()
32
+ self._emb_cache: OrderedDict = OrderedDict()
33
+ self._lock = threading.Lock()
34
+ self.post_step: list = [] # functions latent -> latent after every sampler step (Tab 4)
35
+ self.encode_tag = "" # part of the encoding cache key while a tool changes CLIP
36
+ self.run_notes: list = []
37
+ self.dtype = pipe.unet.dtype
38
+ # Euler in sigma space, configured from the checkpoint's scheduler (same betas, same offset).
39
+ self._scheduler_config = EulerDiscreteScheduler.from_config(pipe.scheduler.config).config
40
+ self._Scheduler = EulerDiscreteScheduler
41
+ for m in (pipe.unet, pipe.text_encoder, pipe.vae):
42
+ m.requires_grad_(False)
43
+ m.eval()
44
+
45
+ @classmethod
46
+ def from_pretrained(cls, model_id: str = E.MODEL_ID, device: str = "cuda") -> "SD15Engine":
47
+ from diffusers import StableDiffusionPipeline
48
+
49
+ # bfloat16 rather than float16: bent activations overflow less.
50
+ dtype = torch.bfloat16 if (device != "cuda" or torch.cuda.is_bf16_supported()) else torch.float16
51
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, dtype=dtype, variant="fp16", safety_checker=None,
52
+ feature_extractor=None, requires_safety_checker=False)
53
+ pipe = pipe.to(device)
54
+ pipe.vae.to(torch.float32)
55
+ # Typed sizes go up to 1536 px, where the fp32 decoder would run out of memory. SD's VAE would
56
+ # tile from 512 px on, so tiles start only above 1024 px and smaller images decode as before.
57
+ pipe.vae.enable_tiling()
58
+ pipe.vae.tile_sample_min_size = 1024
59
+ pipe.vae.tile_latent_min_size = 1024 // 8
60
+ return cls(pipe, device)
61
+
62
+ # ---------------------------------------------------------------- text
63
+
64
+ def encode(self, prompt: str, layers: tuple = (12,), max_len: int = 77,
65
+ shuffle_seed: int | None = None) -> torch.Tensor:
66
+ """CLIP hidden states (1, 77, 768) after the final layer norm, read at one layer. Cached.
67
+
68
+ shuffle_seed permutes the prompt's tokens before the encoder reads them (R4).
69
+ """
70
+ if len(layers) != 1:
71
+ raise ValueError("SD 1.5 reads the text encoder at exactly one layer")
72
+ key = (prompt, tuple(layers), max_len, shuffle_seed, self.encode_tag)
73
+ with self._lock:
74
+ if key in self._emb_cache:
75
+ self._emb_cache.move_to_end(key)
76
+ return self._emb_cache[key]
77
+ te, tok = self.pipe.text_encoder, self.pipe.tokenizer
78
+ ids = tok(prompt, padding="max_length", max_length=tok.model_max_length, truncation=True,
79
+ return_tensors="pt").input_ids
80
+ pos = self.content_positions(prompt)
81
+ if shuffle_seed is not None and len(pos) > 1:
82
+ perm = torch.randperm(len(pos), generator=torch.Generator("cpu").manual_seed(shuffle_seed))
83
+ idx = torch.tensor(pos)
84
+ ids[0, idx] = ids[0, idx[perm]]
85
+ ids = ids.to(self.device)
86
+ with torch.inference_mode():
87
+ out = te(ids, output_hidden_states=True)
88
+ # Layer 12 gives exactly the pipeline's prompt_embeds (last_hidden_state).
89
+ # transformers 5 keeps the norm on the model itself, older versions on .text_model.
90
+ norm = te.final_layer_norm if hasattr(te, "final_layer_norm") else te.text_model.final_layer_norm
91
+ emb = norm(out.hidden_states[layers[0]]).to(self.dtype)
92
+ with self._lock:
93
+ self._emb_cache[key] = emb
94
+ while len(self._emb_cache) > E.EMB_CACHE_SIZE:
95
+ self._emb_cache.popitem(last=False)
96
+ return emb
97
+
98
+ def prompt_embeddings(self, s: Settings, max_len: int) -> tuple[torch.Tensor, torch.Tensor]:
99
+ # The UNet's cross-attention has no positions on the text side, so permuting the encoded
100
+ # vectors would change nothing. R4 shuffles the word order before CLIP reads it instead.
101
+ seed = s.seed + E.SEED_SHUFFLE if s.emb_shuffle else None
102
+ return (self.encode(s.prompt_a, s.te_layers, max_len, seed).float(),
103
+ self.encode(s.prompt_b, s.te_layers, max_len, seed).float())
104
+
105
+ def shuffle_cond(self, s: Settings, cond: torch.Tensor, max_len: int) -> torch.Tensor:
106
+ return cond # already shuffled before the encoder
107
+
108
+ def content_positions(self, prompt: str, max_len: int = 77) -> list[int]:
109
+ """Positions of the prompt's tokens: after the start token, before the end token and the padding."""
110
+ n = len(self.pipe.tokenizer(prompt, add_special_tokens=False).input_ids)
111
+ return list(range(1, 1 + min(n, self.pipe.tokenizer.model_max_length - 2)))
112
+
113
+ # ---------------------------------------------------------------- blocks
114
+
115
+ def block(self, block_id: str):
116
+ unet = self.pipe.unet
117
+ if block_id == "mid":
118
+ return unet.mid_block
119
+ kind, k = block_id.split(".")
120
+ return {"down": unet.down_blocks, "up": unet.up_blocks}[kind][int(k)]
121
+
122
+ def block_ids(self) -> list[str]:
123
+ unet = self.pipe.unet
124
+ return ([f"down.{k}" for k in range(len(unet.down_blocks))] + ["mid"]
125
+ + [f"up.{k}" for k in range(len(unet.up_blocks))])
126
+
127
+ def reads_text(self, block_id: str) -> bool:
128
+ return bool(getattr(self.block(block_id), "has_cross_attention", False))
129
+
130
+ def text_bend_note(self, s: Settings) -> str | None:
131
+ if s.bend_stream == "text" and not self.reads_text(s.bend_block):
132
+ return ("Dieser Block liest den Text nicht, er hat keine Cross-Attention. "
133
+ "Der Eingriff ändert deshalb nichts. Wählt einen anderen Block.")
134
+ return None
135
+
136
+ @contextmanager
137
+ def interventions(self, s: Settings, lat_h: int, lat_w: int, txt_len: int):
138
+ """R8 and R9 as in the FLUX engine, plus the tools of Tab 4."""
139
+ import tools_sd15
140
+
141
+ with super().interventions(s, lat_h, lat_w, txt_len), tools_sd15.apply(self, s) as notes:
142
+ self.run_notes += notes
143
+ yield
144
+
145
+ @contextmanager
146
+ def bending(self, s: Settings, lat_h: int, lat_w: int, txt_len: int):
147
+ """R8. Image stream: the block's output feature map. Text stream: the text the block attends to."""
148
+ if not s.bend_block or s.bend_op == "none" or s.bend_strength == 0:
149
+ yield
150
+ return
151
+ op, st, image = s.bend_op, float(s.bend_strength), s.bend_stream == "image"
152
+ if op not in E.BEND_OPS:
153
+ raise ValueError(f"unknown bending op {op!r}")
154
+ if not image and op in E.SPATIAL_OPS:
155
+ raise ValueError(f"{op} works on the image stream only")
156
+ if not image and not self.reads_text(s.bend_block):
157
+ yield # nothing to bend, render() adds a note
158
+ return
159
+ block = self.block(s.bend_block)
160
+ masks: dict[int, torch.Tensor] = {}
161
+ gen = torch.Generator(self.device).manual_seed(s.seed + E.SEED_BEND_NOISE) if op == "noise" else None
162
+ clock = self.clock
163
+
164
+ def mask(dim: int, device, dtype) -> torch.Tensor | None:
165
+ if op != "ablate":
166
+ return None
167
+ if dim not in masks: # fixed per call, one per channel count
168
+ off = torch.randperm(dim, generator=torch.Generator("cpu").manual_seed(s.seed + E.SEED_ABLATE))
169
+ m = torch.ones(dim)
170
+ m[off[:round(min(max(st, 0.0), 1.0) * dim)]] = 0.0 # typed values may leave 0..1
171
+ masks[dim] = m
172
+ return masks[dim].to(device, dtype)
173
+
174
+ def bend(h: torch.Tensor) -> torch.Tensor:
175
+ if h.dim() == 4: # feature map (B, C, H, W) as tokens (B, H*W, C)
176
+ b, c, hh, ww = h.shape
177
+ tokens = h.permute(0, 2, 3, 1).reshape(b, hh * ww, c)
178
+ out = E.bend_tensor(tokens, op, st, (hh, ww), mask(c, h.device, h.dtype), gen)
179
+ return out.reshape(b, hh, ww, c).permute(0, 3, 1, 2).contiguous()
180
+ return E.bend_tensor(h, op, st, None, mask(h.shape[-1], h.device, h.dtype), gen)
181
+
182
+ def active() -> bool:
183
+ return s.bend_from <= clock.progress <= s.bend_to
184
+
185
+ if image:
186
+ def hook(module, args, output):
187
+ if not active():
188
+ return None
189
+ if isinstance(output, tuple): # down blocks: (hidden states, skip connections)
190
+ return (bend(output[0]),) + tuple(output[1:])
191
+ return bend(output)
192
+
193
+ handle = block.register_forward_hook(hook)
194
+ else:
195
+ def pre_hook(module, args, kwargs):
196
+ if not active() or kwargs.get("encoder_hidden_states") is None:
197
+ return None
198
+ return args, {**kwargs, "encoder_hidden_states": bend(kwargs["encoder_hidden_states"])}
199
+
200
+ handle = block.register_forward_pre_hook(pre_hook, with_kwargs=True)
201
+ try:
202
+ yield
203
+ finally:
204
+ handle.remove()
205
+
206
+ # ---------------------------------------------------------------- loop
207
+
208
+ def denoise(self, s: Settings, cond: torch.Tensor, uncond: torch.Tensor, seeds: list[int],
209
+ guidances: list[float], on_step=None) -> torch.Tensor:
210
+ """Euler in sigma space for one chunk. Returns latents (n, 4, h, w) in float32."""
211
+ dev, N = self.device, s.steps
212
+ n = len(seeds)
213
+ lat_h, lat_w = s.height // 8, s.width // 8
214
+ noise = torch.stack([torch.randn((4, lat_h, lat_w), generator=torch.Generator("cpu").manual_seed(sd))
215
+ for sd in seeds]).to(dev) # float32, device independent
216
+ sched = self._Scheduler.from_config(self._scheduler_config) # fresh: the scheduler is stateful
217
+ sched.set_timesteps(N, device=dev)
218
+ sig = sched.sigmas.float().cpu().tolist() # N + 1 values ending in 0
219
+ lat = noise * sched.init_noise_sigma
220
+ n_run = max(1, round(N * s.stop_at))
221
+
222
+ enc = torch.cat([cond, uncond.expand(n, -1, -1)]).to(self.dtype)
223
+ g = torch.tensor(guidances, device=dev, dtype=torch.float32).view(-1, 1, 1, 1)
224
+ x0_pred = None
225
+ for i, t in enumerate(sched.timesteps[:n_run]):
226
+ self.clock.progress = i / N
227
+ sigma = sig[i]
228
+ t_model = float(t) * s.sigma_mult + s.sigma_offset * 1000 # R6: the model is told a different time
229
+ x = sched.scale_model_input(lat, t) # x / sqrt(sigma^2 + 1)
230
+ x = torch.cat([x, x]).to(self.dtype)
231
+ eps = self.pipe.unet(x, torch.full((2 * n,), t_model, device=dev), encoder_hidden_states=enc,
232
+ return_dict=False)[0].float()
233
+ e_c, e_u = eps.chunk(2)
234
+ eps = e_u + g * (e_c - e_u) # R3: per-sample guidance
235
+ x0_pred = lat - sigma * eps
236
+ lat = sched.step(eps, t, lat, return_dict=False)[0] # x + (sigma_next - sigma) * eps
237
+ for fn in self.post_step: # Tab 4, e.g. the mirror
238
+ lat = fn(lat)
239
+ if on_step is not None:
240
+ on_step()
241
+ return x0_pred if (s.show_x0 and n_run < N) else lat
242
+
243
+ def decode(self, final: torch.Tensor, lat_h: int, lat_w: int) -> tuple[list[Image.Image], list[bool]]:
244
+ vae = self.pipe.vae
245
+ n = final.shape[0]
246
+ finite = torch.isfinite(final).flatten(1).all(1).tolist()
247
+ lat = torch.nan_to_num(final.float(), 0.0, 0.0, 0.0) / vae.config.scaling_factor
248
+ per_call = max(1, DECODE_PIXELS // (lat_h * lat_w * 64))
249
+ images = []
250
+ for k in range(0, n, per_call):
251
+ img = vae.decode(lat[k:k + per_call].to(vae.dtype), return_dict=False)[0]
252
+ img = torch.nan_to_num(img.float(), 0.0, 0.0, 0.0)
253
+ images += self.pipe.image_processor.postprocess(img, output_type="pil",
254
+ do_denormalize=[True] * img.shape[0])
255
+ return images, finite
family.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model families: one app, two engines. MODEL_FAMILY picks SD 1.5 (default) or FLUX.2 [klein] 4B Base.
2
+
3
+ Everything that differs between the models lives here: defaults, the block catalogue, the rules'
4
+ wording and the slider ranges. The engines are in engine.py and engine_sd15.py.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from dataclasses import dataclass, field
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Family:
15
+ key: str
16
+ model_id: str
17
+ default_size: int
18
+ default_steps: int
19
+ grid_n: int
20
+ max_batch: int # images per forward pass at default_size (CFG doubles it)
21
+ max_seq: int # text length the encoder pads to
22
+ g_legal: tuple[float, float] # legal guidance range in Tab 1
23
+ g_default: float
24
+ standard_layers: tuple # reading depth of the text encoder (R5)
25
+ layer_presets: dict
26
+ blocks: list # [(label, block id)] for R8 and R9
27
+ text_blocks: frozenset # blocks whose text stream can be bent
28
+ bend_max: dict # slider maxima per op, 1.0 otherwise
29
+ size_rule: tuple | None # legal width and height range (R1), None = rule dropped
30
+ encoder: str # name in the recipe
31
+ latent_channels: int
32
+ latent_factor: int # pixels per latent position
33
+ rule_texts: dict = field(default_factory=dict) # wording that differs per family
34
+ prompts: tuple = ("", "")
35
+ sec_per_image: float = 1.0 # GPU time per image at the defaults, for the grid size hint
36
+ english_hint: bool = False # show "Prompts am besten auf Englisch."
37
+
38
+
39
+ def _flux_blocks() -> list:
40
+ out = [(f"Getrennte Ströme {k + 1}" + (" (früh)" if k == 0 else ""), f"double.{k}") for k in range(5)]
41
+ out += [(f"Gemeinsamer Strom {k + 1}" + (" (spät)" if k == 19 else ""), f"single.{k}") for k in range(20)]
42
+ return out
43
+
44
+
45
+ FLUX2 = Family(
46
+ key="flux2",
47
+ model_id="black-forest-labs/FLUX.2-klein-base-4B",
48
+ default_size=512, default_steps=20, grid_n=4, max_batch=9, max_seq=512,
49
+ g_legal=(2.0, 7.0), g_default=4.0,
50
+ standard_layers=(9, 18, 27),
51
+ layer_presets={
52
+ "Standard (9, 18, 27)": (9, 18, 27),
53
+ "Vertauscht (27, 18, 9)": (27, 18, 9),
54
+ "Flach (2, 3, 4)": (2, 3, 4),
55
+ "Tief (33, 34, 35)": (33, 34, 35),
56
+ "Dreimal dieselbe (18, 18, 18)": (18, 18, 18),
57
+ },
58
+ blocks=_flux_blocks(),
59
+ # The transformer drops the text tokens after its last block.
60
+ text_blocks=frozenset(b for _, b in _flux_blocks() if b != "single.19"),
61
+ # From the strength calibration: beyond these the image is only noise.
62
+ bend_max={"invert": 0.6, "noise": 0.3},
63
+ size_rule=None, # R1 dropped: no visible degradation from 128 px to 8:1
64
+ encoder="qwen3", latent_channels=128, latent_factor=16,
65
+ rule_texts={"R5": "Der Text-Encoder wird in den Schichten 9, 18 und 27 gelesen"},
66
+ prompts=("ein roter Fuchs im frischen Schnee", "eine Kathedrale aus Glas"),
67
+ sec_per_image=3.3, # L40S: 9 images in 30 s
68
+ )
69
+
70
+ SD15 = Family(
71
+ key="sd15",
72
+ model_id="stable-diffusion-v1-5/stable-diffusion-v1-5",
73
+ default_size=512, default_steps=25, grid_n=9, max_batch=9, max_seq=77,
74
+ g_legal=(5.0, 10.0), g_default=7.5, # below 5 blurry, from 15 oversaturated
75
+ standard_layers=(12,),
76
+ layer_presets={
77
+ "Standard (12, die letzte)": (12,),
78
+ "Vorletzte (11)": (11,),
79
+ "Mitte (6)": (6,),
80
+ "Flach (2)": (2,),
81
+ "Nur die Wort-Embeddings (0)": (0,),
82
+ },
83
+ blocks=[("Abwärts 1 (fein)", "down.0"), ("Abwärts 2", "down.1"), ("Abwärts 3", "down.2"),
84
+ ("Abwärts 4 (grob)", "down.3"), ("Mitte (am gröbsten)", "mid"), ("Aufwärts 1 (grob)", "up.0"),
85
+ ("Aufwärts 2", "up.1"), ("Aufwärts 3", "up.2"), ("Aufwärts 4 (fein)", "up.3")],
86
+ # Only blocks with cross-attention read the text.
87
+ text_blocks=frozenset({"down.0", "down.1", "down.2", "mid", "up.1", "up.2", "up.3"}),
88
+ # The UNet's skip connections absorb most bends, so every op keeps the full range.
89
+ # Only "Aufwärts 4", right before the output, breaks early (from about 0.1).
90
+ bend_max={},
91
+ size_rule=(384, 640), # 256 px turns abstract, from 768 px subjects repeat
92
+ encoder="clip", latent_channels=4, latent_factor=8,
93
+ rule_texts={"R1": "Die Bildgröße bleibt im trainierten Bereich (um 512 px)",
94
+ "R5": "Der Text-Encoder wird in seiner letzten Schicht gelesen"},
95
+ prompts=("a red fox in fresh snow", "a cathedral made of glass"),
96
+ sec_per_image=0.5, # RTX 4090: 36 images in 17.4 s at 25 steps
97
+ english_hint=True, # CLIP reads English. German prompts lose details ("gelber Regenschirm").
98
+ )
99
+
100
+ FAMILIES = {f.key: f for f in (FLUX2, SD15)}
101
+ ACTIVE = FAMILIES[os.environ.get("MODEL_FAMILY", "sd15")]
measure.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """What a bend changed: the first image's activations at every UNet block, step by step, against the
2
+ same render without tools.
3
+
4
+ The recorder keeps a strided sample of each block's output (at most 320 channels on a 16 x 16 grid),
5
+ for the first image's prompt half of the batch, and the first latent after every sampler step. It is
6
+ installed inside the engine's interventions, after the tools, so it sees what the tools left behind
7
+ (a frozen block's cached output, the mirrored latent).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from contextlib import contextmanager
14
+
15
+ import torch
16
+
17
+ BLOCK_PATHS = {"d0": "down_blocks.0", "d1": "down_blocks.1", "d2": "down_blocks.2", "d3": "down_blocks.3",
18
+ "mid": "mid_block", "u0": "up_blocks.0", "u1": "up_blocks.1", "u2": "up_blocks.2",
19
+ "u3": "up_blocks.3"}
20
+ MAX_CHANNELS, MAX_SIDE = 320, 16
21
+
22
+
23
+ def sample(t: torch.Tensor) -> torch.Tensor:
24
+ """Strided sample of one feature map (C, H, W): neighbouring pixels are skipped, not averaged,
25
+ so fine-grained changes (noise, quantisation) still count."""
26
+ c, h, w = t.shape
27
+ return t[:: math.ceil(c / MAX_CHANNELS), :: math.ceil(h / MAX_SIDE), :: math.ceil(w / MAX_SIDE)]
28
+
29
+
30
+ class Recorder:
31
+ """Activations of the first image during the first chunk of one render call."""
32
+
33
+ def __init__(self, steps: int):
34
+ self.steps = steps
35
+ self.calls = 0
36
+ self.acts: dict[str, list] = {b: [] for b in BLOCK_PATHS}
37
+ self.latents: list = []
38
+
39
+ def _tick(self, module, args):
40
+ self.calls += 1
41
+
42
+ def _grab(self, name):
43
+ def hook(module, args, output):
44
+ if self.calls <= self.steps: # later chunks hold other images
45
+ t = output[0] if isinstance(output, tuple) else output
46
+ self.acts[name].append(sample(t[0].detach()).to(torch.float16))
47
+ return hook
48
+
49
+ def _latent(self, lat):
50
+ if len(self.latents) < self.steps:
51
+ self.latents.append(sample(lat[0].detach()).to(torch.float16))
52
+ return lat
53
+
54
+ @contextmanager
55
+ def attached(self, engine):
56
+ unet = engine.pipe.unet
57
+ modules = dict(unet.named_modules())
58
+ handles = [unet.register_forward_pre_hook(self._tick)]
59
+ handles += [modules[path].register_forward_hook(self._grab(name)) for name, path in BLOCK_PATHS.items()]
60
+ engine.post_step.append(self._latent)
61
+ try:
62
+ yield self
63
+ finally:
64
+ for h in handles:
65
+ h.remove()
66
+ engine.post_step.remove(self._latent)
67
+
68
+ def tensors(self) -> dict:
69
+ """{"d0": (steps, c, h, w), ..., "latent": (steps, 4, h, w)} on the CPU."""
70
+ out = {name: torch.stack(v).cpu() for name, v in self.acts.items() if v}
71
+ if self.latents:
72
+ out["latent"] = torch.stack(self.latents).cpu()
73
+ return out
74
+
75
+
76
+ @contextmanager
77
+ def recording(engine, rec: Recorder):
78
+ """Run engine.render with the recorder attached inside the interventions, after the tools."""
79
+ inner = engine.interventions
80
+
81
+ @contextmanager
82
+ def interventions(*args, **kwargs):
83
+ with inner(*args, **kwargs), rec.attached(engine):
84
+ yield
85
+
86
+ engine.interventions = interventions
87
+ try:
88
+ yield rec
89
+ finally:
90
+ del engine.interventions # the class method again
91
+
92
+
93
+ def relative(bent: torch.Tensor, plain: torch.Tensor) -> list[float]:
94
+ """|bent - plain| / |plain| per step (first dimension)."""
95
+ b, p = bent.float().flatten(1), plain.float().flatten(1)
96
+ n = min(len(b), len(p))
97
+ diff = (b[:n] - p[:n]).norm(dim=1) / p[:n].norm(dim=1).clamp_min(1e-6)
98
+ return [round(float(x), 4) if math.isfinite(float(x)) else 9.99 for x in diff]
99
+
100
+
101
+ def effect(plain: dict, bent: dict, threshold: float = 1e-3) -> dict:
102
+ """Per block: the relative change at every step and at the first step where anything changed.
103
+
104
+ The first changed step shows where the bend enters: the latent going in is still the same, so
105
+ only the blocks at and after the bend differ. From the next step on everything differs."""
106
+ blocks = {name: relative(bent[name], plain[name]) for name in BLOCK_PATHS if name in bent and name in plain}
107
+ steps = max((len(v) for v in blocks.values()), default=0)
108
+ first = next((i for i in range(steps) if any(v[i] > threshold for v in blocks.values() if i < len(v))), None)
109
+ return {
110
+ "steps": steps,
111
+ "blocks": blocks,
112
+ "latent": relative(bent["latent"], plain["latent"]) if "latent" in bent and "latent" in plain else [],
113
+ "first": first,
114
+ "impact": {name: (v[first] if first is not None and first < len(v) else 0.0) for name, v in blocks.items()},
115
+ }
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ fonts-dejavu-core
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ torch==2.10.0
2
+ diffusers==0.42.1
3
+ transformers==5.22.1
4
+ accelerate
5
+ safetensors
6
+ numpy
7
+ Pillow
safety.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optional output filter.
2
+
3
+ BFL encourages deployers of the 4B models to add NSFW mitigations. Their FLUX.2 code ships no
4
+ classifier (checked 2026-11-01: only an invisible watermark, unused in the CLI), so we use the one
5
+ their FLUX.1 CLI uses, with the same threshold.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import threading
12
+
13
+ from PIL import Image, ImageDraw
14
+
15
+ SAFETY_FILTER = os.environ.get("SAFETY_FILTER", "1") == "1"
16
+ THRESHOLD = float(os.environ.get("SAFETY_THRESHOLD", "0.85")) # FLUX.1 CLI: NSFW_THRESHOLD = 0.85
17
+ MODEL = os.environ.get("SAFETY_MODEL", "Falconsai/nsfw_image_detection")
18
+ HIDDEN_CAPTION = "(vom Filter ausgeblendet)"
19
+
20
+ _classifier = None
21
+ _lock = threading.Lock()
22
+
23
+
24
+ def classifier():
25
+ global _classifier
26
+ with _lock:
27
+ if _classifier is None:
28
+ import torch
29
+ from transformers import pipeline
30
+
31
+ _classifier = pipeline("image-classification", model=MODEL,
32
+ device=0 if torch.cuda.is_available() else -1)
33
+ return _classifier
34
+
35
+
36
+ def nsfw_scores(images: list[Image.Image]) -> list[float]:
37
+ """Probability of the "nsfw" label for each image."""
38
+ out = classifier()([im.convert("RGB") for im in images], top_k=None)
39
+ return [next((r["score"] for r in res if r["label"].lower() == "nsfw"), 0.0) for res in out]
40
+
41
+
42
+ def grey_tile(size: tuple[int, int]) -> Image.Image:
43
+ img = Image.new("RGB", size, (150, 154, 162))
44
+ d = ImageDraw.Draw(img)
45
+ d.line([(0, 0), size], fill=(170, 174, 182), width=3)
46
+ d.line([(0, size[1]), (size[0], 0)], fill=(170, 174, 182), width=3)
47
+ return img
48
+
49
+
50
+ def filter_items(items: list[tuple[Image.Image, str]], log=print) -> tuple[list[tuple[Image.Image, str]], int]:
51
+ """Replace flagged images with a grey tile. Returns the new items and how many were hidden."""
52
+ if not SAFETY_FILTER or not items:
53
+ return items, 0
54
+ scores = nsfw_scores([im for im, _ in items])
55
+ log("[safety] nsfw scores " + " ".join(f"{s:.3f}" for s in scores) + f" (threshold {THRESHOLD})")
56
+ out, hidden = [], 0
57
+ for (im, caption), score in zip(items, scores):
58
+ if score >= THRESHOLD:
59
+ out.append((grey_tile(im.size), f"{caption} {HIDDEN_CAPTION}"))
60
+ hidden += 1
61
+ else:
62
+ out.append((im, caption))
63
+ return out, hidden
sites.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Where each tool acts in Stable Diffusion 1.5: the sites the map in the app lights up.
2
+
3
+ Site names:
4
+ prompt, tok, pos, clip, ctx text side: prompt, token table, position table, CLIP, context
5
+ ctx_word, ctx_pad the context vectors of one word, and of the end and padding tokens
6
+ promptB the second prompt ("layered")
7
+ d0..d3, mid, u0..u3 UNet blocks (Abwärts 1-4, Mitte, Aufwärts 1-4), each with
8
+ .R ResNets .S self-attention .X cross-attention .out the block's output
9
+ skip.u0..skip.u3 the skip connections an up block reads
10
+ latent the latent x_t between two sampler steps
11
+ vae the VAE decoder
12
+
13
+ SITES is written by hand so the map can say it in words. tests/test_sites.py installs every tool on a
14
+ UNet with SD 1.5's layout and checks the table against the modules the tool actually changed.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+
21
+ import tools_sd15 as T
22
+
23
+ BLOCKS = ("d0", "d1", "d2", "d3", "mid", "u0", "u1", "u2", "u3")
24
+ ATTN_BLOCKS = ("d0", "d1", "d2", "mid", "u1", "u2", "u3") # down.3 and up.0 have no attention
25
+ DOWN_ATTN, UP_ATTN = ("d0", "d1", "d2"), ("u1", "u2", "u3")
26
+ TEXT_SITES = ("prompt", "tok", "pos", "clip", "ctx", "ctx_word", "ctx_pad", "promptB")
27
+
28
+
29
+ def _each(kind: str, blocks=ATTN_BLOCKS) -> tuple:
30
+ return tuple(f"{b}.{kind}" for b in blocks)
31
+
32
+
33
+ SITES = { # (tool, place) -> sites; "" for tools without places
34
+ ("excise", "word_pad"): ("ctx_word", "ctx_pad") + _each("X"),
35
+ ("excise", "word"): ("ctx_word",) + _each("X"),
36
+ ("layered", "up"): ("promptB",) + _each("X", UP_ATTN),
37
+ ("layered", "down"): ("promptB",) + _each("X", DOWN_ATTN),
38
+ ("layered", "mid"): ("promptB", "mid.X"),
39
+ ("positions", ""): ("pos",),
40
+ ("blind", "up"): _each("X", UP_ATTN),
41
+ ("blind", "all"): _each("X"),
42
+ ("erosion", ""): _each("X"),
43
+ ("temperature", "self"): _each("S"),
44
+ ("temperature", "coarse"): ("d2.S", "d2.X", "mid.S", "mid.X", "u1.S", "u1.X"),
45
+ ("temperature", "cross"): _each("X"),
46
+ ("skips", "mid_res"): ("skip.u1", "skip.u2"),
47
+ ("skips", "coarse"): ("skip.u0", "skip.u1"),
48
+ ("mirror", "h"): ("latent",),
49
+ ("mirror", "v"): ("latent",),
50
+ ("mirror", "both"): ("latent",),
51
+ ("freeze", "mid_up1"): ("mid.out", "u1.out"),
52
+ ("freeze", "mid"): ("mid.out",),
53
+ ("boil", ""): _each("R", ("d0", "d1", "d2", "d3")) + _each("S", DOWN_ATTN) + _each("X", DOWN_ATTN),
54
+ ("norm", "up3"): ("u3.R",),
55
+ ("norm", "up2"): ("u2.R",),
56
+ ("vae", ""): ("vae",),
57
+ }
58
+
59
+ ALL_SITES = (TEXT_SITES + tuple(f"{b}.{k}" for b in BLOCKS for k in ("R", "S", "X", "out"))
60
+ + tuple(f"skip.u{j}" for j in range(4)) + ("latent", "vae"))
61
+
62
+
63
+ def places(key: str) -> list[str]:
64
+ """The tool's places, [""] for a tool without places."""
65
+ return [v for _, v in T.TOOLS[key].places] or [""]
66
+
67
+
68
+ def sites(key: str, place: str = "") -> tuple:
69
+ """Where the tool acts at that place (its first place when the place is unknown)."""
70
+ if place not in places(key):
71
+ place = places(key)[0]
72
+ return SITES[(key, place)]
73
+
74
+
75
+ # ---------------------------------------------------------------- module names -> sites
76
+
77
+ _BLOCK = re.compile(r"^(down_blocks\.(\d)|mid_block|up_blocks\.(\d))(.*)$")
78
+
79
+
80
+ def block_of(path: str) -> tuple[str, str] | None:
81
+ """("d1", rest) for "down_blocks.1.rest", ("mid", rest), ("u2", rest); None outside the blocks."""
82
+ m = _BLOCK.match(path)
83
+ if not m:
84
+ return None
85
+ if m.group(2) is not None:
86
+ return f"d{m.group(2)}", m.group(4)
87
+ if m.group(3) is not None:
88
+ return f"u{m.group(3)}", m.group(4)
89
+ return "mid", m.group(4)
90
+
91
+
92
+ def unet_site(path: str, hook: str) -> tuple:
93
+ """Sites for a UNet module that a tool changed. hook: "forward", "pre" or "processor"."""
94
+ found = block_of(path)
95
+ if found is None:
96
+ return ()
97
+ blk, rest = found
98
+ if rest == "":
99
+ return (f"skip.{blk}",) if hook == "pre" and blk.startswith("u") else (f"{blk}.out",)
100
+ if ".resnets." in rest + ".":
101
+ return (f"{blk}.R",)
102
+ if rest.endswith("attn1"):
103
+ return (f"{blk}.S",)
104
+ if rest.endswith("attn2") or ".attn2." in rest:
105
+ return (f"{blk}.X",)
106
+ if re.fullmatch(r"\.attentions\.\d+", rest): # a whole transformer: self- and cross-attention
107
+ return (f"{blk}.S", f"{blk}.X")
108
+ return ()
tools_sd15.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tab 4 "Biegen": tools from the Neural_Bending lab (~/ai/neural_nodes), ported to the SD 1.5 engine.
2
+
3
+ Each tool takes one of Neural_Bending's presets and reduces it to one knob, a place where it applies
4
+ and a window in the schedule. The presets' targets and numbers are the starting points; the defaults
5
+ here come from the calibration sheets in bench_out_sd15/tools/.
6
+
7
+ apply(engine, s) installs everything for one render call and removes it on any exit:
8
+ forward hooks, attention processors, weight edits and steps run after every sampler step.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from contextlib import ExitStack, contextmanager
15
+ from dataclasses import dataclass
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+
20
+ SEED_TOOLS = 11 # offset from the seed for the tools' own noise
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ToolUse:
25
+ """One tool in one slot of Tab 4."""
26
+
27
+ key: str
28
+ value: float # the tool's knob
29
+ place: str = "" # where it applies, one of the tool's places
30
+ start: float = 0.0 # window as fraction of the schedule
31
+ end: float = 1.0
32
+ word: str = "" # "excise" only
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Tool:
37
+ key: str
38
+ label: str
39
+ group: str
40
+ what: str # one or two sentences for the participants
41
+ knob: str # the knob's label
42
+ lo: float # slider range; typed values may go beyond it
43
+ hi: float
44
+ default: float
45
+ step: float
46
+ neutral: float # the knob value that changes nothing
47
+ rule: str # the rule this tool breaks
48
+ places: tuple = () # (label, value)
49
+ window: tuple | None = (0.0, 1.0) # default window, None = the tool has no window
50
+ preset: str = "" # the Neural_Bending preset it comes from
51
+ place_defaults: tuple = () # (place, knob, start, end) where a place needs other values
52
+
53
+ def defaults_for(self, place: str) -> tuple[float, float, float]:
54
+ """Knob and window that suit a place (the calibration sheets in bench_out_sd15/tools/)."""
55
+ for p, value, start, end in self.place_defaults:
56
+ if p == place:
57
+ return value, start, end
58
+ start, end = self.window or (0.0, 1.0)
59
+ return self.default, start, end
60
+
61
+
62
+ TOOLS = {t.key: t for t in [
63
+ # ------------------------------------------------ Semantik
64
+ Tool("excise", "Wort herausschneiden", "Semantik",
65
+ "Nimmt ein Wort aus dem Prompt heraus, aber erst im Bildnetz: Die Quer-Aufmerksamkeit darf es nicht "
66
+ "mehr ansehen. CLIP hat das Wort schon in die Füllpositionen nach dem Prompt kopiert, deshalb wirkt "
67
+ "es erst ganz, wenn auch das Polster maskiert ist. Negative Werte betonen das Wort.",
68
+ "Stärke", -2.0, 1.0, 1.0, 0.05, 0.0, "R8",
69
+ places=(("Wort und Polster", "word_pad"), ("Nur das Wort", "word")), preset="word-excision"),
70
+ Tool("layered", "Zweiter Prompt für die Oberfläche", "Semantik",
71
+ "Prompt A entscheidet, was das Bild zeigt und wo es steht. Einzelne Schichten des Bildnetzes hören "
72
+ "stattdessen Prompt B: im Aufwärtsweg entscheidet B, woraus das Ding gemacht ist.",
73
+ "Anteil von Prompt B", 0.0, 1.0, 1.0, 0.05, 0.0, "R4",
74
+ places=(("Aufwärtsweg (Material)", "up"), ("Abwärtsweg", "down"),
75
+ ("Nur die Mitte (Identität)", "mid")), preset="layered-prompt"),
76
+ Tool("positions", "Wortreihenfolge vergessen", "Semantik",
77
+ "Löscht CLIPs Positionstabelle: Der Prompt kommt als Wortsack an. Die Dinge bleiben, aber die "
78
+ "Eigenschaften wandern zu den falschen Wörtern (der rote Hut wird blau).",
79
+ "Stärke", 0.0, 1.0, 1.0, 0.05, 0.0, "R9", window=None, preset="positional-amnesia"),
80
+ Tool("blind", "Prompt weg ab …", "Semantik",
81
+ "Ab diesem Punkt hört das Bildnetz den Prompt nicht mehr. Bildausschnitt, Pose und Licht stehen "
82
+ "dann schon fest, den Rest malt das Modell aus seinem Gedächtnis.",
83
+ "Ab (%)", 0.0, 100.0, 25.0, 5.0, 100.0, "R8",
84
+ places=(("Aufwärtsweg", "up"), ("Überall", "all")), window=None, preset="prompt-blind-late"),
85
+ Tool("erosion", "Spektrale Erosion", "Semantik",
86
+ "Schneidet jede Abbildung von Wörtern auf Bildmerkmale auf ihre stärksten Richtungen zurück. Das Bild "
87
+ "bleibt fotografisch, wird aber allgemein: Eigenschaften rutschen zum nächsten Nachbarn.",
88
+ "Behaltener Anteil (%)", 2.0, 100.0, 12.0, 1.0, 100.0, "R9", window=None, preset="spectral-erosion"),
89
+ # ------------------------------------------------ Komposition
90
+ Tool("temperature", "Aufmerksamkeit: Nebel und Messer", "Komposition",
91
+ "Die Temperatur der Aufmerksamkeit. Über 1 schaut jede Stelle überallhin, das Bild löst sich in Nebel "
92
+ "auf, der die alte Pose hält. Unter 1 kopiert jede Stelle nur noch ihren besten Treffer: in den groben "
93
+ "Blöcken flache, harte Flächen wie ausgeschnitten, überall angewandt nur Konfetti.",
94
+ "Temperatur", 0.1, 8.0, 4.0, 0.05, 1.0, "R8",
95
+ places=(("Selbst-Aufmerksamkeit überall", "self"), ("Grobe Blöcke (Messer)", "coarse"),
96
+ ("Quer-Aufmerksamkeit (Text)", "cross")), window=(0.2, 1.0), preset="attention-fog",
97
+ place_defaults=(("coarse", 0.25, 0.0, 1.0), ("cross", 3.0, 0.0, 1.0))),
98
+ Tool("skips", "Skip-Verbindungen", "Komposition",
99
+ "Die Abkürzungen der U-Form tragen das Gedächtnis des Abwärtswegs zum Aufwärtsweg. Verstärkt wachsen "
100
+ "überall geätzte Strukturen, gekappt erfindet das Netz Oberflächen aus der Bedeutung allein.",
101
+ "Verstärkung", 0.0, 3.0, 2.5, 0.05, 1.0, "R8",
102
+ places=(("Mittlere Auflösung (Aufwärts 2 und 3)", "mid_res"), ("Grob (Aufwärts 1 und 2)", "coarse")),
103
+ preset="skip-flood"),
104
+ Tool("mirror", "Symmetrie-Gefängnis", "Komposition",
105
+ "Nach jedem Schritt wird eine Hälfte des Bildes mit dem Spiegelbild der anderen überschrieben. Das "
106
+ "Modell will die Symmetrie brechen und darf nicht.",
107
+ "Stärke", 0.0, 1.0, 0.3, 0.05, 0.0, "R8",
108
+ places=(("Links und rechts", "h"), ("Oben und unten", "v"), ("Vierfach", "both")),
109
+ preset="symmetry-prison", place_defaults=(("v", 0.1, 0.0, 1.0), ("both", 0.2, 0.0, 1.0))),
110
+ Tool("freeze", "Eingefroren", "Komposition",
111
+ "Die groben Blöcke entscheiden früh und dürfen danach nicht mehr umdenken, während die feinen weiter "
112
+ "arbeiten: liebevoll gemalte Details auf einem unfertigen Entwurf.",
113
+ "Eingefroren ab (%)", 0.0, 100.0, 8.0, 1.0, 100.0, "R8",
114
+ places=(("Mitte und Aufwärts 2", "mid_up1"), ("Nur die Mitte", "mid")), window=None,
115
+ preset="frozen-in-thought"),
116
+ # ------------------------------------------------ Oberfläche
117
+ Tool("boil", "Kochen", "Oberfläche",
118
+ "Rauschen im ganzen Abwärtsweg, bei jedem Schritt neu: Nichts setzt sich, die Oberflächen köcheln.",
119
+ "Rauschen", 0.0, 1.0, 0.3, 0.01, 0.0, "R8", preset="boiling"),
120
+ Tool("norm", "Norm-Kollaps", "Oberfläche",
121
+ "Schaltet die Normalisierung in einer Schicht ab: Kontrast und Farbe laufen davon, das Motiv bleibt "
122
+ "lesbar.",
123
+ "Stärke", 0.0, 1.0, 1.0, 0.05, 0.0, "R8",
124
+ places=(("Aufwärts 4 (grün)", "up3"), ("Aufwärts 3 (orange)", "up2")), preset="norm-collapse"),
125
+ Tool("vae", "VAE-Fieber", "Oberfläche",
126
+ "Das Entrauschen läuft sauber, nur der Decoder, der das Ergebnis in Pixel übersetzt, rechnet mit "
127
+ "groben Gewichten. Gleiche Szene, falsche Farben.",
128
+ "Bits (weniger = gröber)", 2.0, 8.0, 3.0, 1.0, 16.0, "R9", window=None, preset="vae-fever"),
129
+ ]}
130
+
131
+ TOOL_CHOICES = [("Kein Eingriff", "none")] + [(f"{t.group} · {t.label}", t.key) for t in TOOLS.values()]
132
+
133
+
134
+ def active(u: ToolUse) -> bool:
135
+ return u.key in TOOLS and u.value != TOOLS[u.key].neutral
136
+
137
+
138
+ def place_of(u: ToolUse) -> str:
139
+ """The tool's place, its first place when none or an unknown one is given."""
140
+ places = [v for _, v in TOOLS[u.key].places]
141
+ return u.place if u.place in places else (places[0] if places else "")
142
+
143
+
144
+ def place_label(u: ToolUse) -> str:
145
+ return dict((v, k) for k, v in TOOLS[u.key].places).get(place_of(u), "")
146
+
147
+
148
+ # ---------------------------------------------------------------- attention
149
+
150
+
151
+ class ToolAttnProcessor:
152
+ """SD 1.5's attention with the tools' changes, on PyTorch's fused attention (no maps in memory).
153
+
154
+ mods: dicts with a window "on" and any of: "temperature", "bias" (additive key bias for the
155
+ cond half, cross-attention only), "context" (replacement context for the cond half, with
156
+ weight "mix"), "gain" (factor on the output).
157
+ """
158
+
159
+ def __init__(self, mods: list, clock):
160
+ self.mods, self.clock = mods, clock
161
+
162
+ def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None,
163
+ *args, **kwargs):
164
+ cross = encoder_hidden_states is not None
165
+ live = [m for m in self.mods if m["on"](self.clock.progress)]
166
+ ctx = encoder_hidden_states if cross else hidden_states
167
+ b = hidden_states.shape[0]
168
+ half = b // 2 # the batch is [cond; uncond]
169
+ temperature, bias, gain = 1.0, None, 1.0
170
+ for m in live:
171
+ temperature *= m.get("temperature", 1.0)
172
+ gain *= m.get("gain", 1.0)
173
+ if cross and "context" in m:
174
+ ctx = ctx.clone()
175
+ alt = m["context"].to(ctx.dtype).expand(half, -1, -1)
176
+ ctx[:half] = torch.lerp(ctx[:half], alt, m["mix"]) if m["mix"] != 1.0 else alt
177
+ if cross and "bias" in m:
178
+ bias = m["bias"] if bias is None else bias + m["bias"]
179
+ q, k, v = attn.to_q(hidden_states), attn.to_k(ctx), attn.to_v(ctx)
180
+ heads = attn.heads
181
+ d = k.shape[-1] // heads
182
+ q, k, v = (t.view(b, -1, heads, d).transpose(1, 2) for t in (q, k, v))
183
+ mask = None
184
+ if bias is not None: # (Lk,) on the cond half, nothing on uncond
185
+ mask = torch.zeros(b, 1, 1, k.shape[2], device=q.device, dtype=q.dtype)
186
+ mask[:half, 0, 0] = bias.to(q.dtype)
187
+ scale = attn.scale / _safe_temperature(temperature)
188
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=scale)
189
+ out = out.transpose(1, 2).reshape(b, -1, heads * d).to(q.dtype)
190
+ out = attn.to_out[1](attn.to_out[0](out))
191
+ return out * gain if gain != 1.0 else out
192
+
193
+
194
+ def _safe_temperature(t: float) -> float:
195
+ """Typed temperatures may be negative (attend to the least similar), but never zero."""
196
+ return math.copysign(max(abs(t), 0.02), t if t != 0 else 1.0)
197
+
198
+
199
+ def _attention_modules(unet, kind: str, blocks: list) -> list:
200
+ """kind "attn1" (self) or "attn2" (cross), inside the given UNet blocks."""
201
+ return [m for blk in blocks for name, m in blk.named_modules() if name.endswith(kind)]
202
+
203
+
204
+ # ---------------------------------------------------------------- the tools
205
+
206
+
207
+ @contextmanager
208
+ def apply(engine, s):
209
+ """Every active tool of s.tools for one render call. Removes all of it on any exit."""
210
+ uses = [u for u in getattr(s, "tools", ()) if active(u)]
211
+ if not uses:
212
+ yield []
213
+ return
214
+ unet = engine.pipe.unet
215
+ notes: list[str] = []
216
+ attn_mods: dict = {} # Attention module -> list of mods
217
+ with ExitStack() as stack:
218
+ for i, u in enumerate(uses):
219
+ _install(engine, s, u, i, stack, attn_mods, notes)
220
+ originals = {}
221
+ for module, mods in attn_mods.items():
222
+ originals[module] = module.processor
223
+ module.set_processor(ToolAttnProcessor(mods, engine.clock))
224
+ stack.callback(_restore_processors, originals)
225
+ yield notes
226
+
227
+
228
+ def _restore_processors(originals: dict) -> None:
229
+ for module, proc in originals.items():
230
+ module.set_processor(proc)
231
+
232
+
233
+ def _window(u: ToolUse):
234
+ tool = TOOLS[u.key]
235
+ if tool.window is None:
236
+ return lambda p: True
237
+ return lambda p: u.start <= p <= u.end
238
+
239
+
240
+ def _install(engine, s, u: ToolUse, i: int, stack: ExitStack, attn_mods: dict, notes: list) -> None:
241
+ unet, place, on = engine.pipe.unet, place_of(u), _window(u)
242
+ ups, downs = list(unet.up_blocks), list(unet.down_blocks)
243
+
244
+ def add_attn(modules, mod):
245
+ for m in modules:
246
+ attn_mods.setdefault(m, []).append(mod)
247
+
248
+ def hook(module, fn, pre=False):
249
+ h = (module.register_forward_pre_hook(fn, with_kwargs=True) if pre
250
+ else module.register_forward_hook(fn))
251
+ stack.callback(h.remove)
252
+
253
+ if u.key == "excise":
254
+ positions = word_positions(engine, s.prompt_a, u.word)
255
+ if not positions:
256
+ notes.append(f"„{u.word.strip()}“ kommt in Prompt A nicht vor, „Wort herausschneiden“ ändert nichts."
257
+ if u.word.strip() else "Für „Wort herausschneiden“ fehlt das Wort.")
258
+ return
259
+ if place == "word_pad": # CLIP copied the word into the end token and padding
260
+ n = len(engine.pipe.tokenizer(s.prompt_a, add_special_tokens=False).input_ids)
261
+ positions = positions + list(range(1 + n, engine.pipe.tokenizer.model_max_length))
262
+ keep = 1.0 - u.value # 0 removes, above 1 emphasises
263
+ bias = torch.zeros(engine.pipe.tokenizer.model_max_length, device=engine.device)
264
+ bias[positions] = math.log(keep) if keep > 0 else float("-inf")
265
+ add_attn(_attention_modules(unet, "attn2", [unet]), {"on": on, "bias": bias})
266
+
267
+ elif u.key == "layered":
268
+ alt = engine.encode(s.prompt_b, s.te_layers, 77).to(engine.device)
269
+ blocks = ups if place == "up" else downs if place == "down" else [unet.mid_block]
270
+ add_attn(_attention_modules(unet, "attn2", blocks), {"on": on, "context": alt, "mix": float(u.value)})
271
+
272
+ elif u.key == "positions":
273
+ emb = engine.pipe.text_encoder
274
+ emb = (emb.embeddings if hasattr(emb, "embeddings") else emb.text_model.embeddings).position_embedding
275
+ _edit_weight(stack, emb.weight, lambda w: w * (1.0 - u.value))
276
+ _tag_encodings(engine, stack, f"positions={u.value}")
277
+
278
+ elif u.key == "blind":
279
+ start = u.value / 100.0
280
+ blocks = ups if place == "up" else [unet]
281
+ add_attn(_attention_modules(unet, "attn2", blocks), {"on": lambda p: p >= start, "gain": 0.0})
282
+
283
+ elif u.key == "erosion":
284
+ keep = min(max(u.value / 100.0, 0.0), 1.0)
285
+ for m in _attention_modules(unet, "attn2", [unet]):
286
+ for lin in (m.to_q, m.to_k, m.to_v, m.to_out[0]):
287
+ _edit_weight(stack, lin.weight, lambda w: _svd_keep(w, keep))
288
+
289
+ elif u.key == "temperature":
290
+ if place == "self":
291
+ modules = _attention_modules(unet, "attn1", [unet])
292
+ elif place == "coarse": # Neural_Bending's attention-knife blocks
293
+ blocks = [downs[2], unet.mid_block, ups[1]]
294
+ modules = _attention_modules(unet, "attn1", blocks) + _attention_modules(unet, "attn2", blocks)
295
+ else:
296
+ modules = _attention_modules(unet, "attn2", [unet])
297
+ add_attn(modules, {"on": on, "temperature": float(u.value)})
298
+
299
+ elif u.key == "skips":
300
+ blocks = [ups[1], ups[2]] if place == "mid_res" else [ups[0], ups[1]]
301
+ g = float(u.value)
302
+
303
+ def scale_skips(module, args, kwargs):
304
+ if not on(engine.clock.progress) or "res_hidden_states_tuple" not in kwargs:
305
+ return None
306
+ return args, {**kwargs, "res_hidden_states_tuple": tuple(r * g for r in kwargs["res_hidden_states_tuple"])}
307
+
308
+ for blk in blocks:
309
+ hook(blk, scale_skips, pre=True)
310
+
311
+ elif u.key == "mirror":
312
+ w = float(u.value)
313
+
314
+ def mirror(lat):
315
+ if not on(engine.clock.progress):
316
+ return lat
317
+ out = lat.clone()
318
+ h, wd = lat.shape[-2:]
319
+ if place in ("h", "both"):
320
+ out[..., wd - wd // 2:] = torch.flip(out[..., : wd // 2], dims=[-1])
321
+ if place in ("v", "both"):
322
+ out[..., h - h // 2:, :] = torch.flip(out[..., : h // 2, :], dims=[-2])
323
+ return torch.lerp(lat, out, w) if w != 1.0 else out
324
+
325
+ engine.post_step.append(mirror)
326
+ stack.callback(engine.post_step.remove, mirror)
327
+
328
+ elif u.key == "freeze":
329
+ at = u.value / 100.0
330
+ blocks = [unet.mid_block, ups[1]] if place == "mid_up1" else [unet.mid_block]
331
+ for blk in blocks:
332
+ memo: dict = {}
333
+
334
+ def fossil(module, args, output, memo=memo):
335
+ t = output[0] if isinstance(output, tuple) else output
336
+ if engine.clock.progress <= at or "t" not in memo or memo["t"].shape != t.shape:
337
+ memo["t"] = t.detach().clone() # still live: the cache ends at the freezing step
338
+ return None
339
+ return (memo["t"],) + tuple(output[1:]) if isinstance(output, tuple) else memo["t"]
340
+
341
+ hook(blk, fossil)
342
+
343
+ elif u.key == "boil":
344
+ sigma = float(u.value)
345
+ gen = torch.Generator(engine.device).manual_seed(s.seed + SEED_TOOLS + i)
346
+
347
+ def simmer(module, args, output):
348
+ if not on(engine.clock.progress):
349
+ return None
350
+ t = output[0] if isinstance(output, tuple) else output
351
+ half = t.shape[0] // 2 # cond only, so guidance amplifies it
352
+ z = torch.randn(t[:half].shape, generator=gen, device=t.device, dtype=torch.float32)
353
+ t = t.clone()
354
+ t[:half] = t[:half] + (sigma * t[:half].float().std() * z).to(t.dtype)
355
+ return (t,) + tuple(output[1:]) if isinstance(output, tuple) else t
356
+
357
+ for blk in downs:
358
+ for m in list(blk.resnets) + list(getattr(blk, "attentions", None) or []):
359
+ hook(m, simmer)
360
+
361
+ elif u.key == "norm":
362
+ blk = ups[3] if place == "up3" else ups[2]
363
+ w = float(u.value)
364
+
365
+ def unnormed(module, args, output):
366
+ if not on(engine.clock.progress):
367
+ return None
368
+ return torch.lerp(output, args[0], w) if w != 1.0 else args[0].clone()
369
+
370
+ for res in blk.resnets:
371
+ hook(res.norm1, unnormed)
372
+
373
+ elif u.key == "vae":
374
+ bits = max(1, round(u.value))
375
+ if bits < 16:
376
+ for m in engine.pipe.vae.decoder.modules():
377
+ if isinstance(m, torch.nn.Conv2d):
378
+ _edit_weight(stack, m.weight, lambda w: _quantize(w, bits))
379
+
380
+
381
+ def _edit_weight(stack: ExitStack, p: torch.Tensor, fn) -> None:
382
+ """Replace a weight for this call, restore the exact original afterwards."""
383
+ original = p.detach().clone()
384
+ with torch.no_grad():
385
+ p.copy_(fn(original.float()).to(p.dtype))
386
+
387
+ def restore():
388
+ with torch.no_grad():
389
+ p.copy_(original)
390
+
391
+ stack.callback(restore)
392
+
393
+
394
+ def _tag_encodings(engine, stack: ExitStack, tag: str) -> None:
395
+ """Encodings made with a changed CLIP must not land in, or come from, the plain cache."""
396
+ previous = engine.encode_tag
397
+ engine.encode_tag = f"{previous}|{tag}"
398
+ stack.callback(setattr, engine, "encode_tag", previous)
399
+
400
+
401
+ def _svd_keep(w: torch.Tensor, keep: float) -> torch.Tensor:
402
+ u, sv, vh = torch.linalg.svd(w, full_matrices=False)
403
+ r = max(1, round(keep * sv.numel()))
404
+ return (u[:, :r] * sv[:r]) @ vh[:r]
405
+
406
+
407
+ def _quantize(w: torch.Tensor, bits: int) -> torch.Tensor:
408
+ """Uniform quantisation over the tensor's own range, as in Neural_Bending's weight_quantize."""
409
+ levels = float((1 << bits) - 1)
410
+ lo, hi = w.min(), w.max()
411
+ span = (hi - lo).clamp_min(1e-12)
412
+ return ((w - lo) / span * levels).round() / levels * span + lo
413
+
414
+
415
+ def word_positions(engine, prompt: str, word: str) -> list[int]:
416
+ """Token positions of `word` in the prompt (start token = position 0). Every occurrence."""
417
+ word = (word or "").strip()
418
+ if not word:
419
+ return []
420
+ tok = engine.pipe.tokenizer
421
+ ids = tok(prompt, add_special_tokens=False).input_ids
422
+ target = tok(word, add_special_tokens=False).input_ids
423
+ hits = []
424
+ for k in range(len(ids) - len(target) + 1):
425
+ if ids[k:k + len(target)] == target:
426
+ hits += [1 + k + j for j in range(len(target))]
427
+ return [p for p in hits if p < tok.model_max_length - 1]