Instructions to use arlaz/modular-flux123-multidiffusion with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use arlaz/modular-flux123-multidiffusion with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("arlaz/modular-flux123-multidiffusion", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
Fix windowing bugs and simplify the blocks, runners and docs
Browse filesBug fixes, each with a regression test:
- Wrapped panorama axes with a window offset could leave cells uncovered;
the window grid now adds the window that reaches across the seam.
- FLUX.2 reference crops mapped every reference onto the largest grid; each
reference is now cropped on its own grid.
- The FLUX.2 timestep shift no longer clamps the window sequence length, so
a canvas-sized window gets the upstream schedule.
- `export-hf --push-to-hub` refused every folder inside the checkout; it now
only refuses the checkout root and its model/ folders (hf_export/ ignored).
- The local runner accepts the *ModularPipeline class names of the exported
model/ folders for FLUX.1 and FLUX.2.
- `--lora-path` gets PEFT from the examples extra.
Behaviour changes: `--terra-scale`, `--quantize` and `--lora_path` are
removed; `--window-batch-size` is validated at parse time; FLUX 3 layout
`boxes` with regional prompts raise; `--guidance-scale` on CFG families
keeps the loaded guider config (`guider.new`).
Cleanup: one shared run path for both runners and one model-kind lookup;
the window-loop core owns the captured state, the regional inputs, the
window ids and box, and the denoise sub-block names; a shared top-level
blocks base; a shorter panorama decode and geometry helpers; fewer
defensive getattr defaults and dead parameters. Exported metadata is
unchanged. README, examples/README and AGENTS.md follow the code: verified
quick-start, per-family defaults, pipeline inputs and window rules.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- .gitignore +3 -0
- AGENTS.md +7 -6
- README.md +120 -202
- examples/README.md +49 -32
- examples/example.py +131 -253
- examples/example_remote.py +8 -118
- multidiffusion/composition.py +14 -1
- multidiffusion/flux1.py +9 -32
- multidiffusion/flux2.py +34 -83
- multidiffusion/flux3.py +45 -72
- multidiffusion/geometry.py +78 -111
- multidiffusion/panorama.py +19 -108
- multidiffusion/steps.py +6 -7
- multidiffusion/window_loop.py +101 -173
- pyproject.toml +3 -2
- repository.py +28 -56
- tests/test_denoiser_equivalence.py +32 -0
- tests/test_example_runner.py +55 -121
- tests/test_export.py +18 -7
- tests/test_windowing.py +46 -0
|
@@ -43,3 +43,6 @@ artifacts/
|
|
| 43 |
|
| 44 |
uv.lock.tmp
|
| 45 |
uv.lock
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
uv.lock.tmp
|
| 45 |
uv.lock
|
| 46 |
+
|
| 47 |
+
# standalone Hub exports (`multidiff-modular export-hf hf_export ...`)
|
| 48 |
+
hf_export/
|
|
@@ -3,19 +3,20 @@
|
|
| 3 |
## Project Structure & Module Organization
|
| 4 |
|
| 5 |
This is a Python 3.14 package (`.python-version` pins 3.14.10) for FLUX.1, FLUX.2 and FLUX 3 MultiDiffusion blocks using
|
| 6 |
-
Hugging Face Modular Diffusers 0.42.
|
| 7 |
|
| 8 |
- `block.py`: root Hugging Face remote-code entry point. It only imports and re-exports the blocks; keep it importing
|
| 9 |
every module of `multidiffusion/` as `from .multidiffusion.<module> import ...`, because the Hub loader copies only
|
| 10 |
the modules imported there. It is not importable locally; local code imports `multidiffusion`.
|
| 11 |
- `multidiffusion/`: the implementation. `geometry.py`, `window_loop.py`, `steps.py`, `panorama.py` and
|
| 12 |
-
`composition.py` are shared; `flux1.py`, `flux2.py`
|
| 13 |
-
top-level
|
| 14 |
which the Hub loader resolves from the repo root.
|
| 15 |
- `repository.py`: family selection and Hugging Face export helpers.
|
| 16 |
- `cli.py`: `multidiff-modular` command implementation.
|
| 17 |
-
- `examples/`: runnable scripts. `example.py`
|
| 18 |
-
|
|
|
|
| 19 |
- `tests/`: pytest suite covering blocks, windowing, export metadata, runner wiring, and inference smoke tests.
|
| 20 |
- `config.json`, `modular_config.json`, `modular_model_index.json`: generated Hub metadata. Regenerate them with the export command instead of editing by hand.
|
| 21 |
|
|
@@ -39,7 +40,7 @@ Use Ruff for linting and formatting with a 120-character line length. Prefer typ
|
|
| 39 |
|
| 40 |
Every edit must account for Modular Diffusers block composition, not only isolated functions. Before changing denoising, img2img, image conditioning, scheduling, export, or family-selection code, check how blocks are combined through workflows, auto blocks, `_workflow_map`, and `PipelineState`. Preserve upstream block contracts and add regression tests for changes that affect block ordering, replacement, or shared state.
|
| 41 |
|
| 42 |
-
Upstream auto blocks share module-level sub-block instances, so the builders edit a deep copy; never mutate upstream blocks in place. FLUX.1 and FLUX.2 denoisers read block-state attributes while FLUX 3 denoisers read the `denoiser_input_fields` dict: a family's window-loop mixin declares the state it swaps (`
|
| 43 |
|
| 44 |
## Testing Guidelines
|
| 45 |
|
|
|
|
| 3 |
## Project Structure & Module Organization
|
| 4 |
|
| 5 |
This is a Python 3.14 package (`.python-version` pins 3.14.10) for FLUX.1, FLUX.2 and FLUX 3 MultiDiffusion blocks using
|
| 6 |
+
Hugging Face Modular Diffusers 0.42.1.
|
| 7 |
|
| 8 |
- `block.py`: root Hugging Face remote-code entry point. It only imports and re-exports the blocks; keep it importing
|
| 9 |
every module of `multidiffusion/` as `from .multidiffusion.<module> import ...`, because the Hub loader copies only
|
| 10 |
the modules imported there. It is not importable locally; local code imports `multidiffusion`.
|
| 11 |
- `multidiffusion/`: the implementation. `geometry.py`, `window_loop.py`, `steps.py`, `panorama.py` and
|
| 12 |
+
`composition.py` (with the `MultiDiffusionAutoBlocks` base of the top-level blocks) are shared; `flux1.py`, `flux2.py`
|
| 13 |
+
and `flux3.py` hold one family each (blocks, builder, top-level blocks). Modules import each other as `from . import <module>`, never `from .<module> import ...`,
|
| 14 |
which the Hub loader resolves from the repo root.
|
| 15 |
- `repository.py`: family selection and Hugging Face export helpers.
|
| 16 |
- `cli.py`: `multidiff-modular` command implementation.
|
| 17 |
+
- `examples/`: runnable scripts. `example.py` builds the blocks from the local `multidiffusion` package;
|
| 18 |
+
`example_remote.py` loads the Hub `block.py` (root default family, or `--family`); both share `example.run`.
|
| 19 |
+
- `scripts/`: wrappers running the `export-hf` and `inspect-panorama` commands without installing the project.
|
| 20 |
- `tests/`: pytest suite covering blocks, windowing, export metadata, runner wiring, and inference smoke tests.
|
| 21 |
- `config.json`, `modular_config.json`, `modular_model_index.json`: generated Hub metadata. Regenerate them with the export command instead of editing by hand.
|
| 22 |
|
|
|
|
| 40 |
|
| 41 |
Every edit must account for Modular Diffusers block composition, not only isolated functions. Before changing denoising, img2img, image conditioning, scheduling, export, or family-selection code, check how blocks are combined through workflows, auto blocks, `_workflow_map`, and `PipelineState`. Preserve upstream block contracts and add regression tests for changes that affect block ordering, replacement, or shared state.
|
| 42 |
|
| 43 |
+
Upstream auto blocks share module-level sub-block instances, so the builders edit a deep copy; never mutate upstream blocks in place. FLUX.1 and FLUX.2 denoisers read block-state attributes while FLUX 3 denoisers read the `denoiser_input_fields` dict: a family's window-loop mixin declares the state it swaps (`_md_item_keys`, `_md_regional_keys`, plus the other keys its hooks touch in `_md_state_keys`) and its `_md_*` hooks. Keep new MultiDiffusion state out of `kwargs_type="denoiser_input_fields"`. `tests/test_denoiser_equivalence.py` must stay green: it compares every MultiDiffusion denoise step with its upstream step on tiny random transformers.
|
| 44 |
|
| 45 |
## Testing Guidelines
|
| 46 |
|
|
@@ -15,156 +15,103 @@ tags:
|
|
| 15 |
|
| 16 |
# FLUX.1 / FLUX.2 / FLUX 3 MultiDiffusion Modular Blocks
|
| 17 |
|
| 18 |
-
|
| 19 |
-
FLUX
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
access.
|
| 34 |
|
| 35 |
## Install
|
| 36 |
|
| 37 |
-
Python `3.14`
|
| 38 |
-
|
| 39 |
-
Development install with `uv`:
|
| 40 |
|
| 41 |
```bash
|
| 42 |
uv sync --all-extras
|
| 43 |
```
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
```bash
|
| 48 |
-
UV_CACHE_DIR=/private/tmp/uv-cache uv sync --all-extras
|
| 49 |
-
```
|
| 50 |
-
|
| 51 |
-
Editable install with `pip`:
|
| 52 |
-
|
| 53 |
-
```bash
|
| 54 |
-
python -m pip install -e ".[dev,examples,quantization]"
|
| 55 |
-
```
|
| 56 |
-
|
| 57 |
-
Minimal local install:
|
| 58 |
-
|
| 59 |
-
```bash
|
| 60 |
-
python -m pip install .
|
| 61 |
-
```
|
| 62 |
-
|
| 63 |
-
Optional extras:
|
| 64 |
|
| 65 |
- `dev`: pytest and ruff.
|
| 66 |
-
- `examples`: Pillow for
|
| 67 |
- `quantization`: TorchAO for `--quantization`.
|
| 68 |
|
|
|
|
|
|
|
|
|
|
| 69 |
## Remote Loading
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
|
|
|
| 73 |
|
| 74 |
```python
|
| 75 |
import torch
|
| 76 |
-
from diffusers import ComponentsManager,
|
| 77 |
|
| 78 |
repo_id = "arlaz/modular-flux123-multidiffusion"
|
| 79 |
|
| 80 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 81 |
-
dtype = torch.bfloat16 if device == "cuda" else torch.float32
|
| 82 |
-
|
| 83 |
-
if device == "cuda":
|
| 84 |
-
torch.backends.fp32_precision = "tf32"
|
| 85 |
-
torch.set_float32_matmul_precision("high")
|
| 86 |
-
|
| 87 |
manager = ComponentsManager()
|
| 88 |
-
|
| 89 |
-
manager.enable_auto_cpu_offload(device=device)
|
| 90 |
-
|
| 91 |
-
pipe = ModularPipeline.from_pretrained(
|
| 92 |
-
repo_id,
|
| 93 |
-
trust_remote_code=True,
|
| 94 |
-
components_manager=manager,
|
| 95 |
-
)
|
| 96 |
-
pipe.load_components(dtype=dtype)
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
|
| 102 |
prompt="a dense renaissance fresco",
|
| 103 |
height=1024,
|
| 104 |
-
width=
|
| 105 |
-
height_generation=
|
| 106 |
-
width_generation=
|
| 107 |
window_stride_height=512,
|
| 108 |
window_stride_width=512,
|
| 109 |
-
weighting_type="cosine",
|
| 110 |
-
num_inference_steps=1,
|
| 111 |
-
window_batch_size=1,
|
| 112 |
generator=torch.Generator().manual_seed(42),
|
| 113 |
-
)
|
| 114 |
-
|
| 115 |
-
out.images[0].save("remote_smoke_1024.png")
|
| 116 |
-
print(out.images[0].size)
|
| 117 |
```
|
| 118 |
|
| 119 |
-
Load another family from the same
|
| 120 |
|
| 121 |
```python
|
| 122 |
from diffusers.utils.dynamic_modules_utils import get_class_from_dynamic_module
|
| 123 |
|
| 124 |
blocks_cls = get_class_from_dynamic_module(
|
| 125 |
-
repo_id,
|
| 126 |
-
"block.py",
|
| 127 |
-
class_name="Flux1MultiDiffusionAutoBlocks",
|
| 128 |
-
trust_remote_code=True,
|
| 129 |
)
|
| 130 |
pipe = blocks_cls().init_pipeline("black-forest-labs/FLUX.1-schnell", components_manager=manager)
|
| 131 |
-
pipe.load_components(dtype=
|
| 132 |
-
```
|
| 133 |
-
|
| 134 |
-
Equivalent runner:
|
| 135 |
-
|
| 136 |
-
```bash
|
| 137 |
-
uv run python examples/example_remote.py \
|
| 138 |
-
--repo-id arlaz/modular-flux123-multidiffusion \
|
| 139 |
-
--prompt "a dense renaissance fresco" \
|
| 140 |
-
--height 1024 \
|
| 141 |
-
--width 1024 \
|
| 142 |
-
--height-generation 512 \
|
| 143 |
-
--width-generation 512 \
|
| 144 |
-
--window-stride-height 512 \
|
| 145 |
-
--window-stride-width 512 \
|
| 146 |
-
--num-inference-steps 1 \
|
| 147 |
-
--dtype bfloat16 \
|
| 148 |
-
--device cuda \
|
| 149 |
-
--output remote_smoke_1024.png
|
| 150 |
```
|
| 151 |
|
| 152 |
-
|
|
|
|
| 153 |
|
| 154 |
## Local Python Use
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
|
| 159 |
```python
|
| 160 |
import torch
|
| 161 |
from diffusers import ComponentsManager
|
| 162 |
-
|
|
|
|
| 163 |
|
| 164 |
manager = ComponentsManager()
|
| 165 |
manager.enable_auto_cpu_offload(device="cuda")
|
| 166 |
|
| 167 |
-
pipe =
|
| 168 |
pipe.load_components(dtype=torch.bfloat16)
|
| 169 |
|
| 170 |
image = pipe(
|
|
@@ -179,26 +126,47 @@ image = pipe(
|
|
| 179 |
).images[0]
|
| 180 |
```
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
## Families
|
| 186 |
|
| 187 |
-
| Family | Upstream model repo | Blocks | Upstream license |
|
| 188 |
-
| --- | --- | --- | --- |
|
| 189 |
-
| `flux1-dev` | `black-forest-labs/FLUX.1-dev` | `Flux1MultiDiffusionAutoBlocks` | FLUX.1 [dev] Non-Commercial, gated |
|
| 190 |
-
| `flux1-schnell` | `black-forest-labs/FLUX.1-schnell` | `Flux1MultiDiffusionAutoBlocks` | Apache-2.0, gated |
|
| 191 |
-
| `flux2-dev` | `black-forest-labs/FLUX.2-dev` | `Flux2DevMultiDiffusionAutoBlocks` | FLUX Non-Commercial, gated |
|
| 192 |
-
| `flux2-klein-4b` | `black-forest-labs/FLUX.2-klein-4B` | `Flux2KleinMultiDiffusionAutoBlocks` | Apache-2.0 |
|
| 193 |
-
| `flux2-klein-base-4b` | `black-forest-labs/FLUX.2-klein-base-4B` | `Flux2KleinBaseMultiDiffusionAutoBlocks` | Apache-2.0 |
|
| 194 |
-
| `flux2-klein-9b` | `black-forest-labs/FLUX.2-klein-9B` | `Flux2KleinMultiDiffusionAutoBlocks` | FLUX Non-Commercial, gated |
|
| 195 |
-
| `flux2-klein-base-9b` | `black-forest-labs/FLUX.2-klein-base-9B` | `Flux2KleinBaseMultiDiffusionAutoBlocks` | FLUX Non-Commercial, gated |
|
| 196 |
-
| `flux3-klein` | `black-forest-labs/flux-3-image-klein` | `Flux3KleinMultiDiffusionAutoBlocks` | FLUX Kommunity, gated |
|
| 197 |
-
| `flux3-klein-base` | `black-forest-labs/flux-3-image-klein-base` | `Flux3KleinBaseMultiDiffusionAutoBlocks` | FLUX Kommunity, gated |
|
| 198 |
-
|
| 199 |
-
The
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
### Feature Matrix
|
| 204 |
|
|
@@ -208,21 +176,25 @@ model licenses apply to the weights.
|
|
| 208 |
| Schedule shift from the window size | dev (schnell is static) | yes | not needed (constant shift) |
|
| 209 |
| Regional prompts with masks | yes | yes | yes, each regional prompt encoded on its own |
|
| 210 |
| Panorama wrap with circular VAE decode | yes | yes | yes |
|
| 211 |
-
| Img2img
|
| 212 |
| Reference image conditioning | no (Kontext is not covered) | yes, cropped per window | yes, cropped per window |
|
| 213 |
|
| 214 |
### FLUX 3 Notes
|
| 215 |
|
| 216 |
-
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
-
|
| 220 |
-
|
| 221 |
-
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
```python
|
| 228 |
from copy import deepcopy
|
|
@@ -242,106 +214,52 @@ For the distilled model, keep its 16-step default with `Flux3SetTimestepsStep(sh
|
|
| 242 |
|
| 243 |
## Export Metadata
|
| 244 |
|
| 245 |
-
Refresh the root default metadata:
|
| 246 |
|
| 247 |
```bash
|
| 248 |
uv run multidiff-modular export-hf . --family flux3-klein
|
| 249 |
-
```
|
| 250 |
-
|
| 251 |
-
Refresh a metadata-only family folder:
|
| 252 |
-
|
| 253 |
-
```bash
|
| 254 |
uv run multidiff-modular export-hf model/flux2-klein-base-9b --family flux2-klein-base-9b
|
| 255 |
```
|
| 256 |
|
| 257 |
-
|
| 258 |
-
generated JSON
|
|
|
|
| 259 |
|
| 260 |
```bash
|
| 261 |
-
uv run multidiff-modular export-hf hf_export --family flux2-klein-4b
|
| 262 |
```
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
```bash
|
| 268 |
-
uv run multidiff-modular export-hf hf_export \
|
| 269 |
-
--family flux2-klein-4b \
|
| 270 |
-
--repo-id <user>/<repo> \
|
| 271 |
-
--push-to-hub
|
| 272 |
-
```
|
| 273 |
-
|
| 274 |
-
Equivalent script wrappers:
|
| 275 |
-
|
| 276 |
-
```bash
|
| 277 |
-
uv run python scripts/export_hf_repo.py hf_export --family flux2-klein-4b
|
| 278 |
-
uv run python scripts/inspect_panorama.py panorama.png
|
| 279 |
-
```
|
| 280 |
-
|
| 281 |
-
## Code Layout
|
| 282 |
-
|
| 283 |
-
| Module | Contents |
|
| 284 |
-
| --- | --- |
|
| 285 |
-
| `multidiffusion/geometry.py` | Canvas layout, window grid and weights, reference crops, the window and panorama inputs |
|
| 286 |
-
| `multidiffusion/window_loop.py` | Per-step window preprocessing and the mixin that runs an upstream denoiser per window |
|
| 287 |
-
| `multidiffusion/steps.py` | Shared img2img and regional prompt split steps |
|
| 288 |
-
| `multidiffusion/panorama.py` | Circular-padding VAE decode |
|
| 289 |
-
| `multidiffusion/composition.py` | Helpers that edit a copy of the upstream auto blocks |
|
| 290 |
-
| `multidiffusion/flux1.py`, `flux2.py`, `flux3.py` | Each family's blocks, its builder and its top-level AutoBlocks |
|
| 291 |
-
|
| 292 |
-
The Hub loader only copies the modules that `block.py` imports as `from .multidiffusion.<module> import ...`, so
|
| 293 |
-
`block.py` imports every module of the package. Inside the package, modules import each other as
|
| 294 |
-
`from . import <module>`: the loader resolves `from .<module> import ...` from the repo root and would fail.
|
| 295 |
|
| 296 |
## Hugging Face Setup
|
| 297 |
|
| 298 |
-
No model weights are stored here
|
| 299 |
-
|
| 300 |
|
| 301 |
```bash
|
| 302 |
hf auth login
|
| 303 |
-
```
|
| 304 |
-
|
| 305 |
-
Prefill the cache for one upstream family:
|
| 306 |
-
|
| 307 |
-
```bash
|
| 308 |
hf download black-forest-labs/FLUX.2-klein-4B
|
| 309 |
```
|
| 310 |
|
| 311 |
-
|
| 312 |
-
model
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
- Tiled/windowed denoising over large canvases.
|
| 317 |
-
- Batched windows through `window_batch_size` or `--window-batch-size`.
|
| 318 |
-
- Regional prompting with grayscale masks blended during denoising.
|
| 319 |
-
- Panorama width/height wrapping plus circular VAE decode padding.
|
| 320 |
-
- Img2img, plus FLUX.2 and FLUX 3 reference image conditioning.
|
| 321 |
-
- Optional LoRA, TorchAO quantization, VAE tiling/slicing, TF32, and `torch.compile`.
|
| 322 |
-
|
| 323 |
-
All window and stride values must be positive and divisible by `vae_scale_factor * 2` (16 pixels for every family).
|
| 324 |
|
| 325 |
## Development
|
| 326 |
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
uv run ruff format --check .
|
| 331 |
-
uv run pytest -ra
|
| 332 |
-
uv run python -m compileall block.py multidiffusion repository.py cli.py examples scripts tests model
|
| 333 |
-
```
|
| 334 |
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
Real model smoke tests are opt-in. They load the repo root, or the family named by `MULTIDIFF_MODULAR_SMOKE_FAMILY`:
|
| 339 |
|
| 340 |
```bash
|
| 341 |
MULTIDIFF_MODULAR_RUN_REAL_INFERENCE=1 uv run pytest -ra
|
| 342 |
```
|
| 343 |
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
mounts the workspace, exposes NVIDIA GPUs, and shares the host Hugging Face cache.
|
|
|
|
| 15 |
|
| 16 |
# FLUX.1 / FLUX.2 / FLUX 3 MultiDiffusion Modular Blocks
|
| 17 |
|
| 18 |
+
Hugging Face Modular Diffusers blocks for MultiDiffusion with FLUX.1 dev and schnell, FLUX.2 dev and Klein, and
|
| 19 |
+
FLUX 3 Image Klein (base and distilled): windowed denoising of large canvases, batched windows, regional prompts with
|
| 20 |
+
masks, seamless panoramas, img2img and reference images.
|
| 21 |
|
| 22 |
+
| Path | Contents |
|
| 23 |
+
| --- | --- |
|
| 24 |
+
| `block.py` | Hub remote-code entry point; it imports and re-exports the blocks of `multidiffusion/` |
|
| 25 |
+
| `multidiffusion/geometry.py` | Canvas layout, window grid and weights, reference crops, the window and panorama inputs |
|
| 26 |
+
| `multidiffusion/window_loop.py` | Per-step window preprocessing and the mixin that runs an upstream denoiser per window |
|
| 27 |
+
| `multidiffusion/steps.py` | Shared img2img and regional prompt split steps |
|
| 28 |
+
| `multidiffusion/panorama.py` | Circular-padding VAE decode |
|
| 29 |
+
| `multidiffusion/composition.py` | The top-level blocks base class and the helpers that edit a copy of the upstream blocks |
|
| 30 |
+
| `multidiffusion/flux1.py`, `flux2.py`, `flux3.py` | Each family's blocks, its builder and its top-level blocks |
|
| 31 |
+
| `repository.py`, `cli.py` | Family selection, Hub export helpers and the `multidiff-modular` command |
|
| 32 |
+
| `model/<family>/` | Generated metadata JSON for every family |
|
| 33 |
+
| `examples/` | Local and remote generation runners, see [examples/README.md](examples/README.md) |
|
|
|
|
| 34 |
|
| 35 |
## Install
|
| 36 |
|
| 37 |
+
Python `3.14` (`.python-version` pins `3.14.10`) with Diffusers `0.42.1`:
|
|
|
|
|
|
|
| 38 |
|
| 39 |
```bash
|
| 40 |
uv sync --all-extras
|
| 41 |
```
|
| 42 |
|
| 43 |
+
or `python -m pip install -e ".[dev,examples,quantization]"`. Extras:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
- `dev`: pytest and ruff.
|
| 46 |
+
- `examples`: Pillow for images and masks, PEFT for `--lora-path`.
|
| 47 |
- `quantization`: TorchAO for `--quantization`.
|
| 48 |
|
| 49 |
+
`export-hf` copies `block.py` and `multidiffusion/` from the checkout, so it needs a checkout (`uv sync` or
|
| 50 |
+
`pip install -e .`), not a plain `pip install .`.
|
| 51 |
+
|
| 52 |
## Remote Loading
|
| 53 |
|
| 54 |
+
The quickest test needs no checkout: it loads the blocks from the root `block.py` with `trust_remote_code=True`. You
|
| 55 |
+
need `diffusers>=0.42.1,<0.43`, `transformers>=5.2`, `torch`, `accelerate`, and `torchvision>=0.22` for FLUX 3, plus
|
| 56 |
+
access to the gated upstream weights (accept their licenses on the Hub). The root default family is `flux3-klein`.
|
| 57 |
|
| 58 |
```python
|
| 59 |
import torch
|
| 60 |
+
from diffusers import ComponentsManager, ModularPipelineBlocks
|
| 61 |
|
| 62 |
repo_id = "arlaz/modular-flux123-multidiffusion"
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
manager = ComponentsManager()
|
| 65 |
+
manager.enable_auto_cpu_offload(device="cuda")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
blocks = ModularPipelineBlocks.from_pretrained(repo_id, trust_remote_code=True)
|
| 68 |
+
blocks.sub_blocks.pop("prompt_upsampler") # optional: skip the 9B FLUX 3 prompt upsampler
|
| 69 |
+
pipe = blocks.init_pipeline(repo_id, components_manager=manager)
|
| 70 |
+
pipe.load_components(dtype=torch.bfloat16)
|
| 71 |
|
| 72 |
+
image = pipe(
|
| 73 |
prompt="a dense renaissance fresco",
|
| 74 |
height=1024,
|
| 75 |
+
width=2048,
|
| 76 |
+
height_generation=1024,
|
| 77 |
+
width_generation=1024,
|
| 78 |
window_stride_height=512,
|
| 79 |
window_stride_width=512,
|
|
|
|
|
|
|
|
|
|
| 80 |
generator=torch.Generator().manual_seed(42),
|
| 81 |
+
).images[0]
|
| 82 |
+
image.save("remote_smoke.png")
|
|
|
|
|
|
|
| 83 |
```
|
| 84 |
|
| 85 |
+
Load another family from the same `block.py`, then point it at its upstream model repo:
|
| 86 |
|
| 87 |
```python
|
| 88 |
from diffusers.utils.dynamic_modules_utils import get_class_from_dynamic_module
|
| 89 |
|
| 90 |
blocks_cls = get_class_from_dynamic_module(
|
| 91 |
+
repo_id, "block.py", class_name="Flux1MultiDiffusionAutoBlocks", trust_remote_code=True
|
|
|
|
|
|
|
|
|
|
| 92 |
)
|
| 93 |
pipe = blocks_cls().init_pipeline("black-forest-labs/FLUX.1-schnell", components_manager=manager)
|
| 94 |
+
pipe.load_components(dtype=torch.bfloat16)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
```
|
| 96 |
|
| 97 |
+
The runner equivalent, `examples/example_remote.py --repo-id ... [--family <family>]`, needs this checkout installed;
|
| 98 |
+
see [examples/README.md](examples/README.md#remote-hub-run).
|
| 99 |
|
| 100 |
## Local Python Use
|
| 101 |
|
| 102 |
+
From a checkout, import the blocks from the `multidiffusion` package (root `block.py` is only the Hub entry point), or
|
| 103 |
+
build a family's pipeline on its upstream repo with `repository.build_pipeline`:
|
| 104 |
|
| 105 |
```python
|
| 106 |
import torch
|
| 107 |
from diffusers import ComponentsManager
|
| 108 |
+
|
| 109 |
+
from repository import build_pipeline
|
| 110 |
|
| 111 |
manager = ComponentsManager()
|
| 112 |
manager.enable_auto_cpu_offload(device="cuda")
|
| 113 |
|
| 114 |
+
pipe = build_pipeline("flux2-klein-4b", components_manager=manager)
|
| 115 |
pipe.load_components(dtype=torch.bfloat16)
|
| 116 |
|
| 117 |
image = pipe(
|
|
|
|
| 126 |
).images[0]
|
| 127 |
```
|
| 128 |
|
| 129 |
+
### Pipeline Inputs
|
| 130 |
+
|
| 131 |
+
| Input | Meaning |
|
| 132 |
+
| --- | --- |
|
| 133 |
+
| `height`, `width` | The output canvas in pixels. |
|
| 134 |
+
| `height_generation`, `width_generation` | The denoiser window; defaults to the full canvas. |
|
| 135 |
+
| `window_stride_height`, `window_stride_width` | Distance between windows; defaults to half the window. |
|
| 136 |
+
| `window_stride_height_offset`, `window_stride_width_offset` | Shift of the window grid added at every step. |
|
| 137 |
+
| `weighting_type`, `weighting_range` | Window blending: `"cosine"` (default), `"linear"` or `"none"`; the ramp length as a fraction of the window, defaulting to stride / window. |
|
| 138 |
+
| `window_batch_size` | Windows sent to the transformer at once (default 1). |
|
| 139 |
+
| `panorama_width`, `panorama_height` | Wrap the canvas so its opposite edges join seamlessly. |
|
| 140 |
+
| `prompt=["", p1, ..., pN]` + `regional_masks` | Regional prompts: a fallback prompt plus one prompt per mask; `regional_masks` is `(N, height // 16, width // 16)` and must cover every cell. |
|
| 141 |
+
| `image_img2img` + `strength` | Img2img source as packed, normalized latents shaped like `latents` (the runners build them from an image with `examples.example.prepare_img2img_latents`); `strength` below `1.0` keeps part of the source. |
|
| 142 |
+
| `image` | FLUX.2 and FLUX 3 reference images, cropped per window. |
|
| 143 |
+
|
| 144 |
+
Window sizes, strides and offsets must be multiples of `vae_scale_factor * 2` (16 px for every family); sizes and
|
| 145 |
+
strides must be positive, offsets non-negative, the window at most the canvas and the stride at most the window.
|
| 146 |
|
| 147 |
## Families
|
| 148 |
|
| 149 |
+
| Family | Upstream model repo | Blocks | Default steps | Guidance | Upstream license |
|
| 150 |
+
| --- | --- | --- | --- | --- | --- |
|
| 151 |
+
| `flux1-dev` | `black-forest-labs/FLUX.1-dev` | `Flux1MultiDiffusionAutoBlocks` | 50 | embedded, 3.5 | FLUX.1 [dev] Non-Commercial, gated |
|
| 152 |
+
| `flux1-schnell` | `black-forest-labs/FLUX.1-schnell` | `Flux1MultiDiffusionAutoBlocks` | 50 (runners: 4) | none | Apache-2.0, gated |
|
| 153 |
+
| `flux2-dev` | `black-forest-labs/FLUX.2-dev` | `Flux2DevMultiDiffusionAutoBlocks` | 50 | embedded, 4.0 | FLUX Non-Commercial, gated |
|
| 154 |
+
| `flux2-klein-4b` | `black-forest-labs/FLUX.2-klein-4B` | `Flux2KleinMultiDiffusionAutoBlocks` | 50 (runners: 4) | none | Apache-2.0 |
|
| 155 |
+
| `flux2-klein-base-4b` | `black-forest-labs/FLUX.2-klein-base-4B` | `Flux2KleinBaseMultiDiffusionAutoBlocks` | 50 | CFG, 4.0 | Apache-2.0 |
|
| 156 |
+
| `flux2-klein-9b` | `black-forest-labs/FLUX.2-klein-9B` | `Flux2KleinMultiDiffusionAutoBlocks` | 50 (runners: 4) | none | FLUX Non-Commercial, gated |
|
| 157 |
+
| `flux2-klein-base-9b` | `black-forest-labs/FLUX.2-klein-base-9B` | `Flux2KleinBaseMultiDiffusionAutoBlocks` | 50 | CFG, 4.0 | FLUX Non-Commercial, gated |
|
| 158 |
+
| `flux3-klein` | `black-forest-labs/flux-3-image-klein` | `Flux3KleinMultiDiffusionAutoBlocks` | 16 | none | FLUX Kommunity, gated |
|
| 159 |
+
| `flux3-klein-base` | `black-forest-labs/flux-3-image-klein-base` | `Flux3KleinBaseMultiDiffusionAutoBlocks` | 50 | CFG, 3.5 | FLUX Kommunity, gated |
|
| 160 |
+
|
| 161 |
+
- The step counts are the block defaults. The runners run FLUX.1 schnell and the distilled FLUX.2 Klein in 4 steps,
|
| 162 |
+
and schnell with `max_sequence_length=256`.
|
| 163 |
+
- In Python, pass `guidance_scale` to the embedded-guidance families (FLUX.1 dev, FLUX.2 dev). Swap the guider of the
|
| 164 |
+
CFG families with `pipe.update_components(guider=pipe.guider.new(guidance_scale=4.0))`. The runners do both for
|
| 165 |
+
`--guidance-scale`. The other families ignore it.
|
| 166 |
+
- Both FLUX 3 families also load the prompt upsampler from `black-forest-labs/flux-3-image-klein-pup` (Apache-2.0).
|
| 167 |
+
- The root metadata is the `flux3-klein` export, and `model/<family>/` holds the metadata of every family. Those
|
| 168 |
+
folders are not standalone remote-code repos.
|
| 169 |
+
- The code in this repo is Apache-2.0. The upstream model licenses apply to the weights.
|
| 170 |
|
| 171 |
### Feature Matrix
|
| 172 |
|
|
|
|
| 176 |
| Schedule shift from the window size | dev (schnell is static) | yes | not needed (constant shift) |
|
| 177 |
| Regional prompts with masks | yes | yes | yes, each regional prompt encoded on its own |
|
| 178 |
| Panorama wrap with circular VAE decode | yes | yes | yes |
|
| 179 |
+
| Img2img (`image_img2img` + `strength`) | yes; also the native `image` workflow in Python | yes | yes |
|
| 180 |
| Reference image conditioning | no (Kontext is not covered) | yes, cropped per window | yes, cropped per window |
|
| 181 |
|
| 182 |
### FLUX 3 Notes
|
| 183 |
|
| 184 |
+
- **Prompt upsampler:**
|
| 185 |
+
- By default it runs first, as Black Forest Labs recommends. It is a Qwen3.5-9B fine-tune.
|
| 186 |
+
- The Diffusers docs list about 39 GB in bf16 with it and about 20 GB without it.
|
| 187 |
+
- Skip it with `blocks.sub_blocks.pop("prompt_upsampler")` before `init_pipeline`, or with `--no-prompt-upsampler`
|
| 188 |
+
in the runners.
|
| 189 |
+
- **Regional prompts** (`prompt=["", p1, ..., pN]`): each regional prompt is upsampled and encoded on its own. Windows
|
| 190 |
+
are batched together only when their prompts have the same token length. The upsampler's layout `boxes` describe the
|
| 191 |
+
whole canvas, so they cannot be combined with regional prompts.
|
| 192 |
+
- **Reference images:** a single reference image is cropped back to its own box before it is mapped onto the canvas,
|
| 193 |
+
so give references the canvas aspect ratio.
|
| 194 |
+
- **Sampling defaults:**
|
| 195 |
+
- The blocks keep the Diffusers `0.42.1` defaults: a constant time shift of `6.93`, and CFG `3.5` for the base model.
|
| 196 |
+
- Change the CFG scale with the guider swap above.
|
| 197 |
+
- Change the shift by replacing the `set_timesteps` step before `init_pipeline`:
|
| 198 |
|
| 199 |
```python
|
| 200 |
from copy import deepcopy
|
|
|
|
| 214 |
|
| 215 |
## Export Metadata
|
| 216 |
|
| 217 |
+
Refresh the root default metadata, or a family folder:
|
| 218 |
|
| 219 |
```bash
|
| 220 |
uv run multidiff-modular export-hf . --family flux3-klein
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
uv run multidiff-modular export-hf model/flux2-klein-base-9b --family flux2-klein-base-9b
|
| 222 |
```
|
| 223 |
|
| 224 |
+
To create a standalone single-family Hub repo folder, run the command below. It copies root `block.py` and
|
| 225 |
+
`multidiffusion/` beside the generated JSON. With `--push-to-hub`, the folder is uploaded once all its files are
|
| 226 |
+
written. The checkout root and its `model/` folders are published with git instead.
|
| 227 |
|
| 228 |
```bash
|
| 229 |
+
uv run multidiff-modular export-hf hf_export --family flux2-klein-4b --repo-id <user>/<repo> --push-to-hub
|
| 230 |
```
|
| 231 |
|
| 232 |
+
The root README is copied as-is. Edit its default-family text in the export before publishing.
|
| 233 |
+
`scripts/export_hf_repo.py` runs the same command without installing the project.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
## Hugging Face Setup
|
| 236 |
|
| 237 |
+
No model weights are stored here: the components load from the upstream FLUX repos named in the metadata. Authenticate
|
| 238 |
+
before using gated models, and prefill the cache for offline runs:
|
| 239 |
|
| 240 |
```bash
|
| 241 |
hf auth login
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
hf download black-forest-labs/FLUX.2-klein-4B
|
| 243 |
```
|
| 244 |
|
| 245 |
+
`--local-files-only` needs every repo the run reads already cached:
|
| 246 |
+
- the upstream model repo;
|
| 247 |
+
- for FLUX 3, also `black-forest-labs/flux-3-image-klein-pup` (unless you pass `--no-prompt-upsampler`);
|
| 248 |
+
- for `example_remote.py`, also `arlaz/modular-flux123-multidiffusion` itself.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
## Development
|
| 251 |
|
| 252 |
+
Commands, conventions and the Modular Diffusers rules of this repo are in [AGENTS.md](AGENTS.md).
|
| 253 |
+
`tests/test_denoiser_equivalence.py` checks every MultiDiffusion denoise step against its upstream step, on tiny random
|
| 254 |
+
transformers on CPU.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
+
The real-model smoke test is opt-in and reads models from the local cache. It loads the repo root, or the family named
|
| 257 |
+
by `MULTIDIFF_MODULAR_SMOKE_FAMILY`:
|
|
|
|
|
|
|
| 258 |
|
| 259 |
```bash
|
| 260 |
MULTIDIFF_MODULAR_RUN_REAL_INFERENCE=1 uv run pytest -ra
|
| 261 |
```
|
| 262 |
|
| 263 |
+
The Ubuntu-based dev container (VS Code and PyCharm Dev Containers) mounts the workspace, exposes NVIDIA GPUs and
|
| 264 |
+
shares the host Hugging Face cache, `~/.cache/huggingface`, which must exist on the host. Run `uv sync --all-extras`
|
| 265 |
+
after opening it.
|
|
|
|
@@ -29,30 +29,35 @@ uv run python examples/example.py \
|
|
| 29 |
|
| 30 |
## Remote Hub Run
|
| 31 |
|
| 32 |
-
This is the easiest end-to-end test of the published repo:
|
| 33 |
|
| 34 |
```bash
|
| 35 |
uv run python examples/example_remote.py \
|
| 36 |
--repo-id arlaz/modular-flux123-multidiffusion \
|
| 37 |
--prompt "a dense renaissance fresco" \
|
| 38 |
--height 1024 \
|
| 39 |
-
--width
|
| 40 |
-
--height-generation
|
| 41 |
-
--width-generation
|
| 42 |
--window-stride-height 512 \
|
| 43 |
--window-stride-width 512 \
|
| 44 |
-
--
|
| 45 |
-
--
|
| 46 |
-
--device cuda \
|
| 47 |
-
--output remote_smoke_1024.png
|
| 48 |
```
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
## Model Families
|
| 54 |
|
| 55 |
-
`example.py` picks the blocks from the upstream repo passed to `--base-model`
|
|
|
|
| 56 |
|
| 57 |
```bash
|
| 58 |
# FLUX.1 schnell: 4 steps and a 256-token prompt by default
|
|
@@ -129,6 +134,8 @@ uv run python examples/example.py \
|
|
| 129 |
--enable-slicing
|
| 130 |
```
|
| 131 |
|
|
|
|
|
|
|
| 132 |
## Panorama Run
|
| 133 |
|
| 134 |
```bash
|
|
@@ -148,11 +155,11 @@ uv run python examples/example.py \
|
|
| 148 |
--output panorama.png
|
| 149 |
```
|
| 150 |
|
| 151 |
-
Inspect the wrapped seams
|
|
|
|
| 152 |
|
| 153 |
```bash
|
| 154 |
uv run multidiff-modular inspect-panorama panorama.png
|
| 155 |
-
uv run python scripts/inspect_panorama.py panorama.png
|
| 156 |
```
|
| 157 |
|
| 158 |
## Regional Prompting
|
|
@@ -199,8 +206,13 @@ uv run python examples/example.py \
|
|
| 199 |
|
| 200 |
## Img2Img
|
| 201 |
|
| 202 |
-
Every family encodes `--image-img2img` at the canvas size and renoises it with `--strength`
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
```bash
|
| 206 |
uv run python examples/example.py \
|
|
@@ -269,45 +281,50 @@ Model and loading:
|
|
| 269 |
- `--base-model`: upstream FLUX.1, FLUX.2 or FLUX 3 repo id or local model directory for `example.py`.
|
| 270 |
- `--repo-id`: exported Hub repo id or local exported repo path for `example_remote.py`.
|
| 271 |
- `--family`: `example_remote.py` only; load this family's blocks from the remote `block.py` instead of the root default.
|
| 272 |
-
- `--lora-path`
|
| 273 |
- `--local-files-only`: disable network fetches and use cached/local files only.
|
| 274 |
|
| 275 |
Inputs:
|
| 276 |
|
| 277 |
-
- `--prompt`: text prompt, or a CSV file with `mask,prompt` headers.
|
| 278 |
- `--masks`: mask folder used with prompt CSV files.
|
| 279 |
- `--image-img2img`: image path for img2img initialization.
|
| 280 |
- `--image-conditioning`: image path for FLUX.2 or FLUX 3 reference image conditioning.
|
| 281 |
-
- `--strength`: img2img renoising strength. Default: `1.0`.
|
| 282 |
|
| 283 |
Canvas and windowing:
|
| 284 |
|
| 285 |
-
- `--height`, `--width`: final canvas size in pixels.
|
| 286 |
-
- `--height-generation`, `--width-generation`: local denoising window size.
|
| 287 |
-
- `--window-stride-height`, `--window-stride-width`: sliding-window stride.
|
| 288 |
-
- `--window-stride-height-offset`, `--window-stride-width-offset`: per-step stride offset.
|
| 289 |
- `--panorama-width`, `--panorama-height`: wrap width and/or height.
|
| 290 |
-
- `--weighting-type`: `none`, `linear`, or `cosine`.
|
| 291 |
-
- `--weighting-range`: blend ramp
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
Inference:
|
| 294 |
|
| 295 |
-
- `--num-inference-steps`: denoising steps.
|
| 296 |
-
|
| 297 |
-
- `--
|
|
|
|
| 298 |
- `--seed`: generator seed. Default: `42`.
|
| 299 |
- `--num-images-per-prompt`: output count. Default: `1`.
|
| 300 |
-
- `--window-batch-size`: maximum window/regional work items per denoiser forward pass.
|
| 301 |
- `--no-prompt-upsampler`: FLUX 3 only; encode the prompt as given instead of upsampling it first.
|
| 302 |
|
| 303 |
Runtime:
|
| 304 |
|
| 305 |
-
- `--dtype`: `float16`, `bfloat16`, or `float32`.
|
| 306 |
-
- `--device`: torch device string. Default: `cuda`.
|
| 307 |
-
- `--output`: output path. Images larger than `4096 * 4096` pixels save as BigTIFF automatically.
|
| 308 |
- `--allow-tf32`: enable CUDA TF32 settings.
|
| 309 |
- `--compile`: compile repeated transformer blocks with `torch.compile`.
|
| 310 |
-
- `--quantization`: TorchAO strategy for the transformer, the text encoders, and the VAE
|
|
|
|
| 311 |
- `--transformer-quantization`, `--text-encoder-quantization`, `--vae-quantization`: component-specific overrides;
|
| 312 |
`--text-encoder-quantization` also covers the FLUX.1 T5 `text_encoder_2`.
|
| 313 |
- `--enable-tiling`: enable VAE tiling.
|
|
|
|
| 29 |
|
| 30 |
## Remote Hub Run
|
| 31 |
|
| 32 |
+
This is the easiest end-to-end test of the published repo. It runs the root default family, `flux3-klein`:
|
| 33 |
|
| 34 |
```bash
|
| 35 |
uv run python examples/example_remote.py \
|
| 36 |
--repo-id arlaz/modular-flux123-multidiffusion \
|
| 37 |
--prompt "a dense renaissance fresco" \
|
| 38 |
--height 1024 \
|
| 39 |
+
--width 2048 \
|
| 40 |
+
--height-generation 1024 \
|
| 41 |
+
--width-generation 1024 \
|
| 42 |
--window-stride-height 512 \
|
| 43 |
--window-stride-width 512 \
|
| 44 |
+
--window-batch-size 2 \
|
| 45 |
+
--output remote_smoke.png
|
|
|
|
|
|
|
| 46 |
```
|
| 47 |
|
| 48 |
+
Add `--family <family>` to run another family from the same remote code, for example `--family flux2-klein-4b`. Both
|
| 49 |
+
runners apply the same family defaults: they read the upstream model config of the family.
|
| 50 |
+
|
| 51 |
+
`--local-files-only` needs every repo the run reads already cached:
|
| 52 |
+
- the upstream model;
|
| 53 |
+
- for FLUX 3, also the prompt upsampler `black-forest-labs/flux-3-image-klein-pup` (unless you pass
|
| 54 |
+
`--no-prompt-upsampler`);
|
| 55 |
+
- for `example_remote.py`, also the code repo `--repo-id`.
|
| 56 |
|
| 57 |
## Model Families
|
| 58 |
|
| 59 |
+
`example.py` picks the blocks from the upstream repo passed to `--base-model`. Every recipe below works with any of
|
| 60 |
+
them, except image conditioning, which FLUX.1 does not support.
|
| 61 |
|
| 62 |
```bash
|
| 63 |
# FLUX.1 schnell: 4 steps and a 256-token prompt by default
|
|
|
|
| 134 |
--enable-slicing
|
| 135 |
```
|
| 136 |
|
| 137 |
+
Images larger than `4096 * 4096` pixels are saved as BigTIFF, so this run writes `output.tif`.
|
| 138 |
+
|
| 139 |
## Panorama Run
|
| 140 |
|
| 141 |
```bash
|
|
|
|
| 155 |
--output panorama.png
|
| 156 |
```
|
| 157 |
|
| 158 |
+
Inspect the wrapped seams. The command moves the image corners to the middle; `scripts/inspect_panorama.py` does
|
| 159 |
+
the same without installing the project:
|
| 160 |
|
| 161 |
```bash
|
| 162 |
uv run multidiff-modular inspect-panorama panorama.png
|
|
|
|
| 163 |
```
|
| 164 |
|
| 165 |
## Regional Prompting
|
|
|
|
| 206 |
|
| 207 |
## Img2Img
|
| 208 |
|
| 209 |
+
Every family encodes `--image-img2img` at the canvas size and renoises it with `--strength`. Pass `--strength` below
|
| 210 |
+
`1.0`: at the default `1.0` the source image is fully renoised and ignored.
|
| 211 |
+
|
| 212 |
+
In Python, `image_img2img` takes packed, normalized latents, not an image. Build them with
|
| 213 |
+
`examples.example.prepare_img2img_latents(pipe, image, height=..., width=..., generator=...)`. FLUX.1's own
|
| 214 |
+
image2image workflow stays available in Python through its `image` input; the runner rejects `--image-conditioning`
|
| 215 |
+
for FLUX.1.
|
| 216 |
|
| 217 |
```bash
|
| 218 |
uv run python examples/example.py \
|
|
|
|
| 281 |
- `--base-model`: upstream FLUX.1, FLUX.2 or FLUX 3 repo id or local model directory for `example.py`.
|
| 282 |
- `--repo-id`: exported Hub repo id or local exported repo path for `example_remote.py`.
|
| 283 |
- `--family`: `example_remote.py` only; load this family's blocks from the remote `block.py` instead of the root default.
|
| 284 |
+
- `--lora-path`: LoRA folder holding `pytorch_lora_weights.safetensors`; needs PEFT (the `examples` extra).
|
| 285 |
- `--local-files-only`: disable network fetches and use cached/local files only.
|
| 286 |
|
| 287 |
Inputs:
|
| 288 |
|
| 289 |
+
- `--prompt`: text prompt, or a CSV file with `mask,prompt` headers. Default: `"A dense renaissance fresco."`.
|
| 290 |
- `--masks`: mask folder used with prompt CSV files.
|
| 291 |
- `--image-img2img`: image path for img2img initialization.
|
| 292 |
- `--image-conditioning`: image path for FLUX.2 or FLUX 3 reference image conditioning.
|
| 293 |
+
- `--strength`: img2img renoising strength. Default: `1.0`, which ignores the image.
|
| 294 |
|
| 295 |
Canvas and windowing:
|
| 296 |
|
| 297 |
+
- `--height`, `--width`: final canvas size in pixels. Default: `4096`.
|
| 298 |
+
- `--height-generation`, `--width-generation`: local denoising window size. Default: the full canvas.
|
| 299 |
+
- `--window-stride-height`, `--window-stride-width`: sliding-window stride. Default: half the window.
|
| 300 |
+
- `--window-stride-height-offset`, `--window-stride-width-offset`: per-step stride offset. Default: `0`.
|
| 301 |
- `--panorama-width`, `--panorama-height`: wrap width and/or height.
|
| 302 |
+
- `--weighting-type`: `none`, `linear`, or `cosine`. Default: `cosine`.
|
| 303 |
+
- `--weighting-range`: blend ramp length as a fraction of the window. Default: stride / window.
|
| 304 |
+
|
| 305 |
+
Sizes, strides and offsets must be multiples of 16 px, the window at most the canvas, and the stride at most the
|
| 306 |
+
window.
|
| 307 |
|
| 308 |
Inference:
|
| 309 |
|
| 310 |
+
- `--num-inference-steps`: denoising steps. Default: the family default; the runners use `4` for FLUX.1 schnell and the
|
| 311 |
+
distilled FLUX.2 Klein.
|
| 312 |
+
- `--guidance-scale`: guider override (FLUX.2 Klein Base, FLUX 3 base) or embedded guidance (FLUX.1 dev, FLUX.2 dev);
|
| 313 |
+
the other families ignore it.
|
| 314 |
- `--seed`: generator seed. Default: `42`.
|
| 315 |
- `--num-images-per-prompt`: output count. Default: `1`.
|
| 316 |
+
- `--window-batch-size`: maximum window/regional work items per denoiser forward pass. Default: `1`.
|
| 317 |
- `--no-prompt-upsampler`: FLUX 3 only; encode the prompt as given instead of upsampling it first.
|
| 318 |
|
| 319 |
Runtime:
|
| 320 |
|
| 321 |
+
- `--dtype`: `float16`, `bfloat16`, or `float32`. Default: `bfloat16`.
|
| 322 |
+
- `--device`: torch device string. Default: `cuda`, where the components are offloaded to the CPU between uses.
|
| 323 |
+
- `--output`: output path. Default: `output.png`. Images larger than `4096 * 4096` pixels save as BigTIFF automatically.
|
| 324 |
- `--allow-tf32`: enable CUDA TF32 settings.
|
| 325 |
- `--compile`: compile repeated transformer blocks with `torch.compile`.
|
| 326 |
+
- `--quantization`: TorchAO strategy for the transformer, the text encoders, and the VAE (the FLUX 3 prompt upsampler
|
| 327 |
+
stays unquantized).
|
| 328 |
- `--transformer-quantization`, `--text-encoder-quantization`, `--vae-quantization`: component-specific overrides;
|
| 329 |
`--text-encoder-quantization` also covers the FLUX.1 T5 `text_encoder_2`.
|
| 330 |
- `--enable-tiling`: enable VAE tiling.
|
|
@@ -2,7 +2,6 @@ from __future__ import annotations
|
|
| 2 |
|
| 3 |
import argparse
|
| 4 |
import csv
|
| 5 |
-
import re
|
| 6 |
import warnings
|
| 7 |
from collections.abc import Mapping, Sequence
|
| 8 |
from pathlib import Path
|
|
@@ -24,15 +23,30 @@ DTYPE_MAP = {
|
|
| 24 |
"float32": torch.float32,
|
| 25 |
}
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
DEFAULT_REQUESTED_QUANTIZATION = "float8wo"
|
| 30 |
WEIGHTING_TYPES = ("none", "linear", "cosine")
|
| 31 |
BIGTIFF_PIXEL_THRESHOLD = 4096 * 4096
|
| 32 |
TIFF_SUFFIXES = {".tif", ".tiff"}
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
FLUX_SCHNELL_DEFAULTS = {"num_inference_steps": 4, "max_sequence_length": 256}
|
| 37 |
|
| 38 |
|
|
@@ -42,39 +56,41 @@ def configure_torch(*, allow_tf32: bool) -> None:
|
|
| 42 |
torch.set_float32_matmul_precision("high")
|
| 43 |
|
| 44 |
|
| 45 |
-
def
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
class_name = model_config.get("_class_name")
|
| 56 |
-
if class_name == "FluxPipeline":
|
| 57 |
-
return Flux1MultiDiffusionAutoBlocks()
|
| 58 |
-
if class_name == "Flux2Pipeline":
|
| 59 |
-
return Flux2DevMultiDiffusionAutoBlocks()
|
| 60 |
-
if class_name == "Flux2KleinPipeline":
|
| 61 |
-
if model_config.get("is_distilled"):
|
| 62 |
-
return Flux2KleinMultiDiffusionAutoBlocks()
|
| 63 |
-
return Flux2KleinBaseMultiDiffusionAutoBlocks()
|
| 64 |
-
if class_name == "Flux3ModularPipeline":
|
| 65 |
-
return Flux3KleinBaseMultiDiffusionAutoBlocks()
|
| 66 |
-
if class_name == "Flux3DistilledModularPipeline":
|
| 67 |
-
return Flux3KleinMultiDiffusionAutoBlocks()
|
| 68 |
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
|
| 72 |
-
def drop_prompt_upsampler(blocks):
|
| 73 |
"""FLUX 3: encode the prompt as given instead of expanding it with the prompt upsampler first."""
|
| 74 |
-
sub_blocks
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
|
| 80 |
def add_input_arguments(parser: argparse.ArgumentParser) -> None:
|
|
@@ -83,7 +99,12 @@ def add_input_arguments(parser: argparse.ArgumentParser) -> None:
|
|
| 83 |
inputs.add_argument("--masks", type=Path, default=None)
|
| 84 |
inputs.add_argument("--image-img2img", default=None)
|
| 85 |
inputs.add_argument("--image-conditioning", default=None)
|
| 86 |
-
inputs.add_argument(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
def add_canvas_arguments(parser: argparse.ArgumentParser) -> None:
|
|
@@ -106,10 +127,9 @@ def add_inference_arguments(parser: argparse.ArgumentParser) -> None:
|
|
| 106 |
inference = parser.add_argument_group("inference")
|
| 107 |
inference.add_argument("--num-inference-steps", type=int, default=None)
|
| 108 |
inference.add_argument("--guidance-scale", type=float, default=None)
|
| 109 |
-
inference.add_argument("--terra-scale", type=float, default=None)
|
| 110 |
inference.add_argument("--seed", type=int, default=42)
|
| 111 |
inference.add_argument("--num-images-per-prompt", type=int, default=1)
|
| 112 |
-
inference.add_argument("--window-batch-size", type=
|
| 113 |
inference.add_argument(
|
| 114 |
"--no-prompt-upsampler",
|
| 115 |
dest="prompt_upsampler",
|
|
@@ -120,25 +140,18 @@ def add_inference_arguments(parser: argparse.ArgumentParser) -> None:
|
|
| 120 |
|
| 121 |
def add_runtime_arguments(parser: argparse.ArgumentParser) -> None:
|
| 122 |
runtime = parser.add_argument_group("runtime")
|
|
|
|
| 123 |
runtime.add_argument("--dtype", default="bfloat16", choices=tuple(DTYPE_MAP))
|
| 124 |
runtime.add_argument("--device", default="cuda")
|
| 125 |
runtime.add_argument("--output", default="output.png")
|
| 126 |
runtime.add_argument("--local-files-only", action="store_true")
|
| 127 |
runtime.add_argument("--allow-tf32", action="store_true")
|
| 128 |
runtime.add_argument("--compile", action="store_true")
|
| 129 |
-
runtime.add_argument(
|
| 130 |
-
"--quantize",
|
| 131 |
-
dest="quantization",
|
| 132 |
-
action="store_const",
|
| 133 |
-
const=DEFAULT_REQUESTED_QUANTIZATION,
|
| 134 |
-
default=argparse.SUPPRESS,
|
| 135 |
-
help=argparse.SUPPRESS,
|
| 136 |
-
)
|
| 137 |
runtime.add_argument(
|
| 138 |
"--quantization",
|
| 139 |
nargs="?",
|
| 140 |
const=DEFAULT_REQUESTED_QUANTIZATION,
|
| 141 |
-
default=
|
| 142 |
choices=QUANTIZATION_CHOICES,
|
| 143 |
help=(
|
| 144 |
"TorchAO quantization strategy for the transformer, the text encoders, and the vae. "
|
|
@@ -173,8 +186,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
| 173 |
)
|
| 174 |
|
| 175 |
model = parser.add_argument_group("model")
|
| 176 |
-
model.add_argument("--base-model", required=True)
|
| 177 |
-
model.add_argument("--lora-path", "--lora_path", type=Path)
|
| 178 |
|
| 179 |
add_input_arguments(parser)
|
| 180 |
add_canvas_arguments(parser)
|
|
@@ -188,37 +200,12 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
|
| 188 |
return build_parser().parse_args(argv)
|
| 189 |
|
| 190 |
|
| 191 |
-
def load_model_config(base_model: str, *, local_files_only: bool) -> dict:
|
| 192 |
-
try:
|
| 193 |
-
return dict(DiffusionPipeline.load_config(base_model, local_files_only=local_files_only))
|
| 194 |
-
except OSError:
|
| 195 |
-
# FLUX 3 repos only ship the Modular Diffusers `modular_model_index.json`
|
| 196 |
-
return dict(ModularPipeline.load_config(base_model, local_files_only=local_files_only))
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
def apply_window_stride_defaults(args: argparse.Namespace) -> argparse.Namespace:
|
| 200 |
-
if args.height_generation is not None and args.window_stride_height is None:
|
| 201 |
-
args.window_stride_height = args.height_generation // 2
|
| 202 |
-
if args.width_generation is not None and args.window_stride_width is None:
|
| 203 |
-
args.window_stride_width = args.width_generation // 2
|
| 204 |
-
return args
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
def is_flux_schnell(model_config: Mapping, pipe) -> bool:
|
| 208 |
-
transformer_config = getattr(getattr(pipe, "transformer", None), "config", None)
|
| 209 |
-
return (
|
| 210 |
-
model_config.get("_class_name") in FLUX_PIPELINE_CLASSES
|
| 211 |
-
and transformer_config is not None
|
| 212 |
-
and not transformer_config.guidance_embeds
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
|
| 216 |
def default_call_kwargs(model_config: Mapping, pipe) -> dict:
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
return {"num_inference_steps": 4}
|
| 221 |
-
if
|
| 222 |
return dict(FLUX_SCHNELL_DEFAULTS)
|
| 223 |
return {}
|
| 224 |
|
|
@@ -230,59 +217,29 @@ def apply_vae_memory_options(pipe, *, enable_tiling: bool, enable_slicing: bool)
|
|
| 230 |
pipe.vae.enable_slicing()
|
| 231 |
|
| 232 |
|
| 233 |
-
def _validate_quantization_strategy(strategy: str, *, name: str) -> str:
|
| 234 |
-
if strategy not in QUANTIZATION_CHOICES:
|
| 235 |
-
raise ValueError(f"`{name}` must be one of {QUANTIZATION_CHOICES}, got {strategy!r}.")
|
| 236 |
-
return strategy
|
| 237 |
-
|
| 238 |
-
|
| 239 |
def resolve_quantization_mapping(
|
| 240 |
-
quantization: str
|
| 241 |
*,
|
| 242 |
transformer_quantization: str | None = None,
|
| 243 |
text_encoder_quantization: str | None = None,
|
| 244 |
vae_quantization: str | None = None,
|
| 245 |
) -> dict[str, str]:
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
name="quantization",
|
| 249 |
-
)
|
| 250 |
-
text_encoder_strategy = text_encoder_quantization if text_encoder_quantization is not None else base_quantization
|
| 251 |
component_strategies = {
|
| 252 |
-
"transformer": transformer_quantization
|
| 253 |
"text_encoder": text_encoder_strategy,
|
| 254 |
"text_encoder_2": text_encoder_strategy,
|
| 255 |
-
"vae": vae_quantization
|
| 256 |
-
}
|
| 257 |
-
return {
|
| 258 |
-
component: _validate_quantization_strategy(strategy, name=f"{component}_quantization")
|
| 259 |
-
for component, strategy in component_strategies.items()
|
| 260 |
-
if strategy != "none"
|
| 261 |
}
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
Float8DynamicActivationFloat8WeightConfig,
|
| 267 |
-
Float8WeightOnlyConfig,
|
| 268 |
-
Int4WeightOnlyConfig,
|
| 269 |
-
Int8WeightOnlyConfig,
|
| 270 |
-
)
|
| 271 |
-
|
| 272 |
-
if strategy == "float8wo":
|
| 273 |
-
return Float8WeightOnlyConfig()
|
| 274 |
-
if strategy == "int8wo":
|
| 275 |
-
return Int8WeightOnlyConfig()
|
| 276 |
-
if strategy == "int4wo":
|
| 277 |
-
return Int4WeightOnlyConfig(group_size=128)
|
| 278 |
-
if strategy == "float8dyn":
|
| 279 |
-
return Float8DynamicActivationFloat8WeightConfig()
|
| 280 |
-
|
| 281 |
-
raise ValueError(f"Cannot build TorchAO quantization config for {strategy!r}.")
|
| 282 |
|
| 283 |
|
| 284 |
def build_quantization_config(
|
| 285 |
-
quantization: str
|
| 286 |
*,
|
| 287 |
transformer_quantization: str | None = None,
|
| 288 |
text_encoder_quantization: str | None = None,
|
|
@@ -297,90 +254,53 @@ def build_quantization_config(
|
|
| 297 |
if not quant_mapping:
|
| 298 |
return None
|
| 299 |
|
|
|
|
| 300 |
from diffusers import PipelineQuantizationConfig
|
| 301 |
from diffusers import TorchAoConfig as DiffusersTorchAoConfig
|
| 302 |
from transformers import TorchAoConfig as TransformersTorchAoConfig
|
| 303 |
|
| 304 |
-
|
| 305 |
-
"
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
"vae": DiffusersTorchAoConfig,
|
| 309 |
-
}
|
| 310 |
|
| 311 |
return PipelineQuantizationConfig(
|
| 312 |
-
quant_mapping={
|
| 313 |
-
component: component_config_classes[component](_build_torchao_quant_type(strategy))
|
| 314 |
-
for component, strategy in quant_mapping.items()
|
| 315 |
-
}
|
| 316 |
)
|
| 317 |
|
| 318 |
|
| 319 |
-
def build_components_manager(device: torch.device) -> tuple[ComponentsManager, bool]:
|
| 320 |
-
manager = ComponentsManager()
|
| 321 |
-
use_auto_offload = device.type == "cuda"
|
| 322 |
-
|
| 323 |
-
if use_auto_offload:
|
| 324 |
-
manager.enable_auto_cpu_offload(device=device)
|
| 325 |
-
elif device.type == "mps":
|
| 326 |
-
print("MPS does not support ComponentsManager auto CPU offload; loading components directly on MPS.")
|
| 327 |
-
|
| 328 |
-
return manager, use_auto_offload
|
| 329 |
-
|
| 330 |
-
|
| 331 |
def init_modular_pipeline(
|
| 332 |
-
|
| 333 |
base_model: str,
|
| 334 |
-
|
| 335 |
-
guidance_scale=None,
|
| 336 |
-
dtype: str,
|
| 337 |
-
device: str,
|
| 338 |
-
local_files_only: bool,
|
| 339 |
-
compile: bool,
|
| 340 |
-
|
| 341 |
-
transformer_quantization: str | None = None,
|
| 342 |
-
text_encoder_quantization: str | None = None,
|
| 343 |
-
vae_quantization: str | None = None,
|
| 344 |
-
prompt_upsampler: bool = True,
|
| 345 |
) -> ModularPipeline:
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
)
|
| 352 |
|
| 353 |
-
|
| 354 |
-
if not prompt_upsampler:
|
| 355 |
-
drop_prompt_upsampler(blocks)
|
| 356 |
-
pipe = blocks.init_pipeline(
|
| 357 |
-
base_model,
|
| 358 |
-
components_manager=manager,
|
| 359 |
-
)
|
| 360 |
pipe.load_components(
|
| 361 |
dtype=DTYPE_MAP[dtype],
|
| 362 |
local_files_only=local_files_only,
|
| 363 |
-
quantization_config=
|
| 364 |
-
quantization,
|
| 365 |
-
transformer_quantization=transformer_quantization,
|
| 366 |
-
text_encoder_quantization=text_encoder_quantization,
|
| 367 |
-
vae_quantization=vae_quantization,
|
| 368 |
-
),
|
| 369 |
)
|
| 370 |
-
if
|
| 371 |
-
pipe.to(
|
| 372 |
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
pipe.update_components(
|
| 376 |
-
guider=guider_spec.create(guidance_scale=guidance_scale),
|
| 377 |
-
)
|
| 378 |
|
| 379 |
if compile:
|
| 380 |
-
pipe.transformer.compile_repeated_blocks(
|
| 381 |
-
fullgraph=True,
|
| 382 |
-
dynamic=True,
|
| 383 |
-
)
|
| 384 |
|
| 385 |
return pipe
|
| 386 |
|
|
@@ -434,10 +354,6 @@ def prepare_img2img_latents(pipe, image, *, height: int, width: int, generator):
|
|
| 434 |
return IMG2IMG_ENCODERS[branch](vae_encoder_pipe, image_tensor, generator)
|
| 435 |
|
| 436 |
|
| 437 |
-
def _natural_sort_key(path: Path):
|
| 438 |
-
return [int(part) if part.isdigit() else part.lower() for part in re.split(r"(\d+)", path.name)]
|
| 439 |
-
|
| 440 |
-
|
| 441 |
def _is_csv_prompt(prompt: str) -> bool:
|
| 442 |
return Path(prompt).suffix.lower() == ".csv"
|
| 443 |
|
|
@@ -480,13 +396,12 @@ def _load_regional_masks(
|
|
| 480 |
if not masks_dir.is_dir():
|
| 481 |
raise FileNotFoundError(f"Mask folder does not exist: {masks_dir}")
|
| 482 |
|
| 483 |
-
available_masks = {path.name: path for path in sorted(masks_dir.iterdir(), key=_natural_sort_key) if path.is_file()}
|
| 484 |
masks = []
|
| 485 |
for row in rows:
|
| 486 |
-
|
| 487 |
-
if
|
| 488 |
-
raise FileNotFoundError(f"Mask {
|
| 489 |
-
masks.append(_load_grayscale_mask(
|
| 490 |
|
| 491 |
latent_height = height // (vae_scale_factor * 2)
|
| 492 |
latent_width = width // (vae_scale_factor * 2)
|
|
@@ -523,8 +438,7 @@ def prepare_regional_prompt_inputs(args: argparse.Namespace, pipe) -> tuple[str
|
|
| 523 |
|
| 524 |
def build_call_kwargs(args: argparse.Namespace, pipe, generator, model_config: Mapping | None = None) -> dict:
|
| 525 |
model_config = model_config or {}
|
| 526 |
-
|
| 527 |
-
raise ValueError(f"`--window-batch-size` must be a positive integer, got {args.window_batch_size}.")
|
| 528 |
prompt, regional_masks = prepare_regional_prompt_inputs(args, pipe)
|
| 529 |
call_kwargs = {
|
| 530 |
"prompt": prompt,
|
|
@@ -551,9 +465,7 @@ def build_call_kwargs(args: argparse.Namespace, pipe, generator, model_config: M
|
|
| 551 |
if args.num_inference_steps is not None:
|
| 552 |
call_kwargs["num_inference_steps"] = args.num_inference_steps
|
| 553 |
|
| 554 |
-
|
| 555 |
-
class_name = model_config.get("_class_name")
|
| 556 |
-
if args.guidance_scale is not None and class_name in EMBEDDED_GUIDANCE_PIPELINE_CLASSES:
|
| 557 |
call_kwargs["guidance_scale"] = args.guidance_scale
|
| 558 |
|
| 559 |
if args.image_img2img is not None:
|
|
@@ -567,31 +479,13 @@ def build_call_kwargs(args: argparse.Namespace, pipe, generator, model_config: M
|
|
| 567 |
call_kwargs["strength"] = args.strength
|
| 568 |
|
| 569 |
if args.image_conditioning is not None:
|
| 570 |
-
if
|
| 571 |
raise ValueError("FLUX.1 dev and schnell have no reference image conditioning; use `--image-img2img`.")
|
| 572 |
call_kwargs["image"] = load_image(args.image_conditioning)
|
| 573 |
|
| 574 |
return call_kwargs
|
| 575 |
|
| 576 |
|
| 577 |
-
def load_lora_adapter(pipe, *, lora_path: Path | None, terra_scale: float | None, num_images_per_prompt: int) -> None:
|
| 578 |
-
if lora_path is None:
|
| 579 |
-
return
|
| 580 |
-
|
| 581 |
-
pipe.transformer.load_lora_adapter(
|
| 582 |
-
lora_path,
|
| 583 |
-
weight_name=LORA_WEIGHT_NAME_SAFE,
|
| 584 |
-
)
|
| 585 |
-
print(f"Loaded LoRA weights from {lora_path}")
|
| 586 |
-
print(pipe.transformer)
|
| 587 |
-
|
| 588 |
-
if terra_scale is not None:
|
| 589 |
-
pipe.transformer.set_terra_t(
|
| 590 |
-
[terra_scale] * num_images_per_prompt,
|
| 591 |
-
adapter=None,
|
| 592 |
-
)
|
| 593 |
-
|
| 594 |
-
|
| 595 |
def save_images(images, output: str | Path, *, num_images_per_prompt: int) -> None:
|
| 596 |
output_path = Path(output)
|
| 597 |
|
|
@@ -626,57 +520,41 @@ def _resolve_output_path_for_image(output_path: Path, *, image, use_bigtiff: boo
|
|
| 626 |
return output_path
|
| 627 |
|
| 628 |
|
| 629 |
-
def
|
| 630 |
-
|
| 631 |
configure_torch(allow_tf32=args.allow_tf32)
|
|
|
|
|
|
|
| 632 |
|
| 633 |
-
|
| 634 |
-
args.base_model,
|
| 635 |
-
local_files_only=args.local_files_only,
|
| 636 |
-
)
|
| 637 |
-
|
| 638 |
-
print("Initializing modular pipeline...")
|
| 639 |
-
print(args)
|
| 640 |
-
|
| 641 |
pipe = init_modular_pipeline(
|
| 642 |
-
|
| 643 |
-
|
| 644 |
guidance_scale=args.guidance_scale,
|
| 645 |
dtype=args.dtype,
|
| 646 |
device=args.device,
|
| 647 |
local_files_only=args.local_files_only,
|
| 648 |
compile=args.compile,
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
apply_vae_memory_options(
|
| 656 |
-
pipe,
|
| 657 |
-
enable_tiling=args.enable_tiling,
|
| 658 |
-
enable_slicing=args.enable_slicing,
|
| 659 |
-
)
|
| 660 |
-
load_lora_adapter(
|
| 661 |
-
pipe,
|
| 662 |
-
lora_path=args.lora_path,
|
| 663 |
-
terra_scale=args.terra_scale,
|
| 664 |
-
num_images_per_prompt=args.num_images_per_prompt,
|
| 665 |
)
|
|
|
|
|
|
|
|
|
|
| 666 |
|
| 667 |
generator = torch.Generator().manual_seed(args.seed)
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
)
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
output.images,
|
| 677 |
-
args.output,
|
| 678 |
-
num_images_per_prompt=args.num_images_per_prompt,
|
| 679 |
-
)
|
| 680 |
|
| 681 |
|
| 682 |
if __name__ == "__main__":
|
|
|
|
| 2 |
|
| 3 |
import argparse
|
| 4 |
import csv
|
|
|
|
| 5 |
import warnings
|
| 6 |
from collections.abc import Mapping, Sequence
|
| 7 |
from pathlib import Path
|
|
|
|
| 23 |
"float32": torch.float32,
|
| 24 |
}
|
| 25 |
|
| 26 |
+
# --quantization strategy -> TorchAO config class and its arguments
|
| 27 |
+
TORCHAO_CONFIGS = {
|
| 28 |
+
"float8wo": ("Float8WeightOnlyConfig", {}),
|
| 29 |
+
"int8wo": ("Int8WeightOnlyConfig", {}),
|
| 30 |
+
"int4wo": ("Int4WeightOnlyConfig", {"group_size": 128}),
|
| 31 |
+
"float8dyn": ("Float8DynamicActivationFloat8WeightConfig", {}),
|
| 32 |
+
}
|
| 33 |
+
QUANTIZATION_CHOICES = ("none", *TORCHAO_CONFIGS)
|
| 34 |
DEFAULT_REQUESTED_QUANTIZATION = "float8wo"
|
| 35 |
WEIGHTING_TYPES = ("none", "linear", "cosine")
|
| 36 |
BIGTIFF_PIXEL_THRESHOLD = 4096 * 4096
|
| 37 |
TIFF_SUFFIXES = {".tif", ".tiff"}
|
| 38 |
|
| 39 |
+
# model kind (the pipeline `_class_name` without its suffix) -> MultiDiffusion blocks
|
| 40 |
+
MULTIDIFFUSION_BLOCKS = {
|
| 41 |
+
"Flux": "Flux1MultiDiffusionAutoBlocks",
|
| 42 |
+
"Flux2": "Flux2DevMultiDiffusionAutoBlocks",
|
| 43 |
+
"Flux2Klein": "Flux2KleinMultiDiffusionAutoBlocks",
|
| 44 |
+
"Flux2KleinBase": "Flux2KleinBaseMultiDiffusionAutoBlocks",
|
| 45 |
+
"Flux3": "Flux3KleinBaseMultiDiffusionAutoBlocks",
|
| 46 |
+
"Flux3Distilled": "Flux3KleinMultiDiffusionAutoBlocks",
|
| 47 |
+
}
|
| 48 |
+
# FLUX.1 dev and FLUX.2 dev embed the guidance scale in the transformer instead of running a guider
|
| 49 |
+
EMBEDDED_GUIDANCE_MODELS = {"Flux", "Flux2"}
|
| 50 |
FLUX_SCHNELL_DEFAULTS = {"num_inference_steps": 4, "max_sequence_length": 256}
|
| 51 |
|
| 52 |
|
|
|
|
| 56 |
torch.set_float32_matmul_precision("high")
|
| 57 |
|
| 58 |
|
| 59 |
+
def load_model_config(base_model: str, *, local_files_only: bool) -> dict:
|
| 60 |
+
try:
|
| 61 |
+
return dict(DiffusionPipeline.load_config(base_model, local_files_only=local_files_only))
|
| 62 |
+
except OSError:
|
| 63 |
+
# FLUX 3 repos and the exported MultiDiffusion repos only ship a `modular_model_index.json`
|
| 64 |
+
return dict(ModularPipeline.load_config(base_model, local_files_only=local_files_only))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def model_kind(model_config: Mapping) -> str:
|
| 68 |
+
"""The model family of a (modular) model index: `Flux`, `Flux2`, `Flux2Klein(Base)`, `Flux3(Distilled)`."""
|
| 69 |
+
kind = (model_config.get("_class_name") or "").removesuffix("Pipeline").removesuffix("Modular")
|
| 70 |
+
if kind == "Flux2Klein" and not model_config.get("is_distilled"):
|
| 71 |
+
return "Flux2KleinBase"
|
| 72 |
+
return kind
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
def build_multidiffusion_blocks(model_config: Mapping):
|
| 76 |
+
import multidiffusion
|
| 77 |
+
|
| 78 |
+
class_name = MULTIDIFFUSION_BLOCKS.get(model_kind(model_config))
|
| 79 |
+
if class_name is None:
|
| 80 |
+
raise ValueError(f"Cannot select MultiDiffusion blocks from model class {model_config.get('_class_name')!r}.")
|
| 81 |
+
return getattr(multidiffusion, class_name)()
|
| 82 |
|
| 83 |
|
| 84 |
+
def drop_prompt_upsampler(blocks) -> None:
|
| 85 |
"""FLUX 3: encode the prompt as given instead of expanding it with the prompt upsampler first."""
|
| 86 |
+
blocks.sub_blocks.pop("prompt_upsampler", None)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _positive_int(value: str) -> int:
|
| 90 |
+
number = int(value)
|
| 91 |
+
if number <= 0:
|
| 92 |
+
raise argparse.ArgumentTypeError(f"must be a positive integer, got {value}")
|
| 93 |
+
return number
|
| 94 |
|
| 95 |
|
| 96 |
def add_input_arguments(parser: argparse.ArgumentParser) -> None:
|
|
|
|
| 99 |
inputs.add_argument("--masks", type=Path, default=None)
|
| 100 |
inputs.add_argument("--image-img2img", default=None)
|
| 101 |
inputs.add_argument("--image-conditioning", default=None)
|
| 102 |
+
inputs.add_argument(
|
| 103 |
+
"--strength",
|
| 104 |
+
type=float,
|
| 105 |
+
default=1.0,
|
| 106 |
+
help="How much of the schedule to run on `--image-img2img`; 1.0 ignores the source image.",
|
| 107 |
+
)
|
| 108 |
|
| 109 |
|
| 110 |
def add_canvas_arguments(parser: argparse.ArgumentParser) -> None:
|
|
|
|
| 127 |
inference = parser.add_argument_group("inference")
|
| 128 |
inference.add_argument("--num-inference-steps", type=int, default=None)
|
| 129 |
inference.add_argument("--guidance-scale", type=float, default=None)
|
|
|
|
| 130 |
inference.add_argument("--seed", type=int, default=42)
|
| 131 |
inference.add_argument("--num-images-per-prompt", type=int, default=1)
|
| 132 |
+
inference.add_argument("--window-batch-size", type=_positive_int, default=1)
|
| 133 |
inference.add_argument(
|
| 134 |
"--no-prompt-upsampler",
|
| 135 |
dest="prompt_upsampler",
|
|
|
|
| 140 |
|
| 141 |
def add_runtime_arguments(parser: argparse.ArgumentParser) -> None:
|
| 142 |
runtime = parser.add_argument_group("runtime")
|
| 143 |
+
runtime.add_argument("--lora-path", type=Path, help="LoRA folder holding `pytorch_lora_weights.safetensors`.")
|
| 144 |
runtime.add_argument("--dtype", default="bfloat16", choices=tuple(DTYPE_MAP))
|
| 145 |
runtime.add_argument("--device", default="cuda")
|
| 146 |
runtime.add_argument("--output", default="output.png")
|
| 147 |
runtime.add_argument("--local-files-only", action="store_true")
|
| 148 |
runtime.add_argument("--allow-tf32", action="store_true")
|
| 149 |
runtime.add_argument("--compile", action="store_true")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
runtime.add_argument(
|
| 151 |
"--quantization",
|
| 152 |
nargs="?",
|
| 153 |
const=DEFAULT_REQUESTED_QUANTIZATION,
|
| 154 |
+
default="none",
|
| 155 |
choices=QUANTIZATION_CHOICES,
|
| 156 |
help=(
|
| 157 |
"TorchAO quantization strategy for the transformer, the text encoders, and the vae. "
|
|
|
|
| 186 |
)
|
| 187 |
|
| 188 |
model = parser.add_argument_group("model")
|
| 189 |
+
model.add_argument("--base-model", required=True, help="Upstream model repo, e.g. black-forest-labs/FLUX.1-dev.")
|
|
|
|
| 190 |
|
| 191 |
add_input_arguments(parser)
|
| 192 |
add_canvas_arguments(parser)
|
|
|
|
| 200 |
return build_parser().parse_args(argv)
|
| 201 |
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
def default_call_kwargs(model_config: Mapping, pipe) -> dict:
|
| 204 |
+
"""Runner defaults the blocks don't have: the step-distilled FLUX.2 Klein and FLUX.1 schnell run 4 steps."""
|
| 205 |
+
kind = model_kind(model_config)
|
| 206 |
+
if kind == "Flux2Klein":
|
| 207 |
return {"num_inference_steps": 4}
|
| 208 |
+
if kind == "Flux" and not pipe.transformer.config.guidance_embeds: # schnell
|
| 209 |
return dict(FLUX_SCHNELL_DEFAULTS)
|
| 210 |
return {}
|
| 211 |
|
|
|
|
| 217 |
pipe.vae.enable_slicing()
|
| 218 |
|
| 219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
def resolve_quantization_mapping(
|
| 221 |
+
quantization: str = "none",
|
| 222 |
*,
|
| 223 |
transformer_quantization: str | None = None,
|
| 224 |
text_encoder_quantization: str | None = None,
|
| 225 |
vae_quantization: str | None = None,
|
| 226 |
) -> dict[str, str]:
|
| 227 |
+
"""The strategy of every quantized component; a component without an override uses `quantization`."""
|
| 228 |
+
text_encoder_strategy = text_encoder_quantization or quantization
|
|
|
|
|
|
|
|
|
|
| 229 |
component_strategies = {
|
| 230 |
+
"transformer": transformer_quantization or quantization,
|
| 231 |
"text_encoder": text_encoder_strategy,
|
| 232 |
"text_encoder_2": text_encoder_strategy,
|
| 233 |
+
"vae": vae_quantization or quantization,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
}
|
| 235 |
+
for component, strategy in component_strategies.items():
|
| 236 |
+
if strategy not in QUANTIZATION_CHOICES:
|
| 237 |
+
raise ValueError(f"`{component}_quantization` must be one of {QUANTIZATION_CHOICES}, got {strategy!r}.")
|
| 238 |
+
return {component: strategy for component, strategy in component_strategies.items() if strategy != "none"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
|
| 241 |
def build_quantization_config(
|
| 242 |
+
quantization: str = "none",
|
| 243 |
*,
|
| 244 |
transformer_quantization: str | None = None,
|
| 245 |
text_encoder_quantization: str | None = None,
|
|
|
|
| 254 |
if not quant_mapping:
|
| 255 |
return None
|
| 256 |
|
| 257 |
+
import torchao.quantization
|
| 258 |
from diffusers import PipelineQuantizationConfig
|
| 259 |
from diffusers import TorchAoConfig as DiffusersTorchAoConfig
|
| 260 |
from transformers import TorchAoConfig as TransformersTorchAoConfig
|
| 261 |
|
| 262 |
+
def torchao_config(component: str, strategy: str):
|
| 263 |
+
config_cls = TransformersTorchAoConfig if component.startswith("text_encoder") else DiffusersTorchAoConfig
|
| 264 |
+
quant_type_name, quant_type_kwargs = TORCHAO_CONFIGS[strategy]
|
| 265 |
+
return config_cls(getattr(torchao.quantization, quant_type_name)(**quant_type_kwargs))
|
|
|
|
|
|
|
| 266 |
|
| 267 |
return PipelineQuantizationConfig(
|
| 268 |
+
quant_mapping={component: torchao_config(component, strategy) for component, strategy in quant_mapping.items()}
|
|
|
|
|
|
|
|
|
|
| 269 |
)
|
| 270 |
|
| 271 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
def init_modular_pipeline(
|
| 273 |
+
blocks,
|
| 274 |
base_model: str,
|
| 275 |
+
*,
|
| 276 |
+
guidance_scale: float | None = None,
|
| 277 |
+
dtype: str = "bfloat16",
|
| 278 |
+
device: str = "cuda",
|
| 279 |
+
local_files_only: bool = False,
|
| 280 |
+
compile: bool = False,
|
| 281 |
+
quantization_config=None,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
) -> ModularPipeline:
|
| 283 |
+
"""Load the components of `base_model` into `blocks`; on CUDA they are offloaded to the CPU between uses."""
|
| 284 |
+
device = torch.device(device)
|
| 285 |
+
manager = ComponentsManager()
|
| 286 |
+
if device.type == "cuda":
|
| 287 |
+
manager.enable_auto_cpu_offload(device=device)
|
|
|
|
| 288 |
|
| 289 |
+
pipe = blocks.init_pipeline(base_model, components_manager=manager)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
pipe.load_components(
|
| 291 |
dtype=DTYPE_MAP[dtype],
|
| 292 |
local_files_only=local_files_only,
|
| 293 |
+
quantization_config=quantization_config,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
)
|
| 295 |
+
if device.type not in {"cuda", "cpu"}:
|
| 296 |
+
pipe.to(device)
|
| 297 |
|
| 298 |
+
# the CFG families (FLUX.2 Klein base, FLUX 3 base) take the guidance scale through their guider
|
| 299 |
+
if guidance_scale is not None and getattr(pipe, "guider", None) is not None:
|
| 300 |
+
pipe.update_components(guider=pipe.guider.new(guidance_scale=guidance_scale))
|
|
|
|
|
|
|
| 301 |
|
| 302 |
if compile:
|
| 303 |
+
pipe.transformer.compile_repeated_blocks(fullgraph=True, dynamic=True)
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
return pipe
|
| 306 |
|
|
|
|
| 354 |
return IMG2IMG_ENCODERS[branch](vae_encoder_pipe, image_tensor, generator)
|
| 355 |
|
| 356 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
def _is_csv_prompt(prompt: str) -> bool:
|
| 358 |
return Path(prompt).suffix.lower() == ".csv"
|
| 359 |
|
|
|
|
| 396 |
if not masks_dir.is_dir():
|
| 397 |
raise FileNotFoundError(f"Mask folder does not exist: {masks_dir}")
|
| 398 |
|
|
|
|
| 399 |
masks = []
|
| 400 |
for row in rows:
|
| 401 |
+
mask_path = masks_dir / row["mask"]
|
| 402 |
+
if not mask_path.is_file():
|
| 403 |
+
raise FileNotFoundError(f"Mask {row['mask']!r} from prompt CSV was not found in {masks_dir}.")
|
| 404 |
+
masks.append(_load_grayscale_mask(mask_path, width=width, height=height))
|
| 405 |
|
| 406 |
latent_height = height // (vae_scale_factor * 2)
|
| 407 |
latent_width = width // (vae_scale_factor * 2)
|
|
|
|
| 438 |
|
| 439 |
def build_call_kwargs(args: argparse.Namespace, pipe, generator, model_config: Mapping | None = None) -> dict:
|
| 440 |
model_config = model_config or {}
|
| 441 |
+
kind = model_kind(model_config)
|
|
|
|
| 442 |
prompt, regional_masks = prepare_regional_prompt_inputs(args, pipe)
|
| 443 |
call_kwargs = {
|
| 444 |
"prompt": prompt,
|
|
|
|
| 465 |
if args.num_inference_steps is not None:
|
| 466 |
call_kwargs["num_inference_steps"] = args.num_inference_steps
|
| 467 |
|
| 468 |
+
if args.guidance_scale is not None and kind in EMBEDDED_GUIDANCE_MODELS:
|
|
|
|
|
|
|
| 469 |
call_kwargs["guidance_scale"] = args.guidance_scale
|
| 470 |
|
| 471 |
if args.image_img2img is not None:
|
|
|
|
| 479 |
call_kwargs["strength"] = args.strength
|
| 480 |
|
| 481 |
if args.image_conditioning is not None:
|
| 482 |
+
if kind == "Flux":
|
| 483 |
raise ValueError("FLUX.1 dev and schnell have no reference image conditioning; use `--image-img2img`.")
|
| 484 |
call_kwargs["image"] = load_image(args.image_conditioning)
|
| 485 |
|
| 486 |
return call_kwargs
|
| 487 |
|
| 488 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
def save_images(images, output: str | Path, *, num_images_per_prompt: int) -> None:
|
| 490 |
output_path = Path(output)
|
| 491 |
|
|
|
|
| 520 |
return output_path
|
| 521 |
|
| 522 |
|
| 523 |
+
def run(args: argparse.Namespace, blocks, base_model: str, model_config: Mapping) -> None:
|
| 524 |
+
"""Shared by both runners: load `blocks` on `base_model`, generate with the parsed arguments, save the images."""
|
| 525 |
configure_torch(allow_tf32=args.allow_tf32)
|
| 526 |
+
if not args.prompt_upsampler:
|
| 527 |
+
drop_prompt_upsampler(blocks)
|
| 528 |
|
| 529 |
+
print(f"Initializing {type(blocks).__name__} on {base_model}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
pipe = init_modular_pipeline(
|
| 531 |
+
blocks,
|
| 532 |
+
base_model,
|
| 533 |
guidance_scale=args.guidance_scale,
|
| 534 |
dtype=args.dtype,
|
| 535 |
device=args.device,
|
| 536 |
local_files_only=args.local_files_only,
|
| 537 |
compile=args.compile,
|
| 538 |
+
quantization_config=build_quantization_config(
|
| 539 |
+
args.quantization,
|
| 540 |
+
transformer_quantization=args.transformer_quantization,
|
| 541 |
+
text_encoder_quantization=args.text_encoder_quantization,
|
| 542 |
+
vae_quantization=args.vae_quantization,
|
| 543 |
+
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 544 |
)
|
| 545 |
+
apply_vae_memory_options(pipe, enable_tiling=args.enable_tiling, enable_slicing=args.enable_slicing)
|
| 546 |
+
if args.lora_path is not None:
|
| 547 |
+
pipe.transformer.load_lora_adapter(args.lora_path, weight_name=LORA_WEIGHT_NAME_SAFE)
|
| 548 |
|
| 549 |
generator = torch.Generator().manual_seed(args.seed)
|
| 550 |
+
output = pipe(**build_call_kwargs(args, pipe, generator, model_config))
|
| 551 |
+
save_images(output.images, args.output, num_images_per_prompt=args.num_images_per_prompt)
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def main(argv: Sequence[str] | None = None) -> None:
|
| 555 |
+
args = parse_args(argv)
|
| 556 |
+
model_config = load_model_config(args.base_model, local_files_only=args.local_files_only)
|
| 557 |
+
run(args, build_multidiffusion_blocks(model_config), args.base_model, model_config)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
|
| 559 |
|
| 560 |
if __name__ == "__main__":
|
|
@@ -2,28 +2,17 @@ from __future__ import annotations
|
|
| 2 |
|
| 3 |
import argparse
|
| 4 |
from collections.abc import Sequence
|
| 5 |
-
from pathlib import Path
|
| 6 |
|
| 7 |
-
import
|
| 8 |
-
from diffusers import ModularPipeline, ModularPipelineBlocks
|
| 9 |
from diffusers.utils.dynamic_modules_utils import get_class_from_dynamic_module
|
| 10 |
|
| 11 |
from examples.example import (
|
| 12 |
-
DTYPE_MAP,
|
| 13 |
add_canvas_arguments,
|
| 14 |
add_inference_arguments,
|
| 15 |
add_input_arguments,
|
| 16 |
add_runtime_arguments,
|
| 17 |
-
apply_vae_memory_options,
|
| 18 |
-
apply_window_stride_defaults,
|
| 19 |
-
build_call_kwargs,
|
| 20 |
-
build_components_manager,
|
| 21 |
-
build_quantization_config,
|
| 22 |
-
configure_torch,
|
| 23 |
-
drop_prompt_upsampler,
|
| 24 |
-
load_lora_adapter,
|
| 25 |
load_model_config,
|
| 26 |
-
|
| 27 |
)
|
| 28 |
from repository import DEFAULT_MODEL_REPOS, FAMILY_BLOCK_CLASS_NAMES, SUPPORTED_MODEL_FAMILIES
|
| 29 |
|
|
@@ -45,7 +34,6 @@ def build_parser() -> argparse.ArgumentParser:
|
|
| 45 |
choices=SUPPORTED_MODEL_FAMILIES,
|
| 46 |
help="Load this family's blocks from the remote block.py instead of the repo's default root metadata.",
|
| 47 |
)
|
| 48 |
-
model.add_argument("--lora-path", "--lora_path", type=Path)
|
| 49 |
|
| 50 |
add_input_arguments(parser)
|
| 51 |
add_canvas_arguments(parser)
|
|
@@ -83,111 +71,13 @@ def load_remote_blocks(repo_id: str, *, family: str | None = None, local_files_o
|
|
| 83 |
return blocks_cls()
|
| 84 |
|
| 85 |
|
| 86 |
-
def init_remote_modular_pipeline(
|
| 87 |
-
*,
|
| 88 |
-
repo_id: str,
|
| 89 |
-
family: str | None = None,
|
| 90 |
-
guidance_scale=None,
|
| 91 |
-
dtype: str,
|
| 92 |
-
device: str,
|
| 93 |
-
local_files_only: bool,
|
| 94 |
-
compile: bool,
|
| 95 |
-
quantization: str | None = None,
|
| 96 |
-
transformer_quantization: str | None = None,
|
| 97 |
-
text_encoder_quantization: str | None = None,
|
| 98 |
-
vae_quantization: str | None = None,
|
| 99 |
-
prompt_upsampler: bool = True,
|
| 100 |
-
) -> ModularPipeline:
|
| 101 |
-
device_obj = torch.device(device)
|
| 102 |
-
manager, use_auto_offload = build_components_manager(device_obj)
|
| 103 |
-
|
| 104 |
-
blocks = load_remote_blocks(repo_id, family=family, local_files_only=local_files_only)
|
| 105 |
-
if not prompt_upsampler:
|
| 106 |
-
drop_prompt_upsampler(blocks)
|
| 107 |
-
pipe = blocks.init_pipeline(
|
| 108 |
-
remote_base_model(repo_id, family),
|
| 109 |
-
components_manager=manager,
|
| 110 |
-
)
|
| 111 |
-
pipe.load_components(
|
| 112 |
-
dtype=DTYPE_MAP[dtype],
|
| 113 |
-
local_files_only=local_files_only,
|
| 114 |
-
quantization_config=build_quantization_config(
|
| 115 |
-
quantization,
|
| 116 |
-
transformer_quantization=transformer_quantization,
|
| 117 |
-
text_encoder_quantization=text_encoder_quantization,
|
| 118 |
-
vae_quantization=vae_quantization,
|
| 119 |
-
),
|
| 120 |
-
)
|
| 121 |
-
if not use_auto_offload and device_obj.type != "cpu":
|
| 122 |
-
pipe.to(device_obj)
|
| 123 |
-
|
| 124 |
-
if guidance_scale is not None and hasattr(pipe, "guider") and pipe.guider is not None:
|
| 125 |
-
guider_spec = pipe.get_component_spec("guider")
|
| 126 |
-
pipe.update_components(
|
| 127 |
-
guider=guider_spec.create(guidance_scale=guidance_scale),
|
| 128 |
-
)
|
| 129 |
-
|
| 130 |
-
if compile:
|
| 131 |
-
pipe.transformer.compile_repeated_blocks(
|
| 132 |
-
fullgraph=True,
|
| 133 |
-
dynamic=True,
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
return pipe
|
| 137 |
-
|
| 138 |
-
|
| 139 |
def main(argv: Sequence[str] | None = None) -> None:
|
| 140 |
-
args =
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
# the family defaults key on `_class_name`, which the pipeline's own config does not carry
|
| 144 |
-
model_config = load_model_config(
|
| 145 |
-
|
| 146 |
-
local_files_only=args.local_files_only,
|
| 147 |
-
)
|
| 148 |
-
|
| 149 |
-
print("Initializing remote modular pipeline...")
|
| 150 |
-
print(args)
|
| 151 |
-
|
| 152 |
-
pipe = init_remote_modular_pipeline(
|
| 153 |
-
repo_id=args.repo_id,
|
| 154 |
-
family=args.family,
|
| 155 |
-
guidance_scale=args.guidance_scale,
|
| 156 |
-
dtype=args.dtype,
|
| 157 |
-
device=args.device,
|
| 158 |
-
local_files_only=args.local_files_only,
|
| 159 |
-
compile=args.compile,
|
| 160 |
-
quantization=args.quantization,
|
| 161 |
-
transformer_quantization=args.transformer_quantization,
|
| 162 |
-
text_encoder_quantization=args.text_encoder_quantization,
|
| 163 |
-
vae_quantization=args.vae_quantization,
|
| 164 |
-
prompt_upsampler=args.prompt_upsampler,
|
| 165 |
-
)
|
| 166 |
-
apply_vae_memory_options(
|
| 167 |
-
pipe,
|
| 168 |
-
enable_tiling=args.enable_tiling,
|
| 169 |
-
enable_slicing=args.enable_slicing,
|
| 170 |
-
)
|
| 171 |
-
load_lora_adapter(
|
| 172 |
-
pipe,
|
| 173 |
-
lora_path=args.lora_path,
|
| 174 |
-
terra_scale=args.terra_scale,
|
| 175 |
-
num_images_per_prompt=args.num_images_per_prompt,
|
| 176 |
-
)
|
| 177 |
-
|
| 178 |
-
generator = torch.Generator().manual_seed(args.seed)
|
| 179 |
-
call_kwargs = build_call_kwargs(
|
| 180 |
-
args,
|
| 181 |
-
pipe,
|
| 182 |
-
generator,
|
| 183 |
-
model_config,
|
| 184 |
-
)
|
| 185 |
-
output = pipe(**call_kwargs)
|
| 186 |
-
save_images(
|
| 187 |
-
output.images,
|
| 188 |
-
args.output,
|
| 189 |
-
num_images_per_prompt=args.num_images_per_prompt,
|
| 190 |
-
)
|
| 191 |
|
| 192 |
|
| 193 |
if __name__ == "__main__":
|
|
|
|
| 2 |
|
| 3 |
import argparse
|
| 4 |
from collections.abc import Sequence
|
|
|
|
| 5 |
|
| 6 |
+
from diffusers import ModularPipelineBlocks
|
|
|
|
| 7 |
from diffusers.utils.dynamic_modules_utils import get_class_from_dynamic_module
|
| 8 |
|
| 9 |
from examples.example import (
|
|
|
|
| 10 |
add_canvas_arguments,
|
| 11 |
add_inference_arguments,
|
| 12 |
add_input_arguments,
|
| 13 |
add_runtime_arguments,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
load_model_config,
|
| 15 |
+
run,
|
| 16 |
)
|
| 17 |
from repository import DEFAULT_MODEL_REPOS, FAMILY_BLOCK_CLASS_NAMES, SUPPORTED_MODEL_FAMILIES
|
| 18 |
|
|
|
|
| 34 |
choices=SUPPORTED_MODEL_FAMILIES,
|
| 35 |
help="Load this family's blocks from the remote block.py instead of the repo's default root metadata.",
|
| 36 |
)
|
|
|
|
| 37 |
|
| 38 |
add_input_arguments(parser)
|
| 39 |
add_canvas_arguments(parser)
|
|
|
|
| 71 |
return blocks_cls()
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
def main(argv: Sequence[str] | None = None) -> None:
|
| 75 |
+
args = parse_args(argv)
|
| 76 |
+
blocks = load_remote_blocks(args.repo_id, family=args.family, local_files_only=args.local_files_only)
|
| 77 |
+
base_model = remote_base_model(args.repo_id, args.family)
|
| 78 |
+
# the family defaults key on the model's `_class_name`, which the pipeline's own config does not carry
|
| 79 |
+
model_config = load_model_config(base_model, local_files_only=args.local_files_only)
|
| 80 |
+
run(args, blocks, base_model, model_config)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
|
| 83 |
if __name__ == "__main__":
|
|
@@ -1,13 +1,26 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
from copy import deepcopy
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# Versions the Hub remote code is written against; recorded in `modular_config.json`.
|
| 8 |
BLOCK_REQUIREMENTS = {"diffusers": ">=0.42.1,<0.43", "transformers": ">=5.2"}
|
| 9 |
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
def insert_block(blocks, name: str, block, *, before: str | None = None, after: str | None = None) -> None:
|
| 12 |
keys = list(blocks.sub_blocks.keys())
|
| 13 |
index = keys.index(before) if before is not None else keys.index(after) + 1
|
|
|
|
| 1 |
+
"""The base class of the top-level MultiDiffusion blocks and the helpers that edit a copy of the upstream blocks."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
from copy import deepcopy
|
| 6 |
+
from typing import ClassVar
|
| 7 |
+
|
| 8 |
+
from diffusers.modular_pipelines import OutputParam, SequentialPipelineBlocks
|
| 9 |
|
| 10 |
# Versions the Hub remote code is written against; recorded in `modular_config.json`.
|
| 11 |
BLOCK_REQUIREMENTS = {"diffusers": ">=0.42.1,<0.43", "transformers": ">=5.2"}
|
| 12 |
|
| 13 |
|
| 14 |
+
class MultiDiffusionAutoBlocks(SequentialPipelineBlocks):
|
| 15 |
+
"""Top-level MultiDiffusion blocks; a family subclass sets its sub-blocks, `_workflow_map` and `model_name`."""
|
| 16 |
+
|
| 17 |
+
_requirements: ClassVar = BLOCK_REQUIREMENTS
|
| 18 |
+
|
| 19 |
+
@property
|
| 20 |
+
def outputs(self):
|
| 21 |
+
return [OutputParam.template("images")]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
def insert_block(blocks, name: str, block, *, before: str | None = None, after: str | None = None) -> None:
|
| 25 |
keys = list(blocks.sub_blocks.keys())
|
| 26 |
index = keys.index(before) if before is not None else keys.index(after) + 1
|
|
@@ -5,12 +5,7 @@ from __future__ import annotations
|
|
| 5 |
from typing import ClassVar
|
| 6 |
|
| 7 |
import torch
|
| 8 |
-
from diffusers.modular_pipelines import
|
| 9 |
-
InputParam,
|
| 10 |
-
OutputParam,
|
| 11 |
-
PipelineState,
|
| 12 |
-
SequentialPipelineBlocks,
|
| 13 |
-
)
|
| 14 |
from diffusers.modular_pipelines.flux.before_denoise import (
|
| 15 |
FluxImg2ImgSetTimestepsStep,
|
| 16 |
FluxSetTimestepsStep,
|
|
@@ -116,42 +111,29 @@ class Flux1MultiDiffusionPreprocessingStep(window_loop.MultiDiffusionPreprocessi
|
|
| 116 |
|
| 117 |
|
| 118 |
class _Flux1MultiDiffusionWindowLoopMixin(window_loop.MultiDiffusionWindowLoopMixin):
|
| 119 |
-
_md_state_keys: ClassVar = ("latents", "img_ids", "prompt_embeds", "pooled_prompt_embeds", "guidance")
|
| 120 |
_md_item_keys: ClassVar = ("prompt_embeds", "pooled_prompt_embeds", "guidance")
|
| 121 |
-
_md_regional_keys: ClassVar =
|
| 122 |
-
|
| 123 |
-
InputParam("regional_prompt_embeds", type_hint=torch.Tensor, required=False),
|
| 124 |
-
InputParam("regional_pooled_prompt_embeds", type_hint=torch.Tensor, required=False),
|
| 125 |
-
)
|
| 126 |
-
|
| 127 |
-
def _md_window_ids(self, block_state, base_values: dict[str, object], item_count: int) -> dict[str, torch.Tensor]:
|
| 128 |
-
del item_count
|
| 129 |
-
return {"img_ids": block_state.md_window_latent_ids.to(base_values["img_ids"])}
|
| 130 |
|
| 131 |
|
| 132 |
class Flux1MultiDiffusionLoopStep(_Flux1MultiDiffusionWindowLoopMixin, FluxLoopDenoiser):
|
| 133 |
-
model_name = "flux"
|
| 134 |
-
|
| 135 |
@property
|
| 136 |
def description(self) -> str:
|
| 137 |
return "Run the FLUX.1 denoiser on every window, then merge the window predictions on the full canvas."
|
| 138 |
|
| 139 |
|
| 140 |
-
class Flux1MultiDiffusionDenoiseStep(window_loop.
|
| 141 |
-
model_name = "flux"
|
| 142 |
block_classes: ClassVar = [
|
| 143 |
Flux1MultiDiffusionPreprocessingStep,
|
| 144 |
Flux1MultiDiffusionLoopStep,
|
| 145 |
FluxLoopAfterDenoiser,
|
| 146 |
]
|
| 147 |
-
block_names: ClassVar = ["multidiffusion_preprocessing", "multidiffusion_loop", "after_denoiser"]
|
| 148 |
|
| 149 |
@property
|
| 150 |
def description(self) -> str:
|
| 151 |
return (
|
| 152 |
-
"FLUX.1 MultiDiffusion denoise step
|
| 153 |
-
"
|
| 154 |
-
"scheduler step."
|
| 155 |
)
|
| 156 |
|
| 157 |
|
|
@@ -176,8 +158,8 @@ class Flux1PanoramaDecodeStep(FluxDecodeStep):
|
|
| 176 |
images = panorama.decode_wrapped(
|
| 177 |
vae,
|
| 178 |
latents,
|
| 179 |
-
panorama_height=
|
| 180 |
-
panorama_width=
|
| 181 |
)
|
| 182 |
block_state.images = components.image_processor.postprocess(images, output_type=block_state.output_type)
|
| 183 |
|
|
@@ -218,12 +200,11 @@ def _build_flux1_blocks(base_blocks_cls):
|
|
| 218 |
_FLUX1_MD_BLOCKS = _build_flux1_blocks(FluxAutoBlocks)
|
| 219 |
|
| 220 |
|
| 221 |
-
class Flux1MultiDiffusionAutoBlocks(
|
| 222 |
model_name = "flux"
|
| 223 |
block_classes: ClassVar = list(_FLUX1_MD_BLOCKS.values())
|
| 224 |
block_names: ClassVar = list(_FLUX1_MD_BLOCKS.keys())
|
| 225 |
_workflow_map = FluxAutoBlocks._workflow_map
|
| 226 |
-
_requirements: ClassVar = composition.BLOCK_REQUIREMENTS
|
| 227 |
|
| 228 |
@property
|
| 229 |
def description(self):
|
|
@@ -232,7 +213,3 @@ class Flux1MultiDiffusionAutoBlocks(SequentialPipelineBlocks):
|
|
| 232 |
"`height` and `width` define the output canvas; `height_generation` and `width_generation` "
|
| 233 |
"define the denoiser view window."
|
| 234 |
)
|
| 235 |
-
|
| 236 |
-
@property
|
| 237 |
-
def outputs(self):
|
| 238 |
-
return [OutputParam.template("images")]
|
|
|
|
| 5 |
from typing import ClassVar
|
| 6 |
|
| 7 |
import torch
|
| 8 |
+
from diffusers.modular_pipelines import PipelineState
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from diffusers.modular_pipelines.flux.before_denoise import (
|
| 10 |
FluxImg2ImgSetTimestepsStep,
|
| 11 |
FluxSetTimestepsStep,
|
|
|
|
| 111 |
|
| 112 |
|
| 113 |
class _Flux1MultiDiffusionWindowLoopMixin(window_loop.MultiDiffusionWindowLoopMixin):
|
|
|
|
| 114 |
_md_item_keys: ClassVar = ("prompt_embeds", "pooled_prompt_embeds", "guidance")
|
| 115 |
+
_md_regional_keys: ClassVar = Flux1RegionalPromptSplitStep._regional_fields
|
| 116 |
+
_md_state_keys: ClassVar = ("img_ids",)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
|
| 119 |
class Flux1MultiDiffusionLoopStep(_Flux1MultiDiffusionWindowLoopMixin, FluxLoopDenoiser):
|
|
|
|
|
|
|
| 120 |
@property
|
| 121 |
def description(self) -> str:
|
| 122 |
return "Run the FLUX.1 denoiser on every window, then merge the window predictions on the full canvas."
|
| 123 |
|
| 124 |
|
| 125 |
+
class Flux1MultiDiffusionDenoiseStep(window_loop.MultiDiffusionDenoiseStepMixin, FluxDenoiseLoopWrapper):
|
|
|
|
| 126 |
block_classes: ClassVar = [
|
| 127 |
Flux1MultiDiffusionPreprocessingStep,
|
| 128 |
Flux1MultiDiffusionLoopStep,
|
| 129 |
FluxLoopAfterDenoiser,
|
| 130 |
]
|
|
|
|
| 131 |
|
| 132 |
@property
|
| 133 |
def description(self) -> str:
|
| 134 |
return (
|
| 135 |
+
"FLUX.1 MultiDiffusion denoise step: at every timestep it lays out the window grid, runs the denoiser on "
|
| 136 |
+
"every window, merges the window predictions on the full canvas and takes one scheduler step."
|
|
|
|
| 137 |
)
|
| 138 |
|
| 139 |
|
|
|
|
| 158 |
images = panorama.decode_wrapped(
|
| 159 |
vae,
|
| 160 |
latents,
|
| 161 |
+
panorama_height=block_state.panorama_height,
|
| 162 |
+
panorama_width=block_state.panorama_width,
|
| 163 |
)
|
| 164 |
block_state.images = components.image_processor.postprocess(images, output_type=block_state.output_type)
|
| 165 |
|
|
|
|
| 200 |
_FLUX1_MD_BLOCKS = _build_flux1_blocks(FluxAutoBlocks)
|
| 201 |
|
| 202 |
|
| 203 |
+
class Flux1MultiDiffusionAutoBlocks(composition.MultiDiffusionAutoBlocks):
|
| 204 |
model_name = "flux"
|
| 205 |
block_classes: ClassVar = list(_FLUX1_MD_BLOCKS.values())
|
| 206 |
block_names: ClassVar = list(_FLUX1_MD_BLOCKS.keys())
|
| 207 |
_workflow_map = FluxAutoBlocks._workflow_map
|
|
|
|
| 208 |
|
| 209 |
@property
|
| 210 |
def description(self):
|
|
|
|
| 213 |
"`height` and `width` define the output canvas; `height_generation` and `width_generation` "
|
| 214 |
"define the denoiser view window."
|
| 215 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -6,12 +6,7 @@ from typing import ClassVar
|
|
| 6 |
|
| 7 |
import numpy as np
|
| 8 |
import torch
|
| 9 |
-
from diffusers.modular_pipelines import
|
| 10 |
-
InputParam,
|
| 11 |
-
OutputParam,
|
| 12 |
-
PipelineState,
|
| 13 |
-
SequentialPipelineBlocks,
|
| 14 |
-
)
|
| 15 |
from diffusers.modular_pipelines.flux2.before_denoise import (
|
| 16 |
Flux2SetTimestepsStep,
|
| 17 |
compute_empirical_mu,
|
|
@@ -44,7 +39,7 @@ def _prepare_local_latent_ids(batch_size: int, height: int, width: int, device:
|
|
| 44 |
class Flux2MultiDiffusionSetTimestepsStep(Flux2SetTimestepsStep):
|
| 45 |
@property
|
| 46 |
def description(self) -> str:
|
| 47 |
-
return "Set
|
| 48 |
|
| 49 |
@property
|
| 50 |
def inputs(self):
|
|
@@ -57,10 +52,6 @@ class Flux2MultiDiffusionSetTimestepsStep(Flux2SetTimestepsStep):
|
|
| 57 |
scheduler = components.scheduler
|
| 58 |
layout = geometry.MDLayout.from_state(block_state, components)
|
| 59 |
|
| 60 |
-
window_seq_len = layout.window_h * layout.window_w
|
| 61 |
-
max_image_seq_len = getattr(scheduler.config, "max_image_seq_len", window_seq_len)
|
| 62 |
-
image_seq_len = min(window_seq_len, max_image_seq_len)
|
| 63 |
-
|
| 64 |
num_inference_steps = block_state.num_inference_steps
|
| 65 |
sigmas = block_state.sigmas
|
| 66 |
timesteps = block_state.timesteps
|
|
@@ -70,7 +61,7 @@ class Flux2MultiDiffusionSetTimestepsStep(Flux2SetTimestepsStep):
|
|
| 70 |
if hasattr(scheduler.config, "use_flow_sigmas") and scheduler.config.use_flow_sigmas:
|
| 71 |
sigmas = None
|
| 72 |
|
| 73 |
-
mu = compute_empirical_mu(image_seq_len=
|
| 74 |
timesteps, num_inference_steps = retrieve_timesteps(
|
| 75 |
scheduler,
|
| 76 |
num_inference_steps,
|
|
@@ -106,19 +97,8 @@ class Flux2MultiDiffusionPreprocessingStep(window_loop.MultiDiffusionPreprocessi
|
|
| 106 |
|
| 107 |
|
| 108 |
class _Flux2MultiDiffusionWindowLoopMixin(window_loop.MultiDiffusionWindowLoopMixin):
|
| 109 |
-
_md_state_keys: ClassVar = (
|
| 110 |
-
"latents",
|
| 111 |
-
"latent_ids",
|
| 112 |
-
"image_latents",
|
| 113 |
-
"image_latent_ids",
|
| 114 |
-
"prompt_embeds",
|
| 115 |
-
"negative_prompt_embeds",
|
| 116 |
-
"txt_ids",
|
| 117 |
-
"negative_txt_ids",
|
| 118 |
-
"guidance",
|
| 119 |
-
)
|
| 120 |
_md_item_keys: ClassVar = ("prompt_embeds", "txt_ids", "negative_prompt_embeds", "negative_txt_ids", "guidance")
|
| 121 |
-
|
| 122 |
|
| 123 |
def _md_check_inputs(self, block_state) -> None:
|
| 124 |
has_image_latents = getattr(block_state, "image_latents", None) is not None
|
|
@@ -127,111 +107,96 @@ class _Flux2MultiDiffusionWindowLoopMixin(window_loop.MultiDiffusionWindowLoopMi
|
|
| 127 |
raise ValueError("`image_latents` and `image_latent_ids` must be provided together.")
|
| 128 |
|
| 129 |
def _md_window_ids(self, block_state, base_values: dict[str, object], item_count: int) -> dict[str, torch.Tensor]:
|
|
|
|
| 130 |
del base_values
|
| 131 |
return {"latent_ids": block_state.md_window_latent_ids.repeat(item_count, 1, 1)}
|
| 132 |
|
| 133 |
def _md_reference_inputs(
|
| 134 |
self, block_state, base_values: dict[str, object], item: window_loop.WindowItem
|
| 135 |
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
| 136 |
-
image_latents = base_values
|
| 137 |
if image_latents is window_loop.MISSING or image_latents is None:
|
| 138 |
return {}, {}
|
| 139 |
|
| 140 |
window_latents, window_ids = geometry.image_conditioning_window(
|
| 141 |
-
image_latents,
|
| 142 |
-
base_values["image_latent_ids"],
|
| 143 |
-
top=item.top,
|
| 144 |
-
left=item.left,
|
| 145 |
-
window_h=block_state.md_window_h,
|
| 146 |
-
window_w=block_state.md_window_w,
|
| 147 |
-
full_h=block_state.md_full_h,
|
| 148 |
-
full_w=block_state.md_full_w,
|
| 149 |
-
wrap_height=bool(getattr(block_state, "md_wrap_height", False)),
|
| 150 |
-
wrap_width=bool(getattr(block_state, "md_wrap_width", False)),
|
| 151 |
)
|
| 152 |
return {"image_latents": window_latents, "image_latent_ids": window_ids}, {}
|
| 153 |
|
| 154 |
|
| 155 |
class Flux2DevMultiDiffusionLoopStep(_Flux2MultiDiffusionWindowLoopMixin, Flux2LoopDenoiser):
|
| 156 |
-
model_name = "flux2"
|
| 157 |
-
|
| 158 |
@property
|
| 159 |
def description(self) -> str:
|
| 160 |
-
return "Run the
|
| 161 |
|
| 162 |
|
| 163 |
class Flux2KleinMultiDiffusionLoopStep(_Flux2MultiDiffusionWindowLoopMixin, Flux2KleinLoopDenoiser):
|
| 164 |
-
model_name = "flux2-klein"
|
| 165 |
-
|
| 166 |
@property
|
| 167 |
def description(self) -> str:
|
| 168 |
-
return "Run the
|
| 169 |
|
| 170 |
|
| 171 |
class Flux2KleinBaseMultiDiffusionLoopStep(_Flux2MultiDiffusionWindowLoopMixin, Flux2KleinBaseLoopDenoiser):
|
| 172 |
-
model_name = "flux2-klein"
|
| 173 |
-
|
| 174 |
@property
|
| 175 |
def description(self) -> str:
|
| 176 |
-
return
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
|
| 179 |
-
class Flux2DevMultiDiffusionDenoiseStep(window_loop.
|
| 180 |
-
model_name = "flux2"
|
| 181 |
block_classes: ClassVar = [
|
| 182 |
Flux2MultiDiffusionPreprocessingStep,
|
| 183 |
Flux2DevMultiDiffusionLoopStep,
|
| 184 |
Flux2LoopAfterDenoiser,
|
| 185 |
]
|
| 186 |
-
block_names: ClassVar = ["multidiffusion_preprocessing", "multidiffusion_loop", "after_denoiser"]
|
| 187 |
|
| 188 |
@property
|
| 189 |
def description(self) -> str:
|
| 190 |
return (
|
| 191 |
-
"
|
| 192 |
-
"
|
| 193 |
-
"and then applies a single scheduler step."
|
| 194 |
)
|
| 195 |
|
| 196 |
|
| 197 |
-
class Flux2KleinMultiDiffusionDenoiseStep(window_loop.
|
| 198 |
model_name = "flux2-klein"
|
| 199 |
block_classes: ClassVar = [
|
| 200 |
Flux2MultiDiffusionPreprocessingStep,
|
| 201 |
Flux2KleinMultiDiffusionLoopStep,
|
| 202 |
Flux2LoopAfterDenoiser,
|
| 203 |
]
|
| 204 |
-
block_names: ClassVar = ["multidiffusion_preprocessing", "multidiffusion_loop", "after_denoiser"]
|
| 205 |
|
| 206 |
@property
|
| 207 |
def description(self) -> str:
|
| 208 |
return (
|
| 209 |
-
"
|
| 210 |
-
"
|
| 211 |
)
|
| 212 |
|
| 213 |
|
| 214 |
-
class Flux2KleinBaseMultiDiffusionDenoiseStep(window_loop.
|
| 215 |
model_name = "flux2-klein"
|
| 216 |
block_classes: ClassVar = [
|
| 217 |
Flux2MultiDiffusionPreprocessingStep,
|
| 218 |
Flux2KleinBaseMultiDiffusionLoopStep,
|
| 219 |
Flux2LoopAfterDenoiser,
|
| 220 |
]
|
| 221 |
-
block_names: ClassVar = ["multidiffusion_preprocessing", "multidiffusion_loop", "after_denoiser"]
|
| 222 |
|
| 223 |
@property
|
| 224 |
def description(self) -> str:
|
| 225 |
return (
|
| 226 |
-
"
|
| 227 |
-
"
|
|
|
|
| 228 |
)
|
| 229 |
|
| 230 |
|
| 231 |
class Flux2PanoramaDecodeStep(Flux2DecodeStep):
|
| 232 |
@property
|
| 233 |
def description(self) -> str:
|
| 234 |
-
return "Decode
|
| 235 |
|
| 236 |
@property
|
| 237 |
def inputs(self):
|
|
@@ -247,8 +212,8 @@ class Flux2PanoramaDecodeStep(Flux2DecodeStep):
|
|
| 247 |
images = panorama.decode_wrapped(
|
| 248 |
vae,
|
| 249 |
latents,
|
| 250 |
-
panorama_height=
|
| 251 |
-
panorama_width=
|
| 252 |
)
|
| 253 |
block_state.images = components.image_processor.postprocess(images, output_type=block_state.output_type)
|
| 254 |
|
|
@@ -291,60 +256,46 @@ _FLUX2_KLEIN_MD_BLOCKS = _build_flux2_blocks(Flux2KleinAutoBlocks)
|
|
| 291 |
_FLUX2_KLEIN_BASE_MD_BLOCKS = _build_flux2_blocks(Flux2KleinBaseAutoBlocks)
|
| 292 |
|
| 293 |
|
| 294 |
-
class Flux2DevMultiDiffusionAutoBlocks(
|
| 295 |
model_name = "flux2"
|
| 296 |
block_classes: ClassVar = list(_FLUX2_DEV_MD_BLOCKS.values())
|
| 297 |
block_names: ClassVar = list(_FLUX2_DEV_MD_BLOCKS.keys())
|
| 298 |
_workflow_map = Flux2AutoBlocks._workflow_map
|
| 299 |
-
_requirements: ClassVar = composition.BLOCK_REQUIREMENTS
|
| 300 |
|
| 301 |
@property
|
| 302 |
def description(self):
|
| 303 |
return (
|
| 304 |
-
"Auto
|
| 305 |
"`height` and `width` define the output canvas; `height_generation` and `width_generation` "
|
| 306 |
"define the denoiser view window."
|
| 307 |
)
|
| 308 |
|
| 309 |
-
@property
|
| 310 |
-
def outputs(self):
|
| 311 |
-
return [OutputParam.template("images")]
|
| 312 |
-
|
| 313 |
|
| 314 |
-
class Flux2KleinMultiDiffusionAutoBlocks(
|
| 315 |
model_name = "flux2-klein"
|
| 316 |
block_classes: ClassVar = list(_FLUX2_KLEIN_MD_BLOCKS.values())
|
| 317 |
block_names: ClassVar = list(_FLUX2_KLEIN_MD_BLOCKS.keys())
|
| 318 |
_workflow_map = Flux2KleinAutoBlocks._workflow_map
|
| 319 |
-
_requirements: ClassVar = composition.BLOCK_REQUIREMENTS
|
| 320 |
|
| 321 |
@property
|
| 322 |
def description(self):
|
| 323 |
return (
|
| 324 |
-
"Auto
|
| 325 |
"`height` and `width` define the output canvas; `height_generation` and `width_generation` "
|
| 326 |
"define the denoiser view window."
|
| 327 |
)
|
| 328 |
|
| 329 |
-
@property
|
| 330 |
-
def outputs(self):
|
| 331 |
-
return [OutputParam.template("images")]
|
| 332 |
-
|
| 333 |
|
| 334 |
-
class Flux2KleinBaseMultiDiffusionAutoBlocks(
|
| 335 |
model_name = "flux2-klein"
|
| 336 |
block_classes: ClassVar = list(_FLUX2_KLEIN_BASE_MD_BLOCKS.values())
|
| 337 |
block_names: ClassVar = list(_FLUX2_KLEIN_BASE_MD_BLOCKS.keys())
|
| 338 |
_workflow_map = Flux2KleinBaseAutoBlocks._workflow_map
|
| 339 |
-
_requirements: ClassVar = composition.BLOCK_REQUIREMENTS
|
| 340 |
|
| 341 |
@property
|
| 342 |
def description(self):
|
| 343 |
return (
|
| 344 |
-
"Auto
|
| 345 |
-
"This variant keeps the official Klein Base CFG behavior."
|
|
|
|
| 346 |
)
|
| 347 |
-
|
| 348 |
-
@property
|
| 349 |
-
def outputs(self):
|
| 350 |
-
return [OutputParam.template("images")]
|
|
|
|
| 6 |
|
| 7 |
import numpy as np
|
| 8 |
import torch
|
| 9 |
+
from diffusers.modular_pipelines import PipelineState
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
from diffusers.modular_pipelines.flux2.before_denoise import (
|
| 11 |
Flux2SetTimestepsStep,
|
| 12 |
compute_empirical_mu,
|
|
|
|
| 39 |
class Flux2MultiDiffusionSetTimestepsStep(Flux2SetTimestepsStep):
|
| 40 |
@property
|
| 41 |
def description(self) -> str:
|
| 42 |
+
return "Set FLUX.2 timesteps from the generation window instead of the full canvas."
|
| 43 |
|
| 44 |
@property
|
| 45 |
def inputs(self):
|
|
|
|
| 52 |
scheduler = components.scheduler
|
| 53 |
layout = geometry.MDLayout.from_state(block_state, components)
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
num_inference_steps = block_state.num_inference_steps
|
| 56 |
sigmas = block_state.sigmas
|
| 57 |
timesteps = block_state.timesteps
|
|
|
|
| 61 |
if hasattr(scheduler.config, "use_flow_sigmas") and scheduler.config.use_flow_sigmas:
|
| 62 |
sigmas = None
|
| 63 |
|
| 64 |
+
mu = compute_empirical_mu(image_seq_len=layout.window_h * layout.window_w, num_steps=num_inference_steps)
|
| 65 |
timesteps, num_inference_steps = retrieve_timesteps(
|
| 66 |
scheduler,
|
| 67 |
num_inference_steps,
|
|
|
|
| 97 |
|
| 98 |
|
| 99 |
class _Flux2MultiDiffusionWindowLoopMixin(window_loop.MultiDiffusionWindowLoopMixin):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
_md_item_keys: ClassVar = ("prompt_embeds", "txt_ids", "negative_prompt_embeds", "negative_txt_ids", "guidance")
|
| 101 |
+
_md_state_keys: ClassVar = ("latent_ids", "image_latents", "image_latent_ids")
|
| 102 |
|
| 103 |
def _md_check_inputs(self, block_state) -> None:
|
| 104 |
has_image_latents = getattr(block_state, "image_latents", None) is not None
|
|
|
|
| 107 |
raise ValueError("`image_latents` and `image_latent_ids` must be provided together.")
|
| 108 |
|
| 109 |
def _md_window_ids(self, block_state, base_values: dict[str, object], item_count: int) -> dict[str, torch.Tensor]:
|
| 110 |
+
"""FLUX.2 ids carry a batch dimension: one copy per item."""
|
| 111 |
del base_values
|
| 112 |
return {"latent_ids": block_state.md_window_latent_ids.repeat(item_count, 1, 1)}
|
| 113 |
|
| 114 |
def _md_reference_inputs(
|
| 115 |
self, block_state, base_values: dict[str, object], item: window_loop.WindowItem
|
| 116 |
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
| 117 |
+
image_latents = base_values["image_latents"]
|
| 118 |
if image_latents is window_loop.MISSING or image_latents is None:
|
| 119 |
return {}, {}
|
| 120 |
|
| 121 |
window_latents, window_ids = geometry.image_conditioning_window(
|
| 122 |
+
image_latents, base_values["image_latent_ids"], **self._md_window_box(block_state, item)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
)
|
| 124 |
return {"image_latents": window_latents, "image_latent_ids": window_ids}, {}
|
| 125 |
|
| 126 |
|
| 127 |
class Flux2DevMultiDiffusionLoopStep(_Flux2MultiDiffusionWindowLoopMixin, Flux2LoopDenoiser):
|
|
|
|
|
|
|
| 128 |
@property
|
| 129 |
def description(self) -> str:
|
| 130 |
+
return "Run the FLUX.2 dev denoiser on every window, then merge the window predictions on the full canvas."
|
| 131 |
|
| 132 |
|
| 133 |
class Flux2KleinMultiDiffusionLoopStep(_Flux2MultiDiffusionWindowLoopMixin, Flux2KleinLoopDenoiser):
|
|
|
|
|
|
|
| 134 |
@property
|
| 135 |
def description(self) -> str:
|
| 136 |
+
return "Run the FLUX.2 Klein denoiser on every window, then merge the window predictions on the full canvas."
|
| 137 |
|
| 138 |
|
| 139 |
class Flux2KleinBaseMultiDiffusionLoopStep(_Flux2MultiDiffusionWindowLoopMixin, Flux2KleinBaseLoopDenoiser):
|
|
|
|
|
|
|
| 140 |
@property
|
| 141 |
def description(self) -> str:
|
| 142 |
+
return (
|
| 143 |
+
"Run the FLUX.2 Klein Base CFG denoiser on every window, then merge the window predictions on the full "
|
| 144 |
+
"canvas."
|
| 145 |
+
)
|
| 146 |
|
| 147 |
|
| 148 |
+
class Flux2DevMultiDiffusionDenoiseStep(window_loop.MultiDiffusionDenoiseStepMixin, Flux2DenoiseLoopWrapper):
|
|
|
|
| 149 |
block_classes: ClassVar = [
|
| 150 |
Flux2MultiDiffusionPreprocessingStep,
|
| 151 |
Flux2DevMultiDiffusionLoopStep,
|
| 152 |
Flux2LoopAfterDenoiser,
|
| 153 |
]
|
|
|
|
| 154 |
|
| 155 |
@property
|
| 156 |
def description(self) -> str:
|
| 157 |
return (
|
| 158 |
+
"FLUX.2 dev MultiDiffusion denoise step: at every timestep it lays out the window grid, runs the denoiser "
|
| 159 |
+
"on every window, merges the window predictions on the full canvas and takes one scheduler step."
|
|
|
|
| 160 |
)
|
| 161 |
|
| 162 |
|
| 163 |
+
class Flux2KleinMultiDiffusionDenoiseStep(window_loop.MultiDiffusionDenoiseStepMixin, Flux2DenoiseLoopWrapper):
|
| 164 |
model_name = "flux2-klein"
|
| 165 |
block_classes: ClassVar = [
|
| 166 |
Flux2MultiDiffusionPreprocessingStep,
|
| 167 |
Flux2KleinMultiDiffusionLoopStep,
|
| 168 |
Flux2LoopAfterDenoiser,
|
| 169 |
]
|
|
|
|
| 170 |
|
| 171 |
@property
|
| 172 |
def description(self) -> str:
|
| 173 |
return (
|
| 174 |
+
"FLUX.2 Klein MultiDiffusion denoise step: at every timestep it lays out the window grid, runs the "
|
| 175 |
+
"denoiser on every window, merges the window predictions on the full canvas and takes one scheduler step."
|
| 176 |
)
|
| 177 |
|
| 178 |
|
| 179 |
+
class Flux2KleinBaseMultiDiffusionDenoiseStep(window_loop.MultiDiffusionDenoiseStepMixin, Flux2DenoiseLoopWrapper):
|
| 180 |
model_name = "flux2-klein"
|
| 181 |
block_classes: ClassVar = [
|
| 182 |
Flux2MultiDiffusionPreprocessingStep,
|
| 183 |
Flux2KleinBaseMultiDiffusionLoopStep,
|
| 184 |
Flux2LoopAfterDenoiser,
|
| 185 |
]
|
|
|
|
| 186 |
|
| 187 |
@property
|
| 188 |
def description(self) -> str:
|
| 189 |
return (
|
| 190 |
+
"FLUX.2 Klein Base MultiDiffusion denoise step: at every timestep it lays out the window grid, runs the "
|
| 191 |
+
"CFG denoiser on every window, merges the window predictions on the full canvas and takes one scheduler "
|
| 192 |
+
"step."
|
| 193 |
)
|
| 194 |
|
| 195 |
|
| 196 |
class Flux2PanoramaDecodeStep(Flux2DecodeStep):
|
| 197 |
@property
|
| 198 |
def description(self) -> str:
|
| 199 |
+
return "Decode FLUX.2 latents, circular-padding VAE latents for panorama axes before cropping back."
|
| 200 |
|
| 201 |
@property
|
| 202 |
def inputs(self):
|
|
|
|
| 212 |
images = panorama.decode_wrapped(
|
| 213 |
vae,
|
| 214 |
latents,
|
| 215 |
+
panorama_height=block_state.panorama_height,
|
| 216 |
+
panorama_width=block_state.panorama_width,
|
| 217 |
)
|
| 218 |
block_state.images = components.image_processor.postprocess(images, output_type=block_state.output_type)
|
| 219 |
|
|
|
|
| 256 |
_FLUX2_KLEIN_BASE_MD_BLOCKS = _build_flux2_blocks(Flux2KleinBaseAutoBlocks)
|
| 257 |
|
| 258 |
|
| 259 |
+
class Flux2DevMultiDiffusionAutoBlocks(composition.MultiDiffusionAutoBlocks):
|
| 260 |
model_name = "flux2"
|
| 261 |
block_classes: ClassVar = list(_FLUX2_DEV_MD_BLOCKS.values())
|
| 262 |
block_names: ClassVar = list(_FLUX2_DEV_MD_BLOCKS.keys())
|
| 263 |
_workflow_map = Flux2AutoBlocks._workflow_map
|
|
|
|
| 264 |
|
| 265 |
@property
|
| 266 |
def description(self):
|
| 267 |
return (
|
| 268 |
+
"Auto FLUX.2 dev MultiDiffusion blocks with optional image conditioning and img2img support. "
|
| 269 |
"`height` and `width` define the output canvas; `height_generation` and `width_generation` "
|
| 270 |
"define the denoiser view window."
|
| 271 |
)
|
| 272 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
+
class Flux2KleinMultiDiffusionAutoBlocks(composition.MultiDiffusionAutoBlocks):
|
| 275 |
model_name = "flux2-klein"
|
| 276 |
block_classes: ClassVar = list(_FLUX2_KLEIN_MD_BLOCKS.values())
|
| 277 |
block_names: ClassVar = list(_FLUX2_KLEIN_MD_BLOCKS.keys())
|
| 278 |
_workflow_map = Flux2KleinAutoBlocks._workflow_map
|
|
|
|
| 279 |
|
| 280 |
@property
|
| 281 |
def description(self):
|
| 282 |
return (
|
| 283 |
+
"Auto FLUX.2 Klein MultiDiffusion blocks with optional image conditioning and img2img support. "
|
| 284 |
"`height` and `width` define the output canvas; `height_generation` and `width_generation` "
|
| 285 |
"define the denoiser view window."
|
| 286 |
)
|
| 287 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
|
| 289 |
+
class Flux2KleinBaseMultiDiffusionAutoBlocks(composition.MultiDiffusionAutoBlocks):
|
| 290 |
model_name = "flux2-klein"
|
| 291 |
block_classes: ClassVar = list(_FLUX2_KLEIN_BASE_MD_BLOCKS.values())
|
| 292 |
block_names: ClassVar = list(_FLUX2_KLEIN_BASE_MD_BLOCKS.keys())
|
| 293 |
_workflow_map = Flux2KleinBaseAutoBlocks._workflow_map
|
|
|
|
| 294 |
|
| 295 |
@property
|
| 296 |
def description(self):
|
| 297 |
return (
|
| 298 |
+
"Auto FLUX.2 Klein Base MultiDiffusion blocks with optional image conditioning and img2img support. "
|
| 299 |
+
"This variant keeps the official Klein Base CFG behavior. `height` and `width` define the output canvas; "
|
| 300 |
+
"`height_generation` and `width_generation` define the denoiser view window."
|
| 301 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -10,9 +10,12 @@ from diffusers.modular_pipelines import (
|
|
| 10 |
ModularPipelineBlocks,
|
| 11 |
OutputParam,
|
| 12 |
PipelineState,
|
| 13 |
-
SequentialPipelineBlocks,
|
| 14 |
)
|
| 15 |
-
from diffusers.modular_pipelines.flux3.before_denoise import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
from diffusers.modular_pipelines.flux3.decoders import Flux3DecodeStep
|
| 17 |
from diffusers.modular_pipelines.flux3.denoise import (
|
| 18 |
Flux3DenoiseLoopWrapper,
|
|
@@ -37,12 +40,16 @@ from . import composition, geometry, panorama, steps, window_loop
|
|
| 37 |
_FLUX3_BLOCK_REQUIREMENTS = {**composition.BLOCK_REQUIREMENTS, "torchvision": ">=0.22"}
|
| 38 |
|
| 39 |
|
| 40 |
-
# FLUX 3 scales the H/W position ids of every image token by
|
| 41 |
-
_FLUX3_IMAGE_ROPE_SCALE =
|
| 42 |
|
| 43 |
|
| 44 |
class _Flux3PromptListUpsampleMixin:
|
| 45 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
@property
|
| 48 |
def intermediate_outputs(self):
|
|
@@ -54,43 +61,40 @@ class _Flux3PromptListUpsampleMixin:
|
|
| 54 |
)
|
| 55 |
]
|
| 56 |
|
| 57 |
-
def _upsample_regional_prompt(self, components, block_state, prompt: str) -> str:
|
| 58 |
-
raise NotImplementedError
|
| 59 |
-
|
| 60 |
@torch.no_grad()
|
| 61 |
def __call__(self, components, state: PipelineState):
|
| 62 |
block_state = self.get_block_state(state)
|
| 63 |
if isinstance(block_state.prompt, str):
|
| 64 |
return super().__call__(components, state)
|
|
|
|
|
|
|
| 65 |
|
|
|
|
|
|
|
|
|
|
| 66 |
block_state.prompt = [
|
| 67 |
-
prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
]
|
| 69 |
self.set_block_state(state, block_state)
|
| 70 |
return components, state
|
| 71 |
|
| 72 |
|
| 73 |
class Flux3MultiDiffusionText2ImagePromptUpsampleStep(_Flux3PromptListUpsampleMixin, Flux3Text2ImagePromptUpsampleStep):
|
| 74 |
-
|
| 75 |
-
return upsample_prompt(
|
| 76 |
-
components.prompt_upsampler,
|
| 77 |
-
components.prompt_upsampler_processor,
|
| 78 |
-
request=prompt,
|
| 79 |
-
max_new_tokens=block_state.max_new_tokens,
|
| 80 |
-
)
|
| 81 |
|
| 82 |
|
| 83 |
class Flux3MultiDiffusionImageConditionedPromptUpsampleStep(
|
| 84 |
_Flux3PromptListUpsampleMixin, Flux3ImageConditionedPromptUpsampleStep
|
| 85 |
):
|
| 86 |
-
|
| 87 |
-
return upsample_prompt(
|
| 88 |
-
components.prompt_upsampler,
|
| 89 |
-
components.prompt_upsampler_processor,
|
| 90 |
-
request=prompt,
|
| 91 |
-
images=prepare_references(block_state.image),
|
| 92 |
-
max_new_tokens=block_state.max_new_tokens,
|
| 93 |
-
)
|
| 94 |
|
| 95 |
|
| 96 |
class Flux3MultiDiffusionAutoPromptUpsampleStep(Flux3AutoPromptUpsampleStep):
|
|
@@ -223,18 +227,14 @@ class Flux3MultiDiffusionPreprocessingStep(window_loop.MultiDiffusionPreprocessi
|
|
| 223 |
|
| 224 |
class _Flux3MultiDiffusionWindowLoopMixin(window_loop.MultiDiffusionWindowLoopMixin):
|
| 225 |
# FLUX 3 denoisers read their conditioning from the `denoiser_input_fields` dict, so it is rebuilt per batch
|
|
|
|
| 226 |
_md_state_keys: ClassVar = (
|
| 227 |
-
"latents",
|
| 228 |
"denoiser_input_fields",
|
| 229 |
-
"prompt_embeds",
|
| 230 |
-
"negative_prompt_embeds",
|
| 231 |
"txt_ids",
|
| 232 |
-
"negative_txt_ids",
|
| 233 |
"img_ids",
|
| 234 |
"image_cond_hidden_states",
|
| 235 |
"image_cond_ids",
|
| 236 |
)
|
| 237 |
-
_md_item_keys: ClassVar = ("prompt_embeds", "negative_prompt_embeds")
|
| 238 |
_md_extra_inputs: ClassVar = (
|
| 239 |
InputParam(
|
| 240 |
"image_cond_latents",
|
|
@@ -242,33 +242,18 @@ class _Flux3MultiDiffusionWindowLoopMixin(window_loop.MultiDiffusionWindowLoopMi
|
|
| 242 |
required=False,
|
| 243 |
description="Reference latents `(B, C, h_i, w_i)`, each cropped per window as a view of the canvas.",
|
| 244 |
),
|
| 245 |
-
InputParam("regional_prompt_embeds", type_hint=list[torch.Tensor], required=False),
|
| 246 |
)
|
| 247 |
|
| 248 |
-
def _md_window_ids(self, block_state, base_values: dict[str, object], item_count: int) -> dict[str, torch.Tensor]:
|
| 249 |
-
del item_count
|
| 250 |
-
return {"img_ids": block_state.md_window_latent_ids.to(base_values["img_ids"])}
|
| 251 |
-
|
| 252 |
def _md_reference_inputs(
|
| 253 |
self, block_state, base_values: dict[str, object], item: window_loop.WindowItem
|
| 254 |
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
| 255 |
-
image_cond_hidden_states = base_values
|
| 256 |
if image_cond_hidden_states is window_loop.MISSING or image_cond_hidden_states is None:
|
| 257 |
return {}, {}
|
| 258 |
|
| 259 |
tokens, ids = [], []
|
| 260 |
for index, latents in enumerate(block_state.image_cond_latents):
|
| 261 |
-
window_latents = geometry.reference_window(
|
| 262 |
-
latents,
|
| 263 |
-
top=item.top,
|
| 264 |
-
left=item.left,
|
| 265 |
-
window_h=block_state.md_window_h,
|
| 266 |
-
window_w=block_state.md_window_w,
|
| 267 |
-
full_h=block_state.md_full_h,
|
| 268 |
-
full_w=block_state.md_full_w,
|
| 269 |
-
wrap_height=bool(getattr(block_state, "md_wrap_height", False)),
|
| 270 |
-
wrap_width=bool(getattr(block_state, "md_wrap_width", False)),
|
| 271 |
-
)
|
| 272 |
tokens.append(window_latents.flatten(2).transpose(1, 2))
|
| 273 |
ids.append(
|
| 274 |
_prepare_image_ids(
|
|
@@ -297,16 +282,12 @@ class _Flux3MultiDiffusionWindowLoopMixin(window_loop.MultiDiffusionWindowLoopMi
|
|
| 297 |
|
| 298 |
|
| 299 |
class Flux3KleinBaseMultiDiffusionLoopStep(_Flux3MultiDiffusionWindowLoopMixin, Flux3LoopDenoiser):
|
| 300 |
-
model_name = "flux3"
|
| 301 |
-
|
| 302 |
@property
|
| 303 |
def description(self) -> str:
|
| 304 |
return "Run the FLUX 3 CFG denoiser on every window, then merge the window predictions on the full canvas."
|
| 305 |
|
| 306 |
|
| 307 |
class Flux3KleinMultiDiffusionLoopStep(_Flux3MultiDiffusionWindowLoopMixin, Flux3DistilledLoopDenoiser):
|
| 308 |
-
model_name = "flux3-distilled"
|
| 309 |
-
|
| 310 |
@property
|
| 311 |
def description(self) -> str:
|
| 312 |
return (
|
|
@@ -315,37 +296,36 @@ class Flux3KleinMultiDiffusionLoopStep(_Flux3MultiDiffusionWindowLoopMixin, Flux
|
|
| 315 |
)
|
| 316 |
|
| 317 |
|
| 318 |
-
class Flux3KleinBaseMultiDiffusionDenoiseStep(window_loop.
|
| 319 |
-
model_name = "flux3"
|
| 320 |
block_classes: ClassVar = [
|
| 321 |
Flux3MultiDiffusionPreprocessingStep,
|
| 322 |
Flux3KleinBaseMultiDiffusionLoopStep,
|
| 323 |
Flux3LoopAfterDenoiser,
|
| 324 |
]
|
| 325 |
-
block_names: ClassVar = ["multidiffusion_preprocessing", "multidiffusion_loop", "after_denoiser"]
|
| 326 |
|
| 327 |
@property
|
| 328 |
def description(self) -> str:
|
| 329 |
return (
|
| 330 |
-
"FLUX 3 MultiDiffusion denoise step
|
| 331 |
-
"
|
|
|
|
| 332 |
)
|
| 333 |
|
| 334 |
|
| 335 |
-
class Flux3KleinMultiDiffusionDenoiseStep(window_loop.
|
| 336 |
model_name = "flux3-distilled"
|
| 337 |
block_classes: ClassVar = [
|
| 338 |
Flux3MultiDiffusionPreprocessingStep,
|
| 339 |
Flux3KleinMultiDiffusionLoopStep,
|
| 340 |
Flux3LoopAfterDenoiser,
|
| 341 |
]
|
| 342 |
-
block_names: ClassVar = ["multidiffusion_preprocessing", "multidiffusion_loop", "after_denoiser"]
|
| 343 |
|
| 344 |
@property
|
| 345 |
def description(self) -> str:
|
| 346 |
return (
|
| 347 |
-
"
|
| 348 |
-
"flow-map denoiser
|
|
|
|
| 349 |
)
|
| 350 |
|
| 351 |
|
|
@@ -368,8 +348,8 @@ class Flux3PanoramaDecodeStep(Flux3DecodeStep):
|
|
| 368 |
images = panorama.decode_wrapped(
|
| 369 |
vae,
|
| 370 |
latents.to(vae.dtype),
|
| 371 |
-
panorama_height=
|
| 372 |
-
panorama_width=
|
| 373 |
)
|
| 374 |
block_state.images = components.image_processor.postprocess(
|
| 375 |
images, output_type=block_state.output_type, reference_crop=block_state.reference_crop
|
|
@@ -389,7 +369,8 @@ _MD_DENOISE_STEPS = {
|
|
| 389 |
def _build_flux3_blocks(base_blocks_cls):
|
| 390 |
blocks = composition.copy_upstream_blocks(base_blocks_cls)
|
| 391 |
blocks.sub_blocks["prompt_upsampler"] = Flux3MultiDiffusionAutoPromptUpsampleStep()
|
| 392 |
-
|
|
|
|
| 393 |
|
| 394 |
for workflow in composition.iter_denoise_workflows(blocks):
|
| 395 |
if "cond_input" in workflow.sub_blocks:
|
|
@@ -409,7 +390,7 @@ _FLUX3_KLEIN_BASE_MD_BLOCKS = _build_flux3_blocks(Flux3AutoBlocks)
|
|
| 409 |
_FLUX3_KLEIN_MD_BLOCKS = _build_flux3_blocks(Flux3DistilledAutoBlocks)
|
| 410 |
|
| 411 |
|
| 412 |
-
class Flux3KleinBaseMultiDiffusionAutoBlocks(
|
| 413 |
model_name = "flux3"
|
| 414 |
block_classes: ClassVar = list(_FLUX3_KLEIN_BASE_MD_BLOCKS.values())
|
| 415 |
block_names: ClassVar = list(_FLUX3_KLEIN_BASE_MD_BLOCKS.keys())
|
|
@@ -424,12 +405,8 @@ class Flux3KleinBaseMultiDiffusionAutoBlocks(SequentialPipelineBlocks):
|
|
| 424 |
"output canvas; `height_generation` and `width_generation` define the denoiser view window."
|
| 425 |
)
|
| 426 |
|
| 427 |
-
@property
|
| 428 |
-
def outputs(self):
|
| 429 |
-
return [OutputParam.template("images")]
|
| 430 |
-
|
| 431 |
|
| 432 |
-
class Flux3KleinMultiDiffusionAutoBlocks(
|
| 433 |
model_name = "flux3-distilled"
|
| 434 |
block_classes: ClassVar = list(_FLUX3_KLEIN_MD_BLOCKS.values())
|
| 435 |
block_names: ClassVar = list(_FLUX3_KLEIN_MD_BLOCKS.keys())
|
|
@@ -443,7 +420,3 @@ class Flux3KleinMultiDiffusionAutoBlocks(SequentialPipelineBlocks):
|
|
| 443 |
"optional reference images and img2img support. `height` and `width` define the output canvas; "
|
| 444 |
"`height_generation` and `width_generation` define the denoiser view window."
|
| 445 |
)
|
| 446 |
-
|
| 447 |
-
@property
|
| 448 |
-
def outputs(self):
|
| 449 |
-
return [OutputParam.template("images")]
|
|
|
|
| 10 |
ModularPipelineBlocks,
|
| 11 |
OutputParam,
|
| 12 |
PipelineState,
|
|
|
|
| 13 |
)
|
| 14 |
+
from diffusers.modular_pipelines.flux3.before_denoise import (
|
| 15 |
+
Flux3PrepareLatentsStep,
|
| 16 |
+
Flux3TextRoPEInputsStep,
|
| 17 |
+
_prepare_image_ids,
|
| 18 |
+
)
|
| 19 |
from diffusers.modular_pipelines.flux3.decoders import Flux3DecodeStep
|
| 20 |
from diffusers.modular_pipelines.flux3.denoise import (
|
| 21 |
Flux3DenoiseLoopWrapper,
|
|
|
|
| 40 |
_FLUX3_BLOCK_REQUIREMENTS = {**composition.BLOCK_REQUIREMENTS, "torchvision": ">=0.22"}
|
| 41 |
|
| 42 |
|
| 43 |
+
# FLUX 3 scales the H/W position ids of every image token by the upstream latents step factor.
|
| 44 |
+
_FLUX3_IMAGE_ROPE_SCALE = Flux3PrepareLatentsStep().image_rope_scale
|
| 45 |
|
| 46 |
|
| 47 |
class _Flux3PromptListUpsampleMixin:
|
| 48 |
+
"""
|
| 49 |
+
Upsample each regional prompt of `prompt=["", p1, ..., pN]` on its own; the empty fallback stays empty.
|
| 50 |
+
|
| 51 |
+
`boxes` lay out the whole canvas, so they cannot be combined with regional prompts.
|
| 52 |
+
"""
|
| 53 |
|
| 54 |
@property
|
| 55 |
def intermediate_outputs(self):
|
|
|
|
| 61 |
)
|
| 62 |
]
|
| 63 |
|
|
|
|
|
|
|
|
|
|
| 64 |
@torch.no_grad()
|
| 65 |
def __call__(self, components, state: PipelineState):
|
| 66 |
block_state = self.get_block_state(state)
|
| 67 |
if isinstance(block_state.prompt, str):
|
| 68 |
return super().__call__(components, state)
|
| 69 |
+
if block_state.boxes:
|
| 70 |
+
raise ValueError("`boxes` lay out the whole canvas and cannot be combined with regional prompts.")
|
| 71 |
|
| 72 |
+
# only the image-conditioned step declares `image`
|
| 73 |
+
image = getattr(block_state, "image", None)
|
| 74 |
+
images = None if image is None else prepare_references(image)
|
| 75 |
block_state.prompt = [
|
| 76 |
+
prompt
|
| 77 |
+
and upsample_prompt(
|
| 78 |
+
components.prompt_upsampler,
|
| 79 |
+
components.prompt_upsampler_processor,
|
| 80 |
+
request=prompt,
|
| 81 |
+
images=images,
|
| 82 |
+
max_new_tokens=block_state.max_new_tokens,
|
| 83 |
+
)
|
| 84 |
+
for prompt in block_state.prompt
|
| 85 |
]
|
| 86 |
self.set_block_state(state, block_state)
|
| 87 |
return components, state
|
| 88 |
|
| 89 |
|
| 90 |
class Flux3MultiDiffusionText2ImagePromptUpsampleStep(_Flux3PromptListUpsampleMixin, Flux3Text2ImagePromptUpsampleStep):
|
| 91 |
+
"""Text-to-image prompt upsampling that also accepts a list of regional prompts."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
|
| 94 |
class Flux3MultiDiffusionImageConditionedPromptUpsampleStep(
|
| 95 |
_Flux3PromptListUpsampleMixin, Flux3ImageConditionedPromptUpsampleStep
|
| 96 |
):
|
| 97 |
+
"""Image-conditioned prompt upsampling that also accepts a list of regional prompts."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
|
| 100 |
class Flux3MultiDiffusionAutoPromptUpsampleStep(Flux3AutoPromptUpsampleStep):
|
|
|
|
| 227 |
|
| 228 |
class _Flux3MultiDiffusionWindowLoopMixin(window_loop.MultiDiffusionWindowLoopMixin):
|
| 229 |
# FLUX 3 denoisers read their conditioning from the `denoiser_input_fields` dict, so it is rebuilt per batch
|
| 230 |
+
_md_item_keys: ClassVar = ("prompt_embeds", "negative_prompt_embeds")
|
| 231 |
_md_state_keys: ClassVar = (
|
|
|
|
| 232 |
"denoiser_input_fields",
|
|
|
|
|
|
|
| 233 |
"txt_ids",
|
|
|
|
| 234 |
"img_ids",
|
| 235 |
"image_cond_hidden_states",
|
| 236 |
"image_cond_ids",
|
| 237 |
)
|
|
|
|
| 238 |
_md_extra_inputs: ClassVar = (
|
| 239 |
InputParam(
|
| 240 |
"image_cond_latents",
|
|
|
|
| 242 |
required=False,
|
| 243 |
description="Reference latents `(B, C, h_i, w_i)`, each cropped per window as a view of the canvas.",
|
| 244 |
),
|
|
|
|
| 245 |
)
|
| 246 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
def _md_reference_inputs(
|
| 248 |
self, block_state, base_values: dict[str, object], item: window_loop.WindowItem
|
| 249 |
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
| 250 |
+
image_cond_hidden_states = base_values["image_cond_hidden_states"]
|
| 251 |
if image_cond_hidden_states is window_loop.MISSING or image_cond_hidden_states is None:
|
| 252 |
return {}, {}
|
| 253 |
|
| 254 |
tokens, ids = [], []
|
| 255 |
for index, latents in enumerate(block_state.image_cond_latents):
|
| 256 |
+
window_latents = geometry.reference_window(latents, **self._md_window_box(block_state, item))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
tokens.append(window_latents.flatten(2).transpose(1, 2))
|
| 258 |
ids.append(
|
| 259 |
_prepare_image_ids(
|
|
|
|
| 282 |
|
| 283 |
|
| 284 |
class Flux3KleinBaseMultiDiffusionLoopStep(_Flux3MultiDiffusionWindowLoopMixin, Flux3LoopDenoiser):
|
|
|
|
|
|
|
| 285 |
@property
|
| 286 |
def description(self) -> str:
|
| 287 |
return "Run the FLUX 3 CFG denoiser on every window, then merge the window predictions on the full canvas."
|
| 288 |
|
| 289 |
|
| 290 |
class Flux3KleinMultiDiffusionLoopStep(_Flux3MultiDiffusionWindowLoopMixin, Flux3DistilledLoopDenoiser):
|
|
|
|
|
|
|
| 291 |
@property
|
| 292 |
def description(self) -> str:
|
| 293 |
return (
|
|
|
|
| 296 |
)
|
| 297 |
|
| 298 |
|
| 299 |
+
class Flux3KleinBaseMultiDiffusionDenoiseStep(window_loop.MultiDiffusionDenoiseStepMixin, Flux3DenoiseLoopWrapper):
|
|
|
|
| 300 |
block_classes: ClassVar = [
|
| 301 |
Flux3MultiDiffusionPreprocessingStep,
|
| 302 |
Flux3KleinBaseMultiDiffusionLoopStep,
|
| 303 |
Flux3LoopAfterDenoiser,
|
| 304 |
]
|
|
|
|
| 305 |
|
| 306 |
@property
|
| 307 |
def description(self) -> str:
|
| 308 |
return (
|
| 309 |
+
"FLUX 3 Klein Base MultiDiffusion denoise step: at every timestep it lays out the window grid, runs the "
|
| 310 |
+
"CFG denoiser on every window, merges the window predictions on the full canvas and takes one scheduler "
|
| 311 |
+
"step."
|
| 312 |
)
|
| 313 |
|
| 314 |
|
| 315 |
+
class Flux3KleinMultiDiffusionDenoiseStep(window_loop.MultiDiffusionDenoiseStepMixin, Flux3DenoiseLoopWrapper):
|
| 316 |
model_name = "flux3-distilled"
|
| 317 |
block_classes: ClassVar = [
|
| 318 |
Flux3MultiDiffusionPreprocessingStep,
|
| 319 |
Flux3KleinMultiDiffusionLoopStep,
|
| 320 |
Flux3LoopAfterDenoiser,
|
| 321 |
]
|
|
|
|
| 322 |
|
| 323 |
@property
|
| 324 |
def description(self) -> str:
|
| 325 |
return (
|
| 326 |
+
"FLUX 3 Klein (step-distilled) MultiDiffusion denoise step: at every timestep it lays out the window "
|
| 327 |
+
"grid, lets the flow-map denoiser jump every window to the next timestep, merges the window predictions "
|
| 328 |
+
"on the full canvas and takes one scheduler step."
|
| 329 |
)
|
| 330 |
|
| 331 |
|
|
|
|
| 348 |
images = panorama.decode_wrapped(
|
| 349 |
vae,
|
| 350 |
latents.to(vae.dtype),
|
| 351 |
+
panorama_height=block_state.panorama_height,
|
| 352 |
+
panorama_width=block_state.panorama_width,
|
| 353 |
)
|
| 354 |
block_state.images = components.image_processor.postprocess(
|
| 355 |
images, output_type=block_state.output_type, reference_crop=block_state.reference_crop
|
|
|
|
| 369 |
def _build_flux3_blocks(base_blocks_cls):
|
| 370 |
blocks = composition.copy_upstream_blocks(base_blocks_cls)
|
| 371 |
blocks.sub_blocks["prompt_upsampler"] = Flux3MultiDiffusionAutoPromptUpsampleStep()
|
| 372 |
+
regional_prompt_encode = Flux3RegionalPromptEncodeStep(pad_multiple=blocks.sub_blocks["text_encoder"].pad_multiple)
|
| 373 |
+
composition.insert_block(blocks, "regional_prompt_encode", regional_prompt_encode, before="text_encoder")
|
| 374 |
|
| 375 |
for workflow in composition.iter_denoise_workflows(blocks):
|
| 376 |
if "cond_input" in workflow.sub_blocks:
|
|
|
|
| 390 |
_FLUX3_KLEIN_MD_BLOCKS = _build_flux3_blocks(Flux3DistilledAutoBlocks)
|
| 391 |
|
| 392 |
|
| 393 |
+
class Flux3KleinBaseMultiDiffusionAutoBlocks(composition.MultiDiffusionAutoBlocks):
|
| 394 |
model_name = "flux3"
|
| 395 |
block_classes: ClassVar = list(_FLUX3_KLEIN_BASE_MD_BLOCKS.values())
|
| 396 |
block_names: ClassVar = list(_FLUX3_KLEIN_BASE_MD_BLOCKS.keys())
|
|
|
|
| 405 |
"output canvas; `height_generation` and `width_generation` define the denoiser view window."
|
| 406 |
)
|
| 407 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
|
| 409 |
+
class Flux3KleinMultiDiffusionAutoBlocks(composition.MultiDiffusionAutoBlocks):
|
| 410 |
model_name = "flux3-distilled"
|
| 411 |
block_classes: ClassVar = list(_FLUX3_KLEIN_MD_BLOCKS.values())
|
| 412 |
block_names: ClassVar = list(_FLUX3_KLEIN_MD_BLOCKS.keys())
|
|
|
|
| 420 |
"optional reference images and img2img support. `height` and `width` define the output canvas; "
|
| 421 |
"`height_generation` and `width_generation` define the denoiser view window."
|
| 422 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -76,21 +76,6 @@ def _resolve_size(value, fallback: int | None) -> int:
|
|
| 76 |
return fallback if value is None else int(value)
|
| 77 |
|
| 78 |
|
| 79 |
-
def _get_canvas_size(block_state, components) -> tuple[int, int]:
|
| 80 |
-
return (
|
| 81 |
-
_resolve_size(getattr(block_state, "height", None), getattr(components, "default_height", None)),
|
| 82 |
-
_resolve_size(getattr(block_state, "width", None), getattr(components, "default_width", None)),
|
| 83 |
-
)
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
def _get_window_size(block_state, components) -> tuple[int, int]:
|
| 87 |
-
full_h, full_w = _get_canvas_size(block_state, components)
|
| 88 |
-
return (
|
| 89 |
-
_resolve_size(getattr(block_state, "height_generation", None), full_h),
|
| 90 |
-
_resolve_size(getattr(block_state, "width_generation", None), full_w),
|
| 91 |
-
)
|
| 92 |
-
|
| 93 |
-
|
| 94 |
def _packed_hw(size: int, vae_scale_factor: int) -> int:
|
| 95 |
return int(size) // (vae_scale_factor * 2)
|
| 96 |
|
|
@@ -100,32 +85,38 @@ def accumulation_dtype(dtype: torch.dtype) -> torch.dtype:
|
|
| 100 |
|
| 101 |
|
| 102 |
def _window_starts(full: int, window: int, stride: int, *, offset: int = 0, wrap: bool = False) -> list[int]:
|
| 103 |
-
window = min(window, full)
|
| 104 |
-
stride = max(1, stride)
|
| 105 |
-
offset = int(offset) % stride
|
| 106 |
-
|
| 107 |
if full <= window:
|
| 108 |
return [0]
|
| 109 |
|
| 110 |
if wrap:
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
|
| 114 |
-
last = full - window
|
| 115 |
-
return sorted({0, *starts, last})
|
| 116 |
|
| 117 |
|
| 118 |
def _step_offset(offset: int, stride: int, step: int) -> int:
|
| 119 |
-
|
| 120 |
-
return 0
|
| 121 |
-
return (int(step) * int(offset)) % int(stride)
|
| 122 |
|
| 123 |
|
| 124 |
def _window_axis_indices(full: int, start: int, size: int, *, wrap: bool, device: torch.device) -> torch.Tensor:
|
| 125 |
indices = torch.arange(start, start + size, device=device)
|
| 126 |
-
if wrap
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
|
| 131 |
def reshape_packed(x: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
|
@@ -142,12 +133,9 @@ def window_view(
|
|
| 142 |
wrap_height: bool = False,
|
| 143 |
wrap_width: bool = False,
|
| 144 |
) -> torch.Tensor:
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
y_indices = _window_axis_indices(x.shape[1], top, height, wrap=wrap_height, device=x.device)
|
| 149 |
-
x_indices = _window_axis_indices(x.shape[2], left, width, wrap=wrap_width, device=x.device)
|
| 150 |
-
return x.index_select(1, y_indices).index_select(2, x_indices).reshape(x.shape[0], -1, x.shape[-1])
|
| 151 |
|
| 152 |
|
| 153 |
def accumulate_window(
|
|
@@ -183,17 +171,12 @@ def _image_axis_mask_and_local_ids(
|
|
| 183 |
local_ids = torch.zeros_like(coords)
|
| 184 |
end = start + size
|
| 185 |
|
| 186 |
-
segments
|
|
|
|
| 187 |
if wrap and end > full_size:
|
| 188 |
-
segments.append((
|
| 189 |
-
segments.append((0, end % full_size, full_size - start))
|
| 190 |
-
else:
|
| 191 |
-
segments.append((start, min(end, full_size), 0))
|
| 192 |
|
| 193 |
for segment_start, segment_end, local_start in segments:
|
| 194 |
-
if segment_start >= segment_end:
|
| 195 |
-
continue
|
| 196 |
-
|
| 197 |
image_start = segment_start * image_size // full_size
|
| 198 |
image_end = (segment_end * image_size + full_size - 1) // full_size
|
| 199 |
image_end = min(max(image_end, image_start + 1), image_size)
|
|
@@ -219,37 +202,44 @@ def image_conditioning_window(
|
|
| 219 |
wrap_height: bool,
|
| 220 |
wrap_width: bool,
|
| 221 |
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
y_mask, local_y = _image_axis_mask_and_local_ids(
|
| 226 |
-
image_latent_ids[0, :, 1],
|
| 227 |
-
start=top,
|
| 228 |
-
size=window_h,
|
| 229 |
-
full_size=full_h,
|
| 230 |
-
image_size=image_h,
|
| 231 |
-
wrap=wrap_height,
|
| 232 |
-
)
|
| 233 |
-
x_mask, local_x = _image_axis_mask_and_local_ids(
|
| 234 |
-
image_latent_ids[0, :, 2],
|
| 235 |
-
start=left,
|
| 236 |
-
size=window_w,
|
| 237 |
-
full_size=full_w,
|
| 238 |
-
image_size=image_w,
|
| 239 |
-
wrap=wrap_width,
|
| 240 |
-
)
|
| 241 |
-
mask = y_mask & x_mask
|
| 242 |
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
|
|
|
|
|
|
| 253 |
|
| 254 |
|
| 255 |
def _reference_axis_indices(
|
|
@@ -309,12 +299,7 @@ def regional_mask_window(
|
|
| 309 |
wrap_height: bool,
|
| 310 |
wrap_width: bool,
|
| 311 |
) -> torch.Tensor:
|
| 312 |
-
|
| 313 |
-
return masks[:, top : top + height, left : left + width]
|
| 314 |
-
|
| 315 |
-
y_indices = _window_axis_indices(masks.shape[1], top, height, wrap=wrap_height, device=masks.device)
|
| 316 |
-
x_indices = _window_axis_indices(masks.shape[2], left, width, wrap=wrap_width, device=masks.device)
|
| 317 |
-
return masks.index_select(1, y_indices).index_select(2, x_indices)
|
| 318 |
|
| 319 |
|
| 320 |
def _normalize_weighting_type(weighting_type: str | None) -> str | None:
|
|
@@ -395,14 +380,10 @@ def _validate_multidiffusion_args(
|
|
| 395 |
|
| 396 |
@dataclass(frozen=True)
|
| 397 |
class MDLayout:
|
| 398 |
-
|
| 399 |
-
|
| 400 |
window_height: int
|
| 401 |
window_width: int
|
| 402 |
-
stride_height: int
|
| 403 |
-
stride_width: int
|
| 404 |
-
offset_height: int
|
| 405 |
-
offset_width: int
|
| 406 |
full_h: int
|
| 407 |
full_w: int
|
| 408 |
window_h: int
|
|
@@ -416,10 +397,13 @@ class MDLayout:
|
|
| 416 |
|
| 417 |
@classmethod
|
| 418 |
def from_state(cls, block_state, components) -> MDLayout:
|
|
|
|
| 419 |
vae_scale_factor = components.vae_scale_factor
|
| 420 |
token_scale = vae_scale_factor * 2
|
| 421 |
-
canvas_height
|
| 422 |
-
|
|
|
|
|
|
|
| 423 |
stride_height = _resolve_size(getattr(block_state, "window_stride_height", None), window_height // 2)
|
| 424 |
stride_width = _resolve_size(getattr(block_state, "window_stride_width", None), window_width // 2)
|
| 425 |
offset_height = _resolve_size(getattr(block_state, "window_stride_height_offset", None), 0)
|
|
@@ -438,14 +422,8 @@ class MDLayout:
|
|
| 438 |
)
|
| 439 |
|
| 440 |
return cls(
|
| 441 |
-
canvas_height=canvas_height,
|
| 442 |
-
canvas_width=canvas_width,
|
| 443 |
window_height=window_height,
|
| 444 |
window_width=window_width,
|
| 445 |
-
stride_height=stride_height,
|
| 446 |
-
stride_width=stride_width,
|
| 447 |
-
offset_height=offset_height,
|
| 448 |
-
offset_width=offset_width,
|
| 449 |
full_h=_packed_hw(canvas_height, vae_scale_factor),
|
| 450 |
full_w=_packed_hw(canvas_width, vae_scale_factor),
|
| 451 |
window_h=_packed_hw(window_height, vae_scale_factor),
|
|
@@ -459,22 +437,10 @@ class MDLayout:
|
|
| 459 |
)
|
| 460 |
|
| 461 |
def windows(self, step: int) -> list[tuple[int, int]]:
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
ys = _window_starts(
|
| 465 |
-
|
| 466 |
-
self.window_h,
|
| 467 |
-
self.stride_h,
|
| 468 |
-
offset=step_offset_h,
|
| 469 |
-
wrap=self.wrap_height,
|
| 470 |
-
)
|
| 471 |
-
xs = _window_starts(
|
| 472 |
-
self.full_w,
|
| 473 |
-
self.window_w,
|
| 474 |
-
self.stride_w,
|
| 475 |
-
offset=step_offset_w,
|
| 476 |
-
wrap=self.wrap_width,
|
| 477 |
-
)
|
| 478 |
return [(y, x) for y in ys for x in xs]
|
| 479 |
|
| 480 |
|
|
@@ -482,9 +448,10 @@ class MultiDiffusionWindowWeight:
|
|
| 482 |
"""
|
| 483 |
Build a 2D weighting mask for a single window.
|
| 484 |
|
| 485 |
-
`weighting_range` is
|
| 486 |
-
-
|
| 487 |
-
- smaller values keep a
|
|
|
|
| 488 |
"""
|
| 489 |
|
| 490 |
def __init__(
|
|
|
|
| 76 |
return fallback if value is None else int(value)
|
| 77 |
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def _packed_hw(size: int, vae_scale_factor: int) -> int:
|
| 80 |
return int(size) // (vae_scale_factor * 2)
|
| 81 |
|
|
|
|
| 85 |
|
| 86 |
|
| 87 |
def _window_starts(full: int, window: int, stride: int, *, offset: int = 0, wrap: bool = False) -> list[int]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
if full <= window:
|
| 89 |
return [0]
|
| 90 |
|
| 91 |
if wrap:
|
| 92 |
+
starts = list(range(offset, full, stride))
|
| 93 |
+
# the last window must reach past the seam up to the first start, which the offset moved away from 0
|
| 94 |
+
if starts[-1] + window < full + offset:
|
| 95 |
+
starts.append(full + offset - window)
|
| 96 |
+
return starts
|
| 97 |
|
| 98 |
+
return sorted({0, *range(offset, full - window + 1, stride), full - window})
|
|
|
|
|
|
|
| 99 |
|
| 100 |
|
| 101 |
def _step_offset(offset: int, stride: int, step: int) -> int:
|
| 102 |
+
return step * offset % stride
|
|
|
|
|
|
|
| 103 |
|
| 104 |
|
| 105 |
def _window_axis_indices(full: int, start: int, size: int, *, wrap: bool, device: torch.device) -> torch.Tensor:
|
| 106 |
indices = torch.arange(start, start + size, device=device)
|
| 107 |
+
return indices.remainder(full) if wrap else indices
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _crop_window(
|
| 111 |
+
x: torch.Tensor, top: int, left: int, height: int, width: int, *, wrap_height: bool, wrap_width: bool
|
| 112 |
+
) -> torch.Tensor:
|
| 113 |
+
"""Crop dims 1 and 2 of `x` to one window, wrapping around the canvas edges on the panorama axes."""
|
| 114 |
+
if not wrap_height and not wrap_width:
|
| 115 |
+
return x[:, top : top + height, left : left + width]
|
| 116 |
+
|
| 117 |
+
y_indices = _window_axis_indices(x.shape[1], top, height, wrap=wrap_height, device=x.device)
|
| 118 |
+
x_indices = _window_axis_indices(x.shape[2], left, width, wrap=wrap_width, device=x.device)
|
| 119 |
+
return x.index_select(1, y_indices).index_select(2, x_indices)
|
| 120 |
|
| 121 |
|
| 122 |
def reshape_packed(x: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
|
|
|
| 133 |
wrap_height: bool = False,
|
| 134 |
wrap_width: bool = False,
|
| 135 |
) -> torch.Tensor:
|
| 136 |
+
"""The packed tokens `(B, height * width, C)` of one window of an unpacked canvas `(B, H, W, C)`."""
|
| 137 |
+
window = _crop_window(x, top, left, height, width, wrap_height=wrap_height, wrap_width=wrap_width)
|
| 138 |
+
return window.reshape(x.shape[0], -1, x.shape[-1])
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
|
| 141 |
def accumulate_window(
|
|
|
|
| 171 |
local_ids = torch.zeros_like(coords)
|
| 172 |
end = start + size
|
| 173 |
|
| 174 |
+
# canvas segments (start, end, local offset): the window, split in two where it wraps past the seam
|
| 175 |
+
segments = [(start, min(end, full_size), 0)]
|
| 176 |
if wrap and end > full_size:
|
| 177 |
+
segments.append((0, end - full_size, full_size - start))
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
for segment_start, segment_end, local_start in segments:
|
|
|
|
|
|
|
|
|
|
| 180 |
image_start = segment_start * image_size // full_size
|
| 181 |
image_end = (segment_end * image_size + full_size - 1) // full_size
|
| 182 |
image_end = min(max(image_end, image_start + 1), image_size)
|
|
|
|
| 202 |
wrap_height: bool,
|
| 203 |
wrap_width: bool,
|
| 204 |
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 205 |
+
"""
|
| 206 |
+
Crop packed FLUX.2 reference tokens `(B, N, C)` and their `(t, h, w, l)` ids to one canvas window.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
+
The references are concatenated along N, each with its own time coordinate `t` and its own 0-based grid, so each
|
| 209 |
+
one is mapped proportionally onto the canvas on its own; the crops keep the reference order.
|
| 210 |
+
"""
|
| 211 |
+
window_latents, window_ids = [], []
|
| 212 |
+
for t in torch.unique_consecutive(image_latent_ids[0, :, 0]):
|
| 213 |
+
reference = image_latent_ids[0, :, 0] == t
|
| 214 |
+
ids = image_latent_ids[:, reference]
|
| 215 |
+
y_mask, local_y = _image_axis_mask_and_local_ids(
|
| 216 |
+
ids[0, :, 1],
|
| 217 |
+
start=top,
|
| 218 |
+
size=window_h,
|
| 219 |
+
full_size=full_h,
|
| 220 |
+
image_size=int(ids[0, :, 1].max()) + 1,
|
| 221 |
+
wrap=wrap_height,
|
| 222 |
+
)
|
| 223 |
+
x_mask, local_x = _image_axis_mask_and_local_ids(
|
| 224 |
+
ids[0, :, 2],
|
| 225 |
+
start=left,
|
| 226 |
+
size=window_w,
|
| 227 |
+
full_size=full_w,
|
| 228 |
+
image_size=int(ids[0, :, 2].max()) + 1,
|
| 229 |
+
wrap=wrap_width,
|
| 230 |
+
)
|
| 231 |
+
mask = y_mask & x_mask
|
| 232 |
+
ids = ids[:, mask].clone()
|
| 233 |
+
ids[:, :, 1] = local_y[mask]
|
| 234 |
+
ids[:, :, 2] = local_x[mask]
|
| 235 |
|
| 236 |
+
# row-major order over the local (h, w, l) grid, which a wrapped crop otherwise breaks
|
| 237 |
+
local_w = int(ids[0, :, 2].max()) + 1
|
| 238 |
+
local_layers = int(ids[0, :, 3].max()) + 1
|
| 239 |
+
order = torch.argsort((ids[0, :, 1] * local_w + ids[0, :, 2]) * local_layers + ids[0, :, 3])
|
| 240 |
+
window_latents.append(image_latents[:, reference][:, mask][:, order])
|
| 241 |
+
window_ids.append(ids[:, order])
|
| 242 |
+
return torch.cat(window_latents, dim=1), torch.cat(window_ids, dim=1)
|
| 243 |
|
| 244 |
|
| 245 |
def _reference_axis_indices(
|
|
|
|
| 299 |
wrap_height: bool,
|
| 300 |
wrap_width: bool,
|
| 301 |
) -> torch.Tensor:
|
| 302 |
+
return _crop_window(masks, top, left, height, width, wrap_height=wrap_height, wrap_width=wrap_width)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
|
| 305 |
def _normalize_weighting_type(weighting_type: str | None) -> str | None:
|
|
|
|
| 380 |
|
| 381 |
@dataclass(frozen=True)
|
| 382 |
class MDLayout:
|
| 383 |
+
"""The validated window grid of one canvas: the window size in pixels, everything else in packed tokens."""
|
| 384 |
+
|
| 385 |
window_height: int
|
| 386 |
window_width: int
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
full_h: int
|
| 388 |
full_w: int
|
| 389 |
window_h: int
|
|
|
|
| 397 |
|
| 398 |
@classmethod
|
| 399 |
def from_state(cls, block_state, components) -> MDLayout:
|
| 400 |
+
# getattr: FLUX 3 has no `default_height` and the set-timesteps steps don't declare the panorama flags
|
| 401 |
vae_scale_factor = components.vae_scale_factor
|
| 402 |
token_scale = vae_scale_factor * 2
|
| 403 |
+
canvas_height = _resolve_size(getattr(block_state, "height", None), getattr(components, "default_height", None))
|
| 404 |
+
canvas_width = _resolve_size(getattr(block_state, "width", None), getattr(components, "default_width", None))
|
| 405 |
+
window_height = _resolve_size(getattr(block_state, "height_generation", None), canvas_height)
|
| 406 |
+
window_width = _resolve_size(getattr(block_state, "width_generation", None), canvas_width)
|
| 407 |
stride_height = _resolve_size(getattr(block_state, "window_stride_height", None), window_height // 2)
|
| 408 |
stride_width = _resolve_size(getattr(block_state, "window_stride_width", None), window_width // 2)
|
| 409 |
offset_height = _resolve_size(getattr(block_state, "window_stride_height_offset", None), 0)
|
|
|
|
| 422 |
)
|
| 423 |
|
| 424 |
return cls(
|
|
|
|
|
|
|
| 425 |
window_height=window_height,
|
| 426 |
window_width=window_width,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
full_h=_packed_hw(canvas_height, vae_scale_factor),
|
| 428 |
full_w=_packed_hw(canvas_width, vae_scale_factor),
|
| 429 |
window_h=_packed_hw(window_height, vae_scale_factor),
|
|
|
|
| 437 |
)
|
| 438 |
|
| 439 |
def windows(self, step: int) -> list[tuple[int, int]]:
|
| 440 |
+
offset_h = _step_offset(self.offset_h, self.stride_h, step)
|
| 441 |
+
offset_w = _step_offset(self.offset_w, self.stride_w, step)
|
| 442 |
+
ys = _window_starts(self.full_h, self.window_h, self.stride_h, offset=offset_h, wrap=self.wrap_height)
|
| 443 |
+
xs = _window_starts(self.full_w, self.window_w, self.stride_w, offset=offset_w, wrap=self.wrap_width)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
return [(y, x) for y in ys for x in xs]
|
| 445 |
|
| 446 |
|
|
|
|
| 448 |
"""
|
| 449 |
Build a 2D weighting mask for a single window.
|
| 450 |
|
| 451 |
+
`weighting_range` is the ramp length as a fraction of the window size per axis:
|
| 452 |
+
- 0.5 ramps from the border all the way to the center,
|
| 453 |
+
- smaller values keep a flat plateau in the middle,
|
| 454 |
+
- larger values stop the ramp before it reaches full weight.
|
| 455 |
"""
|
| 456 |
|
| 457 |
def __init__(
|
|
@@ -2,125 +2,36 @@
|
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
-
from dataclasses import dataclass
|
| 6 |
-
|
| 7 |
import torch
|
| 8 |
|
| 9 |
|
| 10 |
-
@dataclass(frozen=True)
|
| 11 |
-
class _PanoramaDecodePadding:
|
| 12 |
-
top: int = 0
|
| 13 |
-
bottom: int = 0
|
| 14 |
-
left: int = 0
|
| 15 |
-
right: int = 0
|
| 16 |
-
|
| 17 |
-
@property
|
| 18 |
-
def enabled(self) -> bool:
|
| 19 |
-
return any((self.top, self.bottom, self.left, self.right))
|
| 20 |
-
|
| 21 |
-
@property
|
| 22 |
-
def torch_pad(self) -> tuple[int, int, int, int]:
|
| 23 |
-
return self.left, self.right, self.top, self.bottom
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def _vae_decode_latent_border(vae) -> int:
|
| 27 |
-
return max(0, int(getattr(vae, "tile_latent_min_size", 0) * getattr(vae, "tile_overlap_factor", 0)))
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
def _panorama_decode_padding(
|
| 31 |
-
*,
|
| 32 |
-
border: int,
|
| 33 |
-
panorama_height: bool,
|
| 34 |
-
panorama_width: bool,
|
| 35 |
-
) -> _PanoramaDecodePadding:
|
| 36 |
-
border = max(0, int(border))
|
| 37 |
-
return _PanoramaDecodePadding(
|
| 38 |
-
top=border if panorama_height else 0,
|
| 39 |
-
bottom=border if panorama_height else 0,
|
| 40 |
-
left=border if panorama_width else 0,
|
| 41 |
-
right=border if panorama_width else 0,
|
| 42 |
-
)
|
| 43 |
-
|
| 44 |
-
|
| 45 |
def _pad_panorama_decode_latents(
|
| 46 |
-
latents: torch.Tensor,
|
| 47 |
-
|
| 48 |
-
border
|
| 49 |
-
panorama_height
|
| 50 |
-
panorama_width
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
panorama_height=panorama_height,
|
| 55 |
-
panorama_width=panorama_width,
|
| 56 |
-
)
|
| 57 |
-
if not padding.enabled:
|
| 58 |
-
return latents, padding
|
| 59 |
-
return torch.nn.functional.pad(latents, padding.torch_pad, mode="circular"), padding
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def _decoded_crop_bounds(
|
| 63 |
-
decoded_size: int, padded_latent_size: int, start_latent: int, end_latent: int
|
| 64 |
-
) -> tuple[int, int]:
|
| 65 |
-
scale = decoded_size / padded_latent_size
|
| 66 |
-
start = round(start_latent * scale)
|
| 67 |
-
end = round(end_latent * scale)
|
| 68 |
-
if end <= start:
|
| 69 |
-
raise ValueError(
|
| 70 |
-
"Panorama VAE decode crop is empty. "
|
| 71 |
-
f"Got decoded_size={decoded_size}, padded_latent_size={padded_latent_size}, "
|
| 72 |
-
f"start_latent={start_latent}, end_latent={end_latent}."
|
| 73 |
-
)
|
| 74 |
-
return start, end
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def _crop_panorama_decoded_image(
|
| 78 |
-
image: torch.Tensor,
|
| 79 |
-
*,
|
| 80 |
-
padded_latent_height: int,
|
| 81 |
-
padded_latent_width: int,
|
| 82 |
-
padding: _PanoramaDecodePadding,
|
| 83 |
-
) -> torch.Tensor:
|
| 84 |
-
if not padding.enabled:
|
| 85 |
-
return image
|
| 86 |
-
|
| 87 |
-
top = 0
|
| 88 |
-
bottom = image.shape[-2]
|
| 89 |
-
if padding.top or padding.bottom:
|
| 90 |
-
top, bottom = _decoded_crop_bounds(
|
| 91 |
-
image.shape[-2],
|
| 92 |
-
padded_latent_height,
|
| 93 |
-
padding.top,
|
| 94 |
-
padded_latent_height - padding.bottom,
|
| 95 |
-
)
|
| 96 |
-
|
| 97 |
-
left = 0
|
| 98 |
-
right = image.shape[-1]
|
| 99 |
-
if padding.left or padding.right:
|
| 100 |
-
left, right = _decoded_crop_bounds(
|
| 101 |
-
image.shape[-1],
|
| 102 |
-
padded_latent_width,
|
| 103 |
-
padding.left,
|
| 104 |
-
padded_latent_width - padding.right,
|
| 105 |
-
)
|
| 106 |
-
|
| 107 |
-
return image[..., top:bottom, left:right]
|
| 108 |
|
| 109 |
|
| 110 |
def decode_wrapped(vae, latents: torch.Tensor, *, panorama_height: bool, panorama_width: bool) -> torch.Tensor:
|
| 111 |
-
|
|
|
|
| 112 |
latents,
|
| 113 |
-
border=
|
| 114 |
panorama_height=panorama_height,
|
| 115 |
panorama_width=panorama_width,
|
| 116 |
)
|
| 117 |
-
images = vae.decode(
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
)
|
|
|
|
| 124 |
|
| 125 |
|
| 126 |
def denormalize_flux2_vae_latents(vae, latents: torch.Tensor) -> torch.Tensor:
|
|
|
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
|
|
|
| 5 |
import torch
|
| 6 |
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
def _pad_panorama_decode_latents(
|
| 9 |
+
latents: torch.Tensor, *, border: int, panorama_height: bool, panorama_width: bool
|
| 10 |
+
) -> tuple[torch.Tensor, tuple[int, int]]:
|
| 11 |
+
"""Circular-pad the wrapped axes by `border` latent cells; also returns the `(height, width)` padding."""
|
| 12 |
+
pad_h = border if panorama_height else 0
|
| 13 |
+
pad_w = border if panorama_width else 0
|
| 14 |
+
if pad_h or pad_w:
|
| 15 |
+
latents = torch.nn.functional.pad(latents, (pad_w, pad_w, pad_h, pad_h), mode="circular")
|
| 16 |
+
return latents, (pad_h, pad_w)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
def decode_wrapped(vae, latents: torch.Tensor, *, panorama_height: bool, panorama_width: bool) -> torch.Tensor:
|
| 20 |
+
"""Decode with the wrapped axes circular-padded by the VAE tile overlap, then crop the padding back off."""
|
| 21 |
+
padded, (pad_h, pad_w) = _pad_panorama_decode_latents(
|
| 22 |
latents,
|
| 23 |
+
border=int(vae.tile_latent_min_size * vae.tile_overlap_factor),
|
| 24 |
panorama_height=panorama_height,
|
| 25 |
panorama_width=panorama_width,
|
| 26 |
)
|
| 27 |
+
images = vae.decode(padded, return_dict=False)[0]
|
| 28 |
+
|
| 29 |
+
# the decoder upsamples every latent cell by the same factor per axis
|
| 30 |
+
scale_h = images.shape[-2] / padded.shape[-2]
|
| 31 |
+
scale_w = images.shape[-1] / padded.shape[-1]
|
| 32 |
+
top, bottom = round(pad_h * scale_h), round((padded.shape[-2] - pad_h) * scale_h)
|
| 33 |
+
left, right = round(pad_w * scale_w), round((padded.shape[-1] - pad_w) * scale_w)
|
| 34 |
+
return images[..., top:bottom, left:right]
|
| 35 |
|
| 36 |
|
| 37 |
def denormalize_flux2_vae_latents(vae, latents: torch.Tensor) -> torch.Tensor:
|
|
@@ -60,7 +60,7 @@ class MultiDiffusionImg2ImgStep(ModularPipelineBlocks):
|
|
| 60 |
def __call__(self, components, state: PipelineState):
|
| 61 |
block_state = self.get_block_state(state)
|
| 62 |
|
| 63 |
-
if
|
| 64 |
return components, state
|
| 65 |
|
| 66 |
image_latents = block_state.image_img2img.to(
|
|
@@ -96,7 +96,7 @@ class RegionalPromptSplitStep(ModularPipelineBlocks):
|
|
| 96 |
|
| 97 |
@property
|
| 98 |
def description(self) -> str:
|
| 99 |
-
return
|
| 100 |
|
| 101 |
@property
|
| 102 |
def inputs(self):
|
|
@@ -122,14 +122,13 @@ class RegionalPromptSplitStep(ModularPipelineBlocks):
|
|
| 122 |
@torch.no_grad()
|
| 123 |
def __call__(self, components, state: PipelineState):
|
| 124 |
block_state = self.get_block_state(state)
|
| 125 |
-
|
| 126 |
-
if regional_masks is None:
|
| 127 |
return components, state
|
| 128 |
|
| 129 |
-
region_count = regional_masks.shape[0]
|
| 130 |
if block_state.prompt_embeds.shape[0] != region_count + 1:
|
| 131 |
raise ValueError(
|
| 132 |
-
"
|
| 133 |
f"Got {block_state.prompt_embeds.shape[0]} prompt embeddings and {region_count} masks."
|
| 134 |
)
|
| 135 |
|
|
@@ -139,7 +138,7 @@ class RegionalPromptSplitStep(ModularPipelineBlocks):
|
|
| 139 |
setattr(block_state, name, embeds[:1])
|
| 140 |
|
| 141 |
for name in self._fallback_fields:
|
| 142 |
-
embeds = getattr(block_state, name
|
| 143 |
setattr(block_state, name, None if embeds is None else embeds[:1])
|
| 144 |
|
| 145 |
self.set_block_state(state, block_state)
|
|
|
|
| 60 |
def __call__(self, components, state: PipelineState):
|
| 61 |
block_state = self.get_block_state(state)
|
| 62 |
|
| 63 |
+
if block_state.image_img2img is None:
|
| 64 |
return components, state
|
| 65 |
|
| 66 |
image_latents = block_state.image_img2img.to(
|
|
|
|
| 96 |
|
| 97 |
@property
|
| 98 |
def description(self) -> str:
|
| 99 |
+
return 'Split the `prompt=["", p1, ..., pN]` embeddings into the fallback prompt and one entry per mask.'
|
| 100 |
|
| 101 |
@property
|
| 102 |
def inputs(self):
|
|
|
|
| 122 |
@torch.no_grad()
|
| 123 |
def __call__(self, components, state: PipelineState):
|
| 124 |
block_state = self.get_block_state(state)
|
| 125 |
+
if block_state.regional_masks is None:
|
|
|
|
| 126 |
return components, state
|
| 127 |
|
| 128 |
+
region_count = block_state.regional_masks.shape[0]
|
| 129 |
if block_state.prompt_embeds.shape[0] != region_count + 1:
|
| 130 |
raise ValueError(
|
| 131 |
+
"Regional prompting expects one fallback prompt plus one prompt per mask. "
|
| 132 |
f"Got {block_state.prompt_embeds.shape[0]} prompt embeddings and {region_count} masks."
|
| 133 |
)
|
| 134 |
|
|
|
|
| 138 |
setattr(block_state, name, embeds[:1])
|
| 139 |
|
| 140 |
for name in self._fallback_fields:
|
| 141 |
+
embeds = getattr(block_state, name)
|
| 142 |
setattr(block_state, name, None if embeds is None else embeds[:1])
|
| 143 |
|
| 144 |
self.set_block_state(state, block_state)
|
|
@@ -29,7 +29,7 @@ MISSING = object()
|
|
| 29 |
|
| 30 |
|
| 31 |
def _window_batch_size(value) -> int:
|
| 32 |
-
value =
|
| 33 |
if value <= 0:
|
| 34 |
raise ValueError(f"`window_batch_size` must be a positive integer, got {value}.")
|
| 35 |
return value
|
|
@@ -76,7 +76,7 @@ class MultiDiffusionPreprocessingStep(ModularPipelineBlocks):
|
|
| 76 |
type_hint=str,
|
| 77 |
default="cosine",
|
| 78 |
required=False,
|
| 79 |
-
description="Window blending ramp: 'cosine', 'linear', or
|
| 80 |
),
|
| 81 |
InputParam(
|
| 82 |
"weighting_range",
|
|
@@ -132,8 +132,8 @@ class MultiDiffusionPreprocessingStep(ModularPipelineBlocks):
|
|
| 132 |
|
| 133 |
weighting_range = geometry.normalize_weighting_range(
|
| 134 |
getattr(block_state, "weighting_range", None),
|
| 135 |
-
default_h=layout.
|
| 136 |
-
default_w=layout.
|
| 137 |
)
|
| 138 |
|
| 139 |
block_state.md_full_latents = block_state.latents
|
|
@@ -188,17 +188,18 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 188 |
|
| 189 |
Placed before an upstream denoiser in the MRO. A family subclass names the denoiser state it touches and fills
|
| 190 |
the `_md_*` hooks:
|
| 191 |
-
- `_md_state_keys`: state captured before the window calls and restored after them,
|
| 192 |
- `_md_item_keys`: per-sample tensors repeated once per window in a batch,
|
| 193 |
- `_md_regional_keys`: embeddings replaced by `regional_<name>[region]` for a regional prompt,
|
| 194 |
-
- `
|
|
|
|
|
|
|
| 195 |
Items whose tensors differ in shape (reference crops, regional text lengths) are never batched together, so the
|
| 196 |
`shared` inputs of a batch, which are fully determined by those shapes, are taken from its first item.
|
| 197 |
"""
|
| 198 |
|
| 199 |
-
_md_state_keys: ClassVar[tuple[str, ...]] = ()
|
| 200 |
_md_item_keys: ClassVar[tuple[str, ...]] = ()
|
| 201 |
_md_regional_keys: ClassVar[tuple[str, ...]] = ("prompt_embeds",)
|
|
|
|
| 202 |
_md_extra_inputs: ClassVar[tuple[InputParam, ...]] = ()
|
| 203 |
|
| 204 |
@property
|
|
@@ -217,6 +218,10 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 217 |
InputParam("md_window_weight", required=True, type_hint=torch.Tensor),
|
| 218 |
InputParam("md_window_batch_size", type_hint=int, default=1),
|
| 219 |
InputParam("md_regional_masks", type_hint=torch.Tensor, required=False),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
*self._md_extra_inputs,
|
| 221 |
]
|
| 222 |
|
|
@@ -243,13 +248,35 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 243 |
return f"{kind} {i + 1}/{num_inference_steps}"
|
| 244 |
return kind
|
| 245 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
# Family hooks ----------------------------------------------------------------------------------------------------
|
| 247 |
|
| 248 |
def _md_check_inputs(self, block_state) -> None:
|
| 249 |
del block_state
|
| 250 |
|
| 251 |
def _md_window_ids(self, block_state, base_values: dict[str, object], item_count: int) -> dict[str, torch.Tensor]:
|
| 252 |
-
|
|
|
|
|
|
|
| 253 |
|
| 254 |
def _md_reference_inputs(
|
| 255 |
self, block_state, base_values: dict[str, object], item: WindowItem
|
|
@@ -261,10 +288,12 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 261 |
self, block_state, base_values: dict[str, object], region_index: int, batch_size: int
|
| 262 |
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
| 263 |
del base_values
|
| 264 |
-
batched = {
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
| 268 |
return batched, {}
|
| 269 |
|
| 270 |
def _md_set_inputs(self, block_state, base_values: dict[str, object], values: dict[str, torch.Tensor]) -> None:
|
|
@@ -278,34 +307,18 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 278 |
def __call__(self, components, block_state, i: int, t: torch.Tensor):
|
| 279 |
full_latents = block_state.md_full_latents
|
| 280 |
batch_size, _, channels = full_latents.shape
|
| 281 |
-
full_h = block_state.md_full_h
|
| 282 |
-
full_w = block_state.md_full_w
|
| 283 |
|
| 284 |
-
latents_2d = geometry.reshape_packed(full_latents,
|
| 285 |
accum_dtype = geometry.accumulation_dtype(latents_2d.dtype)
|
| 286 |
noise_sum = torch.zeros_like(latents_2d, dtype=accum_dtype)
|
| 287 |
-
weight_sum = torch.zeros((1,
|
| 288 |
|
| 289 |
self._md_check_inputs(block_state)
|
| 290 |
base_values = self._capture_block_state(block_state)
|
| 291 |
try:
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
else self._run_regional_batches
|
| 296 |
-
)
|
| 297 |
-
run_batches(
|
| 298 |
-
components,
|
| 299 |
-
block_state,
|
| 300 |
-
base_values,
|
| 301 |
-
i=i,
|
| 302 |
-
t=t,
|
| 303 |
-
latents_2d=latents_2d,
|
| 304 |
-
batch_size=batch_size,
|
| 305 |
-
noise_sum=noise_sum,
|
| 306 |
-
weight_sum=weight_sum,
|
| 307 |
-
accum_dtype=accum_dtype,
|
| 308 |
-
)
|
| 309 |
finally:
|
| 310 |
self._restore_block_state(block_state, base_values)
|
| 311 |
|
|
@@ -319,7 +332,8 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 319 |
return components, block_state
|
| 320 |
|
| 321 |
def _capture_block_state(self, block_state) -> dict[str, object]:
|
| 322 |
-
|
|
|
|
| 323 |
|
| 324 |
@staticmethod
|
| 325 |
def _restore_block_state(block_state, values: dict[str, object]) -> None:
|
|
@@ -331,59 +345,41 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 331 |
setattr(block_state, name, value)
|
| 332 |
|
| 333 |
def _item_inputs(
|
| 334 |
-
self,
|
| 335 |
-
block_state,
|
| 336 |
-
base_values: dict[str, object],
|
| 337 |
-
item: WindowItem,
|
| 338 |
-
*,
|
| 339 |
-
latents_2d: torch.Tensor,
|
| 340 |
-
batch_size: int,
|
| 341 |
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
}
|
| 353 |
-
reference_batched, shared = self._md_reference_inputs(block_state, base_values, item)
|
| 354 |
-
batched.update(reference_batched)
|
| 355 |
if item.region_index is not None:
|
| 356 |
text_batched, text_shared = self._md_regional_inputs(
|
| 357 |
-
block_state, base_values, item.region_index,
|
| 358 |
)
|
| 359 |
batched.update(text_batched)
|
| 360 |
shared = {**shared, **text_shared}
|
| 361 |
return batched, shared
|
| 362 |
|
| 363 |
def _run_denoiser_batch(
|
| 364 |
-
self,
|
| 365 |
-
components,
|
| 366 |
-
block_state,
|
| 367 |
-
base_values: dict[str, object],
|
| 368 |
-
chunk: list,
|
| 369 |
-
*,
|
| 370 |
-
batch_size: int,
|
| 371 |
-
i: int,
|
| 372 |
-
t: torch.Tensor,
|
| 373 |
) -> torch.Tensor:
|
| 374 |
item_count = len(chunk)
|
| 375 |
_, first_batched, first_shared = chunk[0]
|
| 376 |
values = {name: torch.cat([batched[name] for _, batched, _ in chunk], dim=0) for name in first_batched}
|
| 377 |
for name in self._md_item_keys:
|
| 378 |
-
if name not in values and base_values
|
| 379 |
values[name] = _repeat_for_items(base_values[name], item_count)
|
| 380 |
values.update(first_shared)
|
| 381 |
values.update(self._md_window_ids(block_state, base_values, item_count))
|
| 382 |
|
| 383 |
self._md_set_inputs(block_state, base_values, values)
|
| 384 |
_, block_state = super().__call__(components, block_state, i=i, t=t)
|
| 385 |
-
|
| 386 |
-
return block_state.noise_pred.reshape(item_count, batch_size, latents.shape[1], latents.shape[2])
|
| 387 |
|
| 388 |
def _denoise_items(
|
| 389 |
self,
|
|
@@ -391,24 +387,18 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 391 |
block_state,
|
| 392 |
base_values: dict[str, object],
|
| 393 |
items: list[WindowItem],
|
| 394 |
-
*,
|
| 395 |
latents_2d: torch.Tensor,
|
| 396 |
-
|
| 397 |
i: int,
|
| 398 |
t: torch.Tensor,
|
| 399 |
desc: str,
|
| 400 |
):
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
(item, *self._item_inputs(block_state, base_values, item, latents_2d=latents_2d, batch_size=batch_size))
|
| 404 |
-
for item in items
|
| 405 |
-
]
|
| 406 |
with self._inner_denoising_progress_bar(total=len(items), desc=desc) as progress_bar:
|
| 407 |
for group in _group_by_shapes(entries):
|
| 408 |
for chunk in _chunks(group, window_batch_size):
|
| 409 |
-
noise_pred = self._run_denoiser_batch(
|
| 410 |
-
components, block_state, base_values, chunk, batch_size=batch_size, i=i, t=t
|
| 411 |
-
)
|
| 412 |
for (item, _, _), item_noise in zip(chunk, noise_pred, strict=True):
|
| 413 |
yield item, item_noise
|
| 414 |
progress_bar.update(len(chunk))
|
|
@@ -418,56 +408,35 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 418 |
components,
|
| 419 |
block_state,
|
| 420 |
base_values: dict[str, object],
|
| 421 |
-
*,
|
| 422 |
-
i: int,
|
| 423 |
-
t: torch.Tensor,
|
| 424 |
latents_2d: torch.Tensor,
|
| 425 |
-
batch_size: int,
|
| 426 |
noise_sum: torch.Tensor,
|
| 427 |
weight_sum: torch.Tensor,
|
| 428 |
-
|
|
|
|
|
|
|
| 429 |
) -> None:
|
| 430 |
window_h = block_state.md_window_h
|
| 431 |
window_w = block_state.md_window_w
|
| 432 |
items = [WindowItem(index, top, left) for index, (top, left) in enumerate(block_state.md_windows)]
|
| 433 |
-
|
| 434 |
|
| 435 |
for item, item_noise in self._denoise_items(
|
| 436 |
-
components,
|
| 437 |
-
block_state,
|
| 438 |
-
base_values,
|
| 439 |
-
items,
|
| 440 |
-
latents_2d=latents_2d,
|
| 441 |
-
batch_size=batch_size,
|
| 442 |
-
i=i,
|
| 443 |
-
t=t,
|
| 444 |
-
desc=progress_desc,
|
| 445 |
):
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
weight_sum,
|
| 449 |
-
geometry.reshape_packed(item_noise, window_h, window_w),
|
| 450 |
-
block_state.md_window_weight,
|
| 451 |
-
top=item.top,
|
| 452 |
-
left=item.left,
|
| 453 |
-
wrap_height=bool(getattr(block_state, "md_wrap_height", False)),
|
| 454 |
-
wrap_width=bool(getattr(block_state, "md_wrap_width", False)),
|
| 455 |
-
accum_dtype=accum_dtype,
|
| 456 |
-
)
|
| 457 |
|
| 458 |
def _run_regional_batches(
|
| 459 |
self,
|
| 460 |
components,
|
| 461 |
block_state,
|
| 462 |
base_values: dict[str, object],
|
| 463 |
-
*,
|
| 464 |
-
i: int,
|
| 465 |
-
t: torch.Tensor,
|
| 466 |
latents_2d: torch.Tensor,
|
| 467 |
-
batch_size: int,
|
| 468 |
noise_sum: torch.Tensor,
|
| 469 |
weight_sum: torch.Tensor,
|
| 470 |
-
|
|
|
|
|
|
|
| 471 |
) -> None:
|
| 472 |
regional_masks = block_state.md_regional_masks
|
| 473 |
regional_prompt_embeds = getattr(block_state, "regional_prompt_embeds", None)
|
|
@@ -481,56 +450,37 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 481 |
|
| 482 |
window_h = block_state.md_window_h
|
| 483 |
window_w = block_state.md_window_w
|
| 484 |
-
|
| 485 |
-
wrap_width = bool(getattr(block_state, "md_wrap_width", False))
|
| 486 |
windows = list(enumerate(block_state.md_windows))
|
| 487 |
blend_sums = [
|
| 488 |
torch.zeros(
|
| 489 |
-
(
|
|
|
|
|
|
|
| 490 |
)
|
| 491 |
for _ in windows
|
| 492 |
]
|
| 493 |
blend_weights = [
|
| 494 |
torch.zeros((1, window_h, window_w, 1), device=latents_2d.device, dtype=accum_dtype) for _ in windows
|
| 495 |
]
|
| 496 |
-
items = []
|
| 497 |
|
|
|
|
| 498 |
for window_index, (top, left) in windows:
|
| 499 |
window_masks = geometry.regional_mask_window(
|
| 500 |
-
regional_masks,
|
| 501 |
-
top,
|
| 502 |
-
left,
|
| 503 |
-
window_h,
|
| 504 |
-
window_w,
|
| 505 |
-
wrap_height=wrap_height,
|
| 506 |
-
wrap_width=wrap_width,
|
| 507 |
).to(device=latents_2d.device, dtype=accum_dtype)
|
| 508 |
active_regions = torch.nonzero(window_masks.flatten(1).sum(dim=1) > 0, as_tuple=False).flatten().tolist()
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
top=top,
|
| 514 |
-
left=left,
|
| 515 |
-
region_index=region_index,
|
| 516 |
-
mask=window_masks[region_index],
|
| 517 |
-
)
|
| 518 |
-
)
|
| 519 |
|
| 520 |
if not items:
|
| 521 |
raise ValueError("No regional masks overlap any MultiDiffusion window.")
|
| 522 |
|
| 523 |
-
|
| 524 |
for item, item_noise in self._denoise_items(
|
| 525 |
-
components,
|
| 526 |
-
block_state,
|
| 527 |
-
base_values,
|
| 528 |
-
items,
|
| 529 |
-
latents_2d=latents_2d,
|
| 530 |
-
batch_size=batch_size,
|
| 531 |
-
i=i,
|
| 532 |
-
t=t,
|
| 533 |
-
desc=progress_desc,
|
| 534 |
):
|
| 535 |
mask = item.mask[None, :, :, None]
|
| 536 |
blend_sums[item.window_index] += (
|
|
@@ -542,50 +492,28 @@ class MultiDiffusionWindowLoopMixin:
|
|
| 542 |
if torch.any(blend_weights[window_index] <= 0):
|
| 543 |
raise ValueError("Regional masks must cover every latent cell in each MultiDiffusion window.")
|
| 544 |
window_noise = blend_sums[window_index] / blend_weights[window_index]
|
| 545 |
-
self._accumulate_window_noise(
|
| 546 |
-
noise_sum,
|
| 547 |
-
weight_sum,
|
| 548 |
-
window_noise,
|
| 549 |
-
block_state.md_window_weight,
|
| 550 |
-
top=top,
|
| 551 |
-
left=left,
|
| 552 |
-
wrap_height=wrap_height,
|
| 553 |
-
wrap_width=wrap_width,
|
| 554 |
-
accum_dtype=accum_dtype,
|
| 555 |
-
)
|
| 556 |
|
| 557 |
-
@staticmethod
|
| 558 |
def _accumulate_window_noise(
|
|
|
|
|
|
|
| 559 |
noise_sum: torch.Tensor,
|
| 560 |
weight_sum: torch.Tensor,
|
| 561 |
window_noise: torch.Tensor,
|
| 562 |
-
weight: torch.Tensor,
|
| 563 |
-
*,
|
| 564 |
top: int,
|
| 565 |
left: int,
|
| 566 |
-
wrap_height: bool,
|
| 567 |
-
wrap_width: bool,
|
| 568 |
-
accum_dtype: torch.dtype,
|
| 569 |
) -> None:
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
geometry.accumulate_window(
|
| 579 |
-
weight_sum,
|
| 580 |
-
weight,
|
| 581 |
-
top,
|
| 582 |
-
left,
|
| 583 |
-
wrap_height=wrap_height,
|
| 584 |
-
wrap_width=wrap_width,
|
| 585 |
-
)
|
| 586 |
|
|
|
|
| 587 |
|
| 588 |
-
class MultiDiffusionProgressConfigMixin:
|
| 589 |
def set_progress_bar_config(self, **kwargs) -> None:
|
| 590 |
super().set_progress_bar_config(**kwargs)
|
| 591 |
for sub_block in self.sub_blocks.values():
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
def _window_batch_size(value) -> int:
|
| 32 |
+
value = int(value)
|
| 33 |
if value <= 0:
|
| 34 |
raise ValueError(f"`window_batch_size` must be a positive integer, got {value}.")
|
| 35 |
return value
|
|
|
|
| 76 |
type_hint=str,
|
| 77 |
default="cosine",
|
| 78 |
required=False,
|
| 79 |
+
description="Window blending ramp: 'cosine', 'linear', or 'none' for a flat average.",
|
| 80 |
),
|
| 81 |
InputParam(
|
| 82 |
"weighting_range",
|
|
|
|
| 132 |
|
| 133 |
weighting_range = geometry.normalize_weighting_range(
|
| 134 |
getattr(block_state, "weighting_range", None),
|
| 135 |
+
default_h=layout.stride_h / layout.window_h,
|
| 136 |
+
default_w=layout.stride_w / layout.window_w,
|
| 137 |
)
|
| 138 |
|
| 139 |
block_state.md_full_latents = block_state.latents
|
|
|
|
| 188 |
|
| 189 |
Placed before an upstream denoiser in the MRO. A family subclass names the denoiser state it touches and fills
|
| 190 |
the `_md_*` hooks:
|
|
|
|
| 191 |
- `_md_item_keys`: per-sample tensors repeated once per window in a batch,
|
| 192 |
- `_md_regional_keys`: embeddings replaced by `regional_<name>[region]` for a regional prompt,
|
| 193 |
+
- `_md_state_keys`: the other state the hooks read from `base_values` or overwrite; with `latents` and the two
|
| 194 |
+
lists above, it is captured before the window calls and restored after them,
|
| 195 |
+
- `_md_extra_inputs`: family inputs such as the reference latents.
|
| 196 |
Items whose tensors differ in shape (reference crops, regional text lengths) are never batched together, so the
|
| 197 |
`shared` inputs of a batch, which are fully determined by those shapes, are taken from its first item.
|
| 198 |
"""
|
| 199 |
|
|
|
|
| 200 |
_md_item_keys: ClassVar[tuple[str, ...]] = ()
|
| 201 |
_md_regional_keys: ClassVar[tuple[str, ...]] = ("prompt_embeds",)
|
| 202 |
+
_md_state_keys: ClassVar[tuple[str, ...]] = ()
|
| 203 |
_md_extra_inputs: ClassVar[tuple[InputParam, ...]] = ()
|
| 204 |
|
| 205 |
@property
|
|
|
|
| 218 |
InputParam("md_window_weight", required=True, type_hint=torch.Tensor),
|
| 219 |
InputParam("md_window_batch_size", type_hint=int, default=1),
|
| 220 |
InputParam("md_regional_masks", type_hint=torch.Tensor, required=False),
|
| 221 |
+
*(
|
| 222 |
+
InputParam(f"regional_{name}", required=False, description=f"One `{name}` entry per regional mask.")
|
| 223 |
+
for name in self._md_regional_keys
|
| 224 |
+
),
|
| 225 |
*self._md_extra_inputs,
|
| 226 |
]
|
| 227 |
|
|
|
|
| 248 |
return f"{kind} {i + 1}/{num_inference_steps}"
|
| 249 |
return kind
|
| 250 |
|
| 251 |
+
@staticmethod
|
| 252 |
+
def _md_wrap(block_state) -> dict[str, bool]:
|
| 253 |
+
# getattr: block states built by hand may leave out the panorama flags
|
| 254 |
+
return {
|
| 255 |
+
"wrap_height": getattr(block_state, "md_wrap_height", False),
|
| 256 |
+
"wrap_width": getattr(block_state, "md_wrap_width", False),
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
def _md_window_box(self, block_state, item: WindowItem) -> dict[str, int | bool]:
|
| 260 |
+
"""Where the window of `item` sits on the canvas, as keyword arguments of the geometry crop helpers."""
|
| 261 |
+
return {
|
| 262 |
+
"top": item.top,
|
| 263 |
+
"left": item.left,
|
| 264 |
+
"window_h": block_state.md_window_h,
|
| 265 |
+
"window_w": block_state.md_window_w,
|
| 266 |
+
"full_h": block_state.md_full_h,
|
| 267 |
+
"full_w": block_state.md_full_w,
|
| 268 |
+
**self._md_wrap(block_state),
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
# Family hooks ----------------------------------------------------------------------------------------------------
|
| 272 |
|
| 273 |
def _md_check_inputs(self, block_state) -> None:
|
| 274 |
del block_state
|
| 275 |
|
| 276 |
def _md_window_ids(self, block_state, base_values: dict[str, object], item_count: int) -> dict[str, torch.Tensor]:
|
| 277 |
+
"""FLUX.1 and FLUX 3: the 2D `img_ids` of the window, shared by every item of a batch."""
|
| 278 |
+
del item_count
|
| 279 |
+
return {"img_ids": block_state.md_window_latent_ids.to(base_values["img_ids"])}
|
| 280 |
|
| 281 |
def _md_reference_inputs(
|
| 282 |
self, block_state, base_values: dict[str, object], item: WindowItem
|
|
|
|
| 288 |
self, block_state, base_values: dict[str, object], region_index: int, batch_size: int
|
| 289 |
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
| 290 |
del base_values
|
| 291 |
+
batched = {
|
| 292 |
+
name: _repeat_for_items(
|
| 293 |
+
getattr(block_state, f"regional_{name}")[region_index : region_index + 1], batch_size
|
| 294 |
+
)
|
| 295 |
+
for name in self._md_regional_keys
|
| 296 |
+
}
|
| 297 |
return batched, {}
|
| 298 |
|
| 299 |
def _md_set_inputs(self, block_state, base_values: dict[str, object], values: dict[str, torch.Tensor]) -> None:
|
|
|
|
| 307 |
def __call__(self, components, block_state, i: int, t: torch.Tensor):
|
| 308 |
full_latents = block_state.md_full_latents
|
| 309 |
batch_size, _, channels = full_latents.shape
|
|
|
|
|
|
|
| 310 |
|
| 311 |
+
latents_2d = geometry.reshape_packed(full_latents, block_state.md_full_h, block_state.md_full_w)
|
| 312 |
accum_dtype = geometry.accumulation_dtype(latents_2d.dtype)
|
| 313 |
noise_sum = torch.zeros_like(latents_2d, dtype=accum_dtype)
|
| 314 |
+
weight_sum = torch.zeros((1, *latents_2d.shape[1:3], 1), device=latents_2d.device, dtype=accum_dtype)
|
| 315 |
|
| 316 |
self._md_check_inputs(block_state)
|
| 317 |
base_values = self._capture_block_state(block_state)
|
| 318 |
try:
|
| 319 |
+
regional = getattr(block_state, "md_regional_masks", None) is not None
|
| 320 |
+
run_batches = self._run_regional_batches if regional else self._run_window_batches
|
| 321 |
+
run_batches(components, block_state, base_values, latents_2d, noise_sum, weight_sum, i=i, t=t)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
finally:
|
| 323 |
self._restore_block_state(block_state, base_values)
|
| 324 |
|
|
|
|
| 332 |
return components, block_state
|
| 333 |
|
| 334 |
def _capture_block_state(self, block_state) -> dict[str, object]:
|
| 335 |
+
names = dict.fromkeys(("latents", *self._md_item_keys, *self._md_regional_keys, *self._md_state_keys))
|
| 336 |
+
return {name: getattr(block_state, name, MISSING) for name in names}
|
| 337 |
|
| 338 |
@staticmethod
|
| 339 |
def _restore_block_state(block_state, values: dict[str, object]) -> None:
|
|
|
|
| 345 |
setattr(block_state, name, value)
|
| 346 |
|
| 347 |
def _item_inputs(
|
| 348 |
+
self, block_state, base_values: dict[str, object], item: WindowItem, latents_2d: torch.Tensor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
| 350 |
+
window_latents = geometry.window_view(
|
| 351 |
+
latents_2d,
|
| 352 |
+
item.top,
|
| 353 |
+
item.left,
|
| 354 |
+
block_state.md_window_h,
|
| 355 |
+
block_state.md_window_w,
|
| 356 |
+
**self._md_wrap(block_state),
|
| 357 |
+
)
|
| 358 |
+
batched, shared = self._md_reference_inputs(block_state, base_values, item)
|
| 359 |
+
batched = {"latents": window_latents, **batched}
|
|
|
|
|
|
|
|
|
|
| 360 |
if item.region_index is not None:
|
| 361 |
text_batched, text_shared = self._md_regional_inputs(
|
| 362 |
+
block_state, base_values, item.region_index, latents_2d.shape[0]
|
| 363 |
)
|
| 364 |
batched.update(text_batched)
|
| 365 |
shared = {**shared, **text_shared}
|
| 366 |
return batched, shared
|
| 367 |
|
| 368 |
def _run_denoiser_batch(
|
| 369 |
+
self, components, block_state, base_values: dict[str, object], chunk: list, *, i: int, t: torch.Tensor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
) -> torch.Tensor:
|
| 371 |
item_count = len(chunk)
|
| 372 |
_, first_batched, first_shared = chunk[0]
|
| 373 |
values = {name: torch.cat([batched[name] for _, batched, _ in chunk], dim=0) for name in first_batched}
|
| 374 |
for name in self._md_item_keys:
|
| 375 |
+
if name not in values and base_values[name] is not MISSING:
|
| 376 |
values[name] = _repeat_for_items(base_values[name], item_count)
|
| 377 |
values.update(first_shared)
|
| 378 |
values.update(self._md_window_ids(block_state, base_values, item_count))
|
| 379 |
|
| 380 |
self._md_set_inputs(block_state, base_values, values)
|
| 381 |
_, block_state = super().__call__(components, block_state, i=i, t=t)
|
| 382 |
+
return block_state.noise_pred.reshape(item_count, -1, *values["latents"].shape[1:])
|
|
|
|
| 383 |
|
| 384 |
def _denoise_items(
|
| 385 |
self,
|
|
|
|
| 387 |
block_state,
|
| 388 |
base_values: dict[str, object],
|
| 389 |
items: list[WindowItem],
|
|
|
|
| 390 |
latents_2d: torch.Tensor,
|
| 391 |
+
*,
|
| 392 |
i: int,
|
| 393 |
t: torch.Tensor,
|
| 394 |
desc: str,
|
| 395 |
):
|
| 396 |
+
entries = [(item, *self._item_inputs(block_state, base_values, item, latents_2d)) for item in items]
|
| 397 |
+
window_batch_size = getattr(block_state, "md_window_batch_size", 1)
|
|
|
|
|
|
|
|
|
|
| 398 |
with self._inner_denoising_progress_bar(total=len(items), desc=desc) as progress_bar:
|
| 399 |
for group in _group_by_shapes(entries):
|
| 400 |
for chunk in _chunks(group, window_batch_size):
|
| 401 |
+
noise_pred = self._run_denoiser_batch(components, block_state, base_values, chunk, i=i, t=t)
|
|
|
|
|
|
|
| 402 |
for (item, _, _), item_noise in zip(chunk, noise_pred, strict=True):
|
| 403 |
yield item, item_noise
|
| 404 |
progress_bar.update(len(chunk))
|
|
|
|
| 408 |
components,
|
| 409 |
block_state,
|
| 410 |
base_values: dict[str, object],
|
|
|
|
|
|
|
|
|
|
| 411 |
latents_2d: torch.Tensor,
|
|
|
|
| 412 |
noise_sum: torch.Tensor,
|
| 413 |
weight_sum: torch.Tensor,
|
| 414 |
+
*,
|
| 415 |
+
i: int,
|
| 416 |
+
t: torch.Tensor,
|
| 417 |
) -> None:
|
| 418 |
window_h = block_state.md_window_h
|
| 419 |
window_w = block_state.md_window_w
|
| 420 |
items = [WindowItem(index, top, left) for index, (top, left) in enumerate(block_state.md_windows)]
|
| 421 |
+
desc = self._inner_progress_desc("Denoising windows", i, block_state)
|
| 422 |
|
| 423 |
for item, item_noise in self._denoise_items(
|
| 424 |
+
components, block_state, base_values, items, latents_2d, i=i, t=t, desc=desc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
):
|
| 426 |
+
window_noise = geometry.reshape_packed(item_noise, window_h, window_w)
|
| 427 |
+
self._accumulate_window_noise(block_state, noise_sum, weight_sum, window_noise, item.top, item.left)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
|
| 429 |
def _run_regional_batches(
|
| 430 |
self,
|
| 431 |
components,
|
| 432 |
block_state,
|
| 433 |
base_values: dict[str, object],
|
|
|
|
|
|
|
|
|
|
| 434 |
latents_2d: torch.Tensor,
|
|
|
|
| 435 |
noise_sum: torch.Tensor,
|
| 436 |
weight_sum: torch.Tensor,
|
| 437 |
+
*,
|
| 438 |
+
i: int,
|
| 439 |
+
t: torch.Tensor,
|
| 440 |
) -> None:
|
| 441 |
regional_masks = block_state.md_regional_masks
|
| 442 |
regional_prompt_embeds = getattr(block_state, "regional_prompt_embeds", None)
|
|
|
|
| 450 |
|
| 451 |
window_h = block_state.md_window_h
|
| 452 |
window_w = block_state.md_window_w
|
| 453 |
+
accum_dtype = noise_sum.dtype
|
|
|
|
| 454 |
windows = list(enumerate(block_state.md_windows))
|
| 455 |
blend_sums = [
|
| 456 |
torch.zeros(
|
| 457 |
+
(latents_2d.shape[0], window_h, window_w, latents_2d.shape[-1]),
|
| 458 |
+
device=latents_2d.device,
|
| 459 |
+
dtype=accum_dtype,
|
| 460 |
)
|
| 461 |
for _ in windows
|
| 462 |
]
|
| 463 |
blend_weights = [
|
| 464 |
torch.zeros((1, window_h, window_w, 1), device=latents_2d.device, dtype=accum_dtype) for _ in windows
|
| 465 |
]
|
|
|
|
| 466 |
|
| 467 |
+
items = []
|
| 468 |
for window_index, (top, left) in windows:
|
| 469 |
window_masks = geometry.regional_mask_window(
|
| 470 |
+
regional_masks, top, left, window_h, window_w, **self._md_wrap(block_state)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 471 |
).to(device=latents_2d.device, dtype=accum_dtype)
|
| 472 |
active_regions = torch.nonzero(window_masks.flatten(1).sum(dim=1) > 0, as_tuple=False).flatten().tolist()
|
| 473 |
+
items.extend(
|
| 474 |
+
WindowItem(window_index, top, left, region_index=region_index, mask=window_masks[region_index])
|
| 475 |
+
for region_index in active_regions
|
| 476 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 477 |
|
| 478 |
if not items:
|
| 479 |
raise ValueError("No regional masks overlap any MultiDiffusion window.")
|
| 480 |
|
| 481 |
+
desc = self._inner_progress_desc("Denoising regions", i, block_state)
|
| 482 |
for item, item_noise in self._denoise_items(
|
| 483 |
+
components, block_state, base_values, items, latents_2d, i=i, t=t, desc=desc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
):
|
| 485 |
mask = item.mask[None, :, :, None]
|
| 486 |
blend_sums[item.window_index] += (
|
|
|
|
| 492 |
if torch.any(blend_weights[window_index] <= 0):
|
| 493 |
raise ValueError("Regional masks must cover every latent cell in each MultiDiffusion window.")
|
| 494 |
window_noise = blend_sums[window_index] / blend_weights[window_index]
|
| 495 |
+
self._accumulate_window_noise(block_state, noise_sum, weight_sum, window_noise, top, left)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
|
|
|
|
| 497 |
def _accumulate_window_noise(
|
| 498 |
+
self,
|
| 499 |
+
block_state,
|
| 500 |
noise_sum: torch.Tensor,
|
| 501 |
weight_sum: torch.Tensor,
|
| 502 |
window_noise: torch.Tensor,
|
|
|
|
|
|
|
| 503 |
top: int,
|
| 504 |
left: int,
|
|
|
|
|
|
|
|
|
|
| 505 |
) -> None:
|
| 506 |
+
weight = block_state.md_window_weight
|
| 507 |
+
wrap = self._md_wrap(block_state)
|
| 508 |
+
geometry.accumulate_window(noise_sum, window_noise.to(noise_sum.dtype) * weight, top, left, **wrap)
|
| 509 |
+
geometry.accumulate_window(weight_sum, weight, top, left, **wrap)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
class MultiDiffusionDenoiseStepMixin:
|
| 513 |
+
"""Sub-block names and progress bars of a MultiDiffusion denoise step; placed before the upstream loop wrapper."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 514 |
|
| 515 |
+
block_names: ClassVar = ["multidiffusion_preprocessing", "multidiffusion_loop", "after_denoiser"]
|
| 516 |
|
|
|
|
| 517 |
def set_progress_bar_config(self, **kwargs) -> None:
|
| 518 |
super().set_progress_bar_config(**kwargs)
|
| 519 |
for sub_block in self.sub_blocks.values():
|
|
@@ -38,6 +38,7 @@ dev = [
|
|
| 38 |
"ruff>=0.12",
|
| 39 |
]
|
| 40 |
examples = [
|
|
|
|
| 41 |
"pillow>=10.0",
|
| 42 |
]
|
| 43 |
quantization = [
|
|
@@ -48,8 +49,8 @@ quantization = [
|
|
| 48 |
multidiff-modular = "cli:main"
|
| 49 |
|
| 50 |
[project.urls]
|
| 51 |
-
Homepage = "https://huggingface.co/"
|
| 52 |
-
Repository = "https://
|
| 53 |
|
| 54 |
[tool.setuptools]
|
| 55 |
py-modules = ["repository", "cli"]
|
|
|
|
| 38 |
"ruff>=0.12",
|
| 39 |
]
|
| 40 |
examples = [
|
| 41 |
+
"peft>=0.17", # --lora-path
|
| 42 |
"pillow>=10.0",
|
| 43 |
]
|
| 44 |
quantization = [
|
|
|
|
| 49 |
multidiff-modular = "cli:main"
|
| 50 |
|
| 51 |
[project.urls]
|
| 52 |
+
Homepage = "https://huggingface.co/arlaz/modular-flux123-multidiffusion"
|
| 53 |
+
Repository = "https://huggingface.co/arlaz/modular-flux123-multidiffusion/tree/main"
|
| 54 |
|
| 55 |
[tool.setuptools]
|
| 56 |
py-modules = ["repository", "cli"]
|
|
@@ -39,66 +39,39 @@ SUPPORTED_MODEL_FAMILIES = tuple(DEFAULT_MODEL_REPOS)
|
|
| 39 |
DEFAULT_MODEL_FAMILY = "flux3-klein"
|
| 40 |
|
| 41 |
|
| 42 |
-
def _blocks_by_family():
|
| 43 |
-
import multidiffusion
|
| 44 |
-
|
| 45 |
-
return {family: getattr(multidiffusion, class_name) for family, class_name in FAMILY_BLOCK_CLASS_NAMES.items()}
|
| 46 |
-
|
| 47 |
-
|
| 48 |
def get_multidiffusion_blocks(model_family: str):
|
| 49 |
"""Return the MultiDiffusion blocks for a supported FLUX model family."""
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
|
| 52 |
-
return _blocks_by_family()[model_family]()
|
| 53 |
-
except KeyError as error:
|
| 54 |
-
raise ValueError(f"`model_family` must be one of {SUPPORTED_MODEL_FAMILIES}, got {model_family!r}.") from error
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def _get_hub_blocks(model_family: str):
|
| 58 |
-
return get_multidiffusion_blocks(model_family)
|
| 59 |
|
|
|
|
| 60 |
|
| 61 |
-
def build_pipeline(
|
| 62 |
-
model_family: str = DEFAULT_MODEL_FAMILY,
|
| 63 |
-
*,
|
| 64 |
-
components_manager: Any | None = None,
|
| 65 |
-
):
|
| 66 |
-
"""Create a ModularPipeline definition for a supported FLUX family.
|
| 67 |
|
| 68 |
-
|
| 69 |
-
pipeline to load upstream components.
|
| 70 |
"""
|
|
|
|
| 71 |
|
|
|
|
|
|
|
| 72 |
blocks = get_multidiffusion_blocks(model_family)
|
| 73 |
return blocks.init_pipeline(DEFAULT_MODEL_REPOS[model_family], components_manager=components_manager)
|
| 74 |
|
| 75 |
|
| 76 |
-
def init_default_multidiffusion_pipeline(model_family: str = DEFAULT_MODEL_FAMILY, *, components_manager=None):
|
| 77 |
-
"""Create a MultiDiffusion pipeline definition for a default upstream FLUX repo."""
|
| 78 |
-
|
| 79 |
-
return build_pipeline(model_family, components_manager=components_manager)
|
| 80 |
-
|
| 81 |
-
|
| 82 |
def _copy_if_present(source: Path, destination: Path) -> None:
|
| 83 |
if not source.exists() or source.resolve() == destination.resolve():
|
| 84 |
return
|
| 85 |
shutil.copyfile(source, destination)
|
| 86 |
|
| 87 |
|
| 88 |
-
def
|
| 89 |
-
|
| 90 |
-
output_path.resolve().relative_to(PROJECT_ROOT.resolve())
|
| 91 |
-
except ValueError:
|
| 92 |
-
return False
|
| 93 |
-
return True
|
| 94 |
|
| 95 |
|
| 96 |
-
def
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
except ValueError:
|
| 100 |
-
return False
|
| 101 |
-
return True
|
| 102 |
|
| 103 |
|
| 104 |
def _write_block_entrypoint(output_path: Path) -> None:
|
|
@@ -133,33 +106,32 @@ def export_hf_repo(
|
|
| 133 |
repo_id: str | None = None,
|
| 134 |
push_to_hub: bool = False,
|
| 135 |
copy_readme: bool = True,
|
| 136 |
-
write_config_alias: bool = True,
|
| 137 |
-
**save_pretrained_kwargs,
|
| 138 |
) -> Path:
|
| 139 |
-
"""
|
|
|
|
| 140 |
|
| 141 |
The JSON metadata is produced by ``ModularPipeline.save_pretrained`` and keeps the upstream component specs. For
|
| 142 |
-
root or
|
| 143 |
-
metadata
|
| 144 |
-
files are written; the
|
| 145 |
"""
|
| 146 |
-
|
| 147 |
output_path = Path(output_dir)
|
| 148 |
-
if push_to_hub and (repo_id is None or
|
| 149 |
-
raise ValueError(
|
|
|
|
|
|
|
|
|
|
| 150 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 151 |
|
| 152 |
-
blocks =
|
| 153 |
pipeline = blocks.init_pipeline(DEFAULT_MODEL_REPOS[model_family])
|
| 154 |
-
|
| 155 |
-
pipeline.save_pretrained(str(output_path), **save_pretrained_kwargs)
|
| 156 |
blocks.save_pretrained(output_path)
|
| 157 |
|
|
|
|
| 158 |
modular_config = output_path / "modular_config.json"
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
if write_config_alias and modular_config.exists():
|
| 162 |
-
shutil.copyfile(modular_config, output_path / "config.json")
|
| 163 |
|
| 164 |
_write_block_entrypoint(output_path)
|
| 165 |
if copy_readme and not _is_project_model_export(output_path):
|
|
|
|
| 39 |
DEFAULT_MODEL_FAMILY = "flux3-klein"
|
| 40 |
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def get_multidiffusion_blocks(model_family: str):
|
| 43 |
"""Return the MultiDiffusion blocks for a supported FLUX model family."""
|
| 44 |
+
if model_family not in FAMILY_BLOCK_CLASS_NAMES:
|
| 45 |
+
raise ValueError(f"`model_family` must be one of {SUPPORTED_MODEL_FAMILIES}, got {model_family!r}.")
|
| 46 |
|
| 47 |
+
import multidiffusion
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
return getattr(multidiffusion, FAMILY_BLOCK_CLASS_NAMES[model_family])()
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
def build_pipeline(model_family: str = DEFAULT_MODEL_FAMILY, *, components_manager: Any | None = None):
|
|
|
|
| 53 |
"""
|
| 54 |
+
Create the MultiDiffusion pipeline of a FLUX family on its upstream repo, without loading weights.
|
| 55 |
|
| 56 |
+
Call ``load_components()`` on the returned pipeline to load the upstream components.
|
| 57 |
+
"""
|
| 58 |
blocks = get_multidiffusion_blocks(model_family)
|
| 59 |
return blocks.init_pipeline(DEFAULT_MODEL_REPOS[model_family], components_manager=components_manager)
|
| 60 |
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
def _copy_if_present(source: Path, destination: Path) -> None:
|
| 63 |
if not source.exists() or source.resolve() == destination.resolve():
|
| 64 |
return
|
| 65 |
shutil.copyfile(source, destination)
|
| 66 |
|
| 67 |
|
| 68 |
+
def _is_project_model_export(output_path: Path) -> bool:
|
| 69 |
+
return output_path.resolve().is_relative_to(PROJECT_ROOT / "model")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
|
| 72 |
+
def _is_checkout_folder(output_path: Path) -> bool:
|
| 73 |
+
"""The checkout root or one of its `model/<family>` folders: git publishes those, not `push_to_hub`."""
|
| 74 |
+
return output_path.resolve() == PROJECT_ROOT or _is_project_model_export(output_path)
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
|
| 77 |
def _write_block_entrypoint(output_path: Path) -> None:
|
|
|
|
| 106 |
repo_id: str | None = None,
|
| 107 |
push_to_hub: bool = False,
|
| 108 |
copy_readme: bool = True,
|
|
|
|
|
|
|
| 109 |
) -> Path:
|
| 110 |
+
"""
|
| 111 |
+
Export a Hub-ready Modular Diffusers repo with official metadata.
|
| 112 |
|
| 113 |
The JSON metadata is produced by ``ModularPipeline.save_pretrained`` and keeps the upstream component specs. For
|
| 114 |
+
root or standalone Hub exports, the root ``block.py`` entry and the ``multidiffusion/`` package are copied beside
|
| 115 |
+
the metadata; project ``model/<family>`` folders stay metadata-only. With ``push_to_hub``, the finished folder is
|
| 116 |
+
uploaded once all files are written; the checkout root and its ``model/`` folders are published with git instead.
|
| 117 |
"""
|
|
|
|
| 118 |
output_path = Path(output_dir)
|
| 119 |
+
if push_to_hub and (repo_id is None or _is_checkout_folder(output_path)):
|
| 120 |
+
raise ValueError(
|
| 121 |
+
"`push_to_hub` needs a `repo_id` and an export folder other than the checkout root or its `model/` "
|
| 122 |
+
"folders, which are published with git."
|
| 123 |
+
)
|
| 124 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 125 |
|
| 126 |
+
blocks = get_multidiffusion_blocks(model_family)
|
| 127 |
pipeline = blocks.init_pipeline(DEFAULT_MODEL_REPOS[model_family])
|
| 128 |
+
pipeline.save_pretrained(str(output_path), overwrite_modular_index=False)
|
|
|
|
| 129 |
blocks.save_pretrained(output_path)
|
| 130 |
|
| 131 |
+
# `blocks.save_pretrained` writes `modular_config.json`; `config.json` is the copy the Hub model page reads
|
| 132 |
modular_config = output_path / "modular_config.json"
|
| 133 |
+
_point_auto_map_at_block_entry(modular_config, type(blocks).__name__)
|
| 134 |
+
shutil.copyfile(modular_config, output_path / "config.json")
|
|
|
|
|
|
|
| 135 |
|
| 136 |
_write_block_entrypoint(output_path)
|
| 137 |
if copy_readme and not _is_project_model_export(output_path):
|
|
@@ -327,3 +327,35 @@ def test_flux_timesteps_match_upstream_for_a_canvas_sized_window_and_follow_the_
|
|
| 327 |
torch.testing.assert_close(canvas_guidance, expected_guidance)
|
| 328 |
assert torch.all(window_timesteps <= expected_timesteps)
|
| 329 |
assert not torch.allclose(window_timesteps, expected_timesteps)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
torch.testing.assert_close(canvas_guidance, expected_guidance)
|
| 328 |
assert torch.all(window_timesteps <= expected_timesteps)
|
| 329 |
assert not torch.allclose(window_timesteps, expected_timesteps)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _flux2_timesteps(step_cls: type, **window_inputs) -> torch.Tensor:
|
| 333 |
+
components = SimpleNamespace(
|
| 334 |
+
scheduler=FlowMatchEulerDiscreteScheduler(use_dynamic_shifting=True, max_image_seq_len=4096),
|
| 335 |
+
vae_scale_factor=8,
|
| 336 |
+
_execution_device=torch.device("cpu"),
|
| 337 |
+
default_height=HEIGHT,
|
| 338 |
+
default_width=WIDTH,
|
| 339 |
+
)
|
| 340 |
+
state = PipelineState()
|
| 341 |
+
# a 2048 x 2048 canvas has 16384 tokens, more than the scheduler's `max_image_seq_len`
|
| 342 |
+
for name, value in {"height": 2048, "width": 2048, "num_inference_steps": 8, **window_inputs}.items():
|
| 343 |
+
state.set(name, value)
|
| 344 |
+
_, state = step_cls()(components, state)
|
| 345 |
+
return state.get("timesteps")
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def test_flux2_timesteps_match_upstream_for_a_canvas_sized_window_and_follow_the_window():
|
| 349 |
+
from diffusers.modular_pipelines.flux2.before_denoise import Flux2SetTimestepsStep
|
| 350 |
+
|
| 351 |
+
from multidiffusion.flux2 import Flux2MultiDiffusionSetTimestepsStep
|
| 352 |
+
|
| 353 |
+
expected_timesteps = _flux2_timesteps(Flux2SetTimestepsStep)
|
| 354 |
+
canvas_timesteps = _flux2_timesteps(Flux2MultiDiffusionSetTimestepsStep)
|
| 355 |
+
window_timesteps = _flux2_timesteps(
|
| 356 |
+
Flux2MultiDiffusionSetTimestepsStep, height_generation=1024, width_generation=1024
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
torch.testing.assert_close(canvas_timesteps, expected_timesteps)
|
| 360 |
+
assert torch.all(window_timesteps <= expected_timesteps)
|
| 361 |
+
assert not torch.allclose(window_timesteps, expected_timesteps)
|
|
@@ -18,7 +18,7 @@ class FakeImage:
|
|
| 18 |
|
| 19 |
|
| 20 |
def _args(*extra):
|
| 21 |
-
return runner.
|
| 22 |
|
| 23 |
|
| 24 |
def test_quantization_parser_defaults_to_none():
|
|
@@ -214,13 +214,11 @@ def test_call_kwargs_forward_window_batch_size():
|
|
| 214 |
assert call_kwargs["window_batch_size"] == 6
|
| 215 |
|
| 216 |
|
| 217 |
-
def
|
| 218 |
-
with pytest.raises(
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
object(),
|
| 223 |
-
)
|
| 224 |
|
| 225 |
|
| 226 |
def test_csv_prompt_loads_regional_masks_in_csv_order(tmp_path):
|
|
@@ -295,6 +293,10 @@ def test_regional_mask_loader_rejects_wrong_size(tmp_path):
|
|
| 295 |
({"_class_name": "FluxPipeline"}, "Flux1MultiDiffusionAutoBlocks"),
|
| 296 |
({"_class_name": "Flux3ModularPipeline"}, "Flux3KleinBaseMultiDiffusionAutoBlocks"),
|
| 297 |
({"_class_name": "Flux3DistilledModularPipeline"}, "Flux3KleinMultiDiffusionAutoBlocks"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
],
|
| 299 |
)
|
| 300 |
def test_multidiffusion_blocks_are_selected_from_loaded_pipeline_config(config, expected_class_name):
|
|
@@ -364,79 +366,47 @@ def test_enable_tiling_and_slicing_call_vae_methods():
|
|
| 364 |
assert pipe.vae.slicing_enabled
|
| 365 |
|
| 366 |
|
| 367 |
-
|
| 368 |
-
|
|
|
|
|
|
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
calls.append((base_model, components_manager))
|
| 373 |
-
return FakePipe()
|
| 374 |
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
self.guider = object()
|
| 378 |
-
self.updated_components = None
|
| 379 |
|
| 380 |
-
def load_components(self, **kwargs):
|
| 381 |
-
self.load_kwargs = kwargs
|
| 382 |
|
| 383 |
-
|
| 384 |
-
|
|
|
|
|
|
|
| 385 |
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
|
| 390 |
pipe = runner.init_modular_pipeline(
|
| 391 |
-
|
| 392 |
-
model_config={"_class_name": "Flux2KleinPipeline"},
|
| 393 |
-
guidance_scale=None,
|
| 394 |
-
dtype="float32",
|
| 395 |
-
device="cpu",
|
| 396 |
-
local_files_only=True,
|
| 397 |
-
compile=False,
|
| 398 |
)
|
| 399 |
|
| 400 |
-
assert
|
| 401 |
-
assert
|
| 402 |
assert pipe.updated_components is None
|
| 403 |
|
| 404 |
|
| 405 |
-
def test_init_applies_explicit_guidance_scale(
|
| 406 |
-
class
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
return {"guidance_scale": guidance_scale}
|
| 410 |
-
|
| 411 |
-
class FakePipe:
|
| 412 |
-
def __init__(self):
|
| 413 |
-
self.guider = object()
|
| 414 |
-
self.updated_components = None
|
| 415 |
-
|
| 416 |
-
def load_components(self, **kwargs):
|
| 417 |
-
self.load_kwargs = kwargs
|
| 418 |
-
|
| 419 |
-
def get_component_spec(self, name):
|
| 420 |
-
assert name == "guider"
|
| 421 |
-
return FakeGuiderSpec()
|
| 422 |
-
|
| 423 |
-
def update_components(self, **components):
|
| 424 |
-
self.updated_components = components
|
| 425 |
-
|
| 426 |
-
monkeypatch.setattr(
|
| 427 |
-
runner,
|
| 428 |
-
"build_multidiffusion_blocks",
|
| 429 |
-
lambda model_config: SimpleNamespace(init_pipeline=lambda base_model, components_manager: FakePipe()),
|
| 430 |
-
)
|
| 431 |
|
| 432 |
pipe = runner.init_modular_pipeline(
|
| 433 |
-
|
| 434 |
-
model_config={"_class_name": "Flux2KleinPipeline"},
|
| 435 |
-
guidance_scale=2.5,
|
| 436 |
-
dtype="float32",
|
| 437 |
-
device="cpu",
|
| 438 |
-
local_files_only=True,
|
| 439 |
-
compile=False,
|
| 440 |
)
|
| 441 |
|
| 442 |
assert pipe.updated_components == {"guider": {"guidance_scale": 2.5}}
|
|
@@ -448,76 +418,38 @@ def test_remote_parser_requires_hub_repo_id():
|
|
| 448 |
assert args.repo_id == "user/multidiff-modular"
|
| 449 |
|
| 450 |
|
| 451 |
-
|
| 452 |
-
def __init__(self, calls):
|
| 453 |
-
self.calls = calls
|
| 454 |
-
self.guider = None
|
| 455 |
-
|
| 456 |
-
def load_components(self, **kwargs):
|
| 457 |
-
self.calls["load_components"] = kwargs
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
class FakeRemoteBlocks:
|
| 461 |
-
def __init__(self, calls):
|
| 462 |
-
self.calls = calls
|
| 463 |
-
self.sub_blocks = {"prompt_upsampler": object(), "text_encoder": object()}
|
| 464 |
-
|
| 465 |
-
def init_pipeline(self, pretrained_model_name_or_path, components_manager):
|
| 466 |
-
self.calls["init_pipeline"] = pretrained_model_name_or_path
|
| 467 |
-
return FakeRemotePipe(self.calls)
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
def test_remote_init_loads_root_blocks_with_remote_code(monkeypatch):
|
| 471 |
calls = {}
|
| 472 |
|
| 473 |
def fake_from_pretrained(repo_id, **kwargs):
|
| 474 |
-
calls["
|
| 475 |
-
|
| 476 |
-
return FakeRemoteBlocks(calls)
|
| 477 |
|
| 478 |
monkeypatch.setattr(remote_runner.ModularPipelineBlocks, "from_pretrained", fake_from_pretrained)
|
| 479 |
|
| 480 |
-
|
| 481 |
-
repo_id="user/multidiff-modular",
|
| 482 |
-
guidance_scale=None,
|
| 483 |
-
dtype="float32",
|
| 484 |
-
device="cpu",
|
| 485 |
-
local_files_only=True,
|
| 486 |
-
compile=False,
|
| 487 |
-
)
|
| 488 |
|
| 489 |
-
assert
|
| 490 |
-
assert calls["
|
| 491 |
-
assert
|
| 492 |
-
assert calls["from_pretrained"]["trust_remote_code"] is True
|
| 493 |
-
assert calls["from_pretrained"]["local_files_only"] is True
|
| 494 |
-
assert calls["load_components"]["dtype"] is runner.DTYPE_MAP["float32"]
|
| 495 |
-
assert calls["load_components"]["local_files_only"] is True
|
| 496 |
|
| 497 |
|
| 498 |
-
def
|
| 499 |
calls = {}
|
| 500 |
-
blocks = FakeRemoteBlocks(calls)
|
| 501 |
|
| 502 |
def fake_get_class(repo_id, module_file, **kwargs):
|
| 503 |
calls["dynamic_module"] = (repo_id, module_file, kwargs["class_name"], kwargs["trust_remote_code"])
|
| 504 |
-
return lambda: blocks
|
| 505 |
|
| 506 |
monkeypatch.setattr(remote_runner, "get_class_from_dynamic_module", fake_get_class)
|
| 507 |
|
| 508 |
-
remote_runner.
|
| 509 |
-
repo_id="user/multidiff-modular",
|
| 510 |
-
family="flux1-schnell",
|
| 511 |
-
dtype="float32",
|
| 512 |
-
device="cpu",
|
| 513 |
-
local_files_only=True,
|
| 514 |
-
compile=False,
|
| 515 |
-
prompt_upsampler=False,
|
| 516 |
-
)
|
| 517 |
|
|
|
|
| 518 |
assert calls["dynamic_module"] == ("user/multidiff-modular", "block.py", "Flux1MultiDiffusionAutoBlocks", True)
|
| 519 |
-
assert
|
| 520 |
-
|
|
|
|
| 521 |
|
| 522 |
|
| 523 |
class FakeRemoteRunPipe:
|
|
@@ -568,9 +500,10 @@ def test_remote_main_applies_family_defaults_from_model_config(
|
|
| 568 |
config_repos.append(base_model)
|
| 569 |
return model_config
|
| 570 |
|
|
|
|
| 571 |
monkeypatch.setattr(remote_runner, "load_model_config", fake_load_model_config)
|
| 572 |
-
monkeypatch.setattr(
|
| 573 |
-
monkeypatch.setattr(
|
| 574 |
|
| 575 |
remote_runner.main(["--repo-id", "user/multidiff-modular", "--family", family, "--device", "cpu", *extra_args])
|
| 576 |
|
|
@@ -719,6 +652,7 @@ def test_flux_img2img_encodes_through_the_img2img_branch_and_packs_2x2(monkeypat
|
|
| 719 |
vae_scale_factor=8,
|
| 720 |
blocks=SimpleNamespace(sub_blocks={"vae_encoder": vae_encoder_block}),
|
| 721 |
image_processor=object(),
|
|
|
|
| 722 |
)
|
| 723 |
generator = object()
|
| 724 |
monkeypatch.setattr(runner, "load_image", lambda path: object())
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
def _args(*extra):
|
| 21 |
+
return runner.parse_args(["--base-model", "model", *extra])
|
| 22 |
|
| 23 |
|
| 24 |
def test_quantization_parser_defaults_to_none():
|
|
|
|
| 214 |
assert call_kwargs["window_batch_size"] == 6
|
| 215 |
|
| 216 |
|
| 217 |
+
def test_parser_rejects_invalid_window_batch_size(capsys):
|
| 218 |
+
with pytest.raises(SystemExit):
|
| 219 |
+
_args("--window-batch-size", "0")
|
| 220 |
+
|
| 221 |
+
assert "positive integer" in capsys.readouterr().err
|
|
|
|
|
|
|
| 222 |
|
| 223 |
|
| 224 |
def test_csv_prompt_loads_regional_masks_in_csv_order(tmp_path):
|
|
|
|
| 293 |
({"_class_name": "FluxPipeline"}, "Flux1MultiDiffusionAutoBlocks"),
|
| 294 |
({"_class_name": "Flux3ModularPipeline"}, "Flux3KleinBaseMultiDiffusionAutoBlocks"),
|
| 295 |
({"_class_name": "Flux3DistilledModularPipeline"}, "Flux3KleinMultiDiffusionAutoBlocks"),
|
| 296 |
+
# the `modular_model_index.json` spellings of the exported `model/<family>` folders
|
| 297 |
+
({"_class_name": "FluxModularPipeline"}, "Flux1MultiDiffusionAutoBlocks"),
|
| 298 |
+
({"_class_name": "Flux2ModularPipeline"}, "Flux2DevMultiDiffusionAutoBlocks"),
|
| 299 |
+
({"_class_name": "Flux2KleinModularPipeline", "is_distilled": True}, "Flux2KleinMultiDiffusionAutoBlocks"),
|
| 300 |
],
|
| 301 |
)
|
| 302 |
def test_multidiffusion_blocks_are_selected_from_loaded_pipeline_config(config, expected_class_name):
|
|
|
|
| 366 |
assert pipe.vae.slicing_enabled
|
| 367 |
|
| 368 |
|
| 369 |
+
class FakeInitPipe:
|
| 370 |
+
def __init__(self, guider=None):
|
| 371 |
+
self.guider = guider
|
| 372 |
+
self.updated_components = None
|
| 373 |
|
| 374 |
+
def load_components(self, **kwargs):
|
| 375 |
+
self.load_kwargs = kwargs
|
|
|
|
|
|
|
| 376 |
|
| 377 |
+
def update_components(self, **components):
|
| 378 |
+
self.updated_components = components
|
|
|
|
|
|
|
| 379 |
|
|
|
|
|
|
|
| 380 |
|
| 381 |
+
class FakeInitBlocks:
|
| 382 |
+
def __init__(self, pipe):
|
| 383 |
+
self.pipe = pipe
|
| 384 |
+
self.base_model = None
|
| 385 |
|
| 386 |
+
def init_pipeline(self, base_model, components_manager):
|
| 387 |
+
self.base_model = base_model
|
| 388 |
+
return self.pipe
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def test_init_loads_the_base_model_components_and_keeps_the_guider_default():
|
| 392 |
+
blocks = FakeInitBlocks(FakeInitPipe(guider=object()))
|
| 393 |
|
| 394 |
pipe = runner.init_modular_pipeline(
|
| 395 |
+
blocks, "black-forest-labs/FLUX.2-klein-base-4B", dtype="float32", device="cpu", local_files_only=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
)
|
| 397 |
|
| 398 |
+
assert blocks.base_model == "black-forest-labs/FLUX.2-klein-base-4B"
|
| 399 |
+
assert pipe.load_kwargs == {"dtype": torch.float32, "local_files_only": True, "quantization_config": None}
|
| 400 |
assert pipe.updated_components is None
|
| 401 |
|
| 402 |
|
| 403 |
+
def test_init_applies_explicit_guidance_scale():
|
| 404 |
+
class FakeGuider:
|
| 405 |
+
def new(self, **config):
|
| 406 |
+
return config
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
|
| 408 |
pipe = runner.init_modular_pipeline(
|
| 409 |
+
FakeInitBlocks(FakeInitPipe(FakeGuider())), "model", guidance_scale=2.5, device="cpu"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
)
|
| 411 |
|
| 412 |
assert pipe.updated_components == {"guider": {"guidance_scale": 2.5}}
|
|
|
|
| 418 |
assert args.repo_id == "user/multidiff-modular"
|
| 419 |
|
| 420 |
|
| 421 |
+
def test_remote_loader_loads_root_blocks_with_remote_code(monkeypatch):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
calls = {}
|
| 423 |
|
| 424 |
def fake_from_pretrained(repo_id, **kwargs):
|
| 425 |
+
calls["from_pretrained"] = (repo_id, kwargs)
|
| 426 |
+
return "root-blocks"
|
|
|
|
| 427 |
|
| 428 |
monkeypatch.setattr(remote_runner.ModularPipelineBlocks, "from_pretrained", fake_from_pretrained)
|
| 429 |
|
| 430 |
+
blocks = remote_runner.load_remote_blocks("user/multidiff-modular", local_files_only=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
|
| 432 |
+
assert blocks == "root-blocks"
|
| 433 |
+
assert calls["from_pretrained"] == ("user/multidiff-modular", {"trust_remote_code": True, "local_files_only": True})
|
| 434 |
+
assert remote_runner.remote_base_model("user/multidiff-modular", None) == "user/multidiff-modular"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 435 |
|
| 436 |
|
| 437 |
+
def test_remote_loader_loads_family_blocks_from_root_block_code(monkeypatch):
|
| 438 |
calls = {}
|
|
|
|
| 439 |
|
| 440 |
def fake_get_class(repo_id, module_file, **kwargs):
|
| 441 |
calls["dynamic_module"] = (repo_id, module_file, kwargs["class_name"], kwargs["trust_remote_code"])
|
| 442 |
+
return lambda: "family-blocks"
|
| 443 |
|
| 444 |
monkeypatch.setattr(remote_runner, "get_class_from_dynamic_module", fake_get_class)
|
| 445 |
|
| 446 |
+
blocks = remote_runner.load_remote_blocks("user/multidiff-modular", family="flux1-schnell")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
|
| 448 |
+
assert blocks == "family-blocks"
|
| 449 |
assert calls["dynamic_module"] == ("user/multidiff-modular", "block.py", "Flux1MultiDiffusionAutoBlocks", True)
|
| 450 |
+
assert (
|
| 451 |
+
remote_runner.remote_base_model("user/multidiff-modular", "flux1-schnell") == "black-forest-labs/FLUX.1-schnell"
|
| 452 |
+
)
|
| 453 |
|
| 454 |
|
| 455 |
class FakeRemoteRunPipe:
|
|
|
|
| 500 |
config_repos.append(base_model)
|
| 501 |
return model_config
|
| 502 |
|
| 503 |
+
monkeypatch.setattr(remote_runner, "load_remote_blocks", lambda repo_id, **kwargs: SimpleNamespace(sub_blocks={}))
|
| 504 |
monkeypatch.setattr(remote_runner, "load_model_config", fake_load_model_config)
|
| 505 |
+
monkeypatch.setattr(runner, "init_modular_pipeline", lambda blocks, base_model, **kwargs: pipe)
|
| 506 |
+
monkeypatch.setattr(runner, "save_images", lambda *args, **kwargs: None)
|
| 507 |
|
| 508 |
remote_runner.main(["--repo-id", "user/multidiff-modular", "--family", family, "--device", "cpu", *extra_args])
|
| 509 |
|
|
|
|
| 652 |
vae_scale_factor=8,
|
| 653 |
blocks=SimpleNamespace(sub_blocks={"vae_encoder": vae_encoder_block}),
|
| 654 |
image_processor=object(),
|
| 655 |
+
transformer=_flux_pipe(guidance_embeds=True).transformer,
|
| 656 |
)
|
| 657 |
generator = object()
|
| 658 |
monkeypatch.setattr(runner, "load_image", lambda path: object())
|
|
@@ -41,7 +41,9 @@ def test_export_hf_repo_uses_save_pretrained_and_copies_block(monkeypatch, tmp_p
|
|
| 41 |
def save_pretrained(self, output_dir):
|
| 42 |
pass
|
| 43 |
|
| 44 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
| 45 |
|
| 46 |
output_dir = repository.export_hf_repo(tmp_path, model_family="flux2-klein-4b", copy_readme=False)
|
| 47 |
|
|
@@ -71,7 +73,7 @@ def test_project_model_exports_skip_readme_copy(monkeypatch, tmp_path):
|
|
| 71 |
def save_pretrained(self, output_dir):
|
| 72 |
pass
|
| 73 |
|
| 74 |
-
monkeypatch.setattr(repository, "
|
| 75 |
monkeypatch.setattr(repository, "PROJECT_ROOT", tmp_path)
|
| 76 |
(tmp_path / "block.py").write_text("# root block\n", encoding="utf-8")
|
| 77 |
(tmp_path / "README.md").write_text("root readme\n", encoding="utf-8")
|
|
@@ -122,7 +124,7 @@ def test_export_keeps_upstream_component_specs_and_pushes_the_finished_folder(mo
|
|
| 122 |
|
| 123 |
import huggingface_hub
|
| 124 |
|
| 125 |
-
monkeypatch.setattr(repository, "
|
| 126 |
monkeypatch.setattr(huggingface_hub, "HfApi", FakeHfApi)
|
| 127 |
|
| 128 |
output_dir = repository.export_hf_repo(
|
|
@@ -141,14 +143,23 @@ def test_export_keeps_upstream_component_specs_and_pushes_the_finished_folder(mo
|
|
| 141 |
]
|
| 142 |
|
| 143 |
|
| 144 |
-
@pytest.mark.parametrize(
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
| 147 |
|
| 148 |
with pytest.raises(ValueError, match="push_to_hub"):
|
| 149 |
repository.export_hf_repo(output_path, repo_id=repo_id, push_to_hub=True)
|
| 150 |
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
def test_committed_remote_code_loads_without_local_package(monkeypatch, tmp_path):
|
| 153 |
import builtins
|
| 154 |
import shutil
|
|
@@ -202,7 +213,7 @@ def test_family_export_uses_supported_block_class(monkeypatch, tmp_path, model_f
|
|
| 202 |
def save_pretrained(self, output_dir):
|
| 203 |
pass
|
| 204 |
|
| 205 |
-
monkeypatch.setattr(repository, "
|
| 206 |
|
| 207 |
output_dir = repository.export_hf_repo(tmp_path / model_family, model_family=model_family, copy_readme=False)
|
| 208 |
|
|
|
|
| 41 |
def save_pretrained(self, output_dir):
|
| 42 |
pass
|
| 43 |
|
| 44 |
+
monkeypatch.setattr(
|
| 45 |
+
repository, "get_multidiffusion_blocks", lambda model_family: calls.append(model_family) or FakeBlocks()
|
| 46 |
+
)
|
| 47 |
|
| 48 |
output_dir = repository.export_hf_repo(tmp_path, model_family="flux2-klein-4b", copy_readme=False)
|
| 49 |
|
|
|
|
| 73 |
def save_pretrained(self, output_dir):
|
| 74 |
pass
|
| 75 |
|
| 76 |
+
monkeypatch.setattr(repository, "get_multidiffusion_blocks", lambda model_family: FakeBlocks())
|
| 77 |
monkeypatch.setattr(repository, "PROJECT_ROOT", tmp_path)
|
| 78 |
(tmp_path / "block.py").write_text("# root block\n", encoding="utf-8")
|
| 79 |
(tmp_path / "README.md").write_text("root readme\n", encoding="utf-8")
|
|
|
|
| 124 |
|
| 125 |
import huggingface_hub
|
| 126 |
|
| 127 |
+
monkeypatch.setattr(repository, "get_multidiffusion_blocks", lambda family: FakeBlocks())
|
| 128 |
monkeypatch.setattr(huggingface_hub, "HfApi", FakeHfApi)
|
| 129 |
|
| 130 |
output_dir = repository.export_hf_repo(
|
|
|
|
| 143 |
]
|
| 144 |
|
| 145 |
|
| 146 |
+
@pytest.mark.parametrize(
|
| 147 |
+
("output_dir", "repo_id"), [("hf_export", None), (".", "user/repo"), ("model/flux1-dev", "user/repo")]
|
| 148 |
+
)
|
| 149 |
+
def test_export_push_needs_a_repo_id_and_a_folder_git_does_not_publish(tmp_path, output_dir, repo_id):
|
| 150 |
+
output_path = tmp_path / output_dir if repo_id is None else repository.PROJECT_ROOT / output_dir
|
| 151 |
|
| 152 |
with pytest.raises(ValueError, match="push_to_hub"):
|
| 153 |
repository.export_hf_repo(output_path, repo_id=repo_id, push_to_hub=True)
|
| 154 |
|
| 155 |
|
| 156 |
+
def test_export_push_accepts_a_standalone_folder_inside_the_checkout():
|
| 157 |
+
# the README exports `hf_export/` from the checkout root before pushing it
|
| 158 |
+
assert not repository._is_checkout_folder(repository.PROJECT_ROOT / "hf_export")
|
| 159 |
+
assert repository._is_checkout_folder(repository.PROJECT_ROOT)
|
| 160 |
+
assert repository._is_checkout_folder(repository.PROJECT_ROOT / "model" / "flux1-dev")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
def test_committed_remote_code_loads_without_local_package(monkeypatch, tmp_path):
|
| 164 |
import builtins
|
| 165 |
import shutil
|
|
|
|
| 213 |
def save_pretrained(self, output_dir):
|
| 214 |
pass
|
| 215 |
|
| 216 |
+
monkeypatch.setattr(repository, "get_multidiffusion_blocks", lambda family: FakeBlocks())
|
| 217 |
|
| 218 |
output_dir = repository.export_hf_repo(tmp_path / model_family, model_family=model_family, copy_readme=False)
|
| 219 |
|
|
@@ -51,6 +51,16 @@ def test_window_starts_apply_offset_and_wrap():
|
|
| 51 |
assert _window_starts(full=10, window=4, stride=3, offset=1, wrap=True) == [1, 4, 7]
|
| 52 |
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
def test_validate_multidiffusion_args_rejects_invalid_window():
|
| 55 |
with pytest.raises(ValueError, match="divisible"):
|
| 56 |
_validate_multidiffusion_args(
|
|
@@ -188,6 +198,29 @@ def test_image_conditioning_window_preserves_wrapped_local_order():
|
|
| 188 |
assert window_ids[0, :, 2].tolist() == [0, 1, 2] * 4
|
| 189 |
|
| 190 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
def test_multidiffusion_window_loop_identity_merge():
|
| 192 |
from multidiffusion.flux2 import _Flux2MultiDiffusionWindowLoopMixin
|
| 193 |
|
|
@@ -842,3 +875,16 @@ def test_flux3_upsampler_upsamples_regional_prompts_one_by_one(monkeypatch):
|
|
| 842 |
_, state = flux3.Flux3MultiDiffusionText2ImagePromptUpsampleStep()(components, state)
|
| 843 |
|
| 844 |
assert state.get("prompt") == ["", "up:a lighthouse", "up:a balloon"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
assert _window_starts(full=10, window=4, stride=3, offset=1, wrap=True) == [1, 4, 7]
|
| 52 |
|
| 53 |
|
| 54 |
+
@pytest.mark.parametrize(("full", "window", "stride"), [(10, 4, 4), (10, 4, 3), (11, 6, 5), (9, 4, 2)])
|
| 55 |
+
def test_wrapped_window_starts_cover_the_seam_for_every_offset(full, window, stride):
|
| 56 |
+
for offset in range(stride):
|
| 57 |
+
starts = _window_starts(full=full, window=window, stride=stride, offset=offset, wrap=True)
|
| 58 |
+
covered = {(start + cell) % full for start in starts for cell in range(window)}
|
| 59 |
+
assert covered == set(range(full)), (offset, starts)
|
| 60 |
+
|
| 61 |
+
assert _window_starts(full=10, window=4, stride=4, offset=2, wrap=True) == [2, 6, 8]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
def test_validate_multidiffusion_args_rejects_invalid_window():
|
| 65 |
with pytest.raises(ValueError, match="divisible"):
|
| 66 |
_validate_multidiffusion_args(
|
|
|
|
| 198 |
assert window_ids[0, :, 2].tolist() == [0, 1, 2] * 4
|
| 199 |
|
| 200 |
|
| 201 |
+
def test_image_conditioning_window_maps_each_reference_on_its_own_grid():
|
| 202 |
+
from diffusers.modular_pipelines.flux2.before_denoise import Flux2PrepareImageLatentsStep
|
| 203 |
+
|
| 204 |
+
# a 4 x 4 and a 2 x 2 reference, told apart by the time coordinate t = 10, 20
|
| 205 |
+
image_latent_ids = Flux2PrepareImageLatentsStep._prepare_image_ids(
|
| 206 |
+
[torch.zeros(1, 1, 4, 4), torch.zeros(1, 1, 2, 2)]
|
| 207 |
+
)
|
| 208 |
+
image_latents = torch.arange(20, dtype=torch.float32).reshape(1, 20, 1)
|
| 209 |
+
window = {"left": 0, "window_h": 2, "window_w": 4, "full_h": 4, "full_w": 4}
|
| 210 |
+
|
| 211 |
+
top_latents, top_ids = image_conditioning_window(
|
| 212 |
+
image_latents, image_latent_ids, top=0, **window, wrap_height=False, wrap_width=False
|
| 213 |
+
)
|
| 214 |
+
bottom_latents, bottom_ids = image_conditioning_window(
|
| 215 |
+
image_latents, image_latent_ids, top=2, **window, wrap_height=False, wrap_width=False
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
assert top_latents.flatten().tolist() == [*range(8), 16, 17]
|
| 219 |
+
assert bottom_latents.flatten().tolist() == [*range(8, 16), 18, 19]
|
| 220 |
+
assert top_ids[0, :, 0].tolist() == [10] * 8 + [20] * 2
|
| 221 |
+
assert bottom_ids[0, -2:, 1:3].tolist() == [[0, 0], [0, 1]]
|
| 222 |
+
|
| 223 |
+
|
| 224 |
def test_multidiffusion_window_loop_identity_merge():
|
| 225 |
from multidiffusion.flux2 import _Flux2MultiDiffusionWindowLoopMixin
|
| 226 |
|
|
|
|
| 875 |
_, state = flux3.Flux3MultiDiffusionText2ImagePromptUpsampleStep()(components, state)
|
| 876 |
|
| 877 |
assert state.get("prompt") == ["", "up:a lighthouse", "up:a balloon"]
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
def test_flux3_upsampler_rejects_layout_boxes_with_regional_prompts():
|
| 881 |
+
from diffusers.modular_pipelines import PipelineState
|
| 882 |
+
|
| 883 |
+
from multidiffusion import flux3
|
| 884 |
+
|
| 885 |
+
state = PipelineState()
|
| 886 |
+
state.set("prompt", ["", "a lighthouse"])
|
| 887 |
+
state.set("boxes", [{"id": 1, "desc": "a lighthouse", "bbox": [0.0, 0.0, 1.0, 0.5]}])
|
| 888 |
+
|
| 889 |
+
with pytest.raises(ValueError, match="boxes"):
|
| 890 |
+
flux3.Flux3MultiDiffusionText2ImagePromptUpsampleStep()(SimpleNamespace(), state)
|