diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..8a22125d9b7394a1bce91d1b0a2fc7fb7665abfa
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,67 @@
+*.7z filter=lfs diff=lfs merge=lfs -text
+*.arrow filter=lfs diff=lfs merge=lfs -text
+*.bin filter=lfs diff=lfs merge=lfs -text
+*.bz2 filter=lfs diff=lfs merge=lfs -text
+*.ckpt filter=lfs diff=lfs merge=lfs -text
+*.ftz filter=lfs diff=lfs merge=lfs -text
+*.gz filter=lfs diff=lfs merge=lfs -text
+*.h5 filter=lfs diff=lfs merge=lfs -text
+*.joblib filter=lfs diff=lfs merge=lfs -text
+*.lfs.* filter=lfs diff=lfs merge=lfs -text
+*.mlmodel filter=lfs diff=lfs merge=lfs -text
+*.model filter=lfs diff=lfs merge=lfs -text
+*.msgpack filter=lfs diff=lfs merge=lfs -text
+*.npy filter=lfs diff=lfs merge=lfs -text
+*.npz filter=lfs diff=lfs merge=lfs -text
+*.onnx filter=lfs diff=lfs merge=lfs -text
+*.ot filter=lfs diff=lfs merge=lfs -text
+*.parquet filter=lfs diff=lfs merge=lfs -text
+*.pb filter=lfs diff=lfs merge=lfs -text
+*.pickle filter=lfs diff=lfs merge=lfs -text
+*.pkl filter=lfs diff=lfs merge=lfs -text
+*.pt filter=lfs diff=lfs merge=lfs -text
+*.pth filter=lfs diff=lfs merge=lfs -text
+*.rar filter=lfs diff=lfs merge=lfs -text
+*.safetensors filter=lfs diff=lfs merge=lfs -text
+saved_model/**/* filter=lfs diff=lfs merge=lfs -text
+*.tar.* filter=lfs diff=lfs merge=lfs -text
+*.tar filter=lfs diff=lfs merge=lfs -text
+*.tflite filter=lfs diff=lfs merge=lfs -text
+*.tgz filter=lfs diff=lfs merge=lfs -text
+*.wasm filter=lfs diff=lfs merge=lfs -text
+*.xz filter=lfs diff=lfs merge=lfs -text
+*.zip filter=lfs diff=lfs merge=lfs -text
+*.zst filter=lfs diff=lfs merge=lfs -text
+*tfevents* filter=lfs diff=lfs merge=lfs -text
+assets/gallery/army.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/boardwalk.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/cat.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/closet.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/constable.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/leopard.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/man.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/man_outside.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/nissan.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/poster_film.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/poster_jazz.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/poster_travel.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/red_perfume.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/still_table.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/still_woman.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/venice.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/window_display.png filter=lfs diff=lfs merge=lfs -text
+text_encoder/tokenizer.json filter=lfs diff=lfs merge=lfs -text
+assets/gallery/beetle.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/cat_grass.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/marina.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/rooster.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/snail.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/station.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/street.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/collier.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/hokusai.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/larson.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/renoir.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/rousseau.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/wahlberg.png filter=lfs diff=lfs merge=lfs -text
+assets/gallery/weenix.png filter=lfs diff=lfs merge=lfs -text
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
new file mode 100644
index 0000000000000000000000000000000000000000..d24a7db8c1bcd53cd162bf8ce04ee99603f52664
--- /dev/null
+++ b/ATTRIBUTION.md
@@ -0,0 +1,45 @@
+# Attribution
+
+## T5Gemma 2 text encoder
+
+The `text_encoder/` folder is derived from
+[`google/t5gemma-2-270m-270m`](https://huggingface.co/google/t5gemma-2-270m-270m),
+published by Google, at revision `7c38f16641f455ef0685b18431faf1b17722d5a1`.
+
+> Zhang et al., "T5Gemma 2: Seeing, Reading, and Understanding Longer," 2025.
+> [arXiv:2512.14856](https://arxiv.org/abs/2512.14856)
+
+The folder is a modified copy of the original. It contains only what dflow_2b
+uses for prompt conditioning:
+
+- the tokenizer files, unchanged;
+- the token embeddings;
+- encoder layers 1 to 12.
+
+The remaining encoder layers and the whole decoder are not included. The kept
+weights are stored in bfloat16 with their values unchanged and with shortened
+tensor names. Data Archetype made these modifications in November 2026.
+
+Gemma is provided under and subject to the Gemma Terms of Use found at
+[gemma.ai/resources/terms](https://gemma.ai/resources/terms). A copy of the
+terms is in `text_encoder/LICENSE-GEMMA.md`. Use of the text encoder is subject
+to the use restrictions in Section 3.2 of those terms, which include the
+[Gemma Prohibited Use Policy](https://gemma.ai/resources/prohibited_use_policy).
+The bundled files are not relicensed under MG-BY-NC-2.0.
+
+## dinac3_96 autoencoder
+
+dflow_2b generates latents for the separately published
+[`data-archetype/dinac3_96`](https://huggingface.co/data-archetype/dinac3_96)
+autoencoder. The loader downloads it at the pinned commit
+`d0ca36daa3e429a510ba465a5f7f8139c66d2f82`. It is not part of this repository,
+and its own repository is the authority for its code, model card and licence.
+
+## dflow_2b
+
+The model weights, the `dflow` package, the documentation and the gallery
+images are distributed under the ModelGo Attribution-NonCommercial License 2.0
+(`MG-BY-NC-2.0`). See `LICENSE`, and retain `NOTICE` in any distribution.
+
+The ComfyUI nodes in `comfyui/` and the root `__init__.py` are distributed
+under GPL-3.0. See `comfyui/LICENSE`.
diff --git a/GALLERY.md b/GALLERY.md
new file mode 100644
index 0000000000000000000000000000000000000000..2f427f595742e645eb4695501222295473aa041b
--- /dev/null
+++ b/GALLERY.md
@@ -0,0 +1,1270 @@
+
+
+# dflow_2b example gallery
+
+[Model card](README.md) · [Manual](MANUAL.md) ·
+[Technical report](TECHNICAL_REPORT.md)
+
+> [!WARNING]
+> **Preview model, version 0.2.** The model is still in training.
+
+Every image was made with dflow_2b 0.2 and the default settings for
+its size, and was chosen from several seeds. Each PNG carries its ComfyUI
+workflow: drop it onto the ComfyUI canvas to load the graph that made it.
+
+
+
+## Photographs
+
+
+
+  Coastal boardwalk |
+  Tortoiseshell cat |
+  Walk-in closet |
+  Studio portrait |
+
+
+  Rooster on a garden path |
+  Outdoor portrait |
+  Snail on sand |
+  Perfume campaign |
+
+
+  Narrow street |
+  Red Beetle |
+  Train station |
+  Armoured man and army |
+
+
+  Leopard at night |
+  Woman by a window |
+  Nissan 300ZX at night |
+  Coastal village at dusk |
+
+
+
+
+
+## Paintings and prints
+
+
+
+  Landscape painting |
+  Mastiff over a fallen dog |
+  Barn and windmill |
+  Roses |
+
+
+  Stormy coast |
+  Portrait with spectacles |
+  River landscape |
+  The Great Wave |
+
+
+
+
+
+## JSON layouts
+
+
+
+  Jazz festival poster |
+  Travel poster |
+  Film poster |
+
+
+
+## Full-size images and settings
+
+### Photographs
+
+
+
+#### Coastal boardwalk
+
+[](assets/gallery/boardwalk.png)
+
+
+Generation settings
+
+**Prompt**
+
+> Wide angle photo of a weathered wooden boardwalk descending steeply from rocky
+> cliffs toward a rugged coastline. The boardwalk, constructed from aged planks
+> with visible cracks and moss growth, is bordered by rustic wooden railings on
+> both sides. Surrounding terrain features uneven, eroded rock formations
+> covered in patches of green vegetation and low-lying shrubs. Below, a
+> crescent-shaped sandy beach meets crashing waves of a deep blue ocean under a
+> stormy, overcast sky with dark clouds and hints of distant sunlight breaking
+> through. The horizon shows turbulent waves colliding with rocky outcrops,
+> creating white foam.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `44` |
+| Size | `1120 × 1664` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.60` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.01` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Tortoiseshell cat
+
+[](assets/gallery/cat_grass.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A close-up portrait of a chunky tortoiseshell cat sitting in tall grass, its
+> dense mottled fur of warm browns, creams and slate grays clearly textured,
+> bright green-yellow eyes looking slightly to the right, long white whiskers
+> and a small dark nose visible, soft natural daylight and a softly blurred
+> earthy background.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `127` |
+| Size | `832 × 1216` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Walk-in closet
+
+[](assets/gallery/closet.png)
+
+
+Generation settings
+
+**Prompt**
+
+> Interior of walk-in closet with white cabinets, shelves, and mirrored doors,
+> plus dark wood floor and crystal chandelier. Clothes hang on rods, shoes line
+> shelves, and a black purse sits on a clear acrylic stool. A vanity holds
+> flowers, perfume, and jewelry.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `42` |
+| Size | `1120 × 1664` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.60` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.01` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Studio portrait
+
+[](assets/gallery/man.png)
+
+
+Generation settings
+
+**Prompt**
+
+> Portrait of a man with medium brown skin tone, long dark hair tied back
+> loosely, full beard and mustache, slight stubble on upper lip. Wearing a dark
+> brown V-neck sweater with a slight sheen, looking directly at the camera with
+> a slight smile, neutral expression, soft lighting from above casting subtle
+> shadows under cheekbones and jawline. Plain light gray background.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `43` |
+| Size | `832 × 1216` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Rooster on a garden path
+
+[](assets/gallery/rooster.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A bright orange and black rooster standing on a damp garden path, surrounded
+> by lush green tropical plants and trees, its red comb upright and long dark
+> tail feathers curving down over the wet concrete.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `42` |
+| Size | `832 × 1216` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Outdoor portrait
+
+[](assets/gallery/man_outside.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A close-up portrait of a muscular man in his mid-40s with a bald head and
+> thick facial hair, standing outdoors in bright daylight. He is shirtless,
+> wearing black knee-length athletic shorts with a green wristband on his right
+> wrist and a gold chain necklace. His left arm is resting on a wooden post
+> wrapped with green vines, while his right hand grips the post near his waist.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `45` |
+| Size | `1120 × 1664` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.60` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.01` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Snail on sand
+
+[](assets/gallery/snail.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A dark brown snail with a glossy, spiral-patterned shell slowly crawls across
+> sandy ground, its long black tentacles extended. The shell has lighter cream
+> streaks and a small spiral center. Around the snail, dry tan soil is scattered
+> with thin green and yellow grass blades and a few small bright pink flower
+> petals, all lit by warm, soft daylight.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `323` |
+| Size | `1216 × 832` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Perfume campaign
+
+[](assets/gallery/red_perfume.png)
+
+
+Generation settings
+
+**Prompt**
+
+> Promotional image: Adult Asian woman with red lipstick holds a red perfume
+> bottle. She wears a black dress with black feathers, plus gold earrings. She
+> stands near a brown wall, with a dark background.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `47` |
+| Size | `1120 × 1664` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.60` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.01` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Narrow street
+
+[](assets/gallery/street.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A narrow, empty street lined with traditional wooden buildings and bamboo
+> blinds, overhead a tangle of utility poles and wires stretching between
+> rooftops; warm brown and ochre facades, paper lantern signs with Japanese
+> characters, a parked bicycle and potted plants at the edges, and a single
+> person in a blue jacket standing in the distance beneath tiled eaves.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `335` |
+| Size | `832 × 1216` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Red Beetle
+
+[](assets/gallery/beetle.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A shiny vintage red Volkswagen Beetle parked on a sunlit cobblestone
+> pedestrian street, seen from the rear with chrome bumpers and an old-fashioned
+> European license plate; the narrow street is lined with low, gabled buildings,
+> shops with awnings and an NKD storefront, leafy green trees casting dappled
+> shade, and groups of casually dressed people walking and window-shopping in
+> the background.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `129` |
+| Size | `832 × 1216` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Train station
+
+[](assets/gallery/station.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A sunlit train station concourse with tall iron-and-glass arched roof, two
+> yellow commuter trains stopped on either side of the central platform, and
+> passengers scattered across the floor waiting, buying tickets at
+> blue-and-silver machines, or walking toward the trains. Overhead signage
+> includes a large black information board reading "INFORMAÇÕES Information" and
+> smaller platform signs with numbers and arrows. Warm, golden daylight streams
+> through the roof, casting long shadows and highlighting the ornate iron
+> columns and the misty depth of the station. Visible text: "INFORMAÇÕES
+> Information," "zona PRT1," and illuminated timetable displays.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `139` |
+| Size | `832 × 1216` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Armoured man and army
+
+[](assets/gallery/army.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A movie still shows an elderly man with a white beard and thinning hair,
+> wearing ornate, weathered bronze plate armor, standing in a dusty field. He
+> faces an unseen person while a dark horse stand besides him. In the
+> background, a large army of soldiers with spears and shields is lined up under
+> a bright, cloudy sky. Another soldier wearing a metal helmet sits on a horse
+> behind the main figure.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `42` |
+| Size | `1536 × 832` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.22` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.02` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Leopard at night
+
+[](assets/gallery/leopard.png)
+
+
+Generation settings
+
+**Prompt**
+
+> Leopard lying down in a tree at night.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `43` |
+| Size | `1216 × 832` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Woman by a window
+
+[](assets/gallery/still_woman.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A movie still shows a young woman with shoulder-length brown hair looking
+> downward while seated indoors. She wears a white, open-knit cardigan over a
+> dark top, a gold heart-shaped locket, and small gold hoop earrings. In the
+> foreground, the back of another person's head and shoulder are visible in soft
+> focus, partially obscuring the right side of the frame. The background
+> features a window with thin, beige curtains and soft, natural light. The image
+> has a shallow depth of field and slight film grain.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `43` |
+| Size | `1536 × 832` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.22` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.02` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Nissan 300ZX at night
+
+[](assets/gallery/nissan.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A silver 1980s Nissan 300ZX sports car is parked at night in front of a
+> corrugated metal building with a large neon sign that reads "CARGOJET". The
+> car is angled towards the camera, with its headlights on. The building has a
+> loading dock and a concrete barrier in front of it.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `42` |
+| Size | `1664 × 1120` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.60` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.01` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Coastal village at dusk
+
+[](assets/gallery/marina.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A calm coastal village at dusk with a small marina in the foreground: dozens
+> of moored fishing boats and dinghies clustered along a stone quay, orange
+> buoys floating in the water, and a white lighthouse with a green stripe
+> standing near low warehouse buildings. Behind the harbor, terraced houses and
+> apartment buildings with red-tiled roofs climb a tree-dotted hillside, their
+> pale walls and balconies softly lit by the last light. The water reflects the
+> boats and lights, and a pebbled shoreline runs along the lower edge of the
+> frame.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `438` |
+| Size | `1216 × 832` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+### Paintings and prints
+
+
+
+#### Landscape painting
+
+[](assets/gallery/constable.png)
+
+
+Generation settings
+
+**Prompt**
+
+> An oil painting of a landscape with sheep and farmers near a mill by John
+> Constable
+
+| Setting | Value |
+| --- | --- |
+| Seed | `44` |
+| Size | `1216 × 1088` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.26` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.02` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Mastiff over a fallen dog
+
+[](assets/gallery/weenix.png)
+
+
+Generation settings
+
+**Prompt**
+
+> An oil painting in the Baroque style by Jan Weenix depicts a large,
+> tan-colored mastiff standing over a dead, dark brown shaggy dog. The standing
+> dog is seen in profile, wearing a thick black leather collar, with a focused,
+> alert expression and its mouth slightly open. The deceased dog lies on its
+> side in the foreground, its mouth agape to reveal teeth, with its coarse fur
+> rendered in deep browns and blacks. Two small, dead songbirds with grey and
+> white plumage lie on the dusty ground near the fallen dog. The setting is a
+> wild landscape under a moody, overcast sky with a glimpse of a valley and
+> distant hills. To the right, a cluster of greenery includes large, curling
+> leaves and a few small red and blue flowers. The lighting is dramatic, with a
+> strong highlight on the standing dog's face and shoulder, casting the rest of
+> the scene in deep, rich shadows. The image has the smooth, blended texture of
+> a classical oil canvas.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `231` |
+| Size | `896 × 1088` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.95` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Barn and windmill
+
+[](assets/gallery/wahlberg.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A black and white oil painting by Alfred Wahlberg in the style of realism,
+> depicting a rural landscape. In the center, a weathered wooden barn with a
+> steep, gabled roof stands beside a tall, tapered windmill tower. A leafless,
+> spindly tree with fine branches dominates the middle ground, partially
+> obscuring the structures. To the left, a calm body of water meets a soft
+> horizon under a vast, overcast sky filled with textured, swirling clouds. To
+> the right, a dirt path winds up a gentle slope toward a few distant cottages.
+> The terrain is rugged, with scrubby bushes, patches of dry grass, and a rustic
+> wooden fence in the foreground. The image is rendered with a fine, painterly
+> grain and a soft contrast, blending muted grey and white tones to create a
+> somber, atmospheric mood.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `426` |
+| Size | `1280 × 768` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.96` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Roses
+
+[](assets/gallery/renoir.png)
+
+
+Generation settings
+
+**Prompt**
+
+> An Impressionist oil painting by Pierre-Auguste Renoir featuring a tight
+> cluster of blooming roses. The composition is a close-up, filling the square
+> frame with vivid red, pale yellow, and creamy white blossoms interspersed with
+> deep green foliage. The brushwork is loose and feathered, creating a soft,
+> blurred texture that blends the petals into one another. The background is a
+> warm, mottled brown and ochre, applied with visible, directional strokes. The
+> painting is rendered on a coarse canvas, with the heavy textile weave showing
+> through the paint throughout the image. Lighting is diffused and bright,
+> creating luminous highlights on the tops of the petals and deep, saturated
+> shadows in the centers of the red roses.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `136` |
+| Size | `1024 × 1024` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.02` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Stormy coast
+
+[](assets/gallery/larson.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A Romanticism oil painting by Marcus Larson depicting a turbulent sea crashing
+> against jagged, dark reddish-brown rock formations. In the foreground, white
+> frothy waves swell and break violently against the sharp edges of the rocks,
+> creating a sense of motion and spray. The middle ground contains several
+> isolated rocky islets emerging from the churning, olive-green water, with
+> distant silhouettes of sailing ships visible on the horizon under a heavy sky.
+> The sky is filled with dramatic, swirling grey and white clouds, through which
+> bright beams of sunlight pierce downward in sharp diagonal lines, illuminating
+> patches of the ocean. Small, dark birds fly sporadically across the expanse of
+> the sky. The painting has a rich, blended texture with visible brushwork in
+> the foam and clouds. In the bottom left corner, a signature reads "Marcus
+> Larson".
+
+| Setting | Value |
+| --- | --- |
+| Seed | `137` |
+| Size | `1216 × 832` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Portrait with spectacles
+
+[](assets/gallery/collier.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A realist oil portrait by John Collier of a middle-aged man with a fair
+> complexion, facing forward. He has short brown hair, thick dark eyebrows, and
+> a full brown mustache. He wears thin-rimmed round spectacles and a
+> high-collared, button-up white garment made of a heavy fabric. The lighting
+> falls from the upper left, casting a soft shadow on the right side of his face
+> and under his mustache. The background is a textured, neutral grey with
+> visible vertical brushstrokes. In the bottom right corner, the artist's
+> signature "John Collier" and the date "1891" are written in dark paint. The
+> image has the texture of a weathered canvas with fine cracks and a matte
+> finish.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `232` |
+| Size | `896 × 1088` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.95` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### River landscape
+
+[](assets/gallery/rousseau.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A landscape painting in the style of Realism by Theodore Rousseau depicts a
+> serene river scene under a pale blue sky with scattered, wispy white clouds.
+> In the center, a cluster of lush, green deciduous trees with dense foliage
+> reflects in the still, glassy water of a winding river. To the left, a small
+> group of figures and brown cattle gather near the riverbank, rendered with
+> small, detailed brushstrokes. The foreground consists of dark, textured
+> shrubbery and earthy riverbanks in deep greens and browns. The composition is
+> a wide horizontal view with a low horizon line, emphasizing the expanse of the
+> sky and the natural layering of the vegetation. The overall rendering features
+> a fine, blended oil texture with soft, natural lighting that creates a hazy,
+> atmospheric quality. The painting is enclosed in a thin, simple gold frame.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `138` |
+| Size | `1216 × 832` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### The Great Wave
+
+[](assets/gallery/hokusai.png)
+
+
+Generation settings
+
+**Prompt**
+
+> A traditional japanese woodblock print, "the great wave off kanagawa" by
+> hokusai, depicts a massive blue and white wave crashing towards the viewer
+> against a pale blue sky.
+
+| Setting | Value |
+| --- | --- |
+| Seed | `424` |
+| Size | `1024 × 1024` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-3.02` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+### JSON layouts
+
+
+
+#### Jazz festival poster
+
+[](assets/gallery/poster_jazz.png)
+
+
+Generation settings
+
+**Layout prompt** (compiled to the image size by the Layout Encode node)
+
+```json
+{
+ "summary": {
+ "meta": [
+ "concert_poster",
+ "flat_illustration",
+ "mid_century_modern"
+ ],
+ "canvas": "single",
+ "caption": "A mid-century style jazz festival poster shows a saxophonist in silhouette against a large orange sun on a deep teal background. The title \"BLUE HARBOR JAZZ\" runs across the top in cream capitals and the line \"JULY 12 – 14, 1996\" sits at the bottom."
+ },
+ "frame": {
+ "caption": "The saxophonist stands in the centre, cut off at the knees, with the sun behind his shoulders. The title fills the top fifth and the date line sits in a band along the bottom edge. Flat colour shapes with a light paper grain.",
+ "tags": [
+ "flat_color",
+ "centered_composition",
+ "paper_grain"
+ ],
+ "palette": [
+ "#0F4C5C",
+ "#F28C28",
+ "#F5E9D0",
+ "#1B1B1B"
+ ]
+ },
+ "items": [
+ {
+ "label": "object",
+ "caption": "A large flat orange circle, the sun, behind the musician.",
+ "tags": [
+ "sun",
+ "circle"
+ ],
+ "palette": [
+ "#F28C28"
+ ],
+ "box_2d": [
+ 230,
+ 170,
+ 720,
+ 830
+ ]
+ },
+ {
+ "label": "character",
+ "caption": "A black silhouette of a man in a hat playing a tenor saxophone, facing right, leaning back slightly.",
+ "tags": [
+ "saxophonist",
+ "silhouette",
+ "hat"
+ ],
+ "palette": [
+ "#1B1B1B"
+ ],
+ "box_2d": [
+ 260,
+ 250,
+ 880,
+ 760
+ ]
+ },
+ {
+ "label": "text",
+ "caption": "The title \"BLUE HARBOR JAZZ\" in bold condensed cream capitals on one line.",
+ "text": "BLUE HARBOR JAZZ",
+ "tags": [
+ "title",
+ "condensed_sans",
+ "uppercase"
+ ],
+ "palette": [
+ "#F5E9D0"
+ ],
+ "box_2d": [
+ 60,
+ 70,
+ 180,
+ 930
+ ]
+ },
+ {
+ "label": "text",
+ "caption": "The date line \"JULY 12 – 14, 1996\" in small spaced cream capitals.",
+ "text": "JULY 12 – 14, 1996",
+ "tags": [
+ "date",
+ "small_caps"
+ ],
+ "palette": [
+ "#F5E9D0"
+ ],
+ "box_2d": [
+ 905,
+ 300,
+ 950,
+ 700
+ ]
+ }
+ ]
+}
+```
+
+| Setting | Value |
+| --- | --- |
+| Seed | `42` |
+| Size | `832 × 1216` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Travel poster
+
+[](assets/gallery/poster_travel.png)
+
+
+Generation settings
+
+**Layout prompt** (compiled to the image size by the Layout Encode node)
+
+```json
+{
+ "summary": {
+ "meta": [
+ "travel_poster",
+ "screenprint",
+ "national_park"
+ ],
+ "canvas": "single",
+ "caption": "A vintage screenprint travel poster of a snow-capped mountain above a pine forest and a still lake at sunrise. The words \"VISIT\" and \"SILVER LAKE\" are set in the sky, and a cream band at the bottom reads \"OPEN ALL YEAR\"."
+ },
+ "frame": {
+ "caption": "The mountain peak rises in the upper middle, pines frame both sides, and the lake reflects the peak in the lower third. A cream border surrounds the image and widens into a band at the bottom. Four flat inks with visible screenprint texture.",
+ "tags": [
+ "limited_palette",
+ "bordered",
+ "symmetrical"
+ ],
+ "palette": [
+ "#F3E6C8",
+ "#E8793A",
+ "#2F5D62",
+ "#1E2F3A"
+ ]
+ },
+ "items": [
+ {
+ "label": "object",
+ "caption": "A snow-capped mountain with orange light on its left face.",
+ "tags": [
+ "mountain",
+ "snow_cap"
+ ],
+ "palette": [
+ "#E8793A",
+ "#F3E6C8",
+ "#2F5D62"
+ ],
+ "box_2d": [
+ 250,
+ 180,
+ 620,
+ 820
+ ]
+ },
+ {
+ "label": "object",
+ "caption": "A calm lake with a soft reflection of the mountain and a small red canoe near the right shore.",
+ "tags": [
+ "lake",
+ "reflection",
+ "canoe"
+ ],
+ "palette": [
+ "#2F5D62",
+ "#E8793A"
+ ],
+ "box_2d": [
+ 620,
+ 60,
+ 860,
+ 940
+ ]
+ },
+ {
+ "label": "text",
+ "caption": "The small word \"VISIT\" in spaced dark capitals.",
+ "text": "VISIT",
+ "tags": [
+ "kicker",
+ "uppercase"
+ ],
+ "palette": [
+ "#1E2F3A"
+ ],
+ "box_2d": [
+ 70,
+ 400,
+ 110,
+ 600
+ ]
+ },
+ {
+ "label": "text",
+ "caption": "The title \"SILVER LAKE\" in tall dark serif capitals.",
+ "text": "SILVER LAKE",
+ "tags": [
+ "title",
+ "serif",
+ "uppercase"
+ ],
+ "palette": [
+ "#1E2F3A"
+ ],
+ "box_2d": [
+ 120,
+ 110,
+ 220,
+ 890
+ ]
+ },
+ {
+ "label": "text",
+ "caption": "The line \"OPEN ALL YEAR\" in dark capitals centred in the cream band.",
+ "text": "OPEN ALL YEAR",
+ "tags": [
+ "tagline",
+ "uppercase"
+ ],
+ "palette": [
+ "#1E2F3A"
+ ],
+ "box_2d": [
+ 895,
+ 260,
+ 945,
+ 740
+ ]
+ }
+ ]
+}
+```
+
+| Setting | Value |
+| --- | --- |
+| Seed | `50` |
+| Size | `832 × 1216` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
+
+
+
+#### Film poster
+
+[](assets/gallery/poster_film.png)
+
+
+Generation settings
+
+**Layout prompt** (compiled to the image size by the Layout Encode node)
+
+```json
+{
+ "summary": {
+ "meta": [
+ "movie_poster",
+ "photographic",
+ "thriller"
+ ],
+ "canvas": "single",
+ "caption": "A moody photographic film poster shows a woman in a long grey coat standing on an empty train platform at night, lit by one overhead lamp, with fog behind her. The title \"THE LAST TRAIN\" is set in thin white capitals across the lower third, above the small line \"A FILM BY MARA VOSS\"."
+ },
+ "frame": {
+ "caption": "The woman stands slightly left of centre, full length, facing the camera, with the platform edge leading into the fog on the right. The top half is dark sky and lamp glow. Cool teal grade with a warm lamp highlight and fine film grain.",
+ "tags": [
+ "low_key_lighting",
+ "teal_orange_grade",
+ "film_grain"
+ ],
+ "palette": [
+ "#0E1B22",
+ "#27505B",
+ "#D9A15B",
+ "#E9EEF0"
+ ]
+ },
+ "items": [
+ {
+ "label": "character",
+ "caption": "A woman in her thirties with dark shoulder-length hair, a long grey wool coat and black boots, hands in her pockets, with a calm, direct look.",
+ "tags": [
+ "woman",
+ "grey_coat",
+ "full_length"
+ ],
+ "palette": [
+ "#6F7C80",
+ "#1A1F22",
+ "#C9A58A"
+ ],
+ "box_2d": [
+ 250,
+ 240,
+ 800,
+ 560
+ ]
+ },
+ {
+ "label": "object",
+ "caption": "A hanging platform lamp with a warm cone of light in the fog.",
+ "tags": [
+ "lamp",
+ "warm_light",
+ "fog"
+ ],
+ "palette": [
+ "#D9A15B",
+ "#F3D9A8"
+ ],
+ "box_2d": [
+ 60,
+ 330,
+ 270,
+ 560
+ ]
+ },
+ {
+ "label": "text",
+ "caption": "The title \"THE LAST TRAIN\" in thin, widely spaced white capitals.",
+ "text": "THE LAST TRAIN",
+ "tags": [
+ "movie_title",
+ "thin_type",
+ "uppercase"
+ ],
+ "palette": [
+ "#E9EEF0"
+ ],
+ "box_2d": [
+ 815,
+ 80,
+ 880,
+ 920
+ ]
+ },
+ {
+ "label": "text",
+ "caption": "The credit line \"A FILM BY MARA VOSS\" in very small white capitals.",
+ "text": "A FILM BY MARA VOSS",
+ "tags": [
+ "credit_line",
+ "small_type"
+ ],
+ "palette": [
+ "#E9EEF0"
+ ],
+ "box_2d": [
+ 900,
+ 300,
+ 930,
+ 700
+ ]
+ }
+ ]
+}
+```
+
+| Setting | Value |
+| --- | --- |
+| Seed | `44` |
+| Size | `832 × 1216` |
+| Sampling | `50` ER-SDE steps, Beta(1.25, 1.25), noise scale `1` |
+| Log-SNR shift | `-2.99` (−0.25 plus the resolution term) |
+| Guidance | PDG, full path drop, constant `2.5`, suffix caption bias `-4`; CFG off |
+| Self-attention gain | `-0.03` |
+| Model | `dflow_2b 0.2`, bfloat16 weights |
+
+
+
+[Back to the top](#top)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..c9a409d58dc4492985b5a3aacfc08a001461d243
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,124 @@
+ModelGo Attribution-NonCommercial License
+Version 2.0, May 2025
+
+By exercising the rights granted in Section 2.1, You acknowledge and agree that You have
+read, understood, and agree to be bound by the terms and conditions of this License. If You
+do not agree to any terms and/or conditions of this License, then the Licensor grants You no
+rights under this License.
+
+1. DEFINITIONS
+
+"Complementary Materials" means the source code and scripts used to define, run, load,
+benchmark and/or evaluate the Model, and prepare data for the purpose of training, pretraining,
+fine-tuning and/or evaluation of the Model, and any tutorials, operating manuals, user guides
+and/or documentation that guide users in using, operating, implementing and/or customising
+the Model.
+
+"Derivative Materials" means all improvements, modifications or derivative works to the
+Licensed Material or any part thereof, which are created or developed by You (either by
+Yourself or jointly with other third parties), including any derivative model developed by
+transferring patterns of weights, parameters, activations and/or Output from the Model, such as
+through distillation methods or synthetic data generation techniques, in order to replicate,
+approximate, or otherwise achieve functional behavior that is similar to the Model.
+
+"Distribution" (or "Distribute") means any transmission, publication, public performance,
+sharing, or other methods of making the Licensed Materials, Derivative Materials and/or Output
+available to a third party, including providing the Licensed Materials or any part thereof as a
+hosted service or remotely accessible service, such as API-based access or web access.
+
+"Licensor" means the rights owner that is granting the License.
+
+"Licensed Materials" means the Model and Complementary Materials that are Distributed by
+the Licensor under this License. The Licensed Materials do not include any datasets used for
+pretraining, training, adapting, or evaluating the Model, which may or may not be made
+available under a separate license.
+
+"Model" means the machine-learning constructs and/or assemblies licensed by the Licensor
+under this License, including any checkpoints, learned weights, parameters (including optimizer
+states) and the model architecture.
+
+"NonCommercial" means not primarily intended for or directed towards commercial advantage
+or monetary compensation.
+
+"Output" means any information, data, and/or content, including but not limited to images, text,
+text effects, audio files, and/or video files, generated through operation of the Model, or through
+operation of any new model developed by transferring patterns from the Model.
+
+"You" (or "Your") means you, or any other person or entity you are entering into this license on
+behalf of, provided you have the legal authority to bind such person or entity.
+
+2. LICENSE RIGHTS
+
+2.1 Grant of Rights
+
+(a) Subject to the conditions in Section 2.2 of this License, the Licensor hereby grants to
+You a non-exclusive, non-sublicensable, revocable, royalty-free, worldwide license under
+the relevant copyrights, patent rights, database rights, and any other intellectual property
+rights to:
+
+(i) make, have made, use, reproduce and Distribute the Licensed Materials;
+
+(ii) use the Licensed Materials to create Derivative Materials; and
+
+(iii) make, have made, use, reproduce and Distribute Derivative Materials;
+
+for NonCommercial purposes only.
+
+2.2 Conditions
+
+(a) If You Distribute any of the Licensed Materials or Derivative Materials, You shall:
+
+(i) provide a copy of this License with the Licensed Material or Derivative Materials;
+
+(ii) in the case of Distributing Derivative Materials, provide as part of the Distribution,
+prominent notices stating that You have modified the Licensed Materials and the
+relevant date of such modification;
+
+(iii) retain as part of the Distribution any existing copyright notice, attribution notice,
+and/or any notice identifying the authors of the Licensed Materials and any
+Derivative Materials.
+
+(b) If You Distribute a collection of Output as a dataset generated wholly or partially using
+the Licensed Materials and/or Derivative Materials, You shall provide a prominent notice
+in the Distribution stating that the dataset is generated using the Licensed Materials
+and/or Derivative Materials provided under this License.
+
+2.3 Reservation of Rights
+
+You shall not refer to the Licensor or use the Licensor's trademarks, trade names, and service
+marks, for any publicity, advertising or marketing purposes, without the Licensor's prior written
+consent.
+
+3. DISCLAIMER
+
+To the maximum extent permissible under applicable law, the Licensed Materials are provided
+on an "as is" and "as available" basis without any representation or warranty of any kind
+(whether express, implied, statutory or otherwise), including of merchantability, satisfactory
+quality, fitness for a particular purpose, title, accuracy, correctness, absence of error, reliability,
+timeliness, non-infringement of or compliance with any laws, regulations and/or third-party
+rights, all of which are expressly disclaimed by the Licensor.
+
+4. LIMITATION OF LIABILITY
+
+To the maximum extent permissible under applicable law, the Licensor shall not be liable for
+any claims, damages, or any other liabilities, in any way arising out of or in connection with the
+Licensed Materials, Derivative Materials, and/or Output, whether on an action or claim in
+contract, tort (including negligence), breach of statutory duty or otherwise, even if the Licensor
+has been advised of the possibility of such damages.
+
+5. TERMINATION
+
+This License shall terminate immediately if You breach any material term and/or condition of
+this License, or if You initiate any legal action against the Licensor alleging that the Licensed
+Materials and/or Derivative Materials infringe any patent worldwide. Sections 3, 4 and 6 shall
+survive the termination of this License.
+
+6. MODIFICATION OF THIS LICENSE
+
+This License is Copyright © 2024 National University of Singapore. Permission is granted to
+copy, distribute, or communicate this License without modification. Nothing in this License
+permits You to modify this License as applied to the Licensed Materials. However, You may
+modify the text of this License and copy, distribute or communicate Your modified version and
+apply it to other original works of authorship, provided that You do not use the name "ModelGo"
+for your version of the license and furnish a readable notice describing Your modifications to
+this License.
diff --git a/MANUAL.md b/MANUAL.md
new file mode 100644
index 0000000000000000000000000000000000000000..55bdf7624228f0868033d155dac51a585b7d6ff0
--- /dev/null
+++ b/MANUAL.md
@@ -0,0 +1,1242 @@
+# dflow_2b Manual
+
+[Model card](README.md) · [Example gallery](GALLERY.md) ·
+[Technical report](TECHNICAL_REPORT.md) · [Release notes](RELEASES.md)
+
+## Contents
+
+1. [Installation](#installation)
+2. [A first image](#a-first-image)
+3. [Prompts](#prompts)
+4. [JSON layouts](#json-layouts)
+5. [Image sizes](#image-sizes)
+6. [Sampling](#sampling)
+7. [Guidance](#guidance)
+8. [Self-attention gain](#self-attention-gain)
+9. [Python API reference](#python-api-reference)
+10. [ComfyUI node reference](#comfyui-node-reference)
+11. [Troubleshooting](#troubleshooting)
+
+## Installation
+
+dflow_2b needs Python 3.12 or later, PyTorch 2.13 with CUDA, and an NVIDIA GPU
+with bfloat16 support. Install a CUDA build of PyTorch first; the
+[PyTorch installation selector](https://pytorch.org/get-started/locally/) gives
+the command for your system.
+
+The repository holds the denoiser weights, the text encoder, the `dflow` Python
+package and the ComfyUI nodes. The autoencoder,
+[dinac3_96](https://huggingface.co/data-archetype/dinac3_96), downloads into the
+Hugging Face cache the first time the model is loaded.
+
+### ComfyUI
+
+The repository is a ComfyUI custom-node folder. Download it into
+`custom_nodes` and install its requirements into ComfyUI's Python environment:
+
+```bash
+cd ComfyUI/custom_nodes
+hf download data-archetype/dflow_2b --local-dir dflow_2b
+pip install -r dflow_2b/requirements.txt
+```
+
+Restart ComfyUI. The nodes appear under the **DFlow** category. Start ComfyUI
+with `--preview-method auto` for live previews.
+
+### Python
+
+Download the repository and install the package from it. The install is
+editable, so Python runs the code in that folder:
+
+```bash
+hf download data-archetype/dflow_2b --local-dir dflow_2b
+pip install -e dflow_2b
+```
+
+`diffusers` is needed only for the optional
+[diffusers wrapper](#diffusers-wrapper).
+
+### Compilation
+
+The denoiser, the text encoder and the autoencoder are compiled with
+`torch.compile` by default. The first generation takes roughly 30 to 45 seconds
+longer while the graphs are built.
+
+To turn compilation off, pass `compile=False` in Python or switch
+`compile_model` off in the DFlow Loader node. The model then starts at once and
+each image takes longer. On an RTX 4090 a 50-step 832×1216 image takes about 10
+seconds compiled and about 13 seconds eagerly, with a peak of about 7 GB of
+VRAM.
+
+## A first image
+
+### In ComfyUI
+
+Load `dflow_2b/comfyui/workflows/dflow_default.json` and queue it. It uses the
+default preset. You can also drop any PNG from the [gallery](GALLERY.md) onto
+the canvas: each one carries the workflow that made it.
+
+The default graph has ten nodes, connected as follows:
+
+- **DFlow Loader** outputs the model, the text encoder and the autoencoder.
+- **DFlow Text Encode** takes the text encoder and the prompt.
+- **DFlow Guider** takes the model and the encoded prompt.
+- **DFlow Empty Latent** sets the image size.
+- **DFlow Sampler** feeds **DFlow Time Schedule**, which also takes the latent
+ and outputs the sigmas and the sampler.
+- **RandomNoise** sets the seed.
+- **SamplerCustomAdvanced** takes the noise, the guider, the sampler, the
+ sigmas and the latent.
+- **VAEDecode** takes the result and the loader's autoencoder, and
+ **SaveImage** stores the image.
+
+RandomNoise, SamplerCustomAdvanced, VAEDecode and SaveImage are ComfyUI's own
+nodes. The [node reference](#comfyui-node-reference) lists every input.
+
+### In Python
+
+```python
+from dflow.inference import GenerationSettings
+from dflow.pipeline import DFlowPipeline
+
+pipe = DFlowPipeline.from_pretrained("dflow_2b")
+settings = GenerationSettings(width=832, height=1216, seed=7)
+image = pipe("A lighthouse on a cliff at dusk.", settings).images[0]
+image.save("lighthouse.png", pnginfo=pipe.png_info(image))
+```
+
+`"dflow_2b"` is the folder downloaded during installation.
+`GenerationSettings()` with no arguments is the default preset, and the seed
+fixes every random draw of the call.
+
+## Prompts
+
+### Plain captions
+
+Natural descriptive captions work best. Write what a careful caption of the
+finished image would say: the subject, what it is doing, the setting, the light
+and the medium (a photograph, an oil painting, a movie still). Full sentences
+work better than lists of keywords, and a long, detailed prompt is fine. The
+limit is 6,144 tokens.
+
+### Quoted text for lettering
+
+To put words in the image, write them in double quotes inside the caption:
+
+```text
+A neon sign in a rainy street that reads "OPEN LATE".
+```
+
+Everything inside double quotes is encoded one character at a time, so the
+model sees the exact spelling. Use double quotes only for text that should be
+visible in the image. To place text precisely, use a
+[JSON layout](#json-layouts).
+
+### Prompt emphasis
+
+A phrase can be given more or less weight with the markup `(phrase:weight)`:
+
+```text
+A portrait of a woman in a (red:1.4) coat, (blurred background:0.7).
+```
+
+The weight changes how much attention the rest of the model pays to the tokens
+of that phrase. A weight of 1 is neutral, a weight above 1 strengthens the
+phrase and a weight between 0 and 1 weakens it.
+
+The markup follows a few rules:
+
+- The weight is the number after the last colon of a parenthesised group. The
+ phrase itself may contain colons.
+- Groups can be nested. An inner weight replaces the outer one for its own
+ words.
+- Parentheses without a numeric weight are ordinary text, and `\(` and `\)`
+ always are.
+
+Two settings control how a weight is applied. Let \\(w\\) be the weight and
+\\(\kappa\\) the strength.
+
+The **mapping** turns a positive weight into a bias added to the attention
+logits of the weighted tokens. `linear` adds \\(2\kappa(w-1)\\). `log` adds
+\\(\kappa \ln w\\), which at strength 1 multiplies the attention those tokens
+receive by exactly \\(w\\). The linear mapping is the stronger of the two: at
+strength 1, a weight of 2 multiplies the attention by about 7.
+
+The **strength** scales every bias. A strength of 0 turns emphasis off without
+removing the markup.
+
+A weight of 0 or below works differently. It scales the content the tokens
+contribute by \\(1 + \kappa(w-1)\\). At strength 1 a weight of 0 mutes the
+phrase and a weight of −1 subtracts it.
+
+The weights act in every attention layer of the denoiser. The **encoder**
+switch applies them inside the text encoder as well.
+
+| Setting | Default | Python (`EmphasisSettings`) | ComfyUI (DFlow Text Encode) |
+| --- | --- | --- | --- |
+| Emphasis on | yes | `emphasis=EmphasisSettings(...)`, or `None` to read prompts verbatim | `emphasis` |
+| Mapping | `linear` | `mapping` | `emphasis_mapping` |
+| Strength | 1.0 | `strength` | `emphasis_strength` |
+| Encoder | on | `encoder` | `emphasis_encoder` |
+
+Emphasis applies to plain-text prompts. Negative prompts and JSON layouts are
+encoded exactly as written: in a layout, parentheses and colons in captions or
+text stay literal and carry no weight.
+
+### Negative prompts
+
+A negative prompt is read by classifier-free guidance (CFG) and by the
+contrastive modes of path-drop guidance, both described under
+[Guidance](#guidance). With those modes, an empty negative prompt selects the
+model's learned null text. The default guidance conditions its reference
+prediction on the prompt itself and ignores the negative prompt.
+
+## JSON layouts
+
+A layout prompt describes an image as a canvas with a list of boxes. It gives
+control over where things are and over the exact text that appears. Layouts
+suit posters, covers, title cards and other designed images.
+
+### The stored format
+
+A layout is a JSON object with exactly three keys: `summary`, `frame` and
+`items`.
+
+**`summary`** describes the image as a whole.
+
+| Field | Type | Meaning |
+| --- | --- | --- |
+| `meta` | list of strings | Tags for the kind of image, such as `concert_poster` |
+| `canvas` | string | The canvas type; `single` in the examples here |
+| `caption` | string | A caption of the whole image |
+
+**`frame`** describes the canvas: the overall arrangement, style and colours.
+
+| Field | Type | Meaning |
+| --- | --- | --- |
+| `caption` | string | How the image is composed |
+| `tags` | list of strings | Style and composition tags |
+| `palette` | list of strings | Main colours as hex codes |
+
+**`items`** is a list of boxes, one per element.
+
+| Field | Type | Meaning |
+| --- | --- | --- |
+| `label` | string | `character`, `object` or `text` |
+| `box_2d` | four integers | The box as `[y0, x0, y1, x1]` on a 0 to 1000 scale |
+| `text` | string | The exact string to render; required for `text` items |
+| `caption` | string | A description of this element |
+| `tags` | list of strings | Tags for this element |
+| `palette` | list of strings | Its colours as hex codes |
+
+Boxes are measured from the top-left corner of the image. `y0` and `y1` are the
+top and bottom edges as thousandths of the image height, and `x0` and `x1` are
+the left and right edges as thousandths of the width. The vertical coordinate
+comes first.
+
+### Optional fields
+
+The required fields are the three top-level keys and, for each item, `label`
+and `box_2d`, plus `text` on a text item. Every other field can be left out:
+training dropped the optional fields at random. Captions, tags and palettes
+give the model more to work with, and a layout with labels and boxes alone
+still works.
+
+Unknown keys raise an error.
+
+### Compiling a layout to a size
+
+Before encoding, a layout is compiled for one image size: the frame becomes a
+first item, labelled `panel`, that covers the whole canvas, and every box is
+converted from the 0 to 1000 scale to integer pixels measured from the centre
+of the image. For an image \\(Y\\) pixels high, the top edge \\(y_0\\) and bottom
+edge \\(y_1\\) of a box become
+
+$$
+y_0' = \left\lfloor \frac{y_0\,Y}{1000} \right\rfloor - \left\lfloor \frac{Y}{2} \right\rfloor,
+\qquad
+y_1' = \left\lceil \frac{y_1\,Y}{1000} \right\rceil - \left\lfloor \frac{Y}{2} \right\rfloor,
+$$
+
+and the left and right edges are computed the same way from the width. At
+832×1216 the panel box is `[-608, -416, 608, 416]`. The result is one line of
+JSON with two fields naming the convention (`abs_centralized`, `yxyx`), in the
+format of the MOSS-Image layout prompts.
+
+The compiled boxes are in pixels, so a compiled layout belongs to one image
+size: the same stored layout compiles to different numbers at 832×1216 and at
+1216×832. Using a compiled layout at another size raises an error.
+
+Keep layouts in the stored format, which is independent of size, and let the
+code compile them:
+
+- In ComfyUI, the **DFlow Layout Encode** node takes the stored JSON together
+ with `width` and `height`. Set them to the size of the latent you sample. The
+ guider stops with a message when they differ.
+- In Python, pass the stored JSON as the prompt. The pipeline compiles it at
+ the size in `GenerationSettings`. The function that does this is
+ `dflow.inference.resolve_prompt`, and `dflow.layout.compile_layout` returns
+ the compiled text if you want to inspect it.
+
+### Worked example: a jazz festival poster
+
+This layout describes an 832×1216 poster with a sun, a saxophonist and two
+lines of text:
+
+```json
+{"summary": {
+ "meta": ["concert_poster", "flat_illustration", "mid_century_modern"],
+ "canvas": "single",
+ "caption": "A mid-century style jazz festival poster shows a saxophonist in silhouette against a large orange sun on a deep teal background. The title \"BLUE HARBOR JAZZ\" runs across the top in cream capitals and the line \"JULY 12 – 14, 1996\" sits at the bottom."},
+ "frame": {
+ "caption": "The saxophonist stands in the centre, cut off at the knees, with the sun behind his shoulders. The title fills the top fifth and the date line sits in a band along the bottom edge. Flat colour shapes with a light paper grain.",
+ "tags": ["flat_color", "centered_composition", "paper_grain"],
+ "palette": ["#0F4C5C", "#F28C28", "#F5E9D0", "#1B1B1B"]},
+ "items": [
+ {"label": "object",
+ "caption": "A large flat orange circle, the sun, behind the musician.",
+ "tags": ["sun", "circle"],
+ "palette": ["#F28C28"],
+ "box_2d": [230, 170, 720, 830]},
+ {"label": "character",
+ "caption": "A black silhouette of a man in a hat playing a tenor saxophone, facing right, leaning back slightly.",
+ "tags": ["saxophonist", "silhouette", "hat"],
+ "palette": ["#1B1B1B"],
+ "box_2d": [260, 250, 880, 760]},
+ {"label": "text",
+ "caption": "The title \"BLUE HARBOR JAZZ\" in bold condensed cream capitals on one line.",
+ "text": "BLUE HARBOR JAZZ",
+ "tags": ["title", "condensed_sans", "uppercase"],
+ "palette": ["#F5E9D0"],
+ "box_2d": [60, 70, 180, 930]},
+ {"label": "text",
+ "caption": "The date line \"JULY 12 – 14, 1996\" in small spaced cream capitals.",
+ "text": "JULY 12 – 14, 1996",
+ "tags": ["date", "small_caps"],
+ "palette": ["#F5E9D0"],
+ "box_2d": [905, 300, 950, 700]}]}
+```
+
+Reading it from the top:
+
+- The summary caption describes the finished poster in one paragraph, as a
+ plain prompt would, and quotes both lines of text.
+- The frame caption says how the canvas is arranged, and the palette lists the
+ four colours of the design.
+- The sun comes first in `items` and the saxophonist second. Their boxes
+ overlap, which is how the layout says that the figure stands in front of the
+ sun.
+- The title box `[60, 70, 180, 930]` spans from 6% to 18% of the height and
+ from 7% to 93% of the width: a wide band near the top. The `text` field holds
+ the string to render and the caption describes the lettering.
+
+The same layout ships as the workflow
+`comfyui/workflows/dflow_layout_poster.json`. In Python:
+
+```python
+from pathlib import Path
+
+from dflow.inference import GenerationSettings
+from dflow.pipeline import DFlowPipeline
+
+pipe = DFlowPipeline.from_pretrained("dflow_2b")
+layout = Path("jazz_poster.json").read_text(encoding="utf-8")
+settings = GenerationSettings(width=832, height=1216, seed=42)
+image = pipe(layout, settings).images[0]
+```
+
+At 832×1216 the sun's box `[230, 170, 720, 830]` compiles to
+`[-329, -275, 268, 275]`: pixels from the image centre, top edge first.
+
+### Tips
+
+- Write the exact characters in `text`, including capitals, punctuation and
+ spaces. The model renders that string; the item's caption describes its style.
+- Keep the number of items small. A handful of well-described boxes works
+ better than many small ones.
+- Boxes may overlap or contain one another.
+- Give each box the shape of its content. A single line of text wants a wide,
+ short box.
+- Small text and long passages often come out wrong in this release, so prefer
+ short strings in generous boxes.
+
+## Image sizes
+
+Width and height must be multiples of 16, because the autoencoder maps each
+16×16 block of pixels to one latent cell.
+
+The model works best at about one megapixel, the area it was trained on, in
+portrait, square or landscape. The default is 832×1216.
+
+| Shape | Sizes of about 1 MP |
+| --- | --- |
+| Portrait | 832×1216 |
+| Square | 1024×1024 |
+| Landscape | 1216×832 |
+
+Larger images work, for example 1536×832, 1216×1088 or 1024×1536. Composition
+and anatomy become less reliable as the area grows, and the
+[self-attention gain](#self-attention-gain) should move towards 0. Shapes far
+from the trained aspect ratios are also less reliable.
+
+## Sampling
+
+Sampling starts from noise and moves to the image in a number of solver steps.
+Time runs from \\(t = 1\\), pure noise, to \\(t = 0\\), the finished image. Three
+choices define a sampling run: the solver, the schedule of times it visits, and
+a shift applied to that schedule.
+
+### Solvers
+
+A solver is the numerical method that takes each step. Some are deterministic,
+and some are stochastic: they add fresh noise at each step. For a stochastic
+solver the noise scale multiplies that noise; deterministic solvers ignore it.
+
+| Name | Method | Stochastic | Noise scale |
+| --- | --- | --- | --- |
+| `er_sde` (default) | Extended reverse-time SDE, three-stage | yes | 1.0; 0 makes it deterministic |
+| `er_sde_bt` | The same with Brownian-tree noise, so runs with different step counts follow one noise path | yes | 1.0 |
+| `euler` | First-order ODE | no | ignored |
+| `euler_maruyama` | First-order reverse SDE | yes | 1.0 is the SDE's own noise level |
+| `dpmpp_2m` | DPM++ 2M, second-order multistep ODE | no | ignored |
+| `dpmpp_2m_sde` | DPM++ 2M SDE | yes | Acts as eta; use 0.5 |
+| `abm2` | Adams–Bashforth–Moulton predictor-corrector | no | ignored |
+
+`abm2` evaluates the model twice per step, so it takes about twice as long per
+step as the others.
+
+### Schedules
+
+The schedule sets where the solver's time points lie between noise and image,
+before the shift.
+
+| Name | Spacing |
+| --- | --- |
+| `beta_1_25` (default) | Quantiles of a Beta(1.25, 1.25) distribution: slightly denser in the middle |
+| `beta_0_6` | Quantiles of Beta(0.6, 0.6): denser at both ends |
+| `linear` | Evenly spaced |
+| `custom_beta` | Quantiles of a Beta distribution you specify by `beta_mean` in (0, 1) and `beta_concentration` above 0 |
+
+For `custom_beta` the two Beta parameters are `beta_mean × beta_concentration`
+and `(1 − beta_mean) × beta_concentration`. A mean above 0.5 puts more steps
+near the noisy end. A concentration of 2 at mean 0.5 is the linear schedule;
+higher values gather steps around the mean and lower values push them to the
+ends.
+
+### Steps
+
+The default is 50 steps, which the gallery uses. With the default guidance each
+step calls the denoiser twice, once in full and once with its middle layers
+skipped.
+
+### Resolution-dependent shift
+
+A larger image needs more noise to hide the same amount of structure. The model
+was trained with a timestep shift that grows with the image area, and the
+sampler applies the same shift by default.
+
+The shift \\(s\\) is expressed in log signal-to-noise ratio. For an image of
+width \\(W\\) and height \\(H\\) in pixels,
+
+$$
+s = \min\!\left(0,\; b - \ln\frac{W H}{256^2}\right), \qquad b = -0.25 .
+$$
+
+Each schedule time \\(t\\) strictly between 0 and 1 is then moved to
+
+$$
+t' = \sigma\!\left(\operatorname{logit}(t) - \tfrac{s}{2}\right),
+$$
+
+where \\(\sigma\\) is the logistic function. A negative shift moves the time
+points towards the noisy end.
+
+| Size | Area | Shift \\(s\\) |
+| --- | --- | --- |
+| 832×1216 | 1.01 MP | −2.99 |
+| 1024×1024 | 1.05 MP | −3.02 |
+| 1536×832 | 1.28 MP | −3.22 |
+| 1024×1536 | 1.57 MP | −3.43 |
+
+Two settings control the shift. `base_log_snr_shift` is \\(b\\), default −0.25.
+`resolution_shift` adds the size term and is on by default; with it off, the
+shift is \\(b\\) alone at every size. The defaults match how the model was
+trained.
+
+## Guidance
+
+Guidance sharpens an image and strengthens its adherence to the prompt by
+comparing two predictions at each step and pushing the result away from the
+weaker one.
+
+### Path-drop guidance
+
+dflow_2b was trained so that it can also run with its 18 middle layers skipped,
+which gives a cheaper and weaker prediction from the same weights. Path-drop
+guidance (PDG) uses that weak prediction as the reference and moves the result
+away from it, towards the full prediction, by a scale. The
+[technical report](TECHNICAL_REPORT.md#sprint-and-path-drop-guidance) explains
+why this works.
+
+With the full prediction \\(v_{\mathrm{full}}\\), the weak one
+\\(v_{\mathrm{weak}}\\) and the scale \\(w\\), the guided prediction is
+
+$$
+v = v_{\mathrm{weak}} + w\,(v_{\mathrm{full}} - v_{\mathrm{weak}}) .
+$$
+
+A scale of 1 is no guidance, and the weak pass is then skipped. The default is
+2.5.
+
+#### Suffix caption bias
+
+By default the weak pass reads the prompt less in its last six blocks: a bias
+of −4 is added to their attention on the prompt's tokens, on every step. This
+strengthens prompt following. Values closer to 0 weaken the effect and 0 turns
+it off; move towards −2 if colours or contrast look too strong. Below about −8
+there is almost no further change. It is `PdgGuidance(suffix_caption_bias=...)`
+in Python and `pdg_suffix_caption_bias` on the DFlow Guider node. The
+[technical report](TECHNICAL_REPORT.md#suffix-caption-bias) gives the details.
+
+### Classifier-free guidance
+
+Classifier-free guidance (CFG) is the familiar alternative. Its reference is
+the full model conditioned on the negative prompt, or on the learned null text
+when the negative prompt is empty. The formula is the same, with that reference
+as \\(v_{\mathrm{weak}}\\). CFG is off by default. It can be used alone or
+combined with PDG through the modes below. With the plain PDG modes, CFG and
+PDG cannot share steps: give them disjoint step windows, or use a mode that
+includes CFG.
+
+### Modes
+
+The PDG mode decides what the reference is at each step. "Negative text" means
+the negative prompt, or the learned null text when it is empty.
+
+| Mode | Reference |
+| --- | --- |
+| `full` (default) | Middle skipped, conditioned on the prompt (read with the suffix caption bias) |
+| `full_contrastive` | Middle skipped, conditioned on the negative text |
+| `three_quarter` | One image token of each 2×2 group goes through the middle; conditioned on the prompt. Width and height must be multiples of 32 |
+| `alternate_contrastive_positive` | `full_contrastive` on even steps, `full` on odd steps |
+| `alternate_pdg_first`, `alternate_cfg_first` | Contrastive PDG and CFG on alternate steps, starting with the one named |
+| `alternate_positive_pdg_first`, `alternate_positive_cfg_first` | The same with prompt-conditioned PDG |
+| `combined_cfg_pdg` | CFG and contrastive PDG on every step, their two corrections averaged |
+| `pdg_with_alternating_cfg` | Contrastive PDG on every step, with CFG averaged in on odd steps |
+| `cfg_to_pdg` | CFG before the PDG step window, prompt-conditioned PDG inside it |
+
+Steps are counted from 0. The modes that involve CFG need a CFG scale even when
+plain CFG is switched off.
+
+In the two averaging modes the scales are extra strengths added on top of the
+full prediction, so a PDG or CFG value of 0 there means no contribution from
+that side.
+
+### Scale curves
+
+The PDG scale can be constant or vary along the trajectory.
+
+| Curve | Behaviour | Parameters and defaults |
+| --- | --- | --- |
+| Constant (default) | One scale at every step | scale 2.5 |
+| Ramp | Starts at one scale at the noisy end, moves linearly to another over the first part of the schedule, then holds | start 4.5, end 2.5, length 0.3 |
+| Endpoint curve | Goes from a scale at the first step to a scale at the last, along a chosen shape | noisy scale 2.0, clean scale 2.5 |
+| Bezier | 1 plus a multiplier times a fixed fitted curve over time | multiplier 3.0 |
+
+The ramp's length is a fraction of the schedule: 0.3 with 50 steps means the
+scale reaches its end value at step 15.
+
+An endpoint curve has one of four shapes:
+
+| Shape | Interpolation between the two scales |
+| --- | --- |
+| `linear` | Linear in the step index |
+| `power` | (step / steps) raised to `power`, default 3: stays near the noisy scale for longer |
+| `s_curve` | A logistic curve with its midpoint at `s_curve_knee` (default 0.5) and slope `s_curve_sharpness` (default 8) |
+| `linear_logsnr` | Linear in the log signal-to-noise ratio of each step |
+
+The ramp cannot be combined with the `cfg_to_pdg` mode, which switches on the
+step window.
+
+### Step windows
+
+PDG and CFG each have a step window: a first and a last step, both inclusive,
+outside which that guidance is off. The default window covers every step. In
+ComfyUI a stop step of −1 means the last step.
+
+### Projected guidance (APG)
+
+High guidance scales raise contrast and saturation. Projected guidance reduces
+this by splitting the guidance correction into a part parallel to the full
+prediction of the clean image and a part orthogonal to it, and keeping only a
+fraction of the parallel part. That fraction is `parallel_weight`: 1 is plain
+guidance and 0 removes the parallel part.
+
+The projection has two forms. `global` projects each image as a whole.
+`per_band` splits the latent into five spatial frequency bands, from the mean
+colour (band 0) and the coarsest structure (band 1) up to the finest detail
+(band 4), and projects each band from `first_band` upwards, leaving the lower
+bands unprojected.
+
+Projected guidance needs PDG or CFG to be on. It cannot be combined with
+guidance rescale or with the two averaging modes.
+
+### Guidance rescale
+
+Guidance rescale is a simpler remedy for the same problem. It pulls the
+magnitude of the guided prediction back towards that of the full prediction. A
+value of 0 is off and 1 matches the magnitude fully.
+
+### Sparse middle steps
+
+This is a speed option. On the chosen steps the full pass sends only one image
+token of each 2×2 group through the middle layers, a configuration the model
+was trained on. `percent` is the share of steps that run this way, and the
+schedule is `prefix` for the first steps of the run or `cyclic` to spread them
+evenly. The default is 0, which is off. Width and height must be multiples of
+32.
+
+### Defaults
+
+| Setting | Default |
+| --- | --- |
+| PDG | on, mode `full`, constant scale 2.5, all steps, suffix caption bias −4 |
+| CFG | off |
+| Self-attention gain | −0.03 on the full pass, 0 on the guidance pass |
+| Projected guidance | off |
+| Guidance rescale | 0 |
+| Sparse middle steps | 0% |
+| Negative prompt | empty |
+
+### Recipes
+
+Each recipe changes one thing from the defaults. The Python snippets build a
+`GuidanceSettings` object, which goes into `GenerationSettings(guidance=...)`.
+They use these imports:
+
+```python
+from dflow.guidance import (
+ BezierPdgCurve,
+ CfgGuidance,
+ ConstantPdgScale,
+ EndpointCurveKind,
+ EndpointPdgCurve,
+ GuidanceSettings,
+ PdgGuidance,
+ PdgMode,
+ ProjectedGuidance,
+ ProjectionMode,
+ RampPdgScale,
+ SparseMiddleSteps,
+ SparseStepSchedule,
+ StepWindow,
+)
+```
+
+In ComfyUI, the mode, the constant scale, the step windows, CFG and the
+self-attention gain are on the **DFlow Guider** node. Curves, projected
+guidance, rescale and sparse steps are on **DFlow Guider Advanced**, which
+takes the guider as input.
+
+**A different PDG scale.** Lower values are softer, higher values add contrast.
+
+```python
+GuidanceSettings(pdg=PdgGuidance(scale=ConstantPdgScale(2.0)))
+```
+
+**Contrastive PDG with a negative prompt.** The negative prompt goes in
+`GenerationSettings(negative_prompt=...)`, or into a second DFlow Text Encode
+node connected to the guider's `negative` input. A lower scale suits this mode.
+
+```python
+GuidanceSettings(
+ pdg=PdgGuidance(mode=PdgMode.FULL_CONTRASTIVE, scale=ConstantPdgScale(1.75))
+)
+```
+
+**A ramp from 4.5 to 2.5 over the first 30% of the schedule.**
+
+```python
+GuidanceSettings(pdg=PdgGuidance(scale=RampPdgScale(4.5, 2.5, 0.3)))
+```
+
+**An endpoint curve**, here an S-curve from 2.0 to 3.0.
+
+```python
+GuidanceSettings(
+ pdg=PdgGuidance(
+ scale=EndpointPdgCurve(
+ kind=EndpointCurveKind.S_CURVE, noisy_scale=2.0, clean_scale=3.0
+ )
+ )
+)
+```
+
+**The Bezier curve.**
+
+```python
+GuidanceSettings(pdg=PdgGuidance(scale=BezierPdgCurve(multiplier=3.0)))
+```
+
+**PDG without the suffix caption bias.**
+
+```python
+GuidanceSettings(pdg=PdgGuidance(suffix_caption_bias=0.0))
+```
+
+**PDG on part of the run only**, here steps 0 to 39 of 50.
+
+```python
+GuidanceSettings(pdg=PdgGuidance(window=StepWindow(0, 39)))
+```
+
+**CFG alone.**
+
+```python
+GuidanceSettings(pdg=None, cfg=CfgGuidance(enabled=True, scale=4.0))
+```
+
+**CFG and PDG on alternate steps.** The CFG scale is set but plain CFG stays
+off; the mode runs the CFG steps itself.
+
+```python
+GuidanceSettings(
+ pdg=PdgGuidance(mode=PdgMode.ALTERNATE_POSITIVE_PDG_FIRST),
+ cfg=CfgGuidance(enabled=False, scale=4.0),
+)
+```
+
+**Projected guidance**, per band from the third band up with the parallel part
+removed, at a slightly higher scale.
+
+```python
+GuidanceSettings(
+ pdg=PdgGuidance(scale=ConstantPdgScale(3.0)),
+ projection=ProjectedGuidance(
+ mode=ProjectionMode.PER_BAND, parallel_weight=0.0, first_band=2
+ ),
+)
+```
+
+**Guidance rescale.**
+
+```python
+GuidanceSettings(rescale=0.5)
+```
+
+**Sparse middle on half of the steps**, spread evenly.
+
+```python
+GuidanceSettings(
+ sparse_middle=SparseMiddleSteps(percent=50.0, schedule=SparseStepSchedule.CYCLIC)
+)
+```
+
+## Self-attention gain
+
+The self-attention gain is a small correction to the full pass that reduces the
+excess contrast guidance produces. It is part of the default preset, and its
+best value depends on the image size.
+
+### What it does
+
+In every image layer of the denoiser, the gain \\(g\\) multiplies the attention
+queries by \\(e^{g}\\). A negative gain makes attention slightly more diffuse and
+a positive one makes it sharper. The main pass uses the gain you set and the
+guidance pass uses 0.
+
+The guidance formula amplifies any difference between the two passes by the
+guidance scale, so a 3% softening of attention in the main pass becomes a
+visible reduction in contrast and in structural errors. The
+[technical report](TECHNICAL_REPORT.md#self-attention-gain) gives the
+derivation.
+
+### Choosing a value
+
+The default, −0.03, was set at the trained sizes of about one megapixel. For
+larger images, move the gain closer to 0 as the area grows.
+
+| Image area | Example sizes | Gain |
+| --- | --- | --- |
+| up to about 1.05 MP | 832×1216, 1216×832, 1024×1024 | −0.03 (default) |
+| about 1.3 MP | 1536×832, 1216×1088 | −0.02 |
+| about 1.6 MP | 1024×1536 | −0.015 |
+| about 2.5 MP and above | 1280×1920 | 0 to −0.01 |
+
+These values are roughly linear in the logarithm of the area, from −0.03 at
+1 MP to 0 at about 2.5 MP, so sizes in between can be interpolated.
+
+At about one megapixel, a gain closer to 0 gives oversaturation and more
+structural defects. At larger sizes, too negative a gain gives washed-out
+images.
+
+In Python the gain is `GuidanceSettings(self_attention_gain=...)`. In ComfyUI
+it is `self_attention_gain` on the DFlow Guider node. The gain of the guidance
+pass can also be set, as `guidance_self_attention_gain`, and should stay at 0.
+
+## Python API reference
+
+All classes below are frozen dataclasses unless noted. Their defaults are the
+default preset, so `GenerationSettings()` reproduces it.
+
+### DFlowPipeline
+
+`dflow.pipeline.DFlowPipeline` loads the model and turns prompts into images.
+
+```python
+DFlowPipeline.from_pretrained(
+ path_or_repository="data-archetype/dflow_2b",
+ *,
+ device="cuda",
+ compile=True,
+ revision=None,
+ cache_dir=None,
+ vae_dir=None,
+)
+```
+
+| Argument | Meaning |
+| --- | --- |
+| `path_or_repository` | A local release folder, or a Hub repository id to download |
+| `device` | A CUDA device |
+| `compile` | Compile with `torch.compile`; `False` runs eagerly |
+| `revision` | Hub revision, for a repository id |
+| `cache_dir` | Hugging Face cache directory; `None` for the default |
+| `vae_dir` | A local copy of `data-archetype/dinac3_96`, for offline use; `None` downloads the pinned commit |
+
+Calling the pipeline generates images:
+
+```python
+pipe(
+ prompt,
+ settings=None,
+ *,
+ num_images=1,
+ output_type=OutputType.PIL,
+ image_to_image=None,
+ callback=None,
+)
+```
+
+| Argument | Meaning |
+| --- | --- |
+| `prompt` | One prompt, or a list of prompts that all have the same number of tokens |
+| `settings` | A `GenerationSettings`; `None` uses `pipe.default_settings` |
+| `num_images` | Images to make from a single prompt string |
+| `output_type` | What to return; see `OutputType` |
+| `image_to_image` | An `ImageToImage`, to start from existing latents |
+| `callback` | A latent callback, called after each solver step |
+
+A prompt may be a plain caption, a stored layout or a compiled layout; a
+compiled layout must have been compiled for the requested size. The images of
+one call share the seed and differ because each gets its own noise.
+
+The result is a `DFlowOutput` with three fields: `images`, a list of PIL images
+for PIL output; `tensors`, the RGB or latent tensor for the other output types;
+and `settings`, the settings used.
+
+### DFlowComponents
+
+`dflow.pipeline.DFlowComponents` holds the loaded parts and is available as
+`pipe.components`. `DFlowComponents.from_pretrained` takes the same arguments
+as the pipeline's.
+
+| Field | Meaning |
+| --- | --- |
+| `engine` | The denoiser and text encoder. `engine.sample(prompts, settings, image_to_image=None, callback=None)` returns latents |
+| `vae` | The autoencoder. `vae.decode(latents)` returns RGB in about [−1, 1]; `vae.encode(images)` takes RGB in [−1, 1] with sides that are multiples of 16 |
+| `compiled` | Whether the model was compiled |
+
+Latents are float32 tensors of shape `[B, 96, height / 16, width / 16]`.
+
+### GenerationSettings
+
+`dflow.inference.GenerationSettings` holds everything except the prompt that
+defines one generation.
+
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `width` | 832 | Image width, a multiple of 16 |
+| `height` | 1216 | Image height, a multiple of 16 |
+| `seed` | 0 | Seed of every random draw, from 0 to 2⁶³ − 1 |
+| `sampling` | `SamplingSettings()` | Solver, schedule and shift |
+| `guidance` | `GuidanceSettings()` | Guidance and gains |
+| `emphasis` | `EmphasisSettings()` | Prompt emphasis; `None` reads prompts verbatim |
+| `negative_prompt` | `""` | Read only by CFG and the contrastive PDG modes; empty selects the learned null text |
+
+The starting noise is drawn on the CPU from the seed, so a seed gives the same
+noise on every GPU.
+
+### SamplingSettings
+
+`dflow.inference.SamplingSettings`:
+
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `solver` | `Solver.ER_SDE` | A member of `dflow.solvers.Solver` |
+| `noise_scale` | 1.0 | Noise multiplier of stochastic solvers |
+| `schedule` | `TimeSchedule()` | Spacing and step count |
+| `base_log_snr_shift` | −0.25 | The size-independent part of the shift |
+| `resolution_shift` | `True` | Add the image-size term |
+
+`dflow.schedules.TimeSchedule` has `kind` (a `ScheduleKind`, default
+`BETA_1_25`), `steps` (default 50), and `beta_mean` and `beta_concentration`
+for `CUSTOM_BETA` (defaults 0.5 and 0.6).
+
+```python
+from dflow.inference import GenerationSettings, SamplingSettings
+from dflow.schedules import ScheduleKind, TimeSchedule
+from dflow.solvers import Solver
+
+settings = GenerationSettings(
+ width=1024,
+ height=1024,
+ seed=3,
+ sampling=SamplingSettings(
+ solver=Solver.DPMPP_2M,
+ schedule=TimeSchedule(kind=ScheduleKind.LINEAR, steps=40),
+ ),
+)
+```
+
+### GuidanceSettings and its parts
+
+`dflow.guidance.GuidanceSettings`:
+
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `pdg` | `PdgGuidance()` | Path-drop guidance; `None` turns it off |
+| `cfg` | `CfgGuidance()` | Classifier-free guidance |
+| `self_attention_gain` | −0.03 | Gain of the main pass, from −0.5 to 0.1 |
+| `guidance_self_attention_gain` | 0.0 | Gain of the guidance passes |
+| `projection` | `ProjectedGuidance()` | Projected guidance (APG) |
+| `rescale` | 0.0 | Guidance rescale, from 0 to 1 |
+| `sparse_middle` | `SparseMiddleSteps()` | Sparse middle steps |
+
+The parts, all in `dflow.guidance`:
+
+| Class | Fields and defaults |
+| --- | --- |
+| `PdgGuidance` | `mode=PdgMode.FULL`, `scale=ConstantPdgScale()`, `window=StepWindow()`, `suffix_caption_bias=-4.0` (from −10 to 0; 0 is off) |
+| `CfgGuidance` | `enabled=False`, `scale=None`, `window=StepWindow()` |
+| `StepWindow` | `start_step=0`, `stop_step=None` (the last step); both inclusive |
+| `ConstantPdgScale` | `scale=2.5` |
+| `RampPdgScale` | `start_scale=4.5`, `end_scale=2.5`, `length=0.3` |
+| `EndpointPdgCurve` | `kind=EndpointCurveKind.POWER`, `noisy_scale=2.0`, `clean_scale=2.5`, `power=3.0`, `s_curve_knee=0.5`, `s_curve_sharpness=8.0` |
+| `BezierPdgCurve` | `multiplier=3.0`, plus the control points of the curve |
+| `ProjectedGuidance` | `mode=ProjectionMode.OFF`, `parallel_weight=1.0`, `first_band=0` |
+| `SparseMiddleSteps` | `percent=0.0`, `schedule=SparseStepSchedule.PREFIX` |
+
+`CfgGuidance.scale` must be set when CFG is enabled or when the PDG mode uses
+CFG, and must be left as `None` otherwise. Inconsistent settings raise a
+`ValueError` when the object is built, before any sampling.
+
+### EmphasisSettings
+
+`dflow.prompt_emphasis.EmphasisSettings` has `mapping`
+(`EmphasisMapping.LINEAR` or `LOG`, default `LINEAR`), `strength` (default 1.0)
+and `encoder` (default `True`). See [Prompt emphasis](#prompt-emphasis).
+
+### ImageToImage
+
+`dflow.inference.ImageToImage` starts sampling from existing latents, noised to
+the time of a later schedule step.
+
+| Field | Meaning |
+| --- | --- |
+| `latents` | `[B or 1, 96, h, w]` latents of the generation size, for example from `pipe.components.vae.encode` |
+| `start_step` | The step of the schedule at which sampling starts, from 0 to `steps − 1` |
+
+The schedule is built at its full step count. The latents are noised to the
+time of `start_step` with the seed's noise, and the remaining steps run. A
+later start step keeps more of the input image. Guidance step windows count
+from the start step.
+
+### OutputType
+
+`dflow.pipeline.OutputType`:
+
+| Member | Result |
+| --- | --- |
+| `PIL` | `images`: PIL images that carry their generation metadata |
+| `TENSOR` | `tensors`: `[B, 3, H, W]` float32 RGB in [−1, 1] |
+| `LATENT` | `tensors`: undecoded `[B, 96, H/16, W/16]` latents |
+
+### Previews during sampling
+
+A latent callback has the signature `callback(latents, completed, total)`. It
+is called after each solver step with the model's current estimate of the
+finished latents and the step counts.
+
+`dflow.preview.LatentRgbPreview` is a fitted projection from those latents to a
+small RGB image, at one eighth of the image resolution.
+
+```python
+from dflow.preview import LatentRgbPreview, preview_images
+
+preview = LatentRgbPreview.bundled().to(pipe.components.engine.device)
+
+
+def show(latents, completed, total):
+ image = preview_images(preview.project(latents))[0]
+ image.save(f"preview_{completed:03d}.png")
+
+
+image = pipe("A lighthouse on a cliff at dusk.", callback=show).images[0]
+```
+
+### PNG metadata
+
+Each PIL image returned by the pipeline carries a JSON description of how it
+was made in `image.info["dflow"]`: the model and package versions, the prompt,
+the index of the image in its batch and the complete settings.
+
+To keep it in the saved file, pass it to `save`:
+
+```python
+image.save("out.png", pnginfo=pipe.png_info(image))
+```
+
+The text is stored in a PNG text chunk named `dflow`.
+
+### Diffusers wrapper
+
+`dflow.diffusers_pipeline.DFlowDiffusersPipeline` offers the call signature of
+a diffusers pipeline. It requires `diffusers` to be installed and wraps a
+`DFlowPipeline`; the model, sampler and guidance are the same.
+
+```python
+from dflow.diffusers_pipeline import DFlowDiffusersPipeline
+
+pipe = DFlowDiffusersPipeline.from_pretrained("dflow_2b")
+image = pipe(
+ "A lighthouse on a cliff at dusk.",
+ height=1216,
+ width=832,
+ num_inference_steps=50,
+ guidance_scale=2.5,
+ generator_seed=7,
+).images[0]
+```
+
+| Argument | Default | Meaning |
+| --- | --- | --- |
+| `prompt` | | The prompt |
+| `negative_prompt` | `""` | Accepted only with `settings`, whose guidance must read it (CFG or contrastive PDG); set it in those settings |
+| `height`, `width` | 1216, 832 | Image size |
+| `num_inference_steps` | 50 | Solver steps |
+| `guidance_scale` | 2.5 | The PDG scale |
+| `num_images_per_prompt` | 1 | Images to generate |
+| `generator_seed` | 0 | The seed |
+| `settings` | `None` | A full `GenerationSettings`; when given it replaces every argument except the prompt and the image count |
+
+`guidance_scale` here is the PDG scale, so values suited to CFG in other models
+are too high. The wrapper is loaded with its own `from_pretrained`, as above.
+It does not support `save_pretrained` or loading through
+`DiffusionPipeline.from_pretrained`.
+
+## ComfyUI node reference
+
+The nodes are in the **DFlow** category. Their defaults are the default preset.
+
+### DFlow Loader
+
+Loads the denoiser, the text encoder and the autoencoder. Outputs: `model`,
+`text_encoder`, `vae`. The `vae` output works with ComfyUI's VAEDecode and
+VAEEncode nodes.
+
+| Input | Default | Meaning |
+| --- | --- | --- |
+| `source` | `bundled` | `bundled` reads the weights in the node folder; `local_dir` another folder; `hub` a Hugging Face repository |
+| `local_dir` | empty | Release folder, for the `local_dir` source |
+| `repository` | `data-archetype/dflow_2b` | Repository id, for the `hub` source |
+| `revision` | empty | Hub revision; empty for `main` |
+| `compile_model` | on | Compile the model with `torch.compile` |
+| `cache_dir` | empty | Hugging Face cache directory; empty for the default |
+
+### DFlow Text Encode
+
+Encodes a plain prompt. Output: `conditioning`.
+
+| Input | Default | Meaning |
+| --- | --- | --- |
+| `text_encoder` | | From the loader |
+| `text` | empty | The prompt |
+| `batch_size` | 1 | Copies of the prompt; must equal the latent's batch size |
+| `emphasis` | on | Apply `(phrase:weight)` markup |
+| `emphasis_mapping` | `linear` | `linear` or `log` |
+| `emphasis_strength` | 1.0 | Multiplier on every weight's effect |
+| `emphasis_encoder` | on | Also apply the weights inside the text encoder |
+
+For a negative prompt, add a second DFlow Text Encode node and connect it to
+the guider's `negative` input. Stored layouts go to DFlow Layout Encode, which
+takes the image size they are compiled for.
+
+### DFlow Layout Encode
+
+Compiles a stored layout at the image size and encodes it. Output:
+`conditioning`.
+
+| Input | Default | Meaning |
+| --- | --- | --- |
+| `text_encoder` | | From the loader |
+| `layout_json` | empty | The stored layout, or an already compiled one |
+| `width` | 832 | Image width the layout is for |
+| `height` | 1216 | Image height the layout is for |
+| `batch_size` | 1 | Copies of the prompt |
+
+`width` and `height` must equal the size of the latent that is sampled.
+
+### DFlow Guider
+
+Sets path-drop guidance, its suffix caption bias, CFG and the self-attention
+gain. Output: `guider`.
+
+| Input | Default | Meaning |
+| --- | --- | --- |
+| `model` | | From the loader |
+| `positive` | | The prompt's conditioning |
+| `negative` | not connected | Optional conditioning for CFG and the contrastive PDG modes |
+| `pdg_enabled` | on | Path-drop guidance |
+| `pdg_mode` | `full` | The [mode](#modes) |
+| `pdg_scale` | 2.5 | Constant PDG scale; 1 is none |
+| `pdg_start_step` | 0 | First PDG step |
+| `pdg_stop_step` | −1 | Last PDG step; −1 for the last step |
+| `pdg_suffix_caption_bias` | −4 | [Suffix caption bias](#suffix-caption-bias) of the reference; 0 is off |
+| `cfg_enabled` | off | Classifier-free guidance |
+| `cfg_scale` | 4.0 | CFG scale, also used by the PDG modes that involve CFG |
+| `cfg_start_step` | 0 | First CFG step |
+| `cfg_stop_step` | −1 | Last CFG step; −1 for the last step |
+| `self_attention_gain` | −0.03 | [Gain](#self-attention-gain) of the main pass |
+
+### DFlow Guider Advanced
+
+Takes a guider from DFlow Guider and returns it with further settings. It is
+optional. Output: `guider`.
+
+| Input | Default | Meaning |
+| --- | --- | --- |
+| `guider` | | From DFlow Guider |
+| `guidance_self_attention_gain` | 0.0 | Gain of the guidance passes |
+| `pdg_curve` | `constant` | `constant`, `ramp`, `linear`, `linear_logsnr`, `power`, `s_curve` or `bezier` |
+| `curve_noisy_scale` | 2.0 | Endpoint curves: scale at the first step |
+| `curve_clean_scale` | 2.5 | Endpoint curves: scale at the last step |
+| `curve_power` | 3.0 | Exponent of the `power` curve |
+| `s_curve_knee` | 0.5 | Midpoint of the `s_curve` |
+| `s_curve_sharpness` | 8.0 | Slope of the `s_curve` |
+| `ramp_start_scale` | 4.5 | Ramp: scale at the noisy end |
+| `ramp_end_scale` | 2.5 | Ramp: scale after the ramp |
+| `ramp_length` | 0.3 | Ramp: fraction of the schedule |
+| `bezier_multiplier` | 3.0 | Height of the Bezier curve |
+| `projection` | `off` | Projected guidance: `off`, `global` or `per_band` |
+| `projection_parallel_weight` | 1.0 | Weight kept on the parallel part |
+| `projection_first_band` | 0 | `per_band`: first projected band, 0 to 4 |
+| `rescale` | 0.0 | Guidance rescale; 0 is off |
+| `sparse_middle_percent` | 0.0 | Percent of steps with a sparse middle |
+| `sparse_middle_schedule` | `prefix` | `prefix` or `cyclic` |
+
+With `pdg_curve` at `constant` the scale is the `pdg_scale` of the DFlow Guider
+node. The other choices replace it and read only their own inputs.
+
+### DFlow Sampler
+
+Chooses the solver. Output: `sampler`, which goes to DFlow Time Schedule.
+
+| Input | Default | Meaning |
+| --- | --- | --- |
+| `solver` | `er_sde` | One of the [solvers](#solvers) |
+| `noise_scale` | 1.0 | Noise multiplier of stochastic solvers; eta for `dpmpp_2m_sde` |
+
+Changing the solver in the ComfyUI interface sets `noise_scale` to that
+solver's recommended value.
+
+### DFlow Time Schedule
+
+Builds the schedule for the size of the latent. Outputs: `sigmas` and
+`sampler`.
+
+| Input | Default | Meaning |
+| --- | --- | --- |
+| `sampler` | | From DFlow Sampler |
+| `latent` | | The latent that will be sampled; gives the image size |
+| `schedule` | `beta_1_25` | One of the [schedules](#schedules) |
+| `steps` | 50 | Solver steps |
+| `base_log_snr_shift` | −0.25 | The size-independent part of the shift |
+| `resolution_shift` | on | Add the image-size term |
+| `beta_mean` | 0.5 | `custom_beta` only |
+| `beta_concentration` | 0.6 | `custom_beta` only |
+
+Connect both outputs to SamplerCustomAdvanced. The `sampler` output carries the
+schedule the sigmas were built from: its kind, its shift and the image size.
+Guidance computes the ramp and the `linear_logsnr` curve from them and checks
+the size against the latent. With a sampler taken straight from DFlow Sampler,
+sampling stops with an error message.
+
+### DFlow Empty Latent
+
+Creates an empty 96-channel latent. Output: `latent`. ComfyUI's stock empty
+latent nodes produce a different latent format and cannot be used.
+
+| Input | Default | Meaning |
+| --- | --- | --- |
+| `width` | 832 | Image width, a multiple of 16 |
+| `height` | 1216 | Image height, a multiple of 16 |
+| `batch_size` | 1 | Images per run |
+
+### Stock nodes
+
+Seeds come from ComfyUI's RandomNoise node. A seed gives the same starting
+noise in ComfyUI as in the Python package.
+
+SamplerCustomAdvanced takes the noise, the guider, the sampler and sigmas from
+DFlow Time Schedule, and the latent. VAEDecode with the loader's `vae` output
+turns the result into an image, and SaveImage stores it with the workflow
+embedded.
+
+## Troubleshooting
+
+**"The dflow_2b weights are not in the node folder", or a file "is a Git LFS
+pointer".** This happens after a `git clone` without the large files. Download
+them into the folder with the command the message prints,
+`hf download data-archetype/dflow_2b --local-dir `, or set the loader's
+`source` to `hub`.
+
+**The first image takes much longer than the following ones.** The model is
+being compiled. This happens once per session.
+
+**Errors during compilation.** `torch.compile` needs a working compiler
+toolchain and a matching PyTorch build. To check whether compilation is the
+cause, run eagerly: `compile=False` in Python, or `compile_model` off in DFlow
+Loader. Eager mode runs the same model at lower speed.
+
+**Out of memory.** An 832×1216 image needs about 7 GB of VRAM at peak, and
+memory grows with the image area and the batch size. Generate one image at a
+time, reduce the size, and close other programs that hold GPU memory. In
+ComfyUI, other loaded models count against the same memory.
+
+**"The prompt has N tokens; the model takes at most 6144."** Shorten the
+prompt. Text in double quotes and `text` fields of a layout use one token per
+character, so long quoted passages add up quickly.
+
+**"Prompts of one batch must have the same token count."** A list of different
+prompts in one Python call must have equal token counts. Run prompts of
+different lengths as separate calls, or use `num_images` to repeat one prompt.
+
+**"This layout prompt was compiled for … the image is …"** A compiled layout is
+being used at a different size. Compile the stored layout again at the image
+size: in ComfyUI, set `width` and `height` on DFlow Layout Encode to the
+latent's size.
+
+**"The schedule was built for … but the latent is …"** The DFlow Time Schedule
+node is connected to a different latent from the one being sampled. Connect the
+same latent to both.
+
+**"Connect the sampler output of DFlow Time Schedule …"** SamplerCustomAdvanced
+is receiving the sampler from DFlow Sampler directly. See
+[DFlow Time Schedule](#dflow-time-schedule).
+
+**"The latent batch is … but the conditioning holds … prompts."** Set the same
+`batch_size` on the text encode node and on DFlow Empty Latent.
+
+**Large images look dark or burnt, or lose coherence.** Adjust the
+[self-attention gain](#self-attention-gain) for the image area.
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..8159eff0dc0a93cf16a2564d1ea12f84139bd0d1
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,55 @@
+dflow_2b
+Copyright 2026 Data Archetype
+
+Different parts of this repository are under different licences.
+
+1. Model weights, dflow/ package, documentation and gallery images
+
+ The dflow_2b model weights (model.safetensors, config.json, release.json),
+ the dflow/ Python package, the documentation and the images under assets/
+ are licensed under the ModelGo Attribution-NonCommercial License 2.0
+ (MG-BY-NC-2.0). See LICENSE.
+
+ Required attribution notice:
+
+ This project uses dflow_2b by Data Archetype.
+ https://huggingface.co/data-archetype/dflow_2b
+
+ Distributions of dflow_2b or of Derivative Materials must retain this
+ notice and include a copy of LICENSE.
+
+2. ComfyUI nodes
+
+ The files in comfyui/ and the root __init__.py are licensed under the GNU
+ General Public License, version 3 (GPL-3.0). See comfyui/LICENSE and
+ comfyui/NOTICE.
+
+3. Text encoder
+
+ The files in text_encoder/ are a modified copy of part of Google's
+ T5Gemma 2 model google/t5gemma-2-270m-270m. They are not relicensed under
+ MG-BY-NC-2.0.
+
+ Gemma is provided under and subject to the Gemma Terms of Use found at
+ gemma.ai/resources/terms
+
+ The same terms were previously published at ai.google.dev/gemma/terms,
+ which now redirects to the address above. Earlier versions of the terms
+ worded this notice as: "Gemma is provided under and subject to the Gemma
+ Terms of Use found at ai.google.dev/gemma/terms".
+
+ A copy of the Gemma Terms of Use is in text_encoder/LICENSE-GEMMA.md. Use
+ of these files is subject to the use restrictions in Section 3.2 of those
+ terms, including the Gemma Prohibited Use Policy at
+ gemma.ai/resources/prohibited_use_policy.
+
+ Modification notice: Data Archetype modified the original files in
+ November 2026. The folder keeps the tokenizer, the token embeddings and
+ encoder layers 1 to 12, removes the remaining encoder layers and the
+ decoder, and stores the weights in bfloat16. See ATTRIBUTION.md.
+
+4. Autoencoder
+
+ data-archetype/dinac3_96 is a separate repository that is downloaded at
+ run time and is not part of this one. Its own repository is the authority
+ for its licence and notices.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..88f7ffa6c7f6729c0fa375085979b204a3be8afe
--- /dev/null
+++ b/README.md
@@ -0,0 +1,174 @@
+---
+license: other
+license_name: mg-by-nc-2.0
+license_link: https://ids.nus.edu.sg/docs/modelgo/v2/MG-BY-NC/LICENSE
+library_name: dflow
+pipeline_tag: text-to-image
+tags:
+ - text-to-image
+ - flow-matching
+ - pytorch
+ - comfyui
+ - photography
+base_model:
+ - google/t5gemma-2-270m-270m
+---
+
+# dflow_2b
+
+> [!WARNING]
+> **Preview, version 0.2.** The model is still training, so checkpoints and
+> behaviour will change between releases. Generations are still uneven, expect
+> some seed hunting.
+
+dflow_2b is an indie text-to-image model, trained from scratch on a single GPU,
+mostly on photographs and classical art.
+
+It takes ordinary captions, and also JSON layout captions (the same format as
+[MOSS-Image](https://github.com/OpenMOSS/MOSS-Image)).
+
+The package contains the weights, the `dflow` inference code and ComfyUI nodes.
+
+[Example gallery](GALLERY.md) · [Manual](MANUAL.md) ·
+[Technical report](TECHNICAL_REPORT.md) · [Release notes](RELEASES.md)
+
+
+
+  |
+  |
+  |
+  |
+
+
+  |
+  |
+  |
+  |
+
+
+
+## What's included
+
+- `model.safetensors`: the 2B denoiser.
+- `text_encoder/`: the part of
+ [T5Gemma 2 270M](https://huggingface.co/google/t5gemma-2-270m-270m) the model
+ uses, under the Gemma Terms of Use.
+- `dflow/`: the Python inference package.
+- `comfyui/`: ComfyUI nodes and example workflows.
+
+The autoencoder, [dinac3_96](https://huggingface.co/data-archetype/dinac3_96),
+is our own and downloads automatically on first use. The
+[technical report](TECHNICAL_REPORT.md) covers the architecture and training.
+
+## Requirements
+
+Python 3.12 or later, PyTorch 2.13 with CUDA, and an NVIDIA GPU with bfloat16
+support and about 7 GB of free VRAM.
+
+Generation is compiled with `torch.compile`. The first image takes an extra 30
+to 45 seconds while it compiles; after that, an 832×1216 image takes about 10
+seconds on an RTX 4090.
+
+## ComfyUI
+
+The repository is a ComfyUI custom-node folder. Download it into
+`custom_nodes` and install its requirements:
+
+```bash
+cd ComfyUI/custom_nodes
+hf download data-archetype/dflow_2b --local-dir dflow_2b
+pip install -r dflow_2b/requirements.txt
+```
+
+Load `dflow_2b/comfyui/workflows/dflow_default.json`, or drag any image from the
+[gallery](GALLERY.md) onto the canvas to get the workflow that made it. Start
+ComfyUI with `--preview-method auto` for live previews.
+
+## Python
+
+```bash
+hf download data-archetype/dflow_2b --local-dir dflow_2b
+pip install -e dflow_2b
+```
+
+```python
+from dflow.inference import GenerationSettings
+from dflow.pipeline import DFlowPipeline
+
+pipe = DFlowPipeline.from_pretrained("dflow_2b")
+image = pipe("A lighthouse on a cliff at dusk.", GenerationSettings(seed=7)).images[0]
+image.save("lighthouse.png", pnginfo=pipe.png_info(image))
+```
+
+`from_pretrained` also takes the Hub id `data-archetype/dflow_2b`, in which case
+the files go to the Hugging Face cache. If you have diffusers installed, a thin
+diffusers-style wrapper is available as
+`dflow.diffusers_pipeline.DFlowDiffusersPipeline`.
+
+## Prompts
+
+Write captions the way you would describe a photo or a painting: the subject,
+the setting, the light and the medium. Long prompts are fine, up to 6,144
+tokens.
+
+Put text you want in the image in double quotes, as in
+`A shop sign that reads "OPEN LATE"`. The model reads quoted text letter by
+letter, which helps with spelling.
+
+A layout describes the picture as a whole and then lists its elements, each
+with a label, a caption and a box `[y0, x0, y1, x1]` on a 0–1000 scale. Text
+elements carry the exact string to render:
+
+```json
+{"summary": {"canvas": "single",
+ "caption": "A travel poster of a mountain above a lake."},
+ "frame": {"caption": "The peak sits in the upper middle.",
+ "palette": ["#F3E6C8", "#2F5D62"]},
+ "items": [
+ {"label": "object", "caption": "A snow-capped mountain.",
+ "box_2d": [250, 180, 620, 820]},
+ {"label": "text", "caption": "The title in tall serif capitals.",
+ "text": "SILVER LAKE", "box_2d": [120, 110, 220, 890]}]}
+```
+
+Use it as the prompt in Python, or paste it into the DFlow Layout Encode node.
+The [manual](MANUAL.md#json-layouts) covers every field and works through a
+full poster.
+
+## Limitations
+
+- It is a preview, and quality varies from prompt to prompt and seed to seed.
+- Hands and anatomy often go wrong.
+- Small text and long passages of text are hit and miss.
+- Above about one megapixel results get less reliable. For large images, move
+ the [self-attention gain](MANUAL.md#self-attention-gain) towards 0.
+- Styles far from photography and classical art are weaker.
+
+You are responsible for how you use the model and its outputs.
+
+## Licence
+
+- The weights, the `dflow` package, the documentation and the gallery images:
+ ModelGo Attribution-NonCommercial 2.0 (`MG-BY-NC-2.0`). See
+ [`LICENSE`](LICENSE) and [`NOTICE`](NOTICE).
+- `comfyui/` and the root `__init__.py`: GPL-3.0. See
+ [`comfyui/LICENSE`](comfyui/LICENSE).
+- `text_encoder/`: Gemma is provided under and subject to the Gemma Terms of Use
+ found at [gemma.ai/resources/terms](https://gemma.ai/resources/terms). A copy
+ is in [`text_encoder/LICENSE-GEMMA.md`](text_encoder/LICENSE-GEMMA.md).
+- dinac3_96 has its own licence, in
+ [its repository](https://huggingface.co/data-archetype/dinac3_96).
+
+Third-party material is listed in [`ATTRIBUTION.md`](ATTRIBUTION.md).
+
+## Citation
+
+```bibtex
+@misc{dflow_2b,
+ title = {dflow\_2b},
+ author = {{Data Archetype}},
+ year = {2026},
+ url = {https://huggingface.co/data-archetype/dflow_2b},
+ note = {Preview release, version 0.2}
+}
+```
diff --git a/RELEASES.md b/RELEASES.md
new file mode 100644
index 0000000000000000000000000000000000000000..8ba8481144cf0495da629fa848ccf4ddeac34d88
--- /dev/null
+++ b/RELEASES.md
@@ -0,0 +1,23 @@
+# dflow_2b releases
+
+[Model card](README.md) · [Manual](MANUAL.md) ·
+[Technical report](TECHNICAL_REPORT.md) · [Example gallery](GALLERY.md)
+
+## 0.2
+
+Preview release. The model is still training, and later checkpoints will behave
+differently. The weights are the exponential moving average (EMA) of the model
+at training step 581,000.
+
+Included:
+
+- the denoiser weights;
+- the part of the T5Gemma 2 270M-270M encoder the model uses;
+- the `dflow` inference package, version 0.2.0, with an optional diffusers
+ wrapper;
+- ComfyUI nodes with a default workflow and a layout poster workflow;
+- the manual, the technical report and the example gallery, whose PNG files
+ carry their ComfyUI workflows.
+
+The autoencoder, [dinac3_96](https://huggingface.co/data-archetype/dinac3_96),
+downloads on first use, at a pinned commit.
diff --git a/TECHNICAL_REPORT.md b/TECHNICAL_REPORT.md
new file mode 100644
index 0000000000000000000000000000000000000000..1fafc68bf9eef57fb77a2f4d95afe20729b9cf7a
--- /dev/null
+++ b/TECHNICAL_REPORT.md
@@ -0,0 +1,699 @@
+# dflow_2b Technical Report
+
+[Model card](README.md) · [Manual](MANUAL.md) · [Example gallery](GALLERY.md) ·
+[Release notes](RELEASES.md)
+
+## Overview
+
+dflow_2b is an indie text-to-image model, trained from scratch on a single GPU,
+mostly on photographs and classical art. Its denoiser has 2.1 billion
+parameters. It reads natural-language prompts and structured JSON layout
+prompts.
+
+A generation has three stages:
+
+```text
+prompt
+ -> T5Gemma 2 encoder (12 layers, three hidden-state taps)
+ -> projection to width 2304, learned suffix tokens
+ -> denoiser: 2 text-refiner blocks, then 30 joint text-image blocks
+ -> 96-channel latent at 1/16 resolution
+ -> dinac3_96 decoder
+ -> RGB image
+```
+
+Text and image tokens share one stream of joint attention. The middle of the
+network is trained mostly on all tokens, a variant of SPRINT described under
+[Dense SPRINT](#dense-sprint).
+
+## Flow matching
+
+Let \\(x_0\\) be a clean image latent and \\(\varepsilon \sim \mathcal{N}(0, I)\\)
+Gaussian noise. The model is trained on the linear path
+
+$$
+x_t = (1-t)\,x_0 + t\,\varepsilon, \qquad t \in [0,1],
+$$
+
+so \\(t=0\\) is data and \\(t=1\\) is pure noise. The velocity along this path is
+constant,
+
+$$
+\frac{\mathrm{d}x_t}{\mathrm{d}t} = \varepsilon - x_0,
+$$
+
+and the network \\(v_\theta\\) predicts it directly. Given a prediction
+\\(v\\) at \\((x_t, t)\\), the clean estimate is \\(\hat{x}_0 = x_t - t\,v\\), and an
+Euler step towards data is \\(x_{t-h} = x_t - h\,v\\).
+
+Noise levels are compared through the log signal-to-noise ratio
+\\(\lambda(t) = 2\ln\frac{1-t}{t}\\). Adding a shift \\(s\\) to \\(\lambda\\) moves a
+time \\(t\\) to
+
+$$
+t' = \sigma\!\left(\operatorname{logit}(t) - \tfrac{s}{2}\right),
+$$
+
+where \\(\sigma\\) is the logistic function. A negative shift moves times towards
+the noisy end. Larger images need more noise to hide the same structure, so both
+training and sampling use a shift that depends on the image size:
+
+$$
+s(A) = \min\!\left(0,\; -0.25 - \ln\frac{A}{256^2}\right),
+$$
+
+where \\(A\\) is the number of pixels in the image. For an 832×1216 image
+this gives \\(s = -2.99\\).
+
+| Symbol | Meaning |
+| --- | --- |
+| \\(x_0\\) | Clean dinac3_96 latent of an image |
+| \\(\varepsilon\\) | Standard Gaussian noise with the shape of \\(x_0\\) |
+| \\(t\\) | Flow time; 0 is data, 1 is noise |
+| \\(x_t\\) | Noised latent on the linear path |
+| \\(v_\theta\\) | The denoiser; it outputs a velocity |
+| \\(\hat{x}_0\\) | Clean estimate \\(x_t - t\,v\\) |
+| \\(\lambda(t)\\) | Log signal-to-noise ratio at time \\(t\\) |
+| \\(s\\) | Additive shift on \\(\lambda\\) |
+| \\(A\\) | Number of pixels in the image, width times height |
+
+## Latent space
+
+The denoiser works in the latent space of
+[dinac3_96](https://huggingface.co/data-archetype/dinac3_96), our own
+deterministic autoencoder. Its latent has 96 channels at a spatial stride of 16
+pixels: 64 unconstrained channels that carry detail and 32 channels aligned
+with DINOv3 features. Its own report describes the autoencoder and its
+measurements.
+
+The denoiser uses a patch size of 1: each latent cell is one image token. An
+832×1216 image is a 52×76 grid, or 3,952 image tokens. Image width and height
+must be multiples of 16.
+
+## Text conditioning
+
+### Encoder and taps
+
+Google's T5Gemma 2 270M-270M is an encoder-decoder language model; dflow_2b
+uses its encoder, frozen, and leaves out the decoder. The encoder's hidden width
+is 640. Only layers 1 to 12 run. Hidden states are read
+after layers 2, 6 and 12, so that the denoiser sees features from early layers,
+which stay close to the tokens and their spelling, together with later, more
+contextual ones.
+
+Gemma hidden states contain a few channels with very large activations. Each
+tap is therefore standardised per channel with fixed means and standard
+deviations, computed once on 20,000 training captions. The three standardised
+taps pass through three bias-free linear maps from 640 to 2304 channels and the
+results are summed:
+
+$$
+e_i = \sum_{k \in \{2,6,12\}} P_k \,\frac{h^{(k)}_i - \operatorname{mean}_k}{\operatorname{std}_k},
+$$
+
+where \\(h^{(k)}_i\\) is the hidden state of token \\(i\\) after layer \\(k\\),
+\\(\operatorname{mean}_k\\) and \\(\operatorname{std}_k\\) are the per-channel
+statistics of that tap, the division is per channel, and \\(P_k\\) is the tap's
+linear map.
+
+### Learned tokens
+
+Three learned tokens are appended to every prompt, so every caption ends with
+the same three text positions whatever its length.
+
+The null text used for classifier-free guidance is also learned: one
+unconditional token followed by the same three suffix tokens, four tokens in
+all. An empty prompt maps to this sequence.
+
+### Tokenisation of visible text
+
+Text that should appear in the image is tokenised one character at a time, so
+each character of the string is its own token and the spelling is explicit in
+the token sequence. LongCat-Image uses the same technique. In a plain prompt
+this applies to every double-quoted span, quote marks included. In a JSON layout
+prompt it applies to the value of every `"text"` field and to escaped-quote
+spans inside other strings. Everything else uses the standard tokeniser.
+
+Prompts can be up to 6,144 tokens long, the longest caption length used in
+training. Longer prompts raise an error.
+
+## Denoiser
+
+### One stream for text and image
+
+Each sample is a single sequence made of its image tokens and its text tokens.
+Every layer applies self-attention over the whole sequence, so image tokens read
+the text and each other in the same operation, and text tokens are updated along
+with the image.
+
+The projected text first passes through two text-only refiner blocks. These
+blocks see only the text, so their output is computed once per prompt and
+reused at every sampling step and by every guidance pass. The image latent is
+embedded by a 1×1 convolution from 96 to 2304 channels.
+
+All blocks have width 2304 and 18 attention heads of 128 channels.
+
+### Position encoding
+
+Position enters through 3D rotary position embeddings (3D RoPE) in attention.
+Each token has a position on three axes, one for sequence order and two spatial
+ones, and each head splits its 128 channels over the axes as 32, 48 and 48,
+with frequency base 10,000.
+
+For a prompt of \\(L\\) tokens and an image grid of \\(n_y\\) rows and \\(n_x\\)
+columns of tokens:
+
+- text token \\(i\\), counted from 1, sits at \\((i, 0, 0)\\);
+- the image token in row \\(i_y\\) and column \\(i_x\\), both counted from 0, sits
+ at \\(\left(L+1,\; i_y - \tfrac{n_y-1}{2},\; i_x - \tfrac{n_x-1}{2}\right)\\).
+
+The first axis orders the text and places the whole image one step after it.
+This 3D layout follows modern single-stream image transformers such as
+Z-Image. Following MOSS-Image, the spatial axes are also centred on the image
+centre, so text tokens, at spatial position 0, sit at the centre of the image at
+every size and aspect ratio, and the largest spatial offset between a text token
+and an image token is half the grid. Attention between image tokens is unchanged
+by the centring because RoPE depends only on position differences.
+
+### Timestep conditioning
+
+The timestep is embedded as 256 sinusoidal features of \\(1000\,t\\), followed by
+a two-layer MLP with a hidden width of 1024 and an output \\(\tau(t)\\) of
+width 256.
+
+Every image block has its own linear projector from
+\\(\operatorname{SiLU}(\tau(t))\\) to four vectors of width 2304: a scale and a gate
+for attention, and a scale and a gate for the MLP. The time embedding is narrow
+because a timestep is a single scalar: measured in model ablations, the per-layer modulation
+signals occupied at most 14 dimensions at 99.99% of their energy.
+With a 256-wide input, an unshared dense projector per layer costs 2.4M
+parameters, 71M over the 30 layers.
+
+### Block
+
+Each block is a standard pre-norm transformer block with shift-free AdaLN
+modulation and sandwich normalisation: an RMSNorm before and after both the
+attention and the MLP branch. The modulation is a scale on the pre-norm output
+and a tanh gate on the branch output:
+
+$$
+z \leftarrow z + \tanh(\rho_{\mathrm{att}})\odot N_2\!\left(\operatorname{Attn}\!\left((1+\alpha_{\mathrm{att}})\odot N_1(z)\right)\right),
+$$
+
+$$
+z \leftarrow z + \tanh(\rho_{\mathrm{mlp}})\odot N_4\!\left(\operatorname{MLP}\!\left((1+\alpha_{\mathrm{mlp}})\odot N_3(z)\right)\right),
+$$
+
+where \\(z\\) is the token stream, \\(N_1\\) to \\(N_4\\) are RMSNorms with learned
+weights, and \\(\alpha\\) and \\(\rho\\) are the layer's scales and gates from its
+AdaLN projector. The modulation applies to every token in the stream, text
+included. The two text-refiner blocks are the same block without modulation.
+
+- **Attention:** fused bias-free QKV projection, RMSNorm on each head's queries
+ and keys, 3D RoPE, scaled dot-product attention, bias-free output projection.
+- **MLP:** GELU, expansion ratio 4, with biases.
+- **Output:** after the last block the image tokens pass through an RMSNorm, a
+ timestep scale and shift, and a linear head from 2304 to 96 channels that
+ predicts the velocity. The text tokens are dropped.
+
+## SPRINT and path-drop guidance
+
+The 30 image blocks are organised as in SPRINT (Park et al.).
+[Dense SPRINT](#dense-sprint) describes what dflow_2b changes.
+
+### Sparse middle
+
+SPRINT splits a diffusion transformer into three parts. A short **prefix** runs
+on every token. A long **middle** runs on a random subset: in the published
+method 75% of the image tokens are dropped before the middle. A
+short **suffix** again runs on every token. Between the middle and the suffix, a
+**tail join** fuses the prefix output with the middle output, with a learned mask
+token standing in at positions the middle did not process.
+
+Most of the network's depth runs on a quarter of the tokens, which cuts
+training cost. At inference the middle runs on all tokens. To close this gap
+between training and inference, SPRINT finishes with a short fine-tuning stage
+on all tokens.
+
+### Path drop
+
+For a fraction of the training samples the whole middle is skipped. The tail
+join then receives the mask token at every position, and the output comes from
+the prefix and suffix alone. This is called path drop. It trains a second,
+shallower predictor inside the same weights.
+
+### Path-drop guidance
+
+Path-drop guidance (PDG) uses that shallow predictor as a guidance reference at
+sampling time. Write \\(v_{\mathrm{full}}\\) for the prediction with every layer
+and \\(v_{\mathrm{weak}}\\) for the prediction of the same network, same input and
+same prompt, with the middle skipped. The guided velocity is
+
+$$
+v_{\mathrm{PDG}}
+= v_{\mathrm{weak}} + w\left(v_{\mathrm{full}} - v_{\mathrm{weak}}\right),
+$$
+
+with scale \\(w \ge 1\\). Like autoguidance (Karras et al.), this extrapolates away
+from a weaker version of the model itself, so it pushes along whatever the
+skipped layers contribute. Both passes see the same prompt (the default weak
+pass reads it with a [bias](#suffix-caption-bias)), so PDG works from the
+prompt alone. The weak pass is cheap: in dflow_2b it runs 12 of the 30 image
+blocks.
+
+## Dense SPRINT
+
+### What changed
+
+dflow_2b keeps SPRINT's structure and its three routes through the middle, and
+changes how often each is trained and how deep the outer parts are.
+
+The layout is 6 prefix, 18 middle and 6 suffix blocks. Each training sample
+takes one of three routes:
+
+| Share of samples | Route | Middle runs on |
+| ---: | --- | --- |
+| 80% | Dense | every image and text token |
+| 10% | Path drop | nothing; the middle is skipped |
+| 10% | Three-quarter drop | one image token of each 2×2 group, chosen at random, and every text token |
+
+A sparse mix trains most samples on the three-quarter route, for example 10%
+dense, 10% path drop and 80% three-quarter drop. Here the middle is trained
+mostly on full token grids from the first step. We call this arrangement dense
+SPRINT.
+
+Counting a block on all image tokens as 1 and a block on a quarter of them as
+0.25, an average training sample costs about
+\\(12 + 18\,(0.8 + 0.1\cdot 0.25) = 26.9\\) block evaluations. The sparse mix
+above costs 17.4 on the same layout, and a network that runs every block on
+every token costs 30. Dense SPRINT saves about 10% of the training compute and
+that sparse mix about 40%.
+
+### The tail join
+
+Let \\(p\\) be the prefix output and \\(m\\) the middle output, both of width
+\\(D = 2304\\). At rows the middle skipped, \\(m\\) is replaced by a learned mask
+token \\(\mu\\); call the result \\(\tilde{m}\\). The join scales the two streams by
+time-dependent gains, concatenates them and projects back to width \\(D\\). Rows
+the middle skipped also receive a separate projection of the prefix stream:
+
+$$
+z = W\left[\,(1+\gamma_p(t))\odot p \;;\; (1+\gamma_m(t))\odot \tilde{m}\,\right]
+ + b + \chi\,R\left((1+\gamma_p(t))\odot p\right),
+$$
+
+where \\([\,\cdot\;;\;\cdot\,]\\) is concatenation along the channel axis.
+
+| Symbol | Meaning |
+| --- | --- |
+| \\(p\\) | Prefix output for one token |
+| \\(z\\) | Token entering the suffix |
+| \\(\tilde{m}\\) | Middle output for that token, or the mask token \\(\mu\\) if the middle skipped it |
+| \\(\gamma_p(t), \gamma_m(t)\\) | Gains of width \\(D\\) each, a linear function of \\(\operatorname{SiLU}(\tau(t))\\) |
+| \\(W, b\\) | Projection from \\(2D\\) to \\(D\\) and its bias |
+| \\(R\\) | Bias-free \\(D \times D\\) projection for skipped rows |
+| \\(\chi\\) | 1 if the middle skipped the token, 0 otherwise |
+
+Under path drop every row has \\(\chi = 1\\). Under the three-quarter route the
+dropped image tokens have \\(\chi = 1\\) and the kept tokens and the text have
+\\(\chi = 0\\). The extra projection \\(R\\) gives skipped rows weights of their own
+for the prefix stream, and the time-dependent gains let the balance between the
+two streams vary along the trajectory. In ablations against the plain
+concatenation join of the original SPRINT, both gave a consistent improvement.
+
+### Why train the middle dense
+
+Sparse SPRINT gives good coherence and textures but struggles to place fine
+detail and text precisely. Good detail never converges at low resolution and
+still lags at high resolution. Training the middle mostly on all tokens
+corrects this.
+
+The two sparse routes stay in the mix for different reasons. The 10% path-drop
+route trains the weak predictor of path-drop guidance, which works like
+guidance by a weaker model and gives much better results than CFG. The 10%
+three-quarter route acts as a regulariser and improves coherence and
+convergence.
+
+The weak predictor needs enough depth to be a useful guidance reference. The 2
+to 4 outer blocks of the original SPRINT proved too few, and in ablations a weak
+path of about a third of the main path's depth was the best compromise. dflow_2b
+therefore has 6 prefix and 6 suffix blocks, 12 of its 30.
+
+One drawback is that on the high-noise part of the trajectory, with \\(t\\) close
+to 1, the full and path-drop predictions largely agree. This gives more
+oversaturation than sparse SPRINT, which the
+[self-attention gain](#self-attention-gain), a small increase of the attention
+temperature, mitigates. Sparse SPRINT has much of the same issue and also
+benefits from this softening.
+
+### Alternatives that were tried
+
+Two layouts that mix sparse and dense blocks inside the middle were tested in
+small-scale experiments: one alternating two sparse blocks with one dense
+block, and one with eight sparse blocks, a second join and four dense blocks.
+Neither improved on the uniform middle that dflow_2b uses.
+
+## Architecture summary
+
+| Component | Setting |
+| --- | --- |
+| Latent | dinac3_96, 96 channels, stride 16, patch size 1 |
+| Text encoder | T5Gemma 2 270M-270M encoder, layers 1–12, frozen |
+| Text taps | After layers 2, 6 and 12, standardised per channel, three linear maps 640 → 2304, summed |
+| Learned text tokens | 3 suffix tokens; 1 unconditional token for the null text |
+| Maximum prompt length | 6,144 tokens |
+| Width, heads | 2304; 18 heads of 128 |
+| Text refiner | 2 blocks, text only, no timestep modulation |
+| Image blocks | 30: 6 prefix, 18 middle, 6 suffix, joint self-attention over text and image |
+| Attention | RMSNorm on queries and keys, bias-free projections |
+| MLP | GELU, expansion ratio 4 |
+| Position encoding | Centred 3D RoPE, 32/48/48 channels per head, base 10,000 |
+| Timestep conditioning | 256-wide embedding; one projector per block to attention and MLP scales and gates |
+| Tail join | Concatenation with time-dependent gains, mask token, separate prefix projection for skipped rows |
+| Prediction | Velocity on the linear flow-matching path |
+| Parameters | 2,133,866,592 |
+
+## Sampling and guidance
+
+### Default preset
+
+| Setting | Default |
+| --- | --- |
+| Size | 832×1216 |
+| Solver | ER-SDE, noise scale 1 |
+| Schedule | 50 steps at the quantiles of Beta(1.25, 1.25) |
+| Timestep shift | \\(s(A)\\), the training shift; −2.99 at 832×1216 |
+| Guidance | PDG, constant scale 2.5, reference conditioned on the prompt with a −4 caption bias in its six suffix blocks |
+| Classifier-free guidance | Off |
+| Self-attention gain | −0.03 on the full pass, 0 on the reference pass |
+
+The schedule places its 51 time points at equal-probability quantiles of a
+Beta(1.25, 1.25) distribution, which is slightly denser in the middle of the
+trajectory than a uniform grid, and then applies the shift \\(s(A)\\) from
+[Flow matching](#flow-matching). Using the training shift at sampling time
+means the sampler spends its steps where training placed its timesteps for that
+image size.
+
+ER-SDE (Cui et al.) is a stochastic solver for the reverse-time SDE; the release
+uses its three-stage form. A noise scale of 1 is the solver's own noise level
+and 0 makes it deterministic. The package also includes Euler, Euler–Maruyama,
+DPM++ 2M, DPM++ 2M SDE and a two-stage Adams–Bashforth–Moulton solver.
+
+Each step runs the full pass and the weak pass, so 50 steps are 100 denoiser
+calls, of which the 50 weak calls run 12 of 30 blocks.
+
+### Guidance formulas
+
+With the prompt \\(c\\), scale \\(w\\), gain \\(g\\) and caption bias \\(b\\) defined below, the
+default guided velocity is
+
+$$
+v = v_{\mathrm{weak}}(x_t, t, c;\, b)
+ + w\left(v_{\mathrm{full}}(x_t, t, c;\, g) - v_{\mathrm{weak}}(x_t, t, c;\, b)\right),
+\qquad w = 2.5,\; b = -4 .
+$$
+
+| Symbol | Meaning |
+| --- | --- |
+| \\(c\\) | Text conditioning of the prompt |
+| \\(v_{\mathrm{full}}\\) | Prediction with all 30 image blocks |
+| \\(v_{\mathrm{weak}}\\) | Prediction with the 18 middle blocks skipped |
+| \\(w\\) | PDG scale; 1 is no guidance |
+| \\(g\\) | Self-attention gain of the full pass |
+| \\(b\\) | Caption bias of the weak pass, described under [Suffix caption bias](#suffix-caption-bias) |
+
+### Self-attention gain
+
+The gain \\(g\\) multiplies the queries of the 30 image blocks by \\(e^{g}\\) after
+the query-key normalisation and RoPE. This divides every attention logit by a
+temperature \\(e^{-g}\\), so a negative gain makes attention slightly more
+diffuse.
+
+The gain is applied to the full pass only. With \\(\delta\\) the change it makes to
+the full prediction, PDG becomes
+
+$$
+v = v_{\mathrm{weak}} + w\left(v_{\mathrm{full}} - v_{\mathrm{weak}}\right) + w\,\delta ,
+$$
+
+so a small softening of the full pass reaches the output multiplied by the
+guidance scale. The weak pass runs without the gain: the same change in both
+passes would largely cancel in their difference. The gain counters the over-contrast and oversaturation that PDG adds, described
+under [Why train the middle dense](#why-train-the-middle-dense), and reduces
+structural errors with it.
+
+The default of −0.03 suits images up to about one megapixel. Larger images need
+a gain closer to 0, roughly linear in the logarithm of the area:
+
+| Image area | Example sizes | Gain |
+| --- | --- | --- |
+| up to about 1.05 MP | 832×1216, 1216×832, 1024×1024 | −0.03 (default) |
+| about 1.3 MP | 1536×832, 1216×1088 | −0.02 |
+| about 1.6 MP | 1024×1536 | −0.015 |
+| about 2.5 MP and above | 1280×1920 | 0 to −0.01 |
+
+At about one megapixel, a gain closer to 0 gives oversaturation and more
+structural defects. At larger sizes, too negative a gain gives washed-out
+images.
+
+### Suffix caption bias
+
+By default the weak pass reads the prompt less in its six suffix blocks. In
+those blocks every query, image or text, has a constant \\(b = -4\\) added to its
+attention logits on the prompt's tokens:
+
+$$
+\ell_{ij} = \frac{q_i \cdot k_j}{\sqrt{d}} + b\,\chi_j .
+$$
+
+| Symbol | Meaning |
+| --- | --- |
+| \\(\ell_{ij}\\) | Attention logit of query \\(i\\) on key \\(j\\) |
+| \\(q_i, k_j\\) | Normalised, rotated query and key of one head |
+| \\(d\\) | Head width, 128 |
+| \\(\chi_j\\) | 1 for a prompt token; 0 for image tokens and the three learned suffix tokens |
+
+The bias applies on every step, to whichever text the weak pass reads: the
+prompt in the default mode, the negative prompt or the null text in the
+contrastive modes. The full pass and the CFG passes are unchanged. Because the
+reference sees less of the prompt, more of the prompt's effect stays in
+\\(v_{\mathrm{full}} - v_{\mathrm{weak}}\\) and is amplified by the guidance
+scale. Prompt following improves, and colour and layout stay close to plain
+PDG.
+
+We also tried biasing the learned suffix tokens, biasing every block or only
+part of the run, other bias strengths, contrastive and alternating references,
+frequency-split guidance, CFG with skipped layers and projected guidance. In
+blind side-by-side comparisons on 18 prompts with the released weights, the
+biased reference was preferred on 16, with fewer anatomy errors and missed
+prompt elements.
+
+### Other guidance options
+
+Contrastive PDG conditions the weak pass on a negative prompt, or on the
+learned null text. It gives stronger guidance and less diversity, and we
+generally prefer plain PDG. The [manual](MANUAL.md#guidance) describes it with
+classifier-free guidance, scale ramps and curves, projected guidance and the
+other options.
+
+## Prompt emphasis
+
+A phrase can be weighted with the markup `(phrase:weight)`. The weight
+\\(\omega\\) is applied inside attention, with a global strength \\(\kappa\\) that
+defaults to 1. For \\(\omega > 0\\), a bias is added to the attention logits of
+every query towards the keys of the weighted tokens. The bias is
+\\(\kappa \ln \omega\\) in the logarithmic mapping, which at \\(\kappa = 1\\)
+multiplies those tokens' unnormalised attention weight by \\(\omega\\), or
+\\(2\kappa(\omega - 1)\\) in the linear mapping. For \\(\omega \le 0\\), the tokens'
+attention values are multiplied by \\(1 + \kappa(\omega - 1)\\), so 0 mutes them
+and −1 subtracts them. The bias and scale apply in the text refiner and in all
+30 image blocks, and optionally inside the text encoder's own attention.
+Emphasis works on plain-text prompts only. A JSON layout is encoded exactly as
+written, so parentheses and colons in its captions and text stay literal and
+carry no weight.
+
+## JSON layout prompts
+
+The model was also trained on structured captions that describe an image as a
+set of boxes. About 10% of the samples in the most recent training used one as
+their caption.
+
+A layout is a JSON object with three parts:
+
+- `summary`: a list of `meta` tags, the `canvas` type and a `caption` of the
+ whole image;
+- `frame`: a `caption`, `tags` and a colour `palette` for the canvas as a whole;
+- `items`: a list of boxes. Each has a `label` (`character`, `object` or
+ `text`), an optional `caption`, `tags` and `palette`, and a box
+ `box_2d = [y0, x0, y1, x1]` on a 0–1000 scale. Text items also carry the exact
+ `text` to render.
+
+The optional fields were dropped at random during training, so they can be
+omitted.
+
+Before encoding, a layout is compiled for the image size: the frame becomes a
+first item covering the whole canvas, and every box is converted to pixels
+measured from the image centre, the same origin as the denoiser's position
+encoding. The compiled format follows the layout prompts of MOSS-Image. The
+[manual](MANUAL.md#json-layouts) gives the format field by field and the
+compilation rules.
+
+## Training
+
+### Objective
+
+Each training sample draws a noise \\(\varepsilon\\), a time \\(t\\), a route \\(r\\)
+through the middle and a possibly dropped caption \\(\tilde{c}\\), and contributes
+a squared velocity error:
+
+$$
+\mathcal{L}
+= \mathbb{E}_{x_0,\,\varepsilon,\,t,\,r,\,\tilde{c}}
+ \left\lVert v_\theta(x_t, t, \tilde{c};\, r) - (\varepsilon - x_0) \right\rVert_2^2 .
+$$
+
+| Symbol | Sampling |
+| --- | --- |
+| \\(t\\) | Beta(2, 2), then log-SNR shifted by \\(s(A) = \min\left(0,\, -0.25 - \ln\frac{A}{256^2}\right)\\) for the sample's pixel area \\(A\\): −0.25 at 256×256, −1.64 at 512×512, −2.99 at 832×1216 ([flow matching](#flow-matching)). 1% of samples are set to \\(t = 1\\) |
+| \\(r\\) | Dense with probability 0.8, path drop 0.1, three-quarter drop 0.1 |
+| \\(\tilde{c}\\) | The caption, replaced by the learned null text with probability 0.1 |
+
+Every sample is one forward pass on one route, and the loss above is the whole
+objective.
+
+### Optimisation
+
+| Setting | Value |
+| --- | --- |
+| Optimiser | Dion ([dionw](https://github.com/JTriggerFish/dionw) implementation) on the large weight matrices, AdamW on the remaining parameters |
+| Learning rate | \\(5 \times 10^{-5}\\), linear warmup over 4,000 steps, then constant |
+| AdamW betas | (0.9, 0.95) |
+| Weight decay | 0.01 |
+| Gradient clipping | Norm 1.0 |
+| Batch size | 128, with gradient accumulation |
+| Precision | bfloat16 autocast |
+| EMA | Updated every 10 steps; half-life 4,000 steps, 2,000 from step 400,000 |
+| Hardware | One GPU |
+
+At 512 px a batch is accumulated over 4 micro-batches. At 1024 px it is
+accumulated over 16, or over 24 when the batch contains very long captions.
+
+For an EMA half-life of \\(T\\) steps and an update every 10 steps, each update
+uses the decay \\(2^{-10/T}\\).
+
+### Resolution stages
+
+Training uses aspect-ratio buckets: each nominal resolution is a family of
+landscape, square and portrait shapes of similar area, and every batch holds
+images of one shape.
+
+| Stage | Steps | Training images |
+| --- | --- | ---: |
+| 256 and 384 px buckets | 0 – 400,000 | about 21 million |
+| 512 px buckets, with 10% of batches at 1024 px | 400,000 – 540,412 | about 20 million |
+| 1024 px buckets | from 540,412 | about 10 million |
+
+Structured layout captions were introduced in the 1024 px stage and make up
+about 10% of its recent samples.
+
+The released weights are the EMA at step 581,000.
+
+## Limitations
+
+- This is a preview of a model that is still training. Quality varies between
+ prompts and seeds, and later checkpoints will behave differently.
+- Anatomy errors are common, in limbs and hands especially.
+- Small text and long passages of text are unreliable.
+- The model was trained on aspect-ratio buckets of about one megapixel. It is
+ less reliable at sizes far from those shapes and well above one megapixel. The
+ default guidance settings were tuned at 832×1216; larger images need a
+ self-attention gain closer to 0.
+- The training data is mostly photographs and classical art, and other styles
+ are covered less well.
+- A compiled layout prompt is valid for one image size only.
+
+## References
+
+### Flow matching
+
+Lipman et al., “Flow Matching for Generative Modeling,” ICLR 2023.
+[arXiv:2210.02747](https://arxiv.org/abs/2210.02747).
+
+Liu et al., “Flow Straight and Fast: Learning to Generate and Transfer Data with
+Rectified Flow,” ICLR 2023.
+[arXiv:2209.03003](https://arxiv.org/abs/2209.03003).
+
+### SPRINT and path-drop guidance
+
+Park et al., “Sprint: Sparse-Dense Residual Fusion for Efficient Diffusion
+Transformers,” 2025. [arXiv:2510.21986](https://arxiv.org/abs/2510.21986).
+Path-drop guidance is introduced in the same paper.
+
+### Autoguidance
+
+Karras et al., “Guiding a Diffusion Model with a Bad Version of Itself,”
+NeurIPS 2024. [arXiv:2406.02507](https://arxiv.org/abs/2406.02507).
+
+### Classifier-free guidance
+
+Ho and Salimans, “Classifier-Free Diffusion Guidance,” 2022.
+[arXiv:2207.12598](https://arxiv.org/abs/2207.12598).
+
+### Adaptive projected guidance
+
+Sadat et al., “Eliminating Oversaturation and Artifacts of High Guidance Scales
+in Diffusion Models,” ICLR 2025.
+[arXiv:2410.02416](https://arxiv.org/abs/2410.02416).
+
+### ER-SDE
+
+Cui et al., “Elucidating the Solution Space of Extended Reverse-Time SDE for
+Diffusion Models,” 2023. [arXiv:2309.06169](https://arxiv.org/abs/2309.06169).
+
+### Rotary position embedding
+
+Su et al., “RoFormer: Enhanced Transformer with Rotary Position Embedding,”
+2021. [arXiv:2104.09864](https://arxiv.org/abs/2104.09864).
+
+### Z-Image
+
+Z-Image Team, “Z-Image: An Efficient Image Generation Foundation Model with
+Single-Stream Diffusion Transformer,” 2025.
+[arXiv:2511.22699](https://arxiv.org/abs/2511.22699).
+
+### T5Gemma 2
+
+Zhang et al., “T5Gemma 2: Seeing, Reading, and Understanding Longer,” 2025.
+[arXiv:2512.14856](https://arxiv.org/abs/2512.14856).
+[Model card](https://huggingface.co/google/t5gemma-2-270m-270m).
+
+### LongCat-Image
+
+Meituan LongCat Team, “LongCat-Image Technical Report,” 2025.
+[arXiv:2512.07584](https://arxiv.org/abs/2512.07584).
+
+### DINOv3 and dinac3_96
+
+Siméoni et al., “DINOv3,” 2025.
+[arXiv:2508.10104](https://arxiv.org/abs/2508.10104).
+
+data-archetype, “dinac3_96,” 2026.
+[Model and technical report](https://huggingface.co/data-archetype/dinac3_96).
+
+### Dion
+
+Ahn et al., “Dion: Distributed Orthonormalized Updates,” 2025.
+[arXiv:2504.05295](https://arxiv.org/abs/2504.05295).
+
+Our implementation, used for training:
+[github.com/JTriggerFish/dionw](https://github.com/JTriggerFish/dionw).
+
+### AdamW
+
+Loshchilov and Hutter, “Decoupled Weight Decay Regularization,” ICLR 2019.
+[arXiv:1711.05101](https://arxiv.org/abs/1711.05101).
+
+### MOSS-Image
+
+MOSI.AI, “MOSS-Image Technical Report,” 2026.
+[arXiv:2610.23374](https://arxiv.org/abs/2610.23374).
diff --git a/__init__.py b/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..58754e9f7083a840c5f0d059e52634e1d7764643
--- /dev/null
+++ b/__init__.py
@@ -0,0 +1,17 @@
+# SPDX-License-Identifier: GPL-3.0-only
+# Copyright 2026 Data Archetype
+"""ComfyUI entry point of the dflow_2b repository (installed as its root
+``__init__.py``).
+
+ComfyUI imports the repository folder as a package and reads
+``NODE_CLASS_MAPPINGS``, ``NODE_DISPLAY_NAME_MAPPINGS`` and ``WEB_DIRECTORY``.
+Outside a package (a pip build, or a test run collecting this file) nothing
+is imported, so ``comfy`` is never required there.
+"""
+
+if __package__:
+ from .comfyui.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
+
+ WEB_DIRECTORY = "./comfyui/web"
+
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
diff --git a/assets/gallery/army.png b/assets/gallery/army.png
new file mode 100644
index 0000000000000000000000000000000000000000..f9009a7d0971bc1fb7efeaae01f4cc6f29aa39db
--- /dev/null
+++ b/assets/gallery/army.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:dad27c2635aae049d953fbbda6e24890e47040fe9dc8951c2a42c73d33c114d2
+size 1635466
diff --git a/assets/gallery/beetle.png b/assets/gallery/beetle.png
new file mode 100644
index 0000000000000000000000000000000000000000..035cd81a0feeccd451d30da0c7fa28ef1b1a650c
--- /dev/null
+++ b/assets/gallery/beetle.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4da43f8fef42e8b58c8396ccf6a6efe52ab0e1acaa896ae203bcd4b3145a45ce
+size 1610709
diff --git a/assets/gallery/boardwalk.png b/assets/gallery/boardwalk.png
new file mode 100644
index 0000000000000000000000000000000000000000..3a221b365fa48191870b0633dbf7279e2277cd2d
--- /dev/null
+++ b/assets/gallery/boardwalk.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cf7783a49c2f7a1440ebbee212c9b8d32b52351bb04a625456837cfeaf7c1030
+size 3191559
diff --git a/assets/gallery/cat_grass.png b/assets/gallery/cat_grass.png
new file mode 100644
index 0000000000000000000000000000000000000000..0c03b32fd420b2bfc31884771dab8dc48f3d0bfe
--- /dev/null
+++ b/assets/gallery/cat_grass.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:106ff8caa588caa3ace1829323fbca7aaadf1ab86e7bdd5afdbcd13fdd4904f8
+size 1498586
diff --git a/assets/gallery/closet.png b/assets/gallery/closet.png
new file mode 100644
index 0000000000000000000000000000000000000000..1612ecc5363e9bfe9a5ab189ff14db163fc6cd07
--- /dev/null
+++ b/assets/gallery/closet.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6f003765f7ed56e49dee849122e9462968007d82a398af3a1d81a82770467fd7
+size 2798953
diff --git a/assets/gallery/collier.png b/assets/gallery/collier.png
new file mode 100644
index 0000000000000000000000000000000000000000..d532cdad946dbca4503005199a738d2c47228298
--- /dev/null
+++ b/assets/gallery/collier.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a0ddc44fd1324809e01459528f43795d01cdae23f031c562d291e4225aff618c
+size 1371072
diff --git a/assets/gallery/constable.png b/assets/gallery/constable.png
new file mode 100644
index 0000000000000000000000000000000000000000..2dda3bf1375f778f81b6c2973c7a7075d8fd72ec
--- /dev/null
+++ b/assets/gallery/constable.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:582a663f0ce8fa128b62023c0100fa5f61d167f772a17aea37435562bdde4510
+size 2273231
diff --git a/assets/gallery/hokusai.png b/assets/gallery/hokusai.png
new file mode 100644
index 0000000000000000000000000000000000000000..b499382cdc91fd49b4a525aede4618a1aa806d1d
--- /dev/null
+++ b/assets/gallery/hokusai.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d30e10ae999b1fd24ba1693756ebad734956c5ab16abce008cadde9da32d3883
+size 1996828
diff --git a/assets/gallery/larson.png b/assets/gallery/larson.png
new file mode 100644
index 0000000000000000000000000000000000000000..d47cc433c7a641dfe4f41d69fe4383adff4aaede
--- /dev/null
+++ b/assets/gallery/larson.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e927672ca94a06b1dbad52ca5951230078acc53a42b023b44b67d779cb94305f
+size 1752612
diff --git a/assets/gallery/leopard.png b/assets/gallery/leopard.png
new file mode 100644
index 0000000000000000000000000000000000000000..7e19fde2881b5db75e1b5f8b211242b15c49c680
--- /dev/null
+++ b/assets/gallery/leopard.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c036cce491b4a4327101c5ca069832436d8ea2f6c3fbbf79e7b8e93bc457c089
+size 1612037
diff --git a/assets/gallery/man.png b/assets/gallery/man.png
new file mode 100644
index 0000000000000000000000000000000000000000..139dbe16bbe608d0f638d2c1130adb3437b90df9
--- /dev/null
+++ b/assets/gallery/man.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9805e08e05adb286d754f204e319befd98ca198a30c1f7b83f80fe88c18379a1
+size 1345431
diff --git a/assets/gallery/man_outside.png b/assets/gallery/man_outside.png
new file mode 100644
index 0000000000000000000000000000000000000000..b227d9925f1b2e1bd4187ea8de174895027f545a
--- /dev/null
+++ b/assets/gallery/man_outside.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a3a370ab1a9ccb886cd05724d209f8589a17308e3aad0fddd179bcc55c93e112
+size 2630111
diff --git a/assets/gallery/marina.png b/assets/gallery/marina.png
new file mode 100644
index 0000000000000000000000000000000000000000..d6eab8d1ce3e2f56bd8446d6e874e26c846c316c
--- /dev/null
+++ b/assets/gallery/marina.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2e3fe673dfacfc3e8c1b8a4fbbbb428abd80e943826d6df4353919026bc855b5
+size 1536846
diff --git a/assets/gallery/nissan.png b/assets/gallery/nissan.png
new file mode 100644
index 0000000000000000000000000000000000000000..9365661f3b7c25dd07f18d9d62bfb02d11c9e863
--- /dev/null
+++ b/assets/gallery/nissan.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7b34f94d0baaafbdb40953d3b685950ae1ae91760ff8eaff74d84bfb06bb3d11
+size 2178465
diff --git a/assets/gallery/poster_film.png b/assets/gallery/poster_film.png
new file mode 100644
index 0000000000000000000000000000000000000000..4a54cc932ed98873c7d4fa409f1d234f6efbc47e
--- /dev/null
+++ b/assets/gallery/poster_film.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:70139152b95028df3942b3e257308eb6e28b105d53ebd8b753e21a5af22a350c
+size 1096380
diff --git a/assets/gallery/poster_jazz.png b/assets/gallery/poster_jazz.png
new file mode 100644
index 0000000000000000000000000000000000000000..e16976546371695dffef8d0f3dbb1017fa0f537f
--- /dev/null
+++ b/assets/gallery/poster_jazz.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0f3dd41a99c185da982bc178045b9fdc73d92b7679fef288330f2807c19f9d0b
+size 1121292
diff --git a/assets/gallery/poster_travel.png b/assets/gallery/poster_travel.png
new file mode 100644
index 0000000000000000000000000000000000000000..67e12d2eb1ace62f38fa16195087281e224e6379
--- /dev/null
+++ b/assets/gallery/poster_travel.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4cfbec139f9a447017565c1203bbd539b8983af00512fc24eea72d5a2f77f033
+size 1499762
diff --git a/assets/gallery/red_perfume.png b/assets/gallery/red_perfume.png
new file mode 100644
index 0000000000000000000000000000000000000000..8a4301c2707b0346506d119f65aeccad2d9ba095
--- /dev/null
+++ b/assets/gallery/red_perfume.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:29e2def98d7dd5576dc94453088cdc9ba59b680e3b19be6a27af212a9a88b9f7
+size 2175406
diff --git a/assets/gallery/renoir.png b/assets/gallery/renoir.png
new file mode 100644
index 0000000000000000000000000000000000000000..a2f1cee1776ba183948628c446cf8f368c8901ee
--- /dev/null
+++ b/assets/gallery/renoir.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7b9c645825373e0fb4cea5e0ec6484fc56611b83ca8ce410a9826079ffe4c0ac
+size 1847276
diff --git a/assets/gallery/rooster.png b/assets/gallery/rooster.png
new file mode 100644
index 0000000000000000000000000000000000000000..c352eb499bd37623f3f450dedc8e16aeb618c411
--- /dev/null
+++ b/assets/gallery/rooster.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:78d13b8b5cfbc9f9e095e29f4e5092ca707f69716fbd89aa1677914c43801396
+size 1754500
diff --git a/assets/gallery/rousseau.png b/assets/gallery/rousseau.png
new file mode 100644
index 0000000000000000000000000000000000000000..7c47e27936733f8fbeaea6a81cbfb4e5fb1312ee
--- /dev/null
+++ b/assets/gallery/rousseau.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:61efa88a152e197092ab8c0d025b48f54e061bf96dc1c337c666b5aaeff7e0ba
+size 1480111
diff --git a/assets/gallery/snail.png b/assets/gallery/snail.png
new file mode 100644
index 0000000000000000000000000000000000000000..67c294ed57a124ecd263e6a75c0fe076f126adb1
--- /dev/null
+++ b/assets/gallery/snail.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7e866e8ce2d3eac5cfaa926f3b3e83507bede47b4593593d7ce8efb2315c61cf
+size 1486466
diff --git a/assets/gallery/station.png b/assets/gallery/station.png
new file mode 100644
index 0000000000000000000000000000000000000000..00b5762d626b16bded1a910b95a2b1251e640765
--- /dev/null
+++ b/assets/gallery/station.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8b350a199b036d7806db9930b317aebf030678df1b2a8a5ffc4cba5b9bf7ebd8
+size 1902170
diff --git a/assets/gallery/still_woman.png b/assets/gallery/still_woman.png
new file mode 100644
index 0000000000000000000000000000000000000000..f184e69387af6bc7eb95addd14a1d675425c0656
--- /dev/null
+++ b/assets/gallery/still_woman.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0042daa6420ece2aefeb7c7890f531c97b5d12494e4ef5a52b6c4de1018c9a62
+size 1327276
diff --git a/assets/gallery/street.png b/assets/gallery/street.png
new file mode 100644
index 0000000000000000000000000000000000000000..ea7e8db287fc6428d89c2d23d8f3c9536a136092
--- /dev/null
+++ b/assets/gallery/street.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a92f84e061478c31af284c9c7d0e85559f9633f6e39ce48dc97cdd0fdb836adb
+size 1659455
diff --git a/assets/gallery/wahlberg.png b/assets/gallery/wahlberg.png
new file mode 100644
index 0000000000000000000000000000000000000000..839bcb6e54563f4d9c0e2e81f4900102741d4a2e
--- /dev/null
+++ b/assets/gallery/wahlberg.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:defea0b385f73566ad8c26149274b525a9feb93033d7f5c0ed1f1c95ce05c2c0
+size 1577007
diff --git a/assets/gallery/weenix.png b/assets/gallery/weenix.png
new file mode 100644
index 0000000000000000000000000000000000000000..83e2a81f8f16f3fd3fd75fa412850fb39f1269c7
--- /dev/null
+++ b/assets/gallery/weenix.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2cb261c05c0ee2d95369f2b2a8354632c8a0f37f3dbd24c6bc358d34d98a2fd9
+size 1442844
diff --git a/comfyui/LICENSE b/comfyui/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7
--- /dev/null
+++ b/comfyui/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/comfyui/NOTICE b/comfyui/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..8d21f8689c1761ec01600d758158f89526542f2e
--- /dev/null
+++ b/comfyui/NOTICE
@@ -0,0 +1,17 @@
+dflow_2b ComfyUI nodes
+Copyright 2026 Data Archetype
+
+The files in this comfyui/ folder and the repository's root __init__.py (the
+ComfyUI entry point) are licensed under the GNU General Public License,
+version 3 (GPL-3.0). See LICENSE in this folder.
+
+Everything else in this repository, including the model weights, the dflow/
+Python package, the documentation and the gallery images, is licensed under
+the ModelGo Attribution-NonCommercial License 2.0 (MG-BY-NC-2.0); see the
+LICENSE and NOTICE files at the repository root. The bundled T5Gemma2 text
+encoder remains under the Gemma terms, and the dinac3_96 autoencoder, which is
+downloaded separately, under its own licence.
+
+The nodes call the dflow package through its public API at run time. The GPL
+covers the node code only; it does not change the licence of the weights or
+of the dflow package.
diff --git a/comfyui/__init__.py b/comfyui/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b3125037e9afcb2e5bdb15b8f1f9608ac08d332
--- /dev/null
+++ b/comfyui/__init__.py
@@ -0,0 +1,8 @@
+# SPDX-License-Identifier: GPL-3.0-only
+# Copyright 2026 Data Archetype
+"""ComfyUI nodes for dflow_2b (GPL-3.0; see LICENSE and NOTICE here).
+
+The node classes are in ``nodes``; the repository root's ``__init__.py``
+registers them with ComfyUI. This folder calls only the public API of the
+``dflow`` package next to it.
+"""
diff --git a/comfyui/loader.py b/comfyui/loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3ea4c61b29aed0e0b99f8934d1eb65098db1772
--- /dev/null
+++ b/comfyui/loader.py
@@ -0,0 +1,128 @@
+# SPDX-License-Identifier: GPL-3.0-only
+# Copyright 2026 Data Archetype
+"""Where the loader node finds the release, and loading it.
+
+The node folder is the Hugging Face repository checkout, so the default
+source is the folder itself. A clone without its large files holds Git LFS
+pointer files instead; the loader detects them and says how to download the
+weights.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from ..dflow.loading import CONFIG_FILENAME, MODEL_FILENAME, RELEASE_FILENAME
+from ..dflow.pipeline import REPOSITORY, TEXT_ENCODER_DIRNAME, DFlowComponents
+from ..dflow.preview import LatentRgbPreview
+from .types import DFlowModelHandle, DFlowWeightSource
+
+if TYPE_CHECKING:
+ import torch
+
+NODE_FOLDER = Path(__file__).parents[1]
+"""The custom-node folder (the repository root)."""
+
+BUNDLED_FILES = (
+ CONFIG_FILENAME,
+ RELEASE_FILENAME,
+ MODEL_FILENAME,
+ f"{TEXT_ENCODER_DIRNAME}/config.json",
+ f"{TEXT_ENCODER_DIRNAME}/model.safetensors",
+ f"{TEXT_ENCODER_DIRNAME}/tokenizer.json",
+)
+"""Release files the bundled source needs, relative to the node folder."""
+
+_LFS_POINTER_PREFIX = b"version https://git-lfs.github.com/spec/"
+# Git LFS pointer files are about 130 bytes; real release files are larger.
+_LFS_POINTER_MAX_BYTES = 1024
+
+
+def is_lfs_pointer(path: Path) -> bool:
+ """Whether ``path`` is a Git LFS pointer file instead of its content."""
+
+ if path.stat().st_size > _LFS_POINTER_MAX_BYTES:
+ return False
+ with path.open("rb") as handle:
+ return handle.read(len(_LFS_POINTER_PREFIX)) == _LFS_POINTER_PREFIX
+
+
+def bundled_release_dir(folder: Path = NODE_FOLDER) -> Path:
+ """Return the node folder after checking it holds the release files.
+
+ Raises:
+ FileNotFoundError: If a file is missing or is a Git LFS pointer; the
+ message gives the download command.
+ """
+
+ missing = [name for name in BUNDLED_FILES if not (folder / name).is_file()]
+ pointers = [
+ name
+ for name in BUNDLED_FILES
+ if name not in missing and is_lfs_pointer(folder / name)
+ ]
+ if missing or pointers:
+ problems = [f"missing {name}" for name in missing] + [
+ f"{name} is a Git LFS pointer" for name in pointers
+ ]
+ raise FileNotFoundError(
+ f"The dflow_2b weights are not in the node folder {folder} "
+ f"({'; '.join(problems)}). Download them with:\n"
+ f" hf download {REPOSITORY} --local-dir {folder}\n"
+ "or choose the hub source in DFlow Loader."
+ )
+ return folder
+
+
+def release_location(
+ source: DFlowWeightSource, *, local_dir: str, repository: str
+) -> Path | str:
+ """The release directory or Hub repository a source reads.
+
+ Each source reads only its own field: BUNDLED neither, LOCAL_DIR
+ ``local_dir``, HUB ``repository``.
+
+ Raises:
+ FileNotFoundError: For missing bundled files or local directory.
+ ValueError: For an empty field the source needs.
+ """
+
+ match source:
+ case DFlowWeightSource.BUNDLED:
+ return bundled_release_dir()
+ case DFlowWeightSource.LOCAL_DIR:
+ if not local_dir.strip():
+ raise ValueError("The local_dir source needs local_dir.")
+ path = Path(local_dir.strip()).expanduser()
+ if not path.is_dir():
+ raise FileNotFoundError(f"No release directory at {path}.")
+ return path
+ case DFlowWeightSource.HUB:
+ if not repository.strip():
+ raise ValueError("The hub source needs a repository id.")
+ return repository.strip()
+ case _ as unreachable:
+ raise ValueError(f"Unsupported weight source: {unreachable}")
+
+
+def load_model(
+ location: Path | str,
+ *,
+ device: torch.device,
+ compile_model: bool,
+ revision: str | None,
+ cache_dir: Path | None,
+) -> DFlowModelHandle:
+ """Load the release and the preview projection onto ``device``."""
+
+ components = DFlowComponents.from_pretrained(
+ location,
+ device=device,
+ compile=compile_model,
+ revision=revision,
+ cache_dir=cache_dir,
+ )
+ return DFlowModelHandle(
+ components=components, preview=LatentRgbPreview.bundled().to(device)
+ )
diff --git a/comfyui/nodes.py b/comfyui/nodes.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a2c44533d2b1441bcb9e8b98ddcb802ccedb7ec
--- /dev/null
+++ b/comfyui/nodes.py
@@ -0,0 +1,941 @@
+# SPDX-License-Identifier: GPL-3.0-only
+# Copyright 2026 Data Archetype
+"""ComfyUI nodes for dflow_2b.
+
+A graph is: DFlow Loader -> DFlow Text Encode (or Layout Encode) -> DFlow
+Guider; DFlow Sampler -> DFlow Time Schedule; DFlow Empty Latent; then the
+stock RandomNoise, SamplerCustomAdvanced, VAEDecode and SaveImage nodes. Every
+default is the release's default preset (``dflow.inference.GenerationSettings``).
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from enum import StrEnum
+from pathlib import Path
+from typing import Protocol
+
+import comfy.model_management
+import torch
+from torch import Tensor
+
+from ..dflow.guidance import (
+ SELF_ATTENTION_GAIN_MAX,
+ SELF_ATTENTION_GAIN_MIN,
+ SUFFIX_CAPTION_BIAS_MAX,
+ SUFFIX_CAPTION_BIAS_MIN,
+ BezierPdgCurve,
+ CfgGuidance,
+ ConstantPdgScale,
+ EndpointCurveKind,
+ EndpointPdgCurve,
+ GuidanceSettings,
+ PdgGuidance,
+ PdgMode,
+ PdgScaleSchedule,
+ ProjectedGuidance,
+ ProjectionMode,
+ RampPdgScale,
+ SparseMiddleSteps,
+ SparseStepSchedule,
+ StepWindow,
+)
+from ..dflow.inference import (
+ DEFAULT_HEIGHT,
+ DEFAULT_WIDTH,
+ GenerationSettings,
+ SamplingSettings,
+)
+from ..dflow.layout import compile_layout, is_compiled_layout, is_stored_layout
+from ..dflow.prompt_emphasis import EmphasisMapping, EmphasisSettings
+from ..dflow.schedules import ScheduleKind, TimeSchedule
+from ..dflow.solvers import Solver
+from ..dflow.vae import LATENT_CHANNELS, LATENT_STRIDE
+from .loader import load_model, release_location
+from .preview import build_model_patcher
+from .sampling import DFlowGuider
+from .types import (
+ DFlowConditioning,
+ DFlowLatent,
+ DFlowModelHandle,
+ DFlowSamplerSpec,
+ DFlowTextEncoderHandle,
+ DFlowWeightSource,
+ PdgCurveChoice,
+ ScheduleBinding,
+)
+from .vae import DFlowVaeAdapter
+
+type InputTypes = dict[str, dict[str, tuple[object, ...]]]
+
+CATEGORY = "DFlow"
+MAX_BATCH = 16
+MAX_SIDE = 8192
+MAX_STEP_INDEX = 9999
+OPEN_STOP_STEP = -1
+"""A stop step of -1 runs a guidance window to the last step."""
+
+# Release defaults, read from the package so the nodes cannot drift from it.
+_GENERATION = GenerationSettings()
+_SAMPLING: SamplingSettings = _GENERATION.sampling
+_GUIDANCE: GuidanceSettings = _GENERATION.guidance
+_PDG = PdgGuidance()
+_PDG_SCALE = ConstantPdgScale().scale
+_EMPHASIS = EmphasisSettings()
+_ENDPOINT = EndpointPdgCurve()
+_RAMP = RampPdgScale()
+_BEZIER = BezierPdgCurve()
+_PROJECTION = ProjectedGuidance()
+_SPARSE = SparseMiddleSteps()
+_CFG_SCALE = 4.0
+
+
+def _choices[E: StrEnum](
+ members: type[E], default: E, tooltip: str
+) -> tuple[object, ...]:
+ """A combo input listing an enum's values."""
+
+ return (
+ [member.value for member in members],
+ {"default": default.value, "tooltip": tooltip},
+ )
+
+
+def _float(
+ default: float, low: float, high: float, step: float, tooltip: str
+) -> tuple[object, ...]:
+ """A FLOAT input."""
+
+ return (
+ "FLOAT",
+ {
+ "default": default,
+ "min": low,
+ "max": high,
+ "step": step,
+ "round": False,
+ "tooltip": tooltip,
+ },
+ )
+
+
+def _int(default: int, low: int, high: int, tooltip: str) -> tuple[object, ...]:
+ """An INT input."""
+
+ return (
+ "INT",
+ {"default": default, "min": low, "max": high, "step": 1, "tooltip": tooltip},
+ )
+
+
+def _bool(default: bool, tooltip: str) -> tuple[object, ...]:
+ """A BOOLEAN input."""
+
+ return ("BOOLEAN", {"default": default, "tooltip": tooltip})
+
+
+def _side(default: int, tooltip: str) -> tuple[object, ...]:
+ """An image side in pixels, a multiple of 16."""
+
+ return (
+ "INT",
+ {
+ "default": default,
+ "min": LATENT_STRIDE,
+ "max": MAX_SIDE,
+ "step": LATENT_STRIDE,
+ "tooltip": tooltip,
+ },
+ )
+
+
+def _window(start: int, stop: int) -> StepWindow:
+ """A guidance step window; ``stop`` -1 is open-ended.
+
+ Raises:
+ ValueError: For a stop below -1 or before the start.
+ """
+
+ if stop < OPEN_STOP_STEP:
+ raise ValueError(f"A stop step must be -1 or a step index, got {stop}.")
+ return StepWindow(start, None if stop == OPEN_STOP_STEP else stop)
+
+
+def _latent_size(latent: DFlowLatent) -> tuple[int, int]:
+ """``(width, height)`` in pixels of a dflow latent.
+
+ Raises:
+ ValueError: If the latent does not have 96 channels.
+ """
+
+ samples = latent["samples"]
+ if samples.ndim != 4 or int(samples.shape[1]) != LATENT_CHANNELS:
+ raise ValueError(
+ f"Expected a dflow latent [batch, {LATENT_CHANNELS}, height, width] "
+ f"(DFlow Empty Latent); got {tuple(samples.shape)}."
+ )
+ return int(samples.shape[3]) * LATENT_STRIDE, int(samples.shape[2]) * LATENT_STRIDE
+
+
+def _encode(
+ encoder: DFlowTextEncoderHandle,
+ prompts: tuple[str, ...],
+ emphasis: EmphasisSettings | None,
+) -> DFlowConditioning:
+ """Encode and refine a prompt batch (as ``DFlowEngine.prepare_texts``)."""
+
+ engine = encoder.model.engine
+ with torch.inference_mode():
+ text = engine.model.prepare_text(
+ engine.text_encoder.encode(list(prompts), emphasis=emphasis)
+ )
+ return DFlowConditioning(
+ model=encoder.model, prompts=prompts, text=text, emphasis=emphasis
+ )
+
+
+def _cfg(
+ enabled: bool, scale: float, window: StepWindow, pdg: PdgGuidance | None
+) -> CfgGuidance:
+ """CFG settings; the scale is kept when CFG or a CFG-using PDG mode runs."""
+
+ needed = enabled or (pdg is not None and pdg.mode.uses_cfg)
+ return CfgGuidance(enabled=enabled, scale=scale if needed else None, window=window)
+
+
+def _dflow_guider(guider: object) -> DFlowGuider:
+ """The dflow guider behind a GUIDER input.
+
+ Raises:
+ TypeError: For a guider of another node pack.
+ """
+
+ match guider:
+ case DFlowGuider():
+ return guider
+ case _:
+ raise TypeError(
+ f"Expected the guider of DFlow Guider, got {type(guider).__name__}."
+ )
+
+
+def _dflow_sampler(sampler: object) -> DFlowSamplerSpec:
+ """The dflow sampler behind a SAMPLER input.
+
+ Raises:
+ TypeError: For a sampler of another node pack.
+ """
+
+ match sampler:
+ case DFlowSamplerSpec():
+ return sampler
+ case _:
+ raise TypeError(
+ f"Expected the sampler of DFlow Sampler, got {type(sampler).__name__}."
+ )
+
+
+class DFlowLoader:
+ """Load the dflow_2b denoiser, text encoder and dinac3_96 autoencoder."""
+
+ DESCRIPTION = (
+ "bundled reads the weights in this node folder; local_dir another "
+ "release folder; hub a Hugging Face repository at a revision. The "
+ "autoencoder downloads from data-archetype/dinac3_96 on first use. "
+ "compile_model compiles the blocks (30 to 45 seconds on first use)."
+ )
+ RETURN_TYPES = ("DFLOW_MODEL", "DFLOW_TEXT_ENCODER", "VAE")
+ RETURN_NAMES = ("model", "text_encoder", "vae")
+ FUNCTION = "load"
+ CATEGORY = CATEGORY
+
+ @classmethod
+ def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API)
+ """Source, its location fields, compile switch and cache directory."""
+
+ return {
+ "required": {
+ "source": _choices(
+ DFlowWeightSource,
+ DFlowWeightSource.BUNDLED,
+ "Where the weights are read from.",
+ ),
+ "local_dir": (
+ "STRING",
+ {"default": "", "tooltip": "Release folder (local_dir only)."},
+ ),
+ "repository": (
+ "STRING",
+ {
+ "default": "data-archetype/dflow_2b",
+ "tooltip": "Hugging Face repository (hub only).",
+ },
+ ),
+ "revision": (
+ "STRING",
+ {"default": "", "tooltip": "Hub revision; empty for main."},
+ ),
+ "compile_model": _bool(True, "torch.compile the model (faster)."),
+ "cache_dir": (
+ "STRING",
+ {"default": "", "tooltip": "Hugging Face cache; empty: default."},
+ ),
+ }
+ }
+
+ def load(
+ self,
+ *,
+ source: str,
+ local_dir: str,
+ repository: str,
+ revision: str,
+ compile_model: bool,
+ cache_dir: str,
+ ) -> tuple[DFlowModelHandle, DFlowTextEncoderHandle, DFlowVaeAdapter]:
+ """Load the release onto ComfyUI's torch device."""
+
+ device = comfy.model_management.get_torch_device()
+ model = load_model(
+ release_location(
+ DFlowWeightSource(source), local_dir=local_dir, repository=repository
+ ),
+ device=device,
+ compile_model=compile_model,
+ revision=revision.strip() or None,
+ cache_dir=Path(cache_dir.strip()).expanduser()
+ if cache_dir.strip()
+ else None,
+ )
+ return (
+ model,
+ DFlowTextEncoderHandle(model),
+ DFlowVaeAdapter(model.components.vae, device=device),
+ )
+
+
+class DFlowTextEncode:
+ """Encode a prompt with the bundled text encoder."""
+
+ DESCRIPTION = (
+ "Plain prompts and compiled layout prompts. (phrase:weight) markup "
+ "weights a phrase when emphasis is on; quoted text is spelled out "
+ "character by character. Use DFlow Layout Encode for stored layouts."
+ )
+ RETURN_TYPES = ("DFLOW_CONDITIONING",)
+ RETURN_NAMES = ("conditioning",)
+ FUNCTION = "encode"
+ CATEGORY = f"{CATEGORY}/conditioning"
+
+ @classmethod
+ def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API)
+ """Text, batch size and the prompt-emphasis settings."""
+
+ return {
+ "required": {
+ "text_encoder": ("DFLOW_TEXT_ENCODER",),
+ "text": ("STRING", {"default": "", "multiline": True}),
+ "batch_size": _int(1, 1, MAX_BATCH, "Copies of the prompt."),
+ "emphasis": _bool(True, "Apply (phrase:weight) markup."),
+ "emphasis_mapping": _choices(
+ EmphasisMapping,
+ _EMPHASIS.mapping,
+ "Weight to attention-bias mapping for weights above 0.",
+ ),
+ "emphasis_strength": _float(
+ _EMPHASIS.strength, 0.0, 4.0, 0.05, "Multiplier on every weight."
+ ),
+ "emphasis_encoder": _bool(
+ _EMPHASIS.encoder, "Also weight inside the text encoder."
+ ),
+ }
+ }
+
+ def encode(
+ self,
+ *,
+ text_encoder: DFlowTextEncoderHandle,
+ text: str,
+ batch_size: int,
+ emphasis: bool,
+ emphasis_mapping: str,
+ emphasis_strength: float,
+ emphasis_encoder: bool,
+ ) -> tuple[DFlowConditioning]:
+ """Encode ``batch_size`` copies of the prompt.
+
+ Raises:
+ ValueError: For a stored layout (it needs the image size).
+ """
+
+ if is_stored_layout(text):
+ raise ValueError(
+ "This is a stored layout; use DFlow Layout Encode, which compiles "
+ "it at the image size."
+ )
+ settings = (
+ EmphasisSettings(
+ mapping=EmphasisMapping(emphasis_mapping),
+ strength=emphasis_strength,
+ encoder=emphasis_encoder,
+ )
+ if emphasis
+ else None
+ )
+ return (_encode(text_encoder, (text,) * batch_size, settings),)
+
+
+class DFlowLayoutEncode:
+ """Compile a stored layout at the image size and encode it."""
+
+ DESCRIPTION = (
+ "Takes the stored layout JSON (summary, frame, items with box_2d on a "
+ "0-1000 grid) or a compiled layout. width and height must match the "
+ "latent; the guider checks it."
+ )
+ RETURN_TYPES = ("DFLOW_CONDITIONING",)
+ RETURN_NAMES = ("conditioning",)
+ FUNCTION = "encode"
+ CATEGORY = f"{CATEGORY}/conditioning"
+
+ @classmethod
+ def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API)
+ """Layout JSON, image size and batch size."""
+
+ return {
+ "required": {
+ "text_encoder": ("DFLOW_TEXT_ENCODER",),
+ "layout_json": ("STRING", {"default": "", "multiline": True}),
+ "width": _side(DEFAULT_WIDTH, "Image width the layout is for."),
+ "height": _side(DEFAULT_HEIGHT, "Image height the layout is for."),
+ "batch_size": _int(1, 1, MAX_BATCH, "Copies of the prompt."),
+ }
+ }
+
+ def encode(
+ self,
+ *,
+ text_encoder: DFlowTextEncoderHandle,
+ layout_json: str,
+ width: int,
+ height: int,
+ batch_size: int,
+ ) -> tuple[DFlowConditioning]:
+ """Compile (or size-check) the layout and encode it verbatim.
+
+ Raises:
+ ValueError: If the text is not a layout, or for a malformed layout.
+ """
+
+ if not (is_stored_layout(layout_json) or is_compiled_layout(layout_json)):
+ raise ValueError(
+ "layout_json is not a layout (a JSON object with summary and "
+ "items); use DFlow Text Encode for plain prompts."
+ )
+ compiled = compile_layout(layout_json, width, height)
+ return (_encode(text_encoder, (compiled,) * batch_size, None),)
+
+
+class DFlowGuiderNode:
+ """Path-drop guidance (PDG), CFG and the self-attention gain."""
+
+ DESCRIPTION = (
+ "PDG compares the model with a copy that skips its middle layers. The "
+ "optional negative is read by CFG and the contrastive PDG modes; "
+ "without it they use the learned null text. The PDG reference reads "
+ "the prompt with a negative attention bias in its last six layers "
+ "(pdg_suffix_caption_bias). Step windows count solver steps from 0; a "
+ "stop step of -1 runs to the end."
+ )
+ RETURN_TYPES = ("GUIDER",)
+ RETURN_NAMES = ("guider",)
+ FUNCTION = "build"
+ CATEGORY = f"{CATEGORY}/sampling"
+
+ @classmethod
+ def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API)
+ """PDG, CFG, windows, the PDG suffix caption bias and the gain;
+ defaults are the release preset."""
+
+ return {
+ "required": {
+ "model": ("DFLOW_MODEL",),
+ "positive": ("DFLOW_CONDITIONING",),
+ "pdg_enabled": _bool(_GUIDANCE.pdg is not None, "Path-drop guidance."),
+ "pdg_mode": _choices(PdgMode, _PDG.mode, "PDG reference policy."),
+ "pdg_scale": _float(
+ _PDG_SCALE, 0.0, 30.0, 0.05, "PDG scale (1: none)."
+ ),
+ "pdg_start_step": _int(0, 0, MAX_STEP_INDEX, "First PDG step."),
+ "pdg_stop_step": _int(
+ OPEN_STOP_STEP, OPEN_STOP_STEP, MAX_STEP_INDEX, "Last PDG step."
+ ),
+ "pdg_suffix_caption_bias": _float(
+ _PDG.suffix_caption_bias,
+ SUFFIX_CAPTION_BIAS_MIN,
+ SUFFIX_CAPTION_BIAS_MAX,
+ 0.25,
+ "Attention-logit bias on the prompt's keys in the suffix layers "
+ "of the PDG reference (0: none).",
+ ),
+ "cfg_enabled": _bool(
+ _GUIDANCE.cfg.enabled, "Classifier-free guidance."
+ ),
+ "cfg_scale": _float(
+ _CFG_SCALE, 0.0, 30.0, 0.05, "CFG scale; also the CFG modes'."
+ ),
+ "cfg_start_step": _int(0, 0, MAX_STEP_INDEX, "First CFG step."),
+ "cfg_stop_step": _int(
+ OPEN_STOP_STEP, OPEN_STOP_STEP, MAX_STEP_INDEX, "Last CFG step."
+ ),
+ "self_attention_gain": _float(
+ _GUIDANCE.self_attention_gain,
+ SELF_ATTENTION_GAIN_MIN,
+ SELF_ATTENTION_GAIN_MAX,
+ 0.005,
+ "Image self-attention logit gain of the main pass.",
+ ),
+ },
+ "optional": {"negative": ("DFLOW_CONDITIONING",)},
+ }
+
+ def build(
+ self,
+ *,
+ model: DFlowModelHandle,
+ positive: DFlowConditioning,
+ pdg_enabled: bool,
+ pdg_mode: str,
+ pdg_scale: float,
+ pdg_start_step: int,
+ pdg_stop_step: int,
+ pdg_suffix_caption_bias: float,
+ cfg_enabled: bool,
+ cfg_scale: float,
+ cfg_start_step: int,
+ cfg_stop_step: int,
+ self_attention_gain: float,
+ negative: DFlowConditioning | None = None,
+ ) -> tuple[DFlowGuider]:
+ """Build the guider."""
+
+ pdg = (
+ PdgGuidance(
+ mode=PdgMode(pdg_mode),
+ scale=ConstantPdgScale(pdg_scale),
+ window=_window(pdg_start_step, pdg_stop_step),
+ suffix_caption_bias=pdg_suffix_caption_bias,
+ )
+ if pdg_enabled
+ else None
+ )
+ guidance = GuidanceSettings(
+ pdg=pdg,
+ cfg=_cfg(
+ cfg_enabled, cfg_scale, _window(cfg_start_step, cfg_stop_step), pdg
+ ),
+ self_attention_gain=self_attention_gain,
+ )
+ return (_guider(model, positive, negative, guidance),)
+
+
+def _guider(
+ model: DFlowModelHandle,
+ positive: DFlowConditioning,
+ negative: DFlowConditioning | None,
+ guidance: GuidanceSettings,
+) -> DFlowGuider:
+ """A guider with the model's preview patcher."""
+
+ return DFlowGuider(
+ model=model,
+ positive=positive,
+ negative=negative,
+ guidance=guidance,
+ model_patcher=build_model_patcher(model.preview, device=model.device),
+ )
+
+
+class DFlowGuiderAdvanced:
+ """Extra guidance controls on top of a DFlow Guider."""
+
+ DESCRIPTION = (
+ "pdg_curve replaces the constant PDG scale: ramp goes from "
+ "ramp_start_scale to ramp_end_scale over the first ramp_length of the "
+ "schedule; the endpoint curves go from curve_noisy_scale to "
+ "curve_clean_scale; bezier is 1 + bezier_multiplier times a fitted "
+ "curve. Projected guidance (APG) and rescale tame over-saturation and "
+ "exclude each other. Sparse middle steps run the main pass with one "
+ "token per 2x2 group through the middle layers (faster)."
+ )
+ RETURN_TYPES = ("GUIDER",)
+ RETURN_NAMES = ("guider",)
+ FUNCTION = "build"
+ CATEGORY = f"{CATEGORY}/sampling"
+
+ @classmethod
+ def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API)
+ """Curve, APG, rescale, sparse-step and guidance-gain controls."""
+
+ return {
+ "required": {
+ "guider": ("GUIDER",),
+ "guidance_self_attention_gain": _float(
+ _GUIDANCE.guidance_self_attention_gain,
+ SELF_ATTENTION_GAIN_MIN,
+ SELF_ATTENTION_GAIN_MAX,
+ 0.005,
+ "Self-attention gain of the guidance passes.",
+ ),
+ "pdg_curve": _choices(
+ PdgCurveChoice, PdgCurveChoice.CONSTANT, "PDG scale schedule."
+ ),
+ "curve_noisy_scale": _float(
+ _ENDPOINT.noisy_scale, 0.0, 30.0, 0.05, "Scale at the first step."
+ ),
+ "curve_clean_scale": _float(
+ _ENDPOINT.clean_scale, 0.0, 30.0, 0.05, "Scale at the last step."
+ ),
+ "curve_power": _float(_ENDPOINT.power, 0.01, 20.0, 0.05, "power."),
+ "s_curve_knee": _float(
+ _ENDPOINT.s_curve_knee, 0.0, 1.0, 0.01, "s_curve midpoint."
+ ),
+ "s_curve_sharpness": _float(
+ _ENDPOINT.s_curve_sharpness, 0.01, 50.0, 0.1, "s_curve slope."
+ ),
+ "ramp_start_scale": _float(
+ _RAMP.start_scale, 0.0, 30.0, 0.05, "Ramp scale at the noisy end."
+ ),
+ "ramp_end_scale": _float(
+ _RAMP.end_scale, 0.0, 30.0, 0.05, "Ramp scale after the ramp."
+ ),
+ "ramp_length": _float(
+ _RAMP.length, 0.01, 1.0, 0.01, "Fraction of the schedule."
+ ),
+ "bezier_multiplier": _float(
+ _BEZIER.multiplier, 0.0, 30.0, 0.05, "Bezier curve height."
+ ),
+ "projection": _choices(
+ ProjectionMode, _PROJECTION.mode, "Projected guidance (APG)."
+ ),
+ "projection_parallel_weight": _float(
+ _PROJECTION.parallel_weight, 0.0, 1.0, 0.01, "APG parallel part."
+ ),
+ "projection_first_band": _int(
+ _PROJECTION.first_band, 0, 4, "per_band: first projected band."
+ ),
+ "rescale": _float(
+ _GUIDANCE.rescale, 0.0, 1.0, 0.01, "Guidance rescale (0: off)."
+ ),
+ "sparse_middle_percent": _float(
+ _SPARSE.percent, 0.0, 100.0, 1.0, "Percent of sparse steps."
+ ),
+ "sparse_middle_schedule": _choices(
+ SparseStepSchedule, _SPARSE.schedule, "Which steps are sparse."
+ ),
+ }
+ }
+
+ def build(
+ self,
+ *,
+ guider: object,
+ guidance_self_attention_gain: float,
+ pdg_curve: str,
+ curve_noisy_scale: float,
+ curve_clean_scale: float,
+ curve_power: float,
+ s_curve_knee: float,
+ s_curve_sharpness: float,
+ ramp_start_scale: float,
+ ramp_end_scale: float,
+ ramp_length: float,
+ bezier_multiplier: float,
+ projection: str,
+ projection_parallel_weight: float,
+ projection_first_band: int,
+ rescale: float,
+ sparse_middle_percent: float,
+ sparse_middle_schedule: str,
+ ) -> tuple[DFlowGuider]:
+ """Return the input guider with these settings applied.
+
+ Raises:
+ TypeError: For a guider of another node pack.
+ ValueError: For a PDG curve with PDG off, or invalid settings.
+ """
+
+ base = _dflow_guider(guider)
+ curve = PdgCurveChoice(pdg_curve)
+ endpoint = EndpointPdgCurve(
+ kind=EndpointCurveKind.POWER,
+ noisy_scale=curve_noisy_scale,
+ clean_scale=curve_clean_scale,
+ power=curve_power,
+ s_curve_knee=s_curve_knee,
+ s_curve_sharpness=s_curve_sharpness,
+ )
+ ramp = RampPdgScale(ramp_start_scale, ramp_end_scale, ramp_length)
+ settings = replace(
+ base.guidance,
+ pdg=_with_curve(
+ base.guidance.pdg, curve, endpoint, ramp, bezier_multiplier
+ ),
+ guidance_self_attention_gain=guidance_self_attention_gain,
+ projection=ProjectedGuidance(
+ mode=ProjectionMode(projection),
+ parallel_weight=projection_parallel_weight,
+ first_band=projection_first_band,
+ ),
+ rescale=rescale,
+ sparse_middle=SparseMiddleSteps(
+ percent=sparse_middle_percent,
+ schedule=SparseStepSchedule(sparse_middle_schedule),
+ ),
+ )
+ return (base.with_guidance(settings),)
+
+
+def _with_curve(
+ pdg: PdgGuidance | None,
+ curve: PdgCurveChoice,
+ endpoint: EndpointPdgCurve,
+ ramp: RampPdgScale,
+ bezier_multiplier: float,
+) -> PdgGuidance | None:
+ """``pdg`` with its scale schedule replaced by the chosen curve.
+
+ Raises:
+ ValueError: For a curve other than constant while PDG is off.
+ """
+
+ if pdg is None:
+ if curve is not PdgCurveChoice.CONSTANT:
+ raise ValueError(f"pdg_curve {curve.value} needs PDG on in the guider.")
+ return None
+ scale: PdgScaleSchedule
+ match curve:
+ case PdgCurveChoice.CONSTANT:
+ scale = pdg.scale
+ case PdgCurveChoice.RAMP:
+ scale = ramp
+ case (
+ PdgCurveChoice.LINEAR
+ | PdgCurveChoice.LINEAR_LOGSNR
+ | PdgCurveChoice.POWER
+ | PdgCurveChoice.S_CURVE
+ ):
+ scale = replace(endpoint, kind=EndpointCurveKind(curve.value))
+ case PdgCurveChoice.BEZIER:
+ scale = BezierPdgCurve(multiplier=bezier_multiplier)
+ case _ as unreachable:
+ raise ValueError(f"Unsupported PDG curve: {unreachable}")
+ return replace(pdg, scale=scale)
+
+
+class DFlowSampler:
+ """Choose dflow's solver and its noise scale."""
+
+ DESCRIPTION = (
+ "noise_scale multiplies the injected noise of the stochastic solvers "
+ "(eta for dpmpp_2m_sde); deterministic solvers ignore it. Connect it "
+ "to DFlow Time Schedule, whose sampler output goes to "
+ "SamplerCustomAdvanced."
+ )
+ RETURN_TYPES = ("SAMPLER",)
+ RETURN_NAMES = ("sampler",)
+ FUNCTION = "build"
+ CATEGORY = f"{CATEGORY}/sampling"
+
+ @classmethod
+ def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API)
+ """Solver and noise scale."""
+
+ return {
+ "required": {
+ "solver": _choices(Solver, _SAMPLING.solver, "Numerical solver."),
+ "noise_scale": _float(
+ _SAMPLING.noise_scale, 0.0, 10.0, 0.05, "SDE noise multiplier."
+ ),
+ }
+ }
+
+ def build(self, *, solver: str, noise_scale: float) -> tuple[DFlowSamplerSpec]:
+ """The sampler, not yet paired with a schedule."""
+
+ return (DFlowSamplerSpec(Solver(solver), noise_scale, binding=None),)
+
+
+def _schedule_inputs(steps_min: int) -> dict[str, tuple[object, ...]]:
+ """Inputs shared by the schedule nodes."""
+
+ schedule = _SAMPLING.schedule
+ return {
+ "sampler": ("SAMPLER",),
+ "latent": ("LATENT",),
+ "schedule": _choices(ScheduleKind, schedule.kind, "Step spacing."),
+ "steps": _int(schedule.steps, steps_min, 1000, "Solver steps."),
+ "base_log_snr_shift": _float(
+ _SAMPLING.base_log_snr_shift, -20.0, 20.0, 0.05, "Size-free shift."
+ ),
+ "resolution_shift": _bool(
+ _SAMPLING.resolution_shift, "Add the trained image-size shift."
+ ),
+ "beta_mean": _float(schedule.beta_mean, 0.01, 0.99, 0.01, "custom_beta."),
+ "beta_concentration": _float(
+ schedule.beta_concentration, 0.01, 100.0, 0.05, "custom_beta."
+ ),
+ }
+
+
+def _full_schedule(
+ sampler: object,
+ latent: DFlowLatent,
+ schedule: TimeSchedule,
+ base_log_snr_shift: float,
+ resolution_shift: bool,
+) -> tuple[Tensor, DFlowSamplerSpec]:
+ """The full CPU schedule for the latent's size and the bound sampler.
+
+ The schedule is computed on the model's device, as the package does, then
+ copied to the CPU.
+ """
+
+ spec = _dflow_sampler(sampler)
+ width, height = _latent_size(latent)
+ sampling = SamplingSettings(
+ solver=spec.solver,
+ noise_scale=spec.noise_scale,
+ schedule=schedule,
+ base_log_snr_shift=base_log_snr_shift,
+ resolution_shift=resolution_shift,
+ )
+ device = comfy.model_management.get_torch_device()
+ sigmas = sampling.timesteps(width, height, device).cpu()
+ binding = ScheduleBinding(
+ schedule=schedule,
+ log_snr_shift=sampling.log_snr_shift(width, height),
+ width=width,
+ height=height,
+ )
+ return sigmas, spec.bound(binding)
+
+
+class DFlowTimeSchedule:
+ """Build dflow's timestep schedule for the latent's size."""
+
+ DESCRIPTION = (
+ "Connect both outputs to SamplerCustomAdvanced. The shift moves steps "
+ "toward the noisy end; with resolution_shift the trained image-size "
+ "term -ln(width*height/256^2) is added (capped at 0)."
+ )
+ RETURN_TYPES = ("SIGMAS", "SAMPLER")
+ RETURN_NAMES = ("sigmas", "sampler")
+ FUNCTION = "build"
+ CATEGORY = f"{CATEGORY}/sampling"
+
+ @classmethod
+ def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API)
+ """Sampler, latent, schedule family, steps and shift."""
+
+ return {"required": _schedule_inputs(steps_min=1)}
+
+ def build(
+ self,
+ *,
+ sampler: object,
+ latent: DFlowLatent,
+ schedule: str,
+ steps: int,
+ base_log_snr_shift: float,
+ resolution_shift: bool,
+ beta_mean: float,
+ beta_concentration: float,
+ ) -> tuple[Tensor, DFlowSamplerSpec]:
+ """The schedule and the sampler paired with it."""
+
+ return _full_schedule(
+ sampler,
+ latent,
+ TimeSchedule(ScheduleKind(schedule), steps, beta_mean, beta_concentration),
+ base_log_snr_shift,
+ resolution_shift,
+ )
+
+
+class DFlowEmptyLatent:
+ """An empty 96-channel dflow latent."""
+
+ RETURN_TYPES = ("LATENT",)
+ RETURN_NAMES = ("latent",)
+ FUNCTION = "create"
+ CATEGORY = f"{CATEGORY}/latent"
+
+ @classmethod
+ def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API)
+ """Image size and batch size."""
+
+ return {
+ "required": {
+ "width": _side(_GENERATION.width, "Image width (multiple of 16)."),
+ "height": _side(_GENERATION.height, "Image height (multiple of 16)."),
+ "batch_size": _int(1, 1, MAX_BATCH, "Images per run."),
+ }
+ }
+
+ def create(self, *, width: int, height: int, batch_size: int) -> tuple[DFlowLatent]:
+ """Zeros ``[batch, 96, height / 16, width / 16]`` on the CPU.
+
+ Raises:
+ ValueError: For a side that is not a multiple of 16.
+ """
+
+ for name, value in (("width", width), ("height", height)):
+ if value <= 0 or value % LATENT_STRIDE:
+ raise ValueError(
+ f"{name} must be a positive multiple of {LATENT_STRIDE}, "
+ f"got {value}."
+ )
+ samples = torch.zeros(
+ (
+ batch_size,
+ LATENT_CHANNELS,
+ height // LATENT_STRIDE,
+ width // LATENT_STRIDE,
+ ),
+ dtype=torch.float32,
+ device="cpu",
+ )
+ return ({"samples": samples, "downscale_ratio_spacial": LATENT_STRIDE},)
+
+
+class ComfyNodeClass(Protocol):
+ """What ComfyUI reads from a node class (beyond its declared constants)."""
+
+ @classmethod
+ def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API)
+ """The node's inputs."""
+ ...
+
+
+NODE_CLASS_MAPPINGS: dict[str, type[ComfyNodeClass]] = {
+ "DFlowLoader": DFlowLoader,
+ "DFlowTextEncode": DFlowTextEncode,
+ "DFlowLayoutEncode": DFlowLayoutEncode,
+ "DFlowGuider": DFlowGuiderNode,
+ "DFlowGuiderAdvanced": DFlowGuiderAdvanced,
+ "DFlowSampler": DFlowSampler,
+ "DFlowTimeSchedule": DFlowTimeSchedule,
+ "DFlowEmptyLatent": DFlowEmptyLatent,
+}
+
+NODE_DISPLAY_NAME_MAPPINGS: dict[str, str] = {
+ "DFlowLoader": "DFlow Loader",
+ "DFlowTextEncode": "DFlow Text Encode",
+ "DFlowLayoutEncode": "DFlow Layout Encode",
+ "DFlowGuider": "DFlow Guider",
+ "DFlowGuiderAdvanced": "DFlow Guider Advanced",
+ "DFlowSampler": "DFlow Sampler",
+ "DFlowTimeSchedule": "DFlow Time Schedule",
+ "DFlowEmptyLatent": "DFlow Empty Latent",
+}
diff --git a/comfyui/preview.py b/comfyui/preview.py
new file mode 100644
index 0000000000000000000000000000000000000000..80772a90eb46fdb6607e09cad6bf774155fbf5f8
--- /dev/null
+++ b/comfyui/preview.py
@@ -0,0 +1,101 @@
+# SPDX-License-Identifier: GPL-3.0-only
+# Copyright 2026 Data Archetype
+"""Live sampling previews and the minimal model surface ComfyUI's custom
+sampler node reads from a guider.
+
+ComfyUI's ``Latent2RGBPreviewer`` applies a per-pixel linear map after an
+optional reshape hook. dflow's preview is a 3x3 convolution to 2x2 RGB cells,
+so the hook runs that projection and the linear map is the identity.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from comfy.latent_formats import LatentFormat
+
+from ..dflow.vae import LATENT_CHANNELS, LATENT_STRIDE
+
+if TYPE_CHECKING:
+ import torch
+ from torch import Tensor
+
+ from ..dflow.preview import LatentRgbPreview
+
+_RGB_IDENTITY = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
+
+
+class DFlowLatentFormat(LatentFormat):
+ """dflow's latent format: 96 whitened channels at stride 16, unscaled."""
+
+ latent_channels = LATENT_CHANNELS
+ spacial_downscale_ratio = LATENT_STRIDE
+ scale_factor = 1.0
+ latent_rgb_factors = _RGB_IDENTITY
+
+ def __init__(self, preview: LatentRgbPreview) -> None:
+ """Use ``preview`` (on the sampling device) for live previews."""
+
+ self.preview = preview
+ self.latent_rgb_factors_reshape = self.project_first
+
+ def project_first(self, latents: Tensor) -> Tensor:
+ """RGB ``[1, 3, 2h, 2w]`` in ``[-1, 1]`` of the batch's first latent
+ (the previewer shows only that one)."""
+
+ return self.preview.project(latents[:1])
+
+ def process_in(self, latent: Tensor) -> Tensor:
+ """dflow latents enter the model unchanged."""
+
+ return latent
+
+ def process_out(self, latent: Tensor) -> Tensor:
+ """dflow latents leave the model unchanged."""
+
+ return latent
+
+
+class DFlowPreviewModel:
+ """The ``model_patcher.model`` attributes the custom sampler reads."""
+
+ def __init__(self, latent_format: DFlowLatentFormat) -> None:
+ self.latent_format = latent_format
+
+ @staticmethod
+ def process_latent_out(latents: Tensor) -> Tensor:
+ """Denoised latents are already in dflow's latent space."""
+
+ return latents
+
+
+class DFlowModelPatcher:
+ """The ``guider.model_patcher`` surface ``SamplerCustomAdvanced`` uses:
+ the device, the latent format and the preview model."""
+
+ def __init__(self, *, device: torch.device, model: DFlowPreviewModel) -> None:
+ self.load_device = device
+ self.model = model
+
+ def get_model_object(self, name: str) -> DFlowLatentFormat:
+ """Return the latent format (the only object dflow exposes).
+
+ Raises:
+ KeyError: For any other name.
+ """
+
+ match name:
+ case "latent_format":
+ return self.model.latent_format
+ case _:
+ raise KeyError(f"dflow does not expose the model object {name!r}.")
+
+
+def build_model_patcher(
+ preview: LatentRgbPreview, *, device: torch.device
+) -> DFlowModelPatcher:
+ """The preview-only model patcher of a dflow guider."""
+
+ return DFlowModelPatcher(
+ device=device, model=DFlowPreviewModel(DFlowLatentFormat(preview))
+ )
diff --git a/comfyui/sampling.py b/comfyui/sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3299404274f78609ad0d8246339e7871fc585ae
--- /dev/null
+++ b/comfyui/sampling.py
@@ -0,0 +1,400 @@
+# SPDX-License-Identifier: GPL-3.0-only
+# Copyright 2026 Data Archetype
+"""The dflow guider: ``dflow``'s guidance plan and solver behind ComfyUI's
+GUIDER interface, driven by the stock ``SamplerCustomAdvanced`` node.
+
+Noise and seed contract (the same as ``dflow.inference``):
+
+- The initial noise is the NOISE input's tensor. Stock ``RandomNoise`` draws
+ it with ``torch.randn`` of the latent shape from a CPU generator seeded with
+ its seed, which is exactly the noise ``DFlowEngine.sample`` draws for that
+ seed, so a stock graph reproduces the package bit for bit.
+- Stochastic solvers draw from a fresh CPU generator seeded with the NOISE
+ node's seed; the three-quarter routing from a CUDA generator with that seed.
+- A schedule that starts at the noisy end (``t >= 1 - 1e-4``) starts from the
+ noise alone, as ``DFlowEngine.sample`` does without image-to-image; the
+ latent input is ignored there, as stock samplers ignore it at full denoise.
+ A schedule that starts later (a sliced SIGMAS) noises the latent to
+ its first time, ``(1 - t) latent + t noise``, as ``ImageToImage`` does.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import replace
+from typing import TYPE_CHECKING
+
+import comfy.sampler_helpers
+import torch
+from torch import Tensor
+
+from ..dflow.guidance import (
+ BranchCall,
+ BranchText,
+ GuidancePlan,
+ GuidanceSettings,
+ build_guidance_plan,
+ check_three_quarter_size,
+)
+from ..dflow.layout import compile_layout, is_compiled_layout
+from ..dflow.modeling import PreparedText, self_attention_gain_tensor
+from ..dflow.schedules import FINITE_NOISY_ENDPOINT_EPSILON
+from ..dflow.solvers import solve, solver_is_stochastic
+from ..dflow.types import DFlowPath
+from ..dflow.vae import LATENT_CHANNELS, LATENT_STRIDE
+from .types import (
+ DFlowConditioning,
+ DFlowModelHandle,
+ DFlowSamplerSpec,
+ ScheduleBinding,
+)
+
+if TYPE_CHECKING:
+ from .preview import DFlowModelPatcher
+
+ComfySamplerCallback = Callable[[int, Tensor, Tensor, int], None]
+VelocityFn = Callable[[Tensor, Tensor, int], Tensor]
+
+# First schedule times at or above this start from the noise alone.
+NOISE_START_TIME = float(
+ torch.tensor(1.0 - FINITE_NOISY_ENDPOINT_EPSILON, dtype=torch.float32)
+)
+
+
+class DFlowGuider:
+ """Guided dflow sampling for ``SamplerCustomAdvanced``.
+
+ Args:
+ model: The loaded model.
+ positive: The prompt conditioning.
+ negative: The negative conditioning, or None for the learned null
+ text (used only by CFG and the contrastive PDG modes).
+ guidance: Validated guidance settings.
+ model_patcher: Preview surface ComfyUI reads from the guider.
+
+ Raises:
+ ValueError: If a conditioning came from another model or the batches
+ differ.
+ """
+
+ def __init__(
+ self,
+ *,
+ model: DFlowModelHandle,
+ positive: DFlowConditioning,
+ negative: DFlowConditioning | None,
+ guidance: GuidanceSettings,
+ model_patcher: DFlowModelPatcher,
+ ) -> None:
+ _require_model(model, positive, "positive")
+ if negative is not None:
+ _require_model(model, negative, "negative")
+ if negative.batch != positive.batch:
+ raise ValueError(
+ f"The negative conditioning has batch {negative.batch}, the "
+ f"positive {positive.batch}; set the same batch_size on both."
+ )
+ self.model = model
+ self.positive = positive
+ self.negative = negative
+ self.guidance = guidance
+ self.model_patcher = model_patcher
+
+ def with_guidance(self, guidance: GuidanceSettings) -> DFlowGuider:
+ """A guider with the same model and conditioning and new settings."""
+
+ return DFlowGuider(
+ model=self.model,
+ positive=self.positive,
+ negative=self.negative,
+ guidance=guidance,
+ model_patcher=self.model_patcher,
+ )
+
+ def sample(
+ self,
+ noise: Tensor,
+ latent_image: Tensor,
+ sampler: object,
+ sigmas: Tensor,
+ *,
+ denoise_mask: Tensor | None = None,
+ callback: ComfySamplerCallback | None = None,
+ disable_pbar: bool = False,
+ seed: int | None = None,
+ ) -> Tensor:
+ """Sample latents (ComfyUI's ``GUIDER.sample`` signature).
+
+ Args:
+ noise: ``[B, 96, h, w]`` initial noise from the NOISE node.
+ latent_image: ``[B, 96, h, w]`` start latents (zeros for an empty
+ latent).
+ sampler: The SAMPLER output of ``DFlow Time Schedule`` or
+ a sliced schedule.
+ sigmas: The descending schedule from the same node.
+ denoise_mask: ComfyUI noise mask, or None.
+ callback: ComfyUI's per-step preview and progress callback.
+ disable_pbar: Unused (ComfyUI reports progress via ``callback``).
+ seed: The NOISE node's seed.
+
+ Returns:
+ Float32 latents ``[B, 96, h, w]`` on the model's device.
+
+ Raises:
+ TypeError: For a sampler that is not a scheduled dflow sampler or a
+ missing seed.
+ ValueError: For inconsistent shapes, sizes or layout prompts.
+ """
+
+ del disable_pbar
+ spec, binding = _scheduled_sampler(sampler)
+ seed_value = _require_seed(seed)
+ self._validate_inputs(noise, latent_image, binding)
+ device = self.model.device
+ with torch.inference_mode():
+ timesteps = sigmas.to(device=device, dtype=torch.float32).contiguous()
+ host_times = timesteps.tolist()
+ plan = self._plan(binding, host_times)
+ device_noise = noise.to(device=device, dtype=torch.float32)
+ device_latent = latent_image.to(device=device, dtype=torch.float32)
+ velocity = self._velocity(plan, seed_value, len(noise))
+ if denoise_mask is not None:
+ velocity = _masked(
+ velocity,
+ latent=device_latent,
+ noise=device_noise,
+ mask=comfy.sampler_helpers.prepare_mask(
+ denoise_mask, noise.shape, device
+ ).to(dtype=torch.float32),
+ )
+ return solve(
+ velocity,
+ _start_state(device_noise, device_latent, timesteps, host_times[0]),
+ timesteps,
+ solver=spec.solver,
+ noise_scale=spec.noise_scale,
+ generator=(
+ torch.Generator(device="cpu").manual_seed(seed_value)
+ if solver_is_stochastic(spec.solver)
+ else None
+ ),
+ callback=_comfy_callback(callback),
+ )
+
+ def _validate_inputs(
+ self, noise: Tensor, latent_image: Tensor, binding: ScheduleBinding
+ ) -> None:
+ """Check shapes, batch, the schedule's size and layout prompt sizes.
+
+ Raises:
+ ValueError: On any mismatch.
+ """
+
+ if noise.ndim != 4 or int(noise.shape[1]) != LATENT_CHANNELS:
+ raise ValueError(
+ f"dflow samples [batch, {LATENT_CHANNELS}, height, width] latents; "
+ f"got noise of shape {tuple(noise.shape)}."
+ )
+ if tuple(latent_image.shape) != tuple(noise.shape):
+ raise ValueError(
+ f"The latent {tuple(latent_image.shape)} and the noise "
+ f"{tuple(noise.shape)} differ in shape."
+ )
+ if int(noise.shape[0]) != self.positive.batch:
+ raise ValueError(
+ f"The latent batch is {noise.shape[0]} but the conditioning holds "
+ f"{self.positive.batch} prompts; set the same batch_size on the "
+ "text encode and latent nodes."
+ )
+ width = int(noise.shape[3]) * LATENT_STRIDE
+ height = int(noise.shape[2]) * LATENT_STRIDE
+ if (binding.width, binding.height) != (width, height):
+ raise ValueError(
+ f"The schedule was built for {binding.width}x{binding.height} but "
+ f"the latent is {width}x{height}; connect the sampled latent to "
+ "the schedule node."
+ )
+ check_three_quarter_size(self.guidance, width, height)
+ conditionings = (
+ [self.positive]
+ if self.negative is None
+ else [
+ self.positive,
+ self.negative,
+ ]
+ )
+ for conditioning in conditionings:
+ for prompt in conditioning.prompts:
+ if is_compiled_layout(prompt):
+ compile_layout(prompt, width, height)
+
+ def _plan(self, binding: ScheduleBinding, host_times: list[float]) -> GuidancePlan:
+ """The guidance plan over ``host_times`` (as ``DFlowEngine.sample``)."""
+
+ return build_guidance_plan(
+ self.guidance,
+ schedule=replace(binding.schedule, steps=len(host_times) - 1),
+ log_snr_shift=binding.log_snr_shift,
+ timesteps=host_times,
+ )
+
+ def _texts(self, batch: int) -> dict[BranchText, PreparedText]:
+ """The positive text and, when guidance needs it, the negative text
+ (the learned null text when no negative is connected)."""
+
+ texts = {BranchText.POSITIVE: self.positive.text}
+ if self.guidance.uses_negative:
+ texts[BranchText.NEGATIVE] = (
+ self.negative.text
+ if self.negative is not None
+ else _null_text(self.model, batch)
+ )
+ return texts
+
+ def _velocity(self, plan: GuidancePlan, seed: int, batch: int) -> VelocityFn:
+ """The guided velocity function the solver integrates."""
+
+ model = self.model.engine.model
+ device = self.model.device
+ texts = self._texts(batch)
+ routing = torch.Generator(device=device).manual_seed(seed)
+ gains: dict[float, Tensor] = {}
+
+ def evaluate_at(state: Tensor, time: Tensor) -> Callable[[BranchCall], Tensor]:
+ def evaluate(call: BranchCall) -> Tensor:
+ path = call.branch.path
+ if call.self_attention_gain not in gains:
+ gains[call.self_attention_gain] = self_attention_gain_tensor(
+ call.self_attention_gain, device=device
+ )
+ return model(
+ state,
+ time,
+ texts[call.branch.text],
+ path=path,
+ self_attention_gain=gains[call.self_attention_gain],
+ suffix_caption_bias=call.suffix_caption_bias,
+ generator=routing if path is DFlowPath.THREE_QUARTER else None,
+ )
+
+ return evaluate
+
+ def velocity(state: Tensor, time: Tensor, index: int) -> Tensor:
+ return plan.guided_velocity(index, state, time, evaluate_at(state, time))
+
+ return velocity
+
+
+def _require_model(
+ model: DFlowModelHandle, conditioning: DFlowConditioning, name: str
+) -> None:
+ """Require conditioning encoded by ``model``.
+
+ Raises:
+ ValueError: Otherwise.
+ """
+
+ if conditioning.model is not model:
+ raise ValueError(
+ f"The {name} conditioning was encoded by a different DFlow Loader; "
+ "connect the text encoder and model outputs of the same loader."
+ )
+
+
+def _scheduled_sampler(sampler: object) -> tuple[DFlowSamplerSpec, ScheduleBinding]:
+ """The dflow sampler and the schedule it is paired with.
+
+ Raises:
+ TypeError: If ``sampler`` is not a dflow sampler with a schedule.
+ """
+
+ match sampler:
+ case DFlowSamplerSpec(binding=None):
+ raise TypeError(
+ "Connect the sampler output of DFlow Time Schedule to "
+ "SamplerCustomAdvanced, not the DFlow Sampler "
+ "output: guidance needs the schedule the sigmas came from."
+ )
+ case DFlowSamplerSpec(binding=ScheduleBinding() as binding) as spec:
+ return spec, binding
+ case _:
+ raise TypeError(
+ "The dflow guider runs dflow's own solvers; connect the sampler "
+ f"output of DFlow Time Schedule, not {type(sampler).__name__}."
+ )
+
+
+def _require_seed(seed: int | None) -> int:
+ """The NOISE node's seed.
+
+ Raises:
+ TypeError: If the noise source has no integer seed.
+ """
+
+ if seed is None or isinstance(seed, bool) or not isinstance(seed, int):
+ raise TypeError(
+ "dflow sampling needs the integer seed of a NOISE node such as "
+ f"RandomNoise; got {seed!r}."
+ )
+ return seed
+
+
+def _null_text(model: DFlowModelHandle, batch: int) -> PreparedText:
+ """The learned null text for ``batch`` rows, refined."""
+
+ engine = model.engine
+ return engine.model.prepare_text(
+ engine.text_encoder.encode([""] * batch, emphasis=None)
+ )
+
+
+def _start_state(
+ noise: Tensor, latent: Tensor, timesteps: Tensor, first_time: float
+) -> Tensor:
+ """The solver's initial state (see the module docstring)."""
+
+ if first_time >= NOISE_START_TIME:
+ return noise.contiguous(memory_format=torch.channels_last)
+ time = timesteps[0]
+ return ((1.0 - time) * latent + time * noise).contiguous(
+ memory_format=torch.channels_last
+ )
+
+
+def _masked(
+ velocity: VelocityFn, *, latent: Tensor, noise: Tensor, mask: Tensor
+) -> VelocityFn:
+ """Keep the latent outside the mask.
+
+ There the velocity is the one whose clean estimate is the latent at the
+ current state, ``(x_t - latent) / t``, so the region returns to the latent
+ even after a stochastic solver injects noise; at ``t = 0`` it is the
+ straight-path velocity ``noise - latent``.
+ """
+
+ straight = noise - latent
+
+ def masked(state: Tensor, time: Tensor, index: int) -> Tensor:
+ t = time.to(dtype=state.dtype).view(-1, 1, 1, 1)
+ kept = torch.where(
+ t > 0.0,
+ (state - latent) / t.clamp_min(torch.finfo(state.dtype).tiny),
+ straight,
+ )
+ return mask * velocity(state, time, index) + (1.0 - mask) * kept
+
+ return masked
+
+
+def _comfy_callback(
+ callback: ComfySamplerCallback | None,
+) -> Callable[[Tensor, int, int], None] | None:
+ """Forward each update's clean estimate to ComfyUI's preview callback."""
+
+ if callback is None:
+ return None
+
+ def publish(predicted_x0: Tensor, completed: int, total: int) -> None:
+ callback(completed - 1, predicted_x0, predicted_x0, total)
+
+ return publish
diff --git a/comfyui/types.py b/comfyui/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..6eab91dabad92f1c0cd07dd751c547e48b5a3cdb
--- /dev/null
+++ b/comfyui/types.py
@@ -0,0 +1,166 @@
+# SPDX-License-Identifier: GPL-3.0-only
+# Copyright 2026 Data Archetype
+"""Values passed between the dflow ComfyUI nodes.
+
+Every handle is a frozen dataclass around ``dflow`` objects; the nodes never
+hand ComfyUI anything untyped except the latent mapping ComfyUI itself
+defines.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, replace
+from enum import StrEnum
+from typing import TYPE_CHECKING, TypedDict
+
+if TYPE_CHECKING:
+ import torch
+ from torch import Tensor
+
+ from ..dflow.inference import DFlowEngine
+ from ..dflow.modeling import PreparedText
+ from ..dflow.pipeline import DFlowComponents
+ from ..dflow.preview import LatentRgbPreview
+ from ..dflow.prompt_emphasis import EmphasisSettings
+ from ..dflow.schedules import TimeSchedule
+ from ..dflow.solvers import Solver
+
+
+class DFlowWeightSource(StrEnum):
+ """Where the loader node reads the release from.
+
+ BUNDLED: the node folder itself (the Hugging Face repository checkout).
+ LOCAL_DIR: another local release directory.
+ HUB: a Hugging Face repository at a revision.
+ """
+
+ BUNDLED = "bundled"
+ LOCAL_DIR = "local_dir"
+ HUB = "hub"
+
+
+class PdgCurveChoice(StrEnum):
+ """PDG scale schedules offered by the advanced guider node.
+
+ CONSTANT: the guider's constant PDG scale.
+ RAMP: linear in the schedule quantile from a start to an end scale.
+ LINEAR, LINEAR_LOGSNR, POWER, S_CURVE: per-step endpoint curves.
+ BEZIER: the cubic Bezier curve over flow time.
+ """
+
+ CONSTANT = "constant"
+ RAMP = "ramp"
+ LINEAR = "linear"
+ LINEAR_LOGSNR = "linear_logsnr"
+ POWER = "power"
+ S_CURVE = "s_curve"
+ BEZIER = "bezier"
+
+
+class DFlowLatent(TypedDict):
+ """ComfyUI's latent mapping for dflow latents ``[B, 96, H/16, W/16]``."""
+
+ samples: Tensor
+ downscale_ratio_spacial: int
+
+
+@dataclass(frozen=True)
+class DFlowModelHandle:
+ """The loaded release and the preview projection on its device.
+
+ Attributes:
+ components: Denoiser, text encoder and autoencoder.
+ preview: Latent-to-RGB preview projection on the model's device.
+ """
+
+ components: DFlowComponents
+ preview: LatentRgbPreview
+
+ @property
+ def engine(self) -> DFlowEngine:
+ """The sampling engine (denoiser and text encoder)."""
+
+ return self.components.engine
+
+ @property
+ def device(self) -> torch.device:
+ """The CUDA device the model runs on."""
+
+ return self.components.engine.device
+
+
+@dataclass(frozen=True)
+class DFlowTextEncoderHandle:
+ """The text-encoder output of the loader; encodes for one model."""
+
+ model: DFlowModelHandle
+
+
+@dataclass(frozen=True)
+class DFlowConditioning:
+ """An encoded and refined prompt batch.
+
+ Attributes:
+ model: The model that encoded it (guiders reject other models').
+ prompts: The texts the encoder read, one per batch row (layouts in
+ their compiled form).
+ text: The refined text tokens.
+ emphasis: The prompt-emphasis settings used, or None for verbatim.
+ """
+
+ model: DFlowModelHandle
+ prompts: tuple[str, ...]
+ text: PreparedText
+ emphasis: EmphasisSettings | None
+
+ @property
+ def batch(self) -> int:
+ """Number of prompts (latents) in the batch."""
+
+ return len(self.prompts)
+
+
+@dataclass(frozen=True)
+class ScheduleBinding:
+ """The schedule a SIGMAS tensor was built from, as guidance needs it.
+
+ The quantile ramp and the linear-logSNR curve read the schedule family and
+ the shift; the size check ties the shift to the latent being sampled.
+
+ Attributes:
+ schedule: Family and beta parameters (``steps`` is the full count).
+ log_snr_shift: Effective shift the schedule was built with.
+ width: Image width the shift was computed for.
+ height: Image height the shift was computed for.
+ """
+
+ schedule: TimeSchedule
+ log_snr_shift: float
+ width: int
+ height: int
+
+
+@dataclass(frozen=True)
+class DFlowSamplerSpec:
+ """The SAMPLER value: solver, noise scale and, once a dflow schedule node
+ has seen it, the schedule it is paired with.
+
+ Raises:
+ ValueError: For a negative or non-finite noise scale.
+ """
+
+ solver: Solver
+ noise_scale: float
+ binding: ScheduleBinding | None = None
+
+ def __post_init__(self) -> None:
+ """Validate the noise scale."""
+
+ if not math.isfinite(self.noise_scale) or self.noise_scale < 0.0:
+ raise ValueError(f"noise_scale must be >= 0, got {self.noise_scale}.")
+
+ def bound(self, binding: ScheduleBinding) -> DFlowSamplerSpec:
+ """Return this sampler paired with a schedule."""
+
+ return replace(self, binding=binding)
diff --git a/comfyui/vae.py b/comfyui/vae.py
new file mode 100644
index 0000000000000000000000000000000000000000..d41acb559c58b8705497c0ea4da7bc2e8bb22e3c
--- /dev/null
+++ b/comfyui/vae.py
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: GPL-3.0-only
+# Copyright 2026 Data Archetype
+"""The dinac3_96 autoencoder behind ComfyUI's VAE interface.
+
+Stock ``VAEDecode`` and ``VAEEncode`` call ``decode(latents)`` and
+``encode(pixels)``; ComfyUI images are ``[B, H, W, C]`` floats in ``[0, 1]``.
+"""
+
+from __future__ import annotations
+
+import comfy.model_management
+import torch
+from torch import Tensor
+
+from ..dflow.vae import LATENT_CHANNELS, LATENT_STRIDE, DFlowVae
+
+_RGB_CHANNELS = 3
+
+
+class DFlowVaeAdapter:
+ """``DFlowVae`` with ComfyUI's decode/encode conventions."""
+
+ latent_channels = LATENT_CHANNELS
+ latent_dim = 2
+
+ def __init__(self, vae: DFlowVae, *, device: torch.device) -> None:
+ """Wrap a loaded autoencoder that runs on ``device``."""
+
+ self.vae = vae
+ self.device = device
+
+ def decode(self, latents: Tensor) -> Tensor:
+ """Decode ``[B, 96, h, w]`` latents to ``[B, 16h, 16w, 3]`` images.
+
+ Raises:
+ ValueError: If the latents do not have 96 channels.
+ """
+
+ if latents.ndim != 4 or int(latents.shape[1]) != LATENT_CHANNELS:
+ raise ValueError(
+ f"dflow latents have shape [batch, {LATENT_CHANNELS}, height, "
+ f"width]; got {tuple(latents.shape)}. Use the dflow VAE only with "
+ "dflow latents."
+ )
+ device_latents = latents.to(device=self.device, dtype=torch.float32)
+ rgb = self.vae.decode(
+ device_latents.contiguous(memory_format=torch.channels_last)
+ ).clamp(-1.0, 1.0)
+ images = rgb.add(1.0).mul(0.5).movedim(1, -1)
+ return images.to(comfy.model_management.intermediate_device())
+
+ def encode(self, pixels: Tensor) -> Tensor:
+ """Encode ``[B, H, W, C]`` images (RGB first) to ``[B, 96, H/16, W/16]``.
+
+ Raises:
+ ValueError: If the image has fewer than three channels, or a side
+ is not a multiple of 16.
+ """
+
+ if pixels.ndim != 4 or int(pixels.shape[-1]) < _RGB_CHANNELS:
+ raise ValueError(
+ f"ComfyUI images have shape [batch, height, width, channels>=3]; "
+ f"got {tuple(pixels.shape)}."
+ )
+ images = (
+ pixels[..., :_RGB_CHANNELS]
+ .movedim(-1, 1)
+ .to(device=self.device, dtype=torch.float32)
+ .mul(2.0)
+ .sub(1.0)
+ .contiguous(memory_format=torch.channels_last)
+ )
+ latents = self.vae.encode(images)
+ return latents.to(comfy.model_management.intermediate_device())
+
+ @staticmethod
+ def spacial_compression_decode() -> int:
+ """Pixels per latent along each side."""
+
+ return LATENT_STRIDE
+
+ @staticmethod
+ def spacial_compression_encode() -> int:
+ """Pixels per latent along each side."""
+
+ return LATENT_STRIDE
+
+ @staticmethod
+ def temporal_compression_decode() -> None:
+ """Image-only autoencoder: no temporal axis."""
+
+ return None
diff --git a/comfyui/web/dflow_solver.js b/comfyui/web/dflow_solver.js
new file mode 100644
index 0000000000000000000000000000000000000000..fe0b63e96ebb393162a0391eb5e781b64f6c7004
--- /dev/null
+++ b/comfyui/web/dflow_solver.js
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Copyright 2026 Data Archetype
+// DFlow Sampler: choosing a solver sets noise_scale to that solver's default
+// (eta 0.5 for DPM++ 2M SDE, 1.0 otherwise), as dflow.solvers.default_noise_scale.
+import { app } from "../../scripts/app.js";
+
+const NODE = "DFlowSampler";
+const SOLVER = "solver";
+const NOISE_SCALE = "noise_scale";
+const DEFAULT_NOISE_SCALE = 1.0;
+const SOLVER_NOISE_SCALE = { dpmpp_2m_sde: 0.5 };
+
+/** Return a named widget, or fail when the node's inputs have changed. */
+function requiredWidget(node, name) {
+ const widget = node.widgets?.find((candidate) => candidate.name === name);
+ if (!widget) {
+ throw new Error(`${NODE} is missing its ${name} widget.`);
+ }
+ return widget;
+}
+
+app.registerExtension({
+ name: "DFlow.SolverDefaults",
+ nodeCreated(node) {
+ if (node.comfyClass !== NODE) {
+ return;
+ }
+ const solver = requiredWidget(node, SOLVER);
+ const noiseScale = requiredWidget(node, NOISE_SCALE);
+ const original = solver.callback;
+ solver.callback = function (value, ...args) {
+ original?.call(this, value, ...args);
+ noiseScale.value = SOLVER_NOISE_SCALE[value] ?? DEFAULT_NOISE_SCALE;
+ node.setDirtyCanvas(true, true);
+ };
+ },
+});
diff --git a/comfyui/workflows/dflow_default.json b/comfyui/workflows/dflow_default.json
new file mode 100644
index 0000000000000000000000000000000000000000..a6fdac9c54405502cd0358d46ab534cc92fca533
--- /dev/null
+++ b/comfyui/workflows/dflow_default.json
@@ -0,0 +1,869 @@
+{
+ "id": "15f35c13-5c1f-4c8d-8cea-b36d167cd276",
+ "revision": 0,
+ "last_node_id": 10,
+ "last_link_id": 13,
+ "nodes": [
+ {
+ "id": 1,
+ "type": "DFlowLoader",
+ "pos": [
+ -820,
+ -40
+ ],
+ "size": [
+ 360,
+ 230
+ ],
+ "flags": {},
+ "order": 0,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "source",
+ "type": "COMBO",
+ "widget": {
+ "name": "source"
+ },
+ "link": null
+ },
+ {
+ "name": "local_dir",
+ "type": "STRING",
+ "widget": {
+ "name": "local_dir"
+ },
+ "link": null
+ },
+ {
+ "name": "repository",
+ "type": "STRING",
+ "widget": {
+ "name": "repository"
+ },
+ "link": null
+ },
+ {
+ "name": "revision",
+ "type": "STRING",
+ "widget": {
+ "name": "revision"
+ },
+ "link": null
+ },
+ {
+ "name": "compile_model",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "compile_model"
+ },
+ "link": null
+ },
+ {
+ "name": "cache_dir",
+ "type": "STRING",
+ "widget": {
+ "name": "cache_dir"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "model",
+ "type": "DFLOW_MODEL",
+ "slot_index": 0,
+ "links": [
+ 1
+ ]
+ },
+ {
+ "name": "text_encoder",
+ "type": "DFLOW_TEXT_ENCODER",
+ "slot_index": 1,
+ "links": [
+ 2
+ ]
+ },
+ {
+ "name": "vae",
+ "type": "VAE",
+ "slot_index": 2,
+ "links": [
+ 3
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowLoader"
+ },
+ "widgets_values": [
+ "bundled",
+ "",
+ "data-archetype/dflow_2b",
+ "",
+ true,
+ ""
+ ]
+ },
+ {
+ "id": 2,
+ "type": "DFlowTextEncode",
+ "pos": [
+ -400,
+ -420
+ ],
+ "size": [
+ 440,
+ 420
+ ],
+ "flags": {},
+ "order": 1,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "text_encoder",
+ "type": "DFLOW_TEXT_ENCODER",
+ "link": 2
+ },
+ {
+ "name": "text",
+ "type": "STRING",
+ "widget": {
+ "name": "text"
+ },
+ "link": null
+ },
+ {
+ "name": "batch_size",
+ "type": "INT",
+ "widget": {
+ "name": "batch_size"
+ },
+ "link": null
+ },
+ {
+ "name": "emphasis",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "emphasis"
+ },
+ "link": null
+ },
+ {
+ "name": "emphasis_mapping",
+ "type": "COMBO",
+ "widget": {
+ "name": "emphasis_mapping"
+ },
+ "link": null
+ },
+ {
+ "name": "emphasis_strength",
+ "type": "FLOAT",
+ "widget": {
+ "name": "emphasis_strength"
+ },
+ "link": null
+ },
+ {
+ "name": "emphasis_encoder",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "emphasis_encoder"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "conditioning",
+ "type": "DFLOW_CONDITIONING",
+ "slot_index": 0,
+ "links": [
+ 4
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowTextEncode"
+ },
+ "widgets_values": [
+ "Wide angle photo of a weathered wooden boardwalk descending steeply from rocky cliffs toward a rugged coastline. The boardwalk, constructed from aged planks with visible cracks and moss growth, is bordered by rustic wooden railings on both sides. Surrounding terrain features uneven, eroded rock formations covered in patches of green vegetation and low-lying shrubs. Below, a crescent-shaped sandy beach meets crashing waves of a deep blue ocean under a stormy, overcast sky with dark clouds and hints of distant sunlight breaking through. The horizon shows turbulent waves colliding with rocky outcrops, creating white foam.",
+ 1,
+ true,
+ "linear",
+ 1.0,
+ true
+ ]
+ },
+ {
+ "id": 3,
+ "type": "DFlowGuider",
+ "pos": [
+ 80,
+ -420
+ ],
+ "size": [
+ 340,
+ 446
+ ],
+ "flags": {},
+ "order": 2,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "model",
+ "type": "DFLOW_MODEL",
+ "link": 1
+ },
+ {
+ "name": "positive",
+ "type": "DFLOW_CONDITIONING",
+ "link": 4
+ },
+ {
+ "name": "pdg_enabled",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "pdg_enabled"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_mode",
+ "type": "COMBO",
+ "widget": {
+ "name": "pdg_mode"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_scale",
+ "type": "FLOAT",
+ "widget": {
+ "name": "pdg_scale"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_start_step",
+ "type": "INT",
+ "widget": {
+ "name": "pdg_start_step"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_stop_step",
+ "type": "INT",
+ "widget": {
+ "name": "pdg_stop_step"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_suffix_caption_bias",
+ "type": "FLOAT",
+ "widget": {
+ "name": "pdg_suffix_caption_bias"
+ },
+ "link": null
+ },
+ {
+ "name": "cfg_enabled",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "cfg_enabled"
+ },
+ "link": null
+ },
+ {
+ "name": "cfg_scale",
+ "type": "FLOAT",
+ "widget": {
+ "name": "cfg_scale"
+ },
+ "link": null
+ },
+ {
+ "name": "cfg_start_step",
+ "type": "INT",
+ "widget": {
+ "name": "cfg_start_step"
+ },
+ "link": null
+ },
+ {
+ "name": "cfg_stop_step",
+ "type": "INT",
+ "widget": {
+ "name": "cfg_stop_step"
+ },
+ "link": null
+ },
+ {
+ "name": "self_attention_gain",
+ "type": "FLOAT",
+ "widget": {
+ "name": "self_attention_gain"
+ },
+ "link": null
+ },
+ {
+ "name": "negative",
+ "type": "DFLOW_CONDITIONING",
+ "link": null,
+ "shape": 7
+ }
+ ],
+ "outputs": [
+ {
+ "name": "guider",
+ "type": "GUIDER",
+ "slot_index": 0,
+ "links": [
+ 8
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowGuider"
+ },
+ "widgets_values": [
+ true,
+ "full",
+ 2.5,
+ 0,
+ -1,
+ -4.0,
+ false,
+ 4.0,
+ 0,
+ -1,
+ -0.03
+ ]
+ },
+ {
+ "id": 4,
+ "type": "DFlowSampler",
+ "pos": [
+ -400,
+ 120
+ ],
+ "size": [
+ 320,
+ 110
+ ],
+ "flags": {},
+ "order": 3,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "solver",
+ "type": "COMBO",
+ "widget": {
+ "name": "solver"
+ },
+ "link": null
+ },
+ {
+ "name": "noise_scale",
+ "type": "FLOAT",
+ "widget": {
+ "name": "noise_scale"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "sampler",
+ "type": "SAMPLER",
+ "slot_index": 0,
+ "links": [
+ 5
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowSampler"
+ },
+ "widgets_values": [
+ "er_sde",
+ 1.0
+ ]
+ },
+ {
+ "id": 5,
+ "type": "DFlowTimeSchedule",
+ "pos": [
+ 80,
+ 120
+ ],
+ "size": [
+ 340,
+ 270
+ ],
+ "flags": {},
+ "order": 6,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "sampler",
+ "type": "SAMPLER",
+ "link": 5
+ },
+ {
+ "name": "latent",
+ "type": "LATENT",
+ "link": 6
+ },
+ {
+ "name": "schedule",
+ "type": "COMBO",
+ "widget": {
+ "name": "schedule"
+ },
+ "link": null
+ },
+ {
+ "name": "steps",
+ "type": "INT",
+ "widget": {
+ "name": "steps"
+ },
+ "link": null
+ },
+ {
+ "name": "base_log_snr_shift",
+ "type": "FLOAT",
+ "widget": {
+ "name": "base_log_snr_shift"
+ },
+ "link": null
+ },
+ {
+ "name": "resolution_shift",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "resolution_shift"
+ },
+ "link": null
+ },
+ {
+ "name": "beta_mean",
+ "type": "FLOAT",
+ "widget": {
+ "name": "beta_mean"
+ },
+ "link": null
+ },
+ {
+ "name": "beta_concentration",
+ "type": "FLOAT",
+ "widget": {
+ "name": "beta_concentration"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "sigmas",
+ "type": "SIGMAS",
+ "slot_index": 0,
+ "links": [
+ 10
+ ]
+ },
+ {
+ "name": "sampler",
+ "type": "SAMPLER",
+ "slot_index": 1,
+ "links": [
+ 9
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowTimeSchedule"
+ },
+ "widgets_values": [
+ "beta_1_25",
+ 50,
+ -0.25,
+ true,
+ 0.5,
+ 0.6
+ ]
+ },
+ {
+ "id": 6,
+ "type": "DFlowEmptyLatent",
+ "pos": [
+ -400,
+ 280
+ ],
+ "size": [
+ 320,
+ 130
+ ],
+ "flags": {},
+ "order": 4,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "width",
+ "type": "INT",
+ "widget": {
+ "name": "width"
+ },
+ "link": null
+ },
+ {
+ "name": "height",
+ "type": "INT",
+ "widget": {
+ "name": "height"
+ },
+ "link": null
+ },
+ {
+ "name": "batch_size",
+ "type": "INT",
+ "widget": {
+ "name": "batch_size"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "latent",
+ "type": "LATENT",
+ "slot_index": 0,
+ "links": [
+ 6,
+ 11
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowEmptyLatent"
+ },
+ "widgets_values": [
+ 832,
+ 1216,
+ 1
+ ]
+ },
+ {
+ "id": 7,
+ "type": "RandomNoise",
+ "pos": [
+ 80,
+ 430
+ ],
+ "size": [
+ 320,
+ 110
+ ],
+ "flags": {},
+ "order": 5,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "noise_seed",
+ "type": "INT",
+ "widget": {
+ "name": "noise_seed"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "NOISE",
+ "type": "NOISE",
+ "slot_index": 0,
+ "links": [
+ 7
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "RandomNoise"
+ },
+ "widgets_values": [
+ 42,
+ "fixed"
+ ]
+ },
+ {
+ "id": 8,
+ "type": "SamplerCustomAdvanced",
+ "pos": [
+ 480,
+ -40
+ ],
+ "size": [
+ 300,
+ 330
+ ],
+ "flags": {},
+ "order": 7,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "noise",
+ "type": "NOISE",
+ "link": 7
+ },
+ {
+ "name": "guider",
+ "type": "GUIDER",
+ "link": 8
+ },
+ {
+ "name": "sampler",
+ "type": "SAMPLER",
+ "link": 9
+ },
+ {
+ "name": "sigmas",
+ "type": "SIGMAS",
+ "link": 10
+ },
+ {
+ "name": "latent_image",
+ "type": "LATENT",
+ "link": 11
+ }
+ ],
+ "outputs": [
+ {
+ "name": "output",
+ "type": "LATENT",
+ "slot_index": 0,
+ "links": [
+ 12
+ ]
+ },
+ {
+ "name": "denoised_output",
+ "type": "LATENT",
+ "slot_index": 1,
+ "links": []
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "SamplerCustomAdvanced"
+ },
+ "widgets_values": []
+ },
+ {
+ "id": 9,
+ "type": "VAEDecode",
+ "pos": [
+ 820,
+ -40
+ ],
+ "size": [
+ 220,
+ 50
+ ],
+ "flags": {},
+ "order": 8,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "samples",
+ "type": "LATENT",
+ "link": 12
+ },
+ {
+ "name": "vae",
+ "type": "VAE",
+ "link": 3
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "slot_index": 0,
+ "links": [
+ 13
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "VAEDecode"
+ },
+ "widgets_values": []
+ },
+ {
+ "id": 10,
+ "type": "SaveImage",
+ "pos": [
+ 1080,
+ -40
+ ],
+ "size": [
+ 520,
+ 760
+ ],
+ "flags": {},
+ "order": 9,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 13
+ },
+ {
+ "name": "filename_prefix",
+ "type": "STRING",
+ "widget": {
+ "name": "filename_prefix"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "slot_index": 0,
+ "links": []
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "SaveImage"
+ },
+ "widgets_values": [
+ "dflow"
+ ]
+ }
+ ],
+ "links": [
+ [
+ 1,
+ 1,
+ 0,
+ 3,
+ 0,
+ "DFLOW_MODEL"
+ ],
+ [
+ 2,
+ 1,
+ 1,
+ 2,
+ 0,
+ "DFLOW_TEXT_ENCODER"
+ ],
+ [
+ 3,
+ 1,
+ 2,
+ 9,
+ 1,
+ "VAE"
+ ],
+ [
+ 4,
+ 2,
+ 0,
+ 3,
+ 1,
+ "DFLOW_CONDITIONING"
+ ],
+ [
+ 5,
+ 4,
+ 0,
+ 5,
+ 0,
+ "SAMPLER"
+ ],
+ [
+ 6,
+ 6,
+ 0,
+ 5,
+ 1,
+ "LATENT"
+ ],
+ [
+ 7,
+ 7,
+ 0,
+ 8,
+ 0,
+ "NOISE"
+ ],
+ [
+ 8,
+ 3,
+ 0,
+ 8,
+ 1,
+ "GUIDER"
+ ],
+ [
+ 9,
+ 5,
+ 1,
+ 8,
+ 2,
+ "SAMPLER"
+ ],
+ [
+ 10,
+ 5,
+ 0,
+ 8,
+ 3,
+ "SIGMAS"
+ ],
+ [
+ 11,
+ 6,
+ 0,
+ 8,
+ 4,
+ "LATENT"
+ ],
+ [
+ 12,
+ 8,
+ 0,
+ 9,
+ 0,
+ "LATENT"
+ ],
+ [
+ 13,
+ 9,
+ 0,
+ 10,
+ 0,
+ "IMAGE"
+ ]
+ ],
+ "groups": [],
+ "config": {},
+ "extra": {
+ "ds": {
+ "scale": 0.7,
+ "offset": [
+ 900,
+ 420
+ ]
+ }
+ },
+ "version": 0.4
+}
diff --git a/comfyui/workflows/dflow_layout_poster.json b/comfyui/workflows/dflow_layout_poster.json
new file mode 100644
index 0000000000000000000000000000000000000000..0fd8ddadb652a1f0bc229d697fc8bc3ff259ac51
--- /dev/null
+++ b/comfyui/workflows/dflow_layout_poster.json
@@ -0,0 +1,851 @@
+{
+ "id": "9d55e4c0-e795-42f5-9362-28188f3af55c",
+ "revision": 0,
+ "last_node_id": 10,
+ "last_link_id": 13,
+ "nodes": [
+ {
+ "id": 1,
+ "type": "DFlowLoader",
+ "pos": [
+ -820,
+ -40
+ ],
+ "size": [
+ 360,
+ 230
+ ],
+ "flags": {},
+ "order": 0,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "source",
+ "type": "COMBO",
+ "widget": {
+ "name": "source"
+ },
+ "link": null
+ },
+ {
+ "name": "local_dir",
+ "type": "STRING",
+ "widget": {
+ "name": "local_dir"
+ },
+ "link": null
+ },
+ {
+ "name": "repository",
+ "type": "STRING",
+ "widget": {
+ "name": "repository"
+ },
+ "link": null
+ },
+ {
+ "name": "revision",
+ "type": "STRING",
+ "widget": {
+ "name": "revision"
+ },
+ "link": null
+ },
+ {
+ "name": "compile_model",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "compile_model"
+ },
+ "link": null
+ },
+ {
+ "name": "cache_dir",
+ "type": "STRING",
+ "widget": {
+ "name": "cache_dir"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "model",
+ "type": "DFLOW_MODEL",
+ "slot_index": 0,
+ "links": [
+ 1
+ ]
+ },
+ {
+ "name": "text_encoder",
+ "type": "DFLOW_TEXT_ENCODER",
+ "slot_index": 1,
+ "links": [
+ 2
+ ]
+ },
+ {
+ "name": "vae",
+ "type": "VAE",
+ "slot_index": 2,
+ "links": [
+ 3
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowLoader"
+ },
+ "widgets_values": [
+ "bundled",
+ "",
+ "data-archetype/dflow_2b",
+ "",
+ true,
+ ""
+ ]
+ },
+ {
+ "id": 2,
+ "type": "DFlowLayoutEncode",
+ "pos": [
+ -400,
+ -520
+ ],
+ "size": [
+ 440,
+ 520
+ ],
+ "flags": {},
+ "order": 1,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "text_encoder",
+ "type": "DFLOW_TEXT_ENCODER",
+ "link": 2
+ },
+ {
+ "name": "layout_json",
+ "type": "STRING",
+ "widget": {
+ "name": "layout_json"
+ },
+ "link": null
+ },
+ {
+ "name": "width",
+ "type": "INT",
+ "widget": {
+ "name": "width"
+ },
+ "link": null
+ },
+ {
+ "name": "height",
+ "type": "INT",
+ "widget": {
+ "name": "height"
+ },
+ "link": null
+ },
+ {
+ "name": "batch_size",
+ "type": "INT",
+ "widget": {
+ "name": "batch_size"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "conditioning",
+ "type": "DFLOW_CONDITIONING",
+ "slot_index": 0,
+ "links": [
+ 4
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowLayoutEncode"
+ },
+ "widgets_values": [
+ "{\n \"summary\": {\n \"meta\": [\n \"concert_poster\",\n \"flat_illustration\",\n \"mid_century_modern\"\n ],\n \"canvas\": \"single\",\n \"caption\": \"A mid-century style jazz festival poster shows a saxophonist in silhouette against a large orange sun on a deep teal background. The title \\\"BLUE HARBOR JAZZ\\\" runs across the top in cream capitals and the line \\\"JULY 12 – 14, 1996\\\" sits at the bottom.\"\n },\n \"frame\": {\n \"caption\": \"The saxophonist stands in the centre, cut off at the knees, with the sun behind his shoulders. The title fills the top fifth and the date line sits in a band along the bottom edge. Flat colour shapes with a light paper grain.\",\n \"tags\": [\n \"flat_color\",\n \"centered_composition\",\n \"paper_grain\"\n ],\n \"palette\": [\n \"#0F4C5C\",\n \"#F28C28\",\n \"#F5E9D0\",\n \"#1B1B1B\"\n ]\n },\n \"items\": [\n {\n \"label\": \"object\",\n \"caption\": \"A large flat orange circle, the sun, behind the musician.\",\n \"tags\": [\n \"sun\",\n \"circle\"\n ],\n \"palette\": [\n \"#F28C28\"\n ],\n \"box_2d\": [\n 230,\n 170,\n 720,\n 830\n ]\n },\n {\n \"label\": \"character\",\n \"caption\": \"A black silhouette of a man in a hat playing a tenor saxophone, facing right, leaning back slightly.\",\n \"tags\": [\n \"saxophonist\",\n \"silhouette\",\n \"hat\"\n ],\n \"palette\": [\n \"#1B1B1B\"\n ],\n \"box_2d\": [\n 260,\n 250,\n 880,\n 760\n ]\n },\n {\n \"label\": \"text\",\n \"caption\": \"The title \\\"BLUE HARBOR JAZZ\\\" in bold condensed cream capitals on one line.\",\n \"text\": \"BLUE HARBOR JAZZ\",\n \"tags\": [\n \"title\",\n \"condensed_sans\",\n \"uppercase\"\n ],\n \"palette\": [\n \"#F5E9D0\"\n ],\n \"box_2d\": [\n 60,\n 70,\n 180,\n 930\n ]\n },\n {\n \"label\": \"text\",\n \"caption\": \"The date line \\\"JULY 12 – 14, 1996\\\" in small spaced cream capitals.\",\n \"text\": \"JULY 12 – 14, 1996\",\n \"tags\": [\n \"date\",\n \"small_caps\"\n ],\n \"palette\": [\n \"#F5E9D0\"\n ],\n \"box_2d\": [\n 905,\n 300,\n 950,\n 700\n ]\n }\n ]\n}",
+ 832,
+ 1216,
+ 1
+ ]
+ },
+ {
+ "id": 3,
+ "type": "DFlowGuider",
+ "pos": [
+ 80,
+ -420
+ ],
+ "size": [
+ 340,
+ 446
+ ],
+ "flags": {},
+ "order": 2,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "model",
+ "type": "DFLOW_MODEL",
+ "link": 1
+ },
+ {
+ "name": "positive",
+ "type": "DFLOW_CONDITIONING",
+ "link": 4
+ },
+ {
+ "name": "pdg_enabled",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "pdg_enabled"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_mode",
+ "type": "COMBO",
+ "widget": {
+ "name": "pdg_mode"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_scale",
+ "type": "FLOAT",
+ "widget": {
+ "name": "pdg_scale"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_start_step",
+ "type": "INT",
+ "widget": {
+ "name": "pdg_start_step"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_stop_step",
+ "type": "INT",
+ "widget": {
+ "name": "pdg_stop_step"
+ },
+ "link": null
+ },
+ {
+ "name": "pdg_suffix_caption_bias",
+ "type": "FLOAT",
+ "widget": {
+ "name": "pdg_suffix_caption_bias"
+ },
+ "link": null
+ },
+ {
+ "name": "cfg_enabled",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "cfg_enabled"
+ },
+ "link": null
+ },
+ {
+ "name": "cfg_scale",
+ "type": "FLOAT",
+ "widget": {
+ "name": "cfg_scale"
+ },
+ "link": null
+ },
+ {
+ "name": "cfg_start_step",
+ "type": "INT",
+ "widget": {
+ "name": "cfg_start_step"
+ },
+ "link": null
+ },
+ {
+ "name": "cfg_stop_step",
+ "type": "INT",
+ "widget": {
+ "name": "cfg_stop_step"
+ },
+ "link": null
+ },
+ {
+ "name": "self_attention_gain",
+ "type": "FLOAT",
+ "widget": {
+ "name": "self_attention_gain"
+ },
+ "link": null
+ },
+ {
+ "name": "negative",
+ "type": "DFLOW_CONDITIONING",
+ "link": null,
+ "shape": 7
+ }
+ ],
+ "outputs": [
+ {
+ "name": "guider",
+ "type": "GUIDER",
+ "slot_index": 0,
+ "links": [
+ 8
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowGuider"
+ },
+ "widgets_values": [
+ true,
+ "full",
+ 2.5,
+ 0,
+ -1,
+ -4.0,
+ false,
+ 4.0,
+ 0,
+ -1,
+ -0.03
+ ]
+ },
+ {
+ "id": 4,
+ "type": "DFlowSampler",
+ "pos": [
+ -400,
+ 120
+ ],
+ "size": [
+ 320,
+ 110
+ ],
+ "flags": {},
+ "order": 3,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "solver",
+ "type": "COMBO",
+ "widget": {
+ "name": "solver"
+ },
+ "link": null
+ },
+ {
+ "name": "noise_scale",
+ "type": "FLOAT",
+ "widget": {
+ "name": "noise_scale"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "sampler",
+ "type": "SAMPLER",
+ "slot_index": 0,
+ "links": [
+ 5
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowSampler"
+ },
+ "widgets_values": [
+ "er_sde",
+ 1.0
+ ]
+ },
+ {
+ "id": 5,
+ "type": "DFlowTimeSchedule",
+ "pos": [
+ 80,
+ 120
+ ],
+ "size": [
+ 340,
+ 270
+ ],
+ "flags": {},
+ "order": 6,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "sampler",
+ "type": "SAMPLER",
+ "link": 5
+ },
+ {
+ "name": "latent",
+ "type": "LATENT",
+ "link": 6
+ },
+ {
+ "name": "schedule",
+ "type": "COMBO",
+ "widget": {
+ "name": "schedule"
+ },
+ "link": null
+ },
+ {
+ "name": "steps",
+ "type": "INT",
+ "widget": {
+ "name": "steps"
+ },
+ "link": null
+ },
+ {
+ "name": "base_log_snr_shift",
+ "type": "FLOAT",
+ "widget": {
+ "name": "base_log_snr_shift"
+ },
+ "link": null
+ },
+ {
+ "name": "resolution_shift",
+ "type": "BOOLEAN",
+ "widget": {
+ "name": "resolution_shift"
+ },
+ "link": null
+ },
+ {
+ "name": "beta_mean",
+ "type": "FLOAT",
+ "widget": {
+ "name": "beta_mean"
+ },
+ "link": null
+ },
+ {
+ "name": "beta_concentration",
+ "type": "FLOAT",
+ "widget": {
+ "name": "beta_concentration"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "sigmas",
+ "type": "SIGMAS",
+ "slot_index": 0,
+ "links": [
+ 10
+ ]
+ },
+ {
+ "name": "sampler",
+ "type": "SAMPLER",
+ "slot_index": 1,
+ "links": [
+ 9
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowTimeSchedule"
+ },
+ "widgets_values": [
+ "beta_1_25",
+ 50,
+ -0.25,
+ true,
+ 0.5,
+ 0.6
+ ]
+ },
+ {
+ "id": 6,
+ "type": "DFlowEmptyLatent",
+ "pos": [
+ -400,
+ 280
+ ],
+ "size": [
+ 320,
+ 130
+ ],
+ "flags": {},
+ "order": 4,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "width",
+ "type": "INT",
+ "widget": {
+ "name": "width"
+ },
+ "link": null
+ },
+ {
+ "name": "height",
+ "type": "INT",
+ "widget": {
+ "name": "height"
+ },
+ "link": null
+ },
+ {
+ "name": "batch_size",
+ "type": "INT",
+ "widget": {
+ "name": "batch_size"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "latent",
+ "type": "LATENT",
+ "slot_index": 0,
+ "links": [
+ 6,
+ 11
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DFlowEmptyLatent"
+ },
+ "widgets_values": [
+ 832,
+ 1216,
+ 1
+ ]
+ },
+ {
+ "id": 7,
+ "type": "RandomNoise",
+ "pos": [
+ 80,
+ 430
+ ],
+ "size": [
+ 320,
+ 110
+ ],
+ "flags": {},
+ "order": 5,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "noise_seed",
+ "type": "INT",
+ "widget": {
+ "name": "noise_seed"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "NOISE",
+ "type": "NOISE",
+ "slot_index": 0,
+ "links": [
+ 7
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "RandomNoise"
+ },
+ "widgets_values": [
+ 42,
+ "fixed"
+ ]
+ },
+ {
+ "id": 8,
+ "type": "SamplerCustomAdvanced",
+ "pos": [
+ 480,
+ -40
+ ],
+ "size": [
+ 300,
+ 330
+ ],
+ "flags": {},
+ "order": 7,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "noise",
+ "type": "NOISE",
+ "link": 7
+ },
+ {
+ "name": "guider",
+ "type": "GUIDER",
+ "link": 8
+ },
+ {
+ "name": "sampler",
+ "type": "SAMPLER",
+ "link": 9
+ },
+ {
+ "name": "sigmas",
+ "type": "SIGMAS",
+ "link": 10
+ },
+ {
+ "name": "latent_image",
+ "type": "LATENT",
+ "link": 11
+ }
+ ],
+ "outputs": [
+ {
+ "name": "output",
+ "type": "LATENT",
+ "slot_index": 0,
+ "links": [
+ 12
+ ]
+ },
+ {
+ "name": "denoised_output",
+ "type": "LATENT",
+ "slot_index": 1,
+ "links": []
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "SamplerCustomAdvanced"
+ },
+ "widgets_values": []
+ },
+ {
+ "id": 9,
+ "type": "VAEDecode",
+ "pos": [
+ 820,
+ -40
+ ],
+ "size": [
+ 220,
+ 50
+ ],
+ "flags": {},
+ "order": 8,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "samples",
+ "type": "LATENT",
+ "link": 12
+ },
+ {
+ "name": "vae",
+ "type": "VAE",
+ "link": 3
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "slot_index": 0,
+ "links": [
+ 13
+ ]
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "VAEDecode"
+ },
+ "widgets_values": []
+ },
+ {
+ "id": 10,
+ "type": "SaveImage",
+ "pos": [
+ 1080,
+ -40
+ ],
+ "size": [
+ 520,
+ 760
+ ],
+ "flags": {},
+ "order": 9,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 13
+ },
+ {
+ "name": "filename_prefix",
+ "type": "STRING",
+ "widget": {
+ "name": "filename_prefix"
+ },
+ "link": null
+ }
+ ],
+ "outputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "slot_index": 0,
+ "links": []
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "SaveImage"
+ },
+ "widgets_values": [
+ "dflow"
+ ]
+ }
+ ],
+ "links": [
+ [
+ 1,
+ 1,
+ 0,
+ 3,
+ 0,
+ "DFLOW_MODEL"
+ ],
+ [
+ 2,
+ 1,
+ 1,
+ 2,
+ 0,
+ "DFLOW_TEXT_ENCODER"
+ ],
+ [
+ 3,
+ 1,
+ 2,
+ 9,
+ 1,
+ "VAE"
+ ],
+ [
+ 4,
+ 2,
+ 0,
+ 3,
+ 1,
+ "DFLOW_CONDITIONING"
+ ],
+ [
+ 5,
+ 4,
+ 0,
+ 5,
+ 0,
+ "SAMPLER"
+ ],
+ [
+ 6,
+ 6,
+ 0,
+ 5,
+ 1,
+ "LATENT"
+ ],
+ [
+ 7,
+ 7,
+ 0,
+ 8,
+ 0,
+ "NOISE"
+ ],
+ [
+ 8,
+ 3,
+ 0,
+ 8,
+ 1,
+ "GUIDER"
+ ],
+ [
+ 9,
+ 5,
+ 1,
+ 8,
+ 2,
+ "SAMPLER"
+ ],
+ [
+ 10,
+ 5,
+ 0,
+ 8,
+ 3,
+ "SIGMAS"
+ ],
+ [
+ 11,
+ 6,
+ 0,
+ 8,
+ 4,
+ "LATENT"
+ ],
+ [
+ 12,
+ 8,
+ 0,
+ 9,
+ 0,
+ "LATENT"
+ ],
+ [
+ 13,
+ 9,
+ 0,
+ 10,
+ 0,
+ "IMAGE"
+ ]
+ ],
+ "groups": [],
+ "config": {},
+ "extra": {
+ "ds": {
+ "scale": 0.7,
+ "offset": [
+ 900,
+ 420
+ ]
+ }
+ },
+ "version": 0.4
+}
diff --git a/config.json b/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..bbb2235c00f9307a03496fb0c9443f77ba2894dd
--- /dev/null
+++ b/config.json
@@ -0,0 +1,30 @@
+{
+ "denoiser": {
+ "heads": 18,
+ "latent_channels": 96,
+ "middle_depth": 18,
+ "mlp_ratio": 4,
+ "norm_eps": 1e-06,
+ "patch_size": 1,
+ "prefix_depth": 6,
+ "rope_axes_dims": [
+ 32,
+ 48,
+ 48
+ ],
+ "rope_axes_lens": [
+ 8192,
+ 512,
+ 512
+ ],
+ "rope_theta": 10000.0,
+ "suffix_depth": 6,
+ "text_refiner_depth": 2,
+ "time_embed_width": 256,
+ "time_frequency_width": 256,
+ "time_hidden_width": 1024,
+ "time_max_period": 10000.0,
+ "time_scale": 1000.0,
+ "width": 2304
+ }
+}
diff --git a/dflow/__init__.py b/dflow/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a29ccbd2aa6316be0c68acaac3d83ecfe242786e
--- /dev/null
+++ b/dflow/__init__.py
@@ -0,0 +1,5 @@
+"""dflow: inference package for the dflow_2b text-to-image model."""
+
+from .version import MODEL_VERSION, __version__
+
+__all__ = ["MODEL_VERSION", "__version__"]
diff --git a/dflow/blocks.py b/dflow/blocks.py
new file mode 100644
index 0000000000000000000000000000000000000000..dae8211d8bb87977b9de8ba49f6b7c04f6b0fce8
--- /dev/null
+++ b/dflow/blocks.py
@@ -0,0 +1,313 @@
+"""The transformer block of the dflow denoiser: dense joint self-attention.
+
+One block class serves the text refiner (unmodulated) and the prefix, middle
+and suffix image layers (scale-and-gate AdaLN from the timestep). Every block
+is a sandwich-norm residual block::
+
+ h = norm2(attention(modulate(norm1(x), s_a)))
+ x = x + tanh(g_a) * h
+ h = norm2'(mlp(modulate(norm1'(x), s_m)))
+ x = x + tanh(g_m) * h
+
+with ``modulate(n, s) = n * (1 + s)`` (no shift); the refiner adds ``h``
+directly. Attention is fused-QKV multi-head attention with RMSNorm on queries
+and keys, adjacent-pair 3-axis RoPE, and dense scaled-dot-product attention.
+
+Extra attention inputs, all built once per forward outside the blocks:
+
+- ``query_scale``: a 0-dim float32 tensor multiplying the queries after RoPE,
+ ``exp(self-attention logit gain)``; a tensor so a new value reuses the
+ compiled graph. None leaves the queries unchanged (the text refiner).
+- ``key_bias``: an additive ``[B, 1, 1, S]`` attention-logit bias on every
+ key (prompt emphasis on text keys, zero elsewhere), or None for the
+ mask-free (flash) path.
+- ``value_scale``: a ``[B, 1, S, 1]`` multiplier on every value, or None.
+
+Blocks hold no validation: shapes are checked where the model builds inputs.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Protocol
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+if TYPE_CHECKING:
+ from .configuration import DFlowConfig
+
+
+class BlockCall(Protocol):
+ """The eager or compiled block implementation."""
+
+ def __call__(
+ self,
+ x: Tensor,
+ *,
+ rope_sin: Tensor,
+ rope_cos: Tensor,
+ modulation: Tensor | None,
+ query_scale: Tensor | None,
+ key_bias: Tensor | None,
+ value_scale: Tensor | None,
+ ) -> Tensor:
+ """Run the block."""
+ ...
+
+
+class RMSNorm(nn.Module):
+ """RMSNorm with an affine weight cast to the input dtype at use.
+
+ The output keeps the input dtype (autocast computes the norm in float32
+ and the result is cast back).
+ """
+
+ weight: nn.Parameter
+ width: int
+ eps: float
+
+ def __init__(self, width: int, *, eps: float) -> None:
+ """Build a unit-initialised ``[width]`` weight."""
+
+ super().__init__()
+ self.width = width
+ self.eps = eps
+ self.weight = nn.Parameter(torch.ones(width))
+
+ def forward(self, x: Tensor) -> Tensor:
+ """Normalise the last dimension of ``x``."""
+
+ out = F.rms_norm(x, (self.width,), self.weight.to(dtype=x.dtype), self.eps)
+ return out if out.dtype == x.dtype else out.to(dtype=x.dtype)
+
+
+def _rotate_adjacent_pairs(x: Tensor) -> Tensor:
+ """Rotate channel pairs ``(x0, x1) -> (-x1, x0)`` along the last dim."""
+
+ pairs = x.reshape(*x.shape[:-1], x.shape[-1] // 2, 2)
+ return torch.stack((-pairs[..., 1], pairs[..., 0]), dim=-1).reshape_as(x)
+
+
+def _apply_rope(x: Tensor, sin: Tensor, cos: Tensor) -> Tensor:
+ """Rotate ``x`` ``[B, S, H, D]`` by float32 ``sin``/``cos`` ``[B, S, 1, D]``
+ in float32, returning ``x``'s dtype."""
+
+ rotated = x.to(dtype=sin.dtype)
+ return (rotated * cos + _rotate_adjacent_pairs(rotated) * sin).to(dtype=x.dtype)
+
+
+class JointSelfAttention(nn.Module):
+ """Fused-QKV multi-head self-attention with QK RMSNorm and 3-axis RoPE."""
+
+ qkv: nn.Linear
+ q_norm: RMSNorm
+ k_norm: RMSNorm
+ proj_out: nn.Linear
+ heads: int
+ head_width: int
+
+ def __init__(self, config: DFlowConfig) -> None:
+ """Build the bias-free projections and the per-head norms."""
+
+ super().__init__()
+ self.heads = config.heads
+ self.head_width = config.head_width
+ self.qkv = nn.Linear(config.width, 3 * config.width, bias=False)
+ self.q_norm = RMSNorm(config.head_width, eps=config.norm_eps)
+ self.k_norm = RMSNorm(config.head_width, eps=config.norm_eps)
+ self.proj_out = nn.Linear(config.width, config.width, bias=False)
+
+ def forward(
+ self,
+ x: Tensor,
+ *,
+ rope_sin: Tensor,
+ rope_cos: Tensor,
+ query_scale: Tensor | None,
+ key_bias: Tensor | None,
+ value_scale: Tensor | None,
+ ) -> Tensor:
+ """Attend over ``x`` ``[B, S, width]``.
+
+ Args:
+ x: Normalised (and modulated) tokens.
+ rope_sin: ``[B, S, head_width]`` float32.
+ rope_cos: ``[B, S, head_width]`` float32.
+ query_scale: 0-dim float32 query multiplier, or None.
+ key_bias: ``[B, 1, 1, S]`` additive logit bias (query dtype), or None.
+ value_scale: ``[B, 1, S, 1]`` value multiplier (value dtype), or None.
+
+ Returns:
+ ``[B, S, width]`` attention output after the output projection.
+ """
+
+ batch, length, width = x.shape
+ qkv = self.qkv(x).view(batch, length, 3, self.heads, self.head_width)
+ q, k, v = qkv.unbind(2)
+ sin = rope_sin.unsqueeze(2)
+ cos = rope_cos.unsqueeze(2)
+ q = _apply_rope(self.q_norm(q), sin, cos)
+ k = _apply_rope(self.k_norm(k), sin, cos)
+ if query_scale is not None:
+ q = (q.to(dtype=torch.float32) * query_scale).to(dtype=k.dtype)
+ v = v.transpose(1, 2)
+ if value_scale is not None:
+ v = v * value_scale
+ out = F.scaled_dot_product_attention(
+ q.transpose(1, 2), k.transpose(1, 2), v, attn_mask=key_bias
+ )
+ return self.proj_out(out.transpose(1, 2).reshape(batch, length, width))
+
+
+class GeluMlp(nn.Module):
+ """``down(gelu(up(x)))`` with biases and the exact (erf) GELU."""
+
+ up: nn.Linear
+ down: nn.Linear
+
+ def __init__(self, config: DFlowConfig) -> None:
+ """Build the two biased projections."""
+
+ super().__init__()
+ self.up = nn.Linear(config.width, config.mlp_hidden_width, bias=True)
+ self.down = nn.Linear(config.mlp_hidden_width, config.width, bias=True)
+
+ def forward(self, x: Tensor) -> Tensor:
+ """Apply the MLP to ``[..., width]`` tokens."""
+
+ return self.down(F.gelu(self.up(x)))
+
+
+def _modulate(normed: Tensor, scale: Tensor) -> Tensor:
+ """``normed * (1 + scale)`` in float32 with per-sample ``scale`` ``[B, D]``,
+ returned in ``normed``'s dtype."""
+
+ out = normed.to(dtype=torch.float32) * (1.0 + scale.unsqueeze(1))
+ return out.to(dtype=normed.dtype)
+
+
+def _gate(gate: Tensor, values: Tensor) -> Tensor:
+ """``tanh(gate) * values`` in float32 with per-sample ``gate`` ``[B, D]``,
+ returned in ``values``' dtype."""
+
+ out = torch.tanh(gate).unsqueeze(1) * values.to(dtype=torch.float32)
+ return out.to(dtype=values.dtype)
+
+
+class DFlowBlock(nn.Module):
+ """One sandwich-norm transformer block (refiner or image layer)."""
+
+ attn_norm1: RMSNorm
+ attn_norm2: RMSNorm
+ mlp_norm1: RMSNorm
+ mlp_norm2: RMSNorm
+ attn: JointSelfAttention
+ mlp: GeluMlp
+ _implementation: BlockCall
+ _compiled: bool
+
+ def __init__(self, config: DFlowConfig) -> None:
+ """Build the four norms, the attention and the MLP."""
+
+ super().__init__()
+ self.attn_norm1 = RMSNorm(config.width, eps=config.norm_eps)
+ self.attn_norm2 = RMSNorm(config.width, eps=config.norm_eps)
+ self.mlp_norm1 = RMSNorm(config.width, eps=config.norm_eps)
+ self.mlp_norm2 = RMSNorm(config.width, eps=config.norm_eps)
+ self.attn = JointSelfAttention(config)
+ self.mlp = GeluMlp(config)
+ self._implementation = self._forward_impl
+ self._compiled = False
+
+ def forward(
+ self,
+ x: Tensor,
+ *,
+ rope_sin: Tensor,
+ rope_cos: Tensor,
+ modulation: Tensor | None,
+ query_scale: Tensor | None,
+ key_bias: Tensor | None,
+ value_scale: Tensor | None,
+ ) -> Tensor:
+ """Run the block, compiled once ``compile_block`` was called.
+
+ Args:
+ x: Residual stream ``[B, S, width]``.
+ rope_sin: ``[B, S, head_width]`` float32 RoPE sines.
+ rope_cos: ``[B, S, head_width]`` float32 RoPE cosines.
+ modulation: Float32 ``[B, 4 * width]`` AdaLN projection, chunked as
+ (attention scale, attention gate, MLP scale, MLP gate); None for
+ the unmodulated refiner.
+ query_scale: See the module docstring.
+ key_bias: See the module docstring.
+ value_scale: See the module docstring.
+
+ Returns:
+ The updated residual stream, in ``x``'s dtype.
+ """
+
+ return self._implementation(
+ x,
+ rope_sin=rope_sin,
+ rope_cos=rope_cos,
+ modulation=modulation,
+ query_scale=query_scale,
+ key_bias=key_bias,
+ value_scale=value_scale,
+ )
+
+ def compile_block(self, *, dynamic: bool) -> None:
+ """Replace the eager implementation by ``torch.compile(fullgraph=True)``.
+
+ Compilation happens on the first call; a graph break or compiler
+ error raises there.
+
+ Raises:
+ RuntimeError: If the block is already compiled.
+ """
+
+ if self._compiled:
+ raise RuntimeError("DFlowBlock is already compiled")
+ self._implementation = torch.compile(
+ self._forward_impl, fullgraph=True, dynamic=dynamic
+ )
+ self._compiled = True
+
+ def _forward_impl(
+ self,
+ x: Tensor,
+ *,
+ rope_sin: Tensor,
+ rope_cos: Tensor,
+ modulation: Tensor | None,
+ query_scale: Tensor | None,
+ key_bias: Tensor | None,
+ value_scale: Tensor | None,
+ ) -> Tensor:
+ """The block math (see ``forward``)."""
+
+ if modulation is None:
+ h = self.attn(
+ self.attn_norm1(x),
+ rope_sin=rope_sin,
+ rope_cos=rope_cos,
+ query_scale=query_scale,
+ key_bias=key_bias,
+ value_scale=value_scale,
+ )
+ x = x + self.attn_norm2(h)
+ return x + self.mlp_norm2(self.mlp(self.mlp_norm1(x)))
+ scale_a, gate_a, scale_m, gate_m = modulation.chunk(4, dim=-1)
+ h = self.attn(
+ _modulate(self.attn_norm1(x), scale_a),
+ rope_sin=rope_sin,
+ rope_cos=rope_cos,
+ query_scale=query_scale,
+ key_bias=key_bias,
+ value_scale=value_scale,
+ )
+ x = x + _gate(gate_a, self.attn_norm2(h))
+ h = self.mlp(_modulate(self.mlp_norm1(x), scale_m))
+ return x + _gate(gate_m, self.mlp_norm2(h))
diff --git a/dflow/brownian_noise.py b/dflow/brownian_noise.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bf47f1a5b01a114356fca6e5601392214b0c306
--- /dev/null
+++ b/dflow/brownian_noise.py
@@ -0,0 +1,148 @@
+"""Per-step standard normals and Brownian-tree increments for the SDE solvers.
+
+Both draw from one explicit ``torch.Generator``. A CPU generator (the
+recommended source) draws float32 values on the host and copies them to the
+state's device without a host sync, so one seed gives the same noise on every
+GPU model. A CUDA generator draws on the state's device; its numbers depend on
+the GPU model.
+"""
+
+from __future__ import annotations
+
+import math
+
+import torch
+from torch import Tensor
+from torchsde import BrownianTree
+
+BROWNIAN_RELATIVE_TOLERANCE = 1.0e-10
+_ENTROPY_HIGH = 2**31 - 1
+
+
+def _require_generator_device(generator: torch.Generator, device: torch.device) -> None:
+ """Fail fast when a non-CPU generator is not on the state's device.
+
+ Raises:
+ ValueError: On a CUDA generator for a state on another device.
+ """
+
+ generator_device = torch.device(generator.device)
+ if generator_device.type == "cpu":
+ return
+ matches = generator_device.type == device.type and (
+ generator_device.index is None
+ or device.index is None
+ or generator_device.index == device.index
+ )
+ if not matches:
+ raise ValueError(
+ f"The noise generator is on {generator_device} but the state is on "
+ f"{device}; use a CPU generator or one on the state's device."
+ )
+
+
+def _to_device(host: Tensor, device: torch.device) -> Tensor:
+ """Copy a host tensor to ``device`` through pinned memory without a sync."""
+
+ if device.type == "cpu":
+ return host
+ return host.pin_memory().to(device=device, non_blocking=True)
+
+
+def standard_normal(
+ shape: tuple[int, ...], *, generator: torch.Generator, device: torch.device
+) -> Tensor:
+ """Draw one float32 ``N(0, 1)`` tensor of ``shape`` on ``device``.
+
+ A CPU generator fills a host buffer (``Tensor.normal_``) and copies it over;
+ a device generator calls ``torch.randn`` on the device.
+
+ Raises:
+ ValueError: If a device generator is on another device.
+ """
+
+ _require_generator_device(generator, device)
+ if torch.device(generator.device).type == "cpu":
+ host = torch.empty(shape, dtype=torch.float32, device="cpu")
+ host.normal_(generator=generator)
+ return _to_device(host, device)
+ return torch.randn(shape, device=device, dtype=torch.float32, generator=generator)
+
+
+class BrownianIntervalNormal:
+ """Normalized Brownian increments on a fixed time domain, one tree per sample.
+
+ ``sample(start, end)`` returns ``(W(end) - W(start)) / sqrt(|end - start|)``
+ in normalized domain units, so increments over adjacent intervals are
+ consistent whatever the schedule. Trees live on the generator's device
+ (the host for a CPU generator).
+ """
+
+ def __init__(
+ self, *, state: Tensor, start: float, end: float, generator: torch.Generator
+ ) -> None:
+ """Draw one tree entropy per batch item from ``generator``.
+
+ Raises:
+ ValueError: For a non-finite or empty domain, or a generator on
+ another device than the state.
+ """
+
+ if not (math.isfinite(start) and math.isfinite(end)) or start >= end:
+ raise ValueError(
+ f"The Brownian domain must be finite with start < end; got "
+ f"[{start}, {end}]."
+ )
+ _require_generator_device(generator, state.device)
+ tree_device = torch.device(generator.device)
+ if tree_device.type != "cpu":
+ tree_device = state.device
+ entropies = torch.randint(
+ low=0,
+ high=_ENTROPY_HIGH,
+ size=(int(state.shape[0]),),
+ device=torch.device(generator.device),
+ dtype=torch.int64,
+ generator=generator,
+ )
+ origin = torch.zeros(
+ tuple(state.shape[1:]), device=tree_device, dtype=torch.float32
+ )
+ self._trees = tuple(
+ BrownianTree(
+ t0=0.0,
+ w0=origin,
+ t1=1.0,
+ entropy=int(entropy),
+ tol=BROWNIAN_RELATIVE_TOLERANCE,
+ )
+ for entropy in entropies.cpu().tolist()
+ )
+ self._start = start
+ self._span = end - start
+ self._end = end
+
+ def sample(self, *, state: Tensor, start: float, end: float) -> Tensor:
+ """Return the normalized increment from ``start`` to ``end`` like ``state``.
+
+ Raises:
+ ValueError: For equal endpoints or a query outside the domain.
+ """
+
+ low, high = min(start, end), max(start, end)
+ if low == high or low < self._start or high > self._end:
+ raise ValueError(
+ f"Brownian query [{start}, {end}] is empty or outside "
+ f"[{self._start}, {self._end}]."
+ )
+ normalized_low = (low - self._start) / self._span
+ normalized_high = (high - self._start) / self._span
+ sign = 1.0 if end > start else -1.0
+ scale = sign / math.sqrt(normalized_high - normalized_low)
+ increments = torch.stack(
+ tuple(tree(normalized_low, normalized_high) for tree in self._trees), dim=0
+ )
+ scaled = increments * scale
+ if scaled.device.type == "cpu":
+ return _to_device(scaled, state.device).to(dtype=state.dtype)
+ return scaled.to(device=state.device, dtype=state.dtype)
diff --git a/dflow/configuration.py b/dflow/configuration.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf6b3cc7e280765af73d24435d2e29f7841f5be1
--- /dev/null
+++ b/dflow/configuration.py
@@ -0,0 +1,194 @@
+"""Architecture constants of the dflow_2b denoiser and their ``config.json`` form.
+
+The denoiser has one fixed architecture. ``DFlowConfig`` holds its constants;
+``DFLOW_2B_CONFIG`` is the released model. ``config.json`` carries the same
+values under the ``"denoiser"`` key, and loading compares them field by field,
+so a file for a different architecture fails before any weight is read.
+Other top-level keys of ``config.json`` belong to other components (the text
+adapter) and are validated by their own loaders.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+DENOISER_CONFIG_KEY = "denoiser"
+
+
+@dataclass(frozen=True)
+class DFlowConfig:
+ """Constants of the single-stream denoiser.
+
+ Attributes:
+ latent_channels: Channels of the (whitened dinac3_96) latent.
+ patch_size: Latent pixels per image token side (a 1x1 patch embed).
+ width: Residual stream width of every block.
+ heads: Attention heads; ``width / heads`` must equal the RoPE head
+ width ``sum(rope_axes_dims)``.
+ mlp_ratio: MLP hidden width as a multiple of ``width``.
+ text_refiner_depth: Unmodulated text-only blocks run once per prompt.
+ prefix_depth: Image layers before the routable middle.
+ middle_depth: Routable middle layers (skipped by path drop).
+ suffix_depth: Image layers after the tail join.
+ time_frequency_width: Sinusoidal timestep features.
+ time_hidden_width: Hidden width of the timestep MLP.
+ time_embed_width: Width of the timestep vector every AdaLN reads.
+ time_scale: Multiplier on ``t`` before the sinusoid.
+ time_max_period: Longest sinusoid period.
+ rope_theta: RoPE frequency base.
+ rope_axes_dims: Head channels of the three RoPE axes (text/frame, y, x).
+ rope_axes_lens: Position capacity of the three RoPE axes.
+ norm_eps: RMSNorm epsilon.
+ """
+
+ latent_channels: int
+ patch_size: int
+ width: int
+ heads: int
+ mlp_ratio: int
+ text_refiner_depth: int
+ prefix_depth: int
+ middle_depth: int
+ suffix_depth: int
+ time_frequency_width: int
+ time_hidden_width: int
+ time_embed_width: int
+ time_scale: float
+ time_max_period: float
+ rope_theta: float
+ rope_axes_dims: tuple[int, int, int]
+ rope_axes_lens: tuple[int, int, int]
+ norm_eps: float
+
+ def __post_init__(self) -> None:
+ """Check the constants are mutually consistent.
+
+ Raises:
+ ValueError: If the head width differs from the RoPE head width, a
+ width does not split into heads, or a size is not positive.
+ """
+
+ for name, value in asdict(self).items():
+ numbers = value if isinstance(value, tuple) else (value,)
+ if any(number <= 0 for number in numbers):
+ raise ValueError(f"DFlowConfig.{name} must be positive")
+ if self.width % self.heads != 0:
+ raise ValueError("DFlowConfig.width must be divisible by heads")
+ if self.head_width != sum(self.rope_axes_dims):
+ raise ValueError(
+ f"DFlowConfig head width {self.head_width} must equal the RoPE "
+ f"head width {sum(self.rope_axes_dims)}"
+ )
+ if any(dim % 2 for dim in self.rope_axes_dims):
+ raise ValueError("DFlowConfig.rope_axes_dims entries must be even")
+ if self.patch_size != 1:
+ raise ValueError("DFlowConfig supports a 1x1 patch embed only")
+
+ @property
+ def head_width(self) -> int:
+ """Channels per attention head."""
+
+ return self.width // self.heads
+
+ @property
+ def mlp_hidden_width(self) -> int:
+ """Hidden channels of every block MLP."""
+
+ return self.width * self.mlp_ratio
+
+ @property
+ def image_layer_count(self) -> int:
+ """Modulated image layers (prefix, middle and suffix)."""
+
+ return self.prefix_depth + self.middle_depth + self.suffix_depth
+
+ def to_json_dict(self) -> dict[str, int | float | list[int]]:
+ """The ``config.json`` ``"denoiser"`` mapping (tuples as lists)."""
+
+ return {
+ key: list(value) if isinstance(value, tuple) else value
+ for key, value in asdict(self).items()
+ }
+
+
+DFLOW_2B_CONFIG = DFlowConfig(
+ latent_channels=96,
+ patch_size=1,
+ width=2304,
+ heads=18,
+ mlp_ratio=4,
+ text_refiner_depth=2,
+ prefix_depth=6,
+ middle_depth=18,
+ suffix_depth=6,
+ time_frequency_width=256,
+ time_hidden_width=1024,
+ time_embed_width=256,
+ time_scale=1000.0,
+ time_max_period=10000.0,
+ rope_theta=10000.0,
+ rope_axes_dims=(32, 48, 48),
+ rope_axes_lens=(8192, 512, 512),
+ norm_eps=1e-6,
+)
+
+
+def validate_denoiser_config(payload: dict[str, object], expected: DFlowConfig) -> None:
+ """Compare a ``config.json`` ``"denoiser"`` mapping with ``expected``.
+
+ Raises:
+ ValueError: If a key is missing or unknown, or a value differs.
+ """
+
+ reference = expected.to_json_dict()
+ missing = sorted(set(reference) - set(payload))
+ unknown = sorted(set(payload) - set(reference))
+ if missing or unknown:
+ raise ValueError(
+ f"config.json denoiser keys differ from this package: missing={missing}, "
+ f"unknown={unknown}"
+ )
+ mismatched = {
+ key: (payload[key], value)
+ for key, value in reference.items()
+ if payload[key] != value or type(payload[key]) is not type(value)
+ }
+ if mismatched:
+ details = ", ".join(
+ f"{key}: file {found!r}, expected {want!r}"
+ for key, (found, want) in sorted(mismatched.items())
+ )
+ raise ValueError(
+ f"config.json describes a different denoiser architecture ({details})"
+ )
+
+
+def read_denoiser_config(path: Path, expected: DFlowConfig) -> DFlowConfig:
+ """Read ``config.json`` and return ``expected`` once its denoiser matches.
+
+ Args:
+ path: The release's ``config.json``.
+ expected: The architecture this package builds.
+
+ Returns:
+ ``expected``.
+
+ Raises:
+ FileNotFoundError: If ``path`` does not exist.
+ ValueError: If the file is not a JSON object with a matching
+ ``"denoiser"`` mapping.
+ """
+
+ if not path.is_file():
+ raise FileNotFoundError(f"Missing denoiser config: {path}")
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ match payload:
+ case {"denoiser": dict() as denoiser}:
+ validate_denoiser_config(denoiser, expected)
+ return expected
+ case dict():
+ raise ValueError(f"{path} has no {DENOISER_CONFIG_KEY!r} mapping")
+ case _:
+ raise ValueError(f"{path} must hold a JSON object")
diff --git a/dflow/diffusers_pipeline.py b/dflow/diffusers_pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef239e4265e206bc0ec6b8a8249c0462bbcff474
--- /dev/null
+++ b/dflow/diffusers_pipeline.py
@@ -0,0 +1,127 @@
+"""An optional 🤗 diffusers wrapper around ``DFlowPipeline``.
+
+``diffusers`` is not a dependency of dflow; importing this module without it
+raises ImportError. The wrapper gives the familiar ``DiffusionPipeline`` call
+signature and output type; the model, sampler and guidance are dflow's own.
+It does not support ``save_pretrained`` or loading through
+``DiffusionPipeline.from_pretrained``.
+
+Example::
+
+ from dflow.diffusers_pipeline import DFlowDiffusersPipeline
+
+ pipe = DFlowDiffusersPipeline.from_pretrained("data-archetype/dflow_2b")
+ image = pipe("A lighthouse on a cliff at dusk.", generator_seed=7).images[0]
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from pathlib import Path
+
+import torch
+from diffusers import DiffusionPipeline
+from diffusers.pipelines.pipeline_utils import ImagePipelineOutput
+
+from .guidance import CfgGuidance, ConstantPdgScale, GuidanceSettings, PdgGuidance
+from .inference import GenerationSettings, SamplingSettings
+from .pipeline import REPOSITORY, DFlowPipeline, OutputType
+from .schedules import TimeSchedule
+
+
+class DFlowDiffusersPipeline(DiffusionPipeline):
+ """``DiffusionPipeline``-style access to dflow_2b.
+
+ Args:
+ pipeline: A loaded ``DFlowPipeline``.
+ """
+
+ def __init__(self, pipeline: DFlowPipeline) -> None:
+ super().__init__()
+ self.dflow = pipeline
+
+ @classmethod
+ def from_pretrained( # type: ignore[override]
+ cls,
+ pretrained_model_name_or_path: str | Path = REPOSITORY,
+ *,
+ device: torch.device | str = "cuda",
+ compile: bool = True,
+ revision: str | None = None,
+ ) -> DFlowDiffusersPipeline:
+ """Load dflow_2b (see ``DFlowPipeline.from_pretrained``)."""
+
+ return cls(
+ DFlowPipeline.from_pretrained(
+ pretrained_model_name_or_path,
+ device=device,
+ compile=compile,
+ revision=revision,
+ )
+ )
+
+ @torch.inference_mode()
+ def __call__(
+ self,
+ prompt: str,
+ negative_prompt: str = "",
+ *,
+ height: int = 1216,
+ width: int = 832,
+ num_inference_steps: int = 50,
+ guidance_scale: float = 2.5,
+ num_images_per_prompt: int = 1,
+ generator_seed: int = 0,
+ settings: GenerationSettings | None = None,
+ ) -> ImagePipelineOutput:
+ """Generate images.
+
+ ``guidance_scale`` is the path-drop guidance (PDG) scale of the
+ default preset. A negative prompt needs a guidance mode that reads
+ one (CFG or contrastive PDG), so it is accepted only together with
+ ``settings`` whose guidance reads it; it then replaces the settings'
+ negative prompt. Pass ``settings`` to control everything else; it then
+ overrides every other argument except the prompt, the negative prompt
+ and the image count.
+
+ Raises:
+ ValueError: For a negative prompt without ``settings``, or with
+ settings whose guidance never reads it.
+ """
+
+ chosen = settings
+ if chosen is not None and negative_prompt:
+ if not chosen.guidance.uses_negative:
+ raise ValueError(
+ "negative_prompt is set but the settings' guidance never reads "
+ "it; enable CFG or a contrastive PDG mode."
+ )
+ chosen = replace(chosen, negative_prompt=negative_prompt)
+ if chosen is None:
+ if negative_prompt:
+ raise ValueError(
+ "The default preset uses no negative prompt; pass settings "
+ "with CFG or contrastive PDG and set negative_prompt there."
+ )
+ defaults = GenerationSettings()
+ chosen = replace(
+ defaults,
+ width=width,
+ height=height,
+ seed=generator_seed,
+ sampling=replace(
+ SamplingSettings(),
+ schedule=TimeSchedule(steps=num_inference_steps),
+ ),
+ guidance=GuidanceSettings(
+ pdg=PdgGuidance(scale=ConstantPdgScale(guidance_scale)),
+ cfg=CfgGuidance(),
+ ),
+ )
+ output = self.dflow(
+ prompt,
+ chosen,
+ num_images=num_images_per_prompt,
+ output_type=OutputType.PIL,
+ )
+ return ImagePipelineOutput(images=output.images)
diff --git a/dflow/guidance.py b/dflow/guidance.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb55362d862f2af4aa02068137ac8c2caa70c09c
--- /dev/null
+++ b/dflow/guidance.py
@@ -0,0 +1,1267 @@
+"""CFG and path-drop guidance (PDG): which forwards each step runs and how
+their velocities combine.
+
+Every denoiser forward is a ``BranchCall``: a text branch (the prompt, or the
+negative prompt / learned null text), a routing path (``DFlowPath``) and the
+image self-attention logit gain of that forward. ``GuidanceSettings`` is
+validated once; ``build_guidance_plan`` resolves it against the run's schedule
+into one ``GuidanceStep`` per schedule point (``0 .. steps``), so the per-step
+code is a table lookup plus tensor arithmetic. ``GuidancePlan.guided_velocity``
+takes a callable ``evaluate(call) -> velocity`` and returns the guided velocity.
+
+The main forward always uses the prompt; its gain is
+``GuidanceSettings.self_attention_gain`` (0 on the CFG steps of the alternating
+modes). Guidance forwards use ``guidance_self_attention_gain``. PDG reference
+forwards also carry ``PdgGuidance.suffix_caption_bias``: an additive
+attention-logit bias on the prompt's keys in the suffix layers (0: none).
+
+Single-reference steps return ``v_ref + s (v_main - v_ref)`` (or its APG
+projection); the combined modes return
+``v_main + 0.5 (s_cfg (v_main - v_cfg) + s_pdg (v_main - v_pdg))``, where the
+scales are extra strengths (a quantile-ramp PDG scale has 1 subtracted). A
+PDG scale of 1 (0 in the combined modes) skips the PDG forward. Guidance
+rescale pulls the guided norm toward the main norm.
+"""
+
+from __future__ import annotations
+
+import itertools
+import math
+from bisect import bisect_right
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass, field
+from enum import StrEnum
+
+import numpy as np
+import torch
+from torch import Tensor
+
+from .schedules import ScheduleCdf, TimeSchedule, build_timesteps
+from .types import DFlowPath
+
+SELF_ATTENTION_GAIN_MIN = -0.5
+SELF_ATTENTION_GAIN_MAX = 0.1
+DEFAULT_SELF_ATTENTION_GAIN = -0.03
+DEFAULT_PDG_SCALE = 2.5
+# Release default: the PDG reference reads the prompt less in its suffix layers.
+DEFAULT_SUFFIX_CAPTION_BIAS = -4.0
+SUFFIX_CAPTION_BIAS_MIN = -10.0
+SUFFIX_CAPTION_BIAS_MAX = 0.0
+# A PDG scale within this distance of its neutral value skips the PDG forward.
+_NEUTRAL_SCALE_TOLERANCE = 1.0e-6
+# The LINEAR_LOGSNR curve interpolates between these logSNR anchors.
+_CURVE_LOGSNR_NOISY = -15.0
+_CURVE_LOGSNR_CLEAN = 15.0
+_BEZIER_SAMPLES = 4096
+# Radial APG band edges in cycles per latent pixel: DC, (0, 1/32], (1/32, 1/8],
+# (1/8, 1/4] and above 1/4.
+PROJECTION_BAND_EDGES: tuple[float, ...] = (0.0, 1 / 32, 1 / 8, 1 / 4)
+PROJECTION_BAND_COUNT = len(PROJECTION_BAND_EDGES) + 1
+
+
+class BranchText(StrEnum):
+ """Text a forward is conditioned on.
+
+ POSITIVE: the prompt.
+ NEGATIVE: the negative prompt, or the learned null text when there is none.
+ """
+
+ POSITIVE = "positive"
+ NEGATIVE = "negative"
+
+
+class GuidanceBranch(StrEnum):
+ """A denoiser forward a guidance step may need: text branch and path."""
+
+ POSITIVE_FULL = "positive_full"
+ POSITIVE_PATH_DROP = "positive_path_drop"
+ POSITIVE_THREE_QUARTER = "positive_three_quarter"
+ NEGATIVE_FULL = "negative_full"
+ NEGATIVE_PATH_DROP = "negative_path_drop"
+ NEGATIVE_THREE_QUARTER = "negative_three_quarter"
+
+ @staticmethod
+ def of(text: BranchText, path: DFlowPath) -> GuidanceBranch:
+ """Return the branch of a text branch and a path."""
+
+ return GuidanceBranch(f"{text.value}_{path.value}")
+
+ @property
+ def text(self) -> BranchText:
+ """The text branch of this forward."""
+
+ return BranchText(self.value.split("_", 1)[0])
+
+ @property
+ def path(self) -> DFlowPath:
+ """The routing path of this forward."""
+
+ return DFlowPath(self.value.split("_", 1)[1])
+
+
+@dataclass(frozen=True)
+class BranchCall:
+ """One denoiser forward: branch, image self-attention logit gain and the
+ suffix layers' prompt-key logit bias (0: none)."""
+
+ branch: GuidanceBranch
+ self_attention_gain: float
+ suffix_caption_bias: float
+
+
+class PdgMode(StrEnum):
+ """Path-drop guidance policies (the reference is the same network with its
+ middle layers skipped).
+
+ FULL: middle dropped, prompt text.
+ FULL_CONTRASTIVE: middle dropped, negative text.
+ THREE_QUARTER: one image token per 2x2 group through the middle, prompt.
+ ALTERNATE_CONTRASTIVE_POSITIVE: FULL_CONTRASTIVE on even steps, FULL on odd.
+ ALTERNATE_PDG_FIRST / ALTERNATE_CFG_FIRST: contrastive full PDG and CFG on
+ alternate steps of the PDG window, starting with PDG / CFG.
+ ALTERNATE_POSITIVE_PDG_FIRST / ALTERNATE_POSITIVE_CFG_FIRST: the same with
+ prompt-text PDG.
+ COMBINED_CFG_PDG: CFG and contrastive PDG every step, differentials averaged.
+ PDG_WITH_ALTERNATING_CFG: contrastive PDG every step, plus CFG (averaged) on
+ odd steps.
+ CFG_TO_PDG: CFG before the PDG window, prompt-text full PDG inside it.
+ """
+
+ FULL = "full"
+ FULL_CONTRASTIVE = "full_contrastive"
+ THREE_QUARTER = "three_quarter"
+ ALTERNATE_CONTRASTIVE_POSITIVE = "alternate_contrastive_positive"
+ ALTERNATE_PDG_FIRST = "alternate_pdg_first"
+ ALTERNATE_CFG_FIRST = "alternate_cfg_first"
+ ALTERNATE_POSITIVE_PDG_FIRST = "alternate_positive_pdg_first"
+ ALTERNATE_POSITIVE_CFG_FIRST = "alternate_positive_cfg_first"
+ COMBINED_CFG_PDG = "combined_cfg_pdg"
+ PDG_WITH_ALTERNATING_CFG = "pdg_with_alternating_cfg"
+ CFG_TO_PDG = "cfg_to_pdg"
+
+ @property
+ def uses_cfg(self) -> bool:
+ """Whether the mode runs CFG forwards (and needs a CFG scale)."""
+
+ match self:
+ case (
+ PdgMode.ALTERNATE_PDG_FIRST
+ | PdgMode.ALTERNATE_CFG_FIRST
+ | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST
+ | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST
+ | PdgMode.COMBINED_CFG_PDG
+ | PdgMode.PDG_WITH_ALTERNATING_CFG
+ | PdgMode.CFG_TO_PDG
+ ):
+ return True
+ case (
+ PdgMode.FULL
+ | PdgMode.FULL_CONTRASTIVE
+ | PdgMode.THREE_QUARTER
+ | PdgMode.ALTERNATE_CONTRASTIVE_POSITIVE
+ ):
+ return False
+ case _ as unreachable:
+ raise ValueError(f"Unsupported PDG mode: {unreachable}")
+
+ @property
+ def alternates_with_cfg(self) -> bool:
+ """Whether PDG and CFG alternate inside the PDG window."""
+
+ return self in _ALTERNATING_MODES
+
+ @property
+ def averages_cfg(self) -> bool:
+ """Whether CFG and PDG differentials are averaged on shared steps."""
+
+ return self in (PdgMode.COMBINED_CFG_PDG, PdgMode.PDG_WITH_ALTERNATING_CFG)
+
+ def text_at(self, step: int) -> BranchText:
+ """Text of this mode's PDG reference on ``step``."""
+
+ match self:
+ case PdgMode.ALTERNATE_CONTRASTIVE_POSITIVE:
+ return BranchText.NEGATIVE if step % 2 == 0 else BranchText.POSITIVE
+ case (
+ PdgMode.FULL_CONTRASTIVE
+ | PdgMode.ALTERNATE_PDG_FIRST
+ | PdgMode.ALTERNATE_CFG_FIRST
+ | PdgMode.COMBINED_CFG_PDG
+ | PdgMode.PDG_WITH_ALTERNATING_CFG
+ ):
+ return BranchText.NEGATIVE
+ case (
+ PdgMode.FULL
+ | PdgMode.THREE_QUARTER
+ | PdgMode.CFG_TO_PDG
+ | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST
+ | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST
+ ):
+ return BranchText.POSITIVE
+ case _ as unreachable:
+ raise ValueError(f"Unsupported PDG mode: {unreachable}")
+
+ @property
+ def uses_negative(self) -> bool:
+ """Whether any step of this mode conditions on the negative text."""
+
+ return self.uses_cfg or BranchText.NEGATIVE in (
+ self.text_at(0),
+ self.text_at(1),
+ )
+
+
+_ALTERNATING_MODES = frozenset(
+ {
+ PdgMode.ALTERNATE_PDG_FIRST,
+ PdgMode.ALTERNATE_CFG_FIRST,
+ PdgMode.ALTERNATE_POSITIVE_PDG_FIRST,
+ PdgMode.ALTERNATE_POSITIVE_CFG_FIRST,
+ }
+)
+
+
+def _alternation_uses_pdg(mode: PdgMode, step: int) -> bool:
+ """Whether an alternating mode runs PDG (not CFG) on ``step``."""
+
+ match mode:
+ case PdgMode.ALTERNATE_PDG_FIRST | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST:
+ return step % 2 == 0
+ case PdgMode.ALTERNATE_CFG_FIRST | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST:
+ return step % 2 == 1
+ case _ as unsupported:
+ raise ValueError(f"{unsupported} does not alternate PDG and CFG.")
+
+
+def _validate_scale(value: float, name: str) -> None:
+ """Require a finite, non-negative guidance value.
+
+ Raises:
+ ValueError: Otherwise.
+ """
+
+ if not math.isfinite(value) or value < 0.0:
+ raise ValueError(f"{name} must be finite and >= 0, got {value}.")
+
+
+def _validate_gain(value: float, name: str) -> None:
+ """Require a self-attention gain in [-0.5, 0.1].
+
+ Raises:
+ ValueError: Otherwise.
+ """
+
+ if not (
+ math.isfinite(value)
+ and SELF_ATTENTION_GAIN_MIN <= value <= SELF_ATTENTION_GAIN_MAX
+ ):
+ raise ValueError(
+ f"{name} must lie in [{SELF_ATTENTION_GAIN_MIN}, "
+ f"{SELF_ATTENTION_GAIN_MAX}], got {value}."
+ )
+
+
+@dataclass(frozen=True)
+class StepWindow:
+ """Inclusive solver-step window; ``stop_step`` None is the last step.
+
+ Raises:
+ ValueError: For a negative start or a stop before the start.
+ """
+
+ start_step: int = 0
+ stop_step: int | None = None
+
+ def __post_init__(self) -> None:
+ """Validate the bounds that do not depend on the step count."""
+
+ if self.start_step < 0:
+ raise ValueError(f"start_step must be >= 0, got {self.start_step}.")
+ if self.stop_step is not None and self.stop_step < self.start_step:
+ raise ValueError(
+ f"stop_step {self.stop_step} is before start_step {self.start_step}."
+ )
+
+ def resolve(self, steps: int, name: str) -> tuple[int, int]:
+ """Return (start, stop) for a run of ``steps`` updates.
+
+ Raises:
+ ValueError: If the window does not fit inside the run.
+ """
+
+ stop = steps - 1 if self.stop_step is None else self.stop_step
+ if stop >= steps or self.start_step > stop:
+ raise ValueError(
+ f"The {name} window [{self.start_step}, {stop}] does not fit in "
+ f"{steps} steps (indices 0 to {steps - 1})."
+ )
+ return self.start_step, stop
+
+
+@dataclass(frozen=True)
+class CfgGuidance:
+ """Classifier-free guidance against the negative text.
+
+ Attributes:
+ enabled: Run CFG inside ``window``. The alternating, combined and
+ CFG-to-PDG PDG modes run CFG forwards of their own and need
+ ``scale`` even when this is False.
+ scale: Guidance scale (1 is no guidance); None when unused.
+ window: Steps where plain CFG applies.
+
+ Raises:
+ ValueError: For a negative scale or CFG enabled without a scale.
+ """
+
+ enabled: bool = False
+ scale: float | None = None
+ window: StepWindow = field(default_factory=StepWindow)
+
+ def __post_init__(self) -> None:
+ """Validate the scale."""
+
+ if self.scale is not None:
+ _validate_scale(self.scale, "CfgGuidance.scale")
+ if self.enabled and self.scale is None:
+ raise ValueError("CfgGuidance.scale is required when CFG is enabled.")
+
+
+@dataclass(frozen=True)
+class ConstantPdgScale:
+ """The same PDG scale at every step."""
+
+ scale: float = DEFAULT_PDG_SCALE
+
+ def __post_init__(self) -> None:
+ """Validate the scale."""
+
+ _validate_scale(self.scale, "ConstantPdgScale.scale")
+
+
+@dataclass(frozen=True)
+class RampPdgScale:
+ """PDG scale linear in the schedule's CDF quantile from ``start_scale`` at the
+ noisy end to ``end_scale`` after ``length`` of the distribution, then held.
+
+ On the standard schedules step ``i`` of ``N`` sits at quantile ``1 - i/N``,
+ so ``length`` is the fraction of the steps (0.3: until step 15 of 50). The
+ scale is read at every evaluation's actual time.
+ """
+
+ start_scale: float = 4.5
+ end_scale: float = DEFAULT_PDG_SCALE
+ length: float = 0.3
+
+ def __post_init__(self) -> None:
+ """Validate scales and length.
+
+ Raises:
+ ValueError: For negative scales or a length outside (0, 1].
+ """
+
+ _validate_scale(self.start_scale, "RampPdgScale.start_scale")
+ _validate_scale(self.end_scale, "RampPdgScale.end_scale")
+ if not (math.isfinite(self.length) and 0.0 < self.length <= 1.0):
+ raise ValueError(
+ f"RampPdgScale.length must lie in (0, 1], got {self.length}."
+ )
+
+ def scale_at_quantile(self, quantile: float) -> float:
+ """Interpolate the two knots (1, start) and (1 - length, end)."""
+
+ knots = ((1.0, self.start_scale), (1.0 - self.length, self.end_scale))
+ q = min(1.0, max(knots[-1][0], quantile))
+ index = min(bisect_right(knots, -q, key=lambda knot: -knot[0]), len(knots) - 1)
+ high, low = knots[max(index - 1, 0)], knots[index]
+ fraction = (high[0] - q) / (high[0] - low[0])
+ return high[1] + fraction * (low[1] - high[1])
+
+
+class EndpointCurveKind(StrEnum):
+ """Shape of a per-step PDG curve from the noisy-end scale to the clean-end one.
+
+ LINEAR: linear in the step index.
+ LINEAR_LOGSNR: linear in the step's log-SNR between -15 and +15.
+ POWER: (step / steps) ** power.
+ S_CURVE: logistic in the step position, normalised to the endpoints.
+ """
+
+ LINEAR = "linear"
+ LINEAR_LOGSNR = "linear_logsnr"
+ POWER = "power"
+ S_CURVE = "s_curve"
+
+
+@dataclass(frozen=True)
+class EndpointPdgCurve:
+ """A per-step PDG scale from ``noisy_scale`` (first point) to ``clean_scale``
+ (last point).
+
+ Raises:
+ ValueError: For negative scales, a non-positive power or sharpness, or
+ a knee outside [0, 1].
+ """
+
+ kind: EndpointCurveKind = EndpointCurveKind.POWER
+ noisy_scale: float = 2.0
+ clean_scale: float = DEFAULT_PDG_SCALE
+ power: float = 3.0
+ s_curve_knee: float = 0.5
+ s_curve_sharpness: float = 8.0
+
+ def __post_init__(self) -> None:
+ """Validate every parameter."""
+
+ _validate_scale(self.noisy_scale, "EndpointPdgCurve.noisy_scale")
+ _validate_scale(self.clean_scale, "EndpointPdgCurve.clean_scale")
+ for name, value in (
+ ("power", self.power),
+ ("s_curve_sharpness", self.s_curve_sharpness),
+ ):
+ if not (math.isfinite(value) and value > 0.0):
+ raise ValueError(f"EndpointPdgCurve.{name} must be > 0, got {value}.")
+ if not (math.isfinite(self.s_curve_knee) and 0.0 <= self.s_curve_knee <= 1.0):
+ raise ValueError(
+ f"EndpointPdgCurve.s_curve_knee must lie in [0, 1], got "
+ f"{self.s_curve_knee}."
+ )
+
+
+@dataclass(frozen=True)
+class BezierPdgCurve:
+ """A per-step PDG scale ``1 + multiplier * y(t)`` with ``y`` a cubic Bezier
+ over flow time from ``(edge, clean_y)`` to ``(1 - edge, noisy_y)``.
+
+ Raises:
+ ValueError: For negative values, an edge outside (0, 0.5), handles
+ outside [edge, 1 - edge] or a clean handle after the noisy one.
+ """
+
+ multiplier: float = 3.0
+ clean_y: float = 0.205
+ clean_handle_t: float = 0.010
+ clean_handle_y: float = 0.408
+ noisy_handle_t: float = 0.995
+ noisy_handle_y: float = 0.275
+ noisy_y: float = 0.523
+ edge: float = 0.005
+
+ def __post_init__(self) -> None:
+ """Validate every control point."""
+
+ for name, value in (
+ ("multiplier", self.multiplier),
+ ("clean_y", self.clean_y),
+ ("clean_handle_y", self.clean_handle_y),
+ ("noisy_handle_y", self.noisy_handle_y),
+ ("noisy_y", self.noisy_y),
+ ):
+ _validate_scale(value, f"BezierPdgCurve.{name}")
+ if not (math.isfinite(self.edge) and 0.0 < self.edge < 0.5):
+ raise ValueError(
+ f"BezierPdgCurve.edge must lie in (0, 0.5), got {self.edge}."
+ )
+ for name, value in (
+ ("clean_handle_t", self.clean_handle_t),
+ ("noisy_handle_t", self.noisy_handle_t),
+ ):
+ if not (math.isfinite(value) and self.edge <= value <= 1.0 - self.edge):
+ raise ValueError(
+ f"BezierPdgCurve.{name} must lie in [edge, 1 - edge], got {value}."
+ )
+ if self.clean_handle_t > self.noisy_handle_t:
+ raise ValueError("BezierPdgCurve.clean_handle_t must be <= noisy_handle_t.")
+
+
+type PdgScaleSchedule = (
+ ConstantPdgScale | RampPdgScale | EndpointPdgCurve | BezierPdgCurve
+)
+
+
+@dataclass(frozen=True)
+class PdgGuidance:
+ """Path-drop guidance: policy, scale schedule, step window and the
+ reference's suffix caption bias.
+
+ Attributes:
+ suffix_caption_bias: Additive attention-logit bias on the prompt's
+ token keys (the learned suffix tokens excluded) in the six suffix
+ layers of every PDG reference forward; negative values make the
+ reference read the prompt less. 0 turns it off; the supported
+ range is ``[SUFFIX_CAPTION_BIAS_MIN, SUFFIX_CAPTION_BIAS_MAX]``.
+
+ Raises:
+ ValueError: For a quantile ramp with CFG_TO_PDG, or a suffix caption
+ bias outside the supported range.
+ """
+
+ mode: PdgMode = PdgMode.FULL
+ scale: PdgScaleSchedule = field(default_factory=ConstantPdgScale)
+ window: StepWindow = field(default_factory=StepWindow)
+ suffix_caption_bias: float = DEFAULT_SUFFIX_CAPTION_BIAS
+
+ def __post_init__(self) -> None:
+ """Reject the ramp with the step-window crossover mode and a bias
+ outside the supported range."""
+
+ if not (
+ math.isfinite(self.suffix_caption_bias)
+ and SUFFIX_CAPTION_BIAS_MIN
+ <= self.suffix_caption_bias
+ <= SUFFIX_CAPTION_BIAS_MAX
+ ):
+ raise ValueError(
+ "suffix_caption_bias must lie in "
+ f"[{SUFFIX_CAPTION_BIAS_MIN}, {SUFFIX_CAPTION_BIAS_MAX}], got "
+ f"{self.suffix_caption_bias}."
+ )
+ if self.mode is PdgMode.CFG_TO_PDG and isinstance(self.scale, RampPdgScale):
+ raise ValueError(
+ "CFG_TO_PDG switches on the step window; use a constant or "
+ "per-step PDG scale with it, not a quantile ramp."
+ )
+
+
+class ProjectionMode(StrEnum):
+ """Adaptive projected guidance (APG) on the x0-space guidance update.
+
+ OFF: plain guidance.
+ GLOBAL: one projection per sample.
+ PER_BAND: one projection per sample and radial frequency band.
+ """
+
+ OFF = "off"
+ GLOBAL = "global"
+ PER_BAND = "per_band"
+
+
+@dataclass(frozen=True)
+class ProjectedGuidance:
+ """APG: the guided x0 is ``x0_main + (w - 1)(D_perp + parallel_weight D_par)``
+ with ``D = x0_main - x0_reference`` split against ``x0_main``.
+
+ Attributes:
+ mode: OFF, GLOBAL or PER_BAND.
+ parallel_weight: Weight kept on the parallel part (1 is plain guidance).
+ first_band: PER_BAND only: bands below it stay unprojected (0 is the
+ mean colour, 1 the coarsest structure).
+
+ Raises:
+ ValueError: For a weight outside [0, 1] or an invalid first band.
+ """
+
+ mode: ProjectionMode = ProjectionMode.OFF
+ parallel_weight: float = 1.0
+ first_band: int = 0
+
+ def __post_init__(self) -> None:
+ """Validate weight and band."""
+
+ if not (
+ math.isfinite(self.parallel_weight) and 0.0 <= self.parallel_weight <= 1.0
+ ):
+ raise ValueError(
+ "ProjectedGuidance.parallel_weight must lie in [0, 1], got "
+ f"{self.parallel_weight}."
+ )
+ if not 0 <= self.first_band < PROJECTION_BAND_COUNT:
+ raise ValueError(
+ f"ProjectedGuidance.first_band must lie in [0, "
+ f"{PROJECTION_BAND_COUNT - 1}], got {self.first_band}."
+ )
+ if self.mode is not ProjectionMode.PER_BAND and self.first_band != 0:
+ raise ValueError("ProjectedGuidance.first_band needs PER_BAND mode.")
+
+
+class SparseStepSchedule(StrEnum):
+ """Which steps run the main and CFG forwards on the three-quarter path.
+
+ PREFIX: the first ``percent`` of the steps.
+ CYCLIC: ``percent`` of the steps spread evenly (50: every other step).
+ """
+
+ PREFIX = "prefix"
+ CYCLIC = "cyclic"
+
+
+@dataclass(frozen=True)
+class SparseMiddleSteps:
+ """Speed option: run the main (and CFG) forwards with one image token per
+ 2x2 group through the middle on some steps; PDG then drops the full middle.
+
+ Raises:
+ ValueError: For a percent outside [0, 100].
+ """
+
+ percent: float = 0.0
+ schedule: SparseStepSchedule = SparseStepSchedule.PREFIX
+
+ def __post_init__(self) -> None:
+ """Validate the percent."""
+
+ if not (math.isfinite(self.percent) and 0.0 <= self.percent <= 100.0):
+ raise ValueError(
+ f"SparseMiddleSteps.percent must lie in [0, 100], got {self.percent}."
+ )
+
+ def active(self, step: int, steps: int) -> bool:
+ """Whether ``step`` (0-based, of ``steps``) is sparse."""
+
+ if self.percent <= 0.0:
+ return False
+ match self.schedule:
+ case SparseStepSchedule.PREFIX:
+ count = math.ceil((self.percent / 100.0) * float(steps))
+ return step < max(0, min(steps, count))
+ case SparseStepSchedule.CYCLIC:
+ before = math.floor((float(step) * self.percent) / 100.0)
+ after = math.floor((float(step + 1) * self.percent) / 100.0)
+ return after > before
+ case _ as unreachable:
+ raise ValueError(f"Unsupported sparse step schedule: {unreachable}")
+
+
+@dataclass(frozen=True)
+class GuidanceSettings:
+ """Complete guidance configuration (defaults: the release's default preset).
+
+ Attributes:
+ pdg: Path-drop guidance, or None for none.
+ cfg: Classifier-free guidance.
+ self_attention_gain: Image self-attention logit gain of the main forward.
+ guidance_self_attention_gain: Gain of the guidance forwards.
+ projection: APG on single-reference steps.
+ rescale: Guidance rescale in [0, 1] (0 off); exclusive with APG.
+ sparse_middle: Sparse middle steps on the main and CFG forwards.
+
+ Raises:
+ ValueError: On inconsistent or out-of-range settings.
+ """
+
+ pdg: PdgGuidance | None = field(default_factory=PdgGuidance)
+ cfg: CfgGuidance = field(default_factory=CfgGuidance)
+ self_attention_gain: float = DEFAULT_SELF_ATTENTION_GAIN
+ guidance_self_attention_gain: float = 0.0
+ projection: ProjectedGuidance = field(default_factory=ProjectedGuidance)
+ rescale: float = 0.0
+ sparse_middle: SparseMiddleSteps = field(default_factory=SparseMiddleSteps)
+
+ def __post_init__(self) -> None:
+ """Validate gains, CFG needs, APG and rescale."""
+
+ _validate_gain(self.self_attention_gain, "self_attention_gain")
+ _validate_gain(
+ self.guidance_self_attention_gain, "guidance_self_attention_gain"
+ )
+ if self.pdg is not None and self.pdg.mode.uses_cfg and self.cfg.scale is None:
+ raise ValueError(f"PDG mode {self.pdg.mode.value} needs cfg.scale.")
+ if (
+ self.cfg.scale is not None
+ and not self.cfg.enabled
+ and not (self.pdg is not None and self.pdg.mode.uses_cfg)
+ ):
+ raise ValueError(
+ "cfg.scale is set but neither CFG nor a CFG-using PDG mode is on."
+ )
+ if not (math.isfinite(self.rescale) and 0.0 <= self.rescale <= 1.0):
+ raise ValueError(f"rescale must lie in [0, 1], got {self.rescale}.")
+ if self.projection.mode is not ProjectionMode.OFF:
+ self._validate_projection()
+
+ def _validate_projection(self) -> None:
+ """APG needs guidance, excludes rescale and the averaged modes.
+
+ Raises:
+ ValueError: Otherwise.
+ """
+
+ if self.pdg is None and not self.cfg.enabled:
+ raise ValueError("Projected guidance needs CFG or PDG on.")
+ if self.rescale > 0.0:
+ raise ValueError("Projected guidance and guidance rescale are exclusive.")
+ if self.pdg is not None and self.pdg.mode.averages_cfg:
+ raise ValueError(
+ f"Projected guidance needs a single reference; {self.pdg.mode.value} "
+ "averages two."
+ )
+
+ @property
+ def uses_negative(self) -> bool:
+ """Whether any forward conditions on the negative (or null) text."""
+
+ return self.cfg.enabled or (
+ self.pdg is not None and self.pdg.mode.uses_negative
+ )
+
+
+@dataclass(frozen=True)
+class UnguidedStep:
+ """Only the main forward."""
+
+ main: BranchCall
+
+
+@dataclass(frozen=True)
+class SingleReferenceStep:
+ """``v_ref + scale (v_main - v_ref)`` (or its APG projection)."""
+
+ main: BranchCall
+ reference: BranchCall
+ scale: float
+
+
+@dataclass(frozen=True)
+class AveragedStep:
+ """``v_main + 0.5 (cfg_scale (v_main - v_cfg) + pdg_scale (v_main - v_pdg))``;
+ ``pdg`` None (neutral PDG scale) uses ``v_pdg = v_main``."""
+
+ main: BranchCall
+ cfg: BranchCall
+ pdg: BranchCall | None
+ cfg_scale: float
+ pdg_scale: float
+
+
+type GuidanceStep = UnguidedStep | SingleReferenceStep | AveragedStep
+
+
+def _sigmoid(value: float) -> float:
+ """Numerically stable logistic function."""
+
+ if value >= 0.0:
+ return 1.0 / (1.0 + math.exp(-value))
+ exp_value = math.exp(value)
+ return exp_value / (1.0 + exp_value)
+
+
+def _positions(count: int) -> list[float]:
+ """Evenly spaced positions in [0, 1] (``[0.0]`` for one point)."""
+
+ if count == 1:
+ return [0.0]
+ return [float(index) / float(count - 1) for index in range(count)]
+
+
+def _endpoint_weights(
+ curve: EndpointPdgCurve, count: int, times: Sequence[float]
+) -> list[float]:
+ """Interpolation weights (0 noisy, 1 clean) of an endpoint curve.
+
+ Raises:
+ ValueError: For fewer than two points or a degenerate S-curve.
+ """
+
+ if count < 2:
+ raise ValueError(f"A {curve.kind.value} PDG curve needs at least two points.")
+ positions = _positions(count)
+ match curve.kind:
+ case EndpointCurveKind.LINEAR:
+ return positions
+ case EndpointCurveKind.POWER:
+ return [position**curve.power for position in positions]
+ case EndpointCurveKind.LINEAR_LOGSNR:
+ span = _CURVE_LOGSNR_CLEAN - _CURVE_LOGSNR_NOISY
+ weights = []
+ for time in times:
+ clamped = min(max(time, 1e-12), 1.0 - 1e-12)
+ log_snr = -2.0 * (math.log(clamped) - math.log1p(-clamped))
+ weights.append(
+ min(max((log_snr - _CURVE_LOGSNR_NOISY) / span, 0.0), 1.0)
+ )
+ return weights
+ case EndpointCurveKind.S_CURVE:
+ raw = [
+ _sigmoid((position - curve.s_curve_knee) * curve.s_curve_sharpness)
+ for position in positions
+ ]
+ if raw[-1] - raw[0] <= 1e-12:
+ raise ValueError("s_curve_sharpness is too small to normalise.")
+ return [(value - raw[0]) / (raw[-1] - raw[0]) for value in raw]
+ case _ as unreachable:
+ raise ValueError(f"Unsupported endpoint curve: {unreachable}")
+
+
+def _bezier_values(curve: BezierPdgCurve, count: int) -> list[float]:
+ """Per-point ``1 + multiplier * y`` of a Bezier curve, noisy point first."""
+
+ u = np.linspace(0.0, 1.0, _BEZIER_SAMPLES, dtype=np.float64)
+ v = 1.0 - u
+ basis = (v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u)
+ xs = (curve.edge, curve.clean_handle_t, curve.noisy_handle_t, 1.0 - curve.edge)
+ ys = (curve.clean_y, curve.clean_handle_y, curve.noisy_handle_y, curve.noisy_y)
+ x_values = basis[0] * xs[0] + basis[1] * xs[1] + basis[2] * xs[2] + basis[3] * xs[3]
+ y_values = basis[0] * ys[0] + basis[1] * ys[1] + basis[2] * ys[2] + basis[3] * ys[3]
+ order = np.argsort(x_values)
+ query = np.asarray([1.0 - position for position in _positions(count)])
+ interpolated = np.interp(query, x_values[order], y_values[order])
+ return [1.0 + curve.multiplier * float(value) for value in interpolated.tolist()]
+
+
+def per_step_pdg_scales(
+ curve: EndpointPdgCurve | BezierPdgCurve,
+ *,
+ schedule: TimeSchedule,
+ log_snr_shift: float,
+) -> tuple[float, ...]:
+ """Return a per-step curve's PDG scale at each of the ``steps + 1`` points,
+ rounded to float32 (as the training code stores them).
+
+ LINEAR_LOGSNR reads the shifted schedule's times without the noisy-endpoint
+ cap.
+ """
+
+ count = schedule.steps + 1
+ match curve:
+ case BezierPdgCurve():
+ values = _bezier_values(curve, count)
+ case EndpointPdgCurve():
+ times = build_timesteps(
+ schedule,
+ log_snr_shift=log_snr_shift,
+ finite_noisy_endpoint=False,
+ device=torch.device("cpu"),
+ ).tolist()
+ weights = _endpoint_weights(curve, count, times)
+ noisy, clean = curve.noisy_scale, curve.clean_scale
+ values = [noisy + (clean - noisy) * weight for weight in weights]
+ case _ as unreachable:
+ raise ValueError(f"Unsupported PDG curve: {unreachable}")
+ return tuple(torch.tensor(values, dtype=torch.float32, device="cpu").tolist())
+
+
+@dataclass(frozen=True)
+class _PlanInputs:
+ """Run-level values the per-step resolution reads."""
+
+ settings: GuidanceSettings
+ steps: int
+ times: tuple[float, ...]
+ cdf: ScheduleCdf
+ pdg_values: tuple[float, ...] | None
+ cfg_window: tuple[int, int] | None
+ pdg_window: tuple[int, int] | None
+
+
+@dataclass(frozen=True)
+class _Activity:
+ """Which guidance runs on one step and the PDG reference path."""
+
+ cfg: bool
+ pdg: bool
+ pdg_path: DFlowPath
+
+
+def _concrete_pdg_path(mode: PdgMode) -> DFlowPath:
+ """The reference path of a single-reference PDG mode."""
+
+ return (
+ DFlowPath.THREE_QUARTER
+ if mode is PdgMode.THREE_QUARTER
+ else DFlowPath.PATH_DROP
+ )
+
+
+def _inside(step: int, window: tuple[int, int] | None) -> bool:
+ """Whether ``step`` lies in an inclusive window (None: never)."""
+
+ return window is not None and window[0] <= step <= window[1]
+
+
+def _resolve_activity(inputs: _PlanInputs, step: int) -> _Activity:
+ """Resolve which of CFG and PDG run on ``step`` (clamped step index)."""
+
+ cfg_window = _inside(step, inputs.cfg_window)
+ pdg_window = _inside(step, inputs.pdg_window)
+ pdg = inputs.settings.pdg
+ if pdg is None:
+ return _Activity(cfg_window, False, DFlowPath.PATH_DROP)
+ mode = pdg.mode
+ if pdg_window and mode.alternates_with_cfg:
+ uses_pdg = _alternation_uses_pdg(mode, step)
+ return _Activity(not uses_pdg, uses_pdg, DFlowPath.PATH_DROP)
+ if mode is PdgMode.CFG_TO_PDG:
+ if pdg_window:
+ return _Activity(False, True, DFlowPath.PATH_DROP)
+ start = inputs.pdg_window[0] if inputs.pdg_window is not None else 0
+ return _Activity(step < start, False, DFlowPath.PATH_DROP)
+ if pdg_window and mode is PdgMode.PDG_WITH_ALTERNATING_CFG:
+ return _Activity(step % 2 == 1, True, DFlowPath.PATH_DROP)
+ if pdg_window and mode is PdgMode.COMBINED_CFG_PDG:
+ return _Activity(True, True, DFlowPath.PATH_DROP)
+ return _Activity(cfg_window, pdg_window, _concrete_pdg_path(mode))
+
+
+def _pdg_scale(inputs: _PlanInputs, index: int) -> float:
+ """The absolute PDG scale at schedule point ``index``."""
+
+ pdg = inputs.settings.pdg
+ if pdg is None:
+ raise ValueError("PDG scale requested without PDG.")
+ match pdg.scale:
+ case ConstantPdgScale(scale=scale):
+ return scale
+ case RampPdgScale() as ramp:
+ return ramp.scale_at_quantile(
+ inputs.cdf.quantile_at_time(inputs.times[index])
+ )
+ case EndpointPdgCurve() | BezierPdgCurve():
+ if inputs.pdg_values is None:
+ raise ValueError("Per-step PDG values were not prepared.")
+ return inputs.pdg_values[index]
+ case _ as unreachable:
+ raise ValueError(f"Unsupported PDG scale: {unreachable}")
+
+
+def _cfg_scale(settings: GuidanceSettings) -> float:
+ """The CFG scale of an active CFG forward."""
+
+ if settings.cfg.scale is None:
+ raise ValueError("A CFG forward is active but cfg.scale is None.")
+ return settings.cfg.scale
+
+
+def _resolve_step(inputs: _PlanInputs, index: int) -> GuidanceStep:
+ """Resolve the forwards and combination of schedule point ``index``."""
+
+ settings = inputs.settings
+ step = min(index, inputs.steps - 1)
+ activity = _resolve_activity(inputs, step)
+ cfg_on, pdg_on = activity.cfg, activity.pdg
+ mode = settings.pdg.mode if settings.pdg is not None else None
+ averaged = cfg_on and pdg_on and mode is not None and mode.averages_cfg
+ ramp = settings.pdg is not None and isinstance(settings.pdg.scale, RampPdgScale)
+ pdg_scale = _pdg_scale(inputs, index) if pdg_on else 0.0
+ neutral = 0.0 if averaged and not ramp else 1.0
+ if pdg_on and math.isclose(
+ pdg_scale, neutral, rel_tol=0.0, abs_tol=_NEUTRAL_SCALE_TOLERANCE
+ ):
+ pdg_on = False
+ alternating_cfg = (
+ cfg_on and not pdg_on and mode is not None and mode.alternates_with_cfg
+ )
+ main_gain = 0.0 if alternating_cfg else settings.self_attention_gain
+ guidance_gain = 0.0 if alternating_cfg else settings.guidance_self_attention_gain
+ sparse = settings.sparse_middle.active(step, inputs.steps)
+ dense_path = DFlowPath.THREE_QUARTER if sparse else DFlowPath.FULL
+ pdg_path = DFlowPath.PATH_DROP if sparse else activity.pdg_path
+ caption_bias = settings.pdg.suffix_caption_bias if settings.pdg is not None else 0.0
+ main = BranchCall(
+ GuidanceBranch.of(BranchText.POSITIVE, dense_path), main_gain, 0.0
+ )
+ if not (cfg_on or pdg_on):
+ return UnguidedStep(main)
+ cfg_call = BranchCall(
+ GuidanceBranch.of(BranchText.NEGATIVE, dense_path), guidance_gain, 0.0
+ )
+ if averaged:
+ pdg_call = (
+ BranchCall(
+ GuidanceBranch.of(BranchText.NEGATIVE, pdg_path),
+ guidance_gain,
+ caption_bias,
+ )
+ if pdg_on
+ else None
+ )
+ pdg_extra = _pdg_scale(inputs, index) - (1.0 if ramp else 0.0)
+ return AveragedStep(main, cfg_call, pdg_call, _cfg_scale(settings), pdg_extra)
+ if not pdg_on or mode is None:
+ return SingleReferenceStep(main, cfg_call, _cfg_scale(settings))
+ text = mode.text_at(step)
+ reference = BranchCall(
+ GuidanceBranch.of(text, pdg_path), guidance_gain, caption_bias
+ )
+ return SingleReferenceStep(main, reference, pdg_scale)
+
+
+def _band_masks(height: int, width: int, device: torch.device) -> Tensor:
+ """Radial ``[bands, H, W]`` FFT masks of ``PROJECTION_BAND_EDGES``."""
+
+ fy = torch.fft.fftfreq(height, device=device)
+ fx = torch.fft.fftfreq(width, device=device)
+ radius = torch.sqrt(fy[:, None].square() + fx[None, :].square())
+ masks = [radius == 0.0]
+ for low, high in itertools.pairwise(PROJECTION_BAND_EDGES):
+ masks.append((radius > low) & (radius <= high))
+ masks.append(radius > PROJECTION_BAND_EDGES[-1])
+ return torch.stack(masks).to(dtype=torch.float32)
+
+
+def _parallel_part(
+ delta: Tensor, reference: Tensor, projection: ProjectedGuidance
+) -> Tensor:
+ """The part of ``delta`` parallel to ``reference`` (float32 ``[B, C, H, W]``),
+ per sample or per sample and band from ``first_band`` on."""
+
+ eps = torch.finfo(torch.float32).eps
+ match projection.mode:
+ case ProjectionMode.GLOBAL:
+ dims = (1, 2, 3)
+ coefficient = (delta * reference).sum(dims, keepdim=True) / (
+ reference.square().sum(dims, keepdim=True) + eps
+ )
+ return coefficient * reference
+ case ProjectionMode.PER_BAND:
+ masks = _band_masks(
+ int(delta.shape[-2]), int(delta.shape[-1]), delta.device
+ )
+ fd = torch.fft.fft2(delta, norm="ortho")
+ fr = torch.fft.fft2(reference, norm="ortho")
+ parallel = torch.zeros_like(fr)
+ for mask in masks[projection.first_band :]:
+ band = fr * mask
+ coefficient = (fd * band.conj()).real.sum((1, 2, 3), keepdim=True) / (
+ band.abs().square().sum((1, 2, 3), keepdim=True) + eps
+ )
+ parallel = parallel + coefficient * band
+ return torch.fft.ifft2(parallel, norm="ortho").real
+ case ProjectionMode.OFF:
+ raise ValueError("An OFF projection has no parallel part.")
+ case _ as unreachable:
+ raise ValueError(f"Unsupported projection mode: {unreachable}")
+
+
+def projected_guidance_velocity(
+ *,
+ main: Tensor,
+ reference: Tensor,
+ state: Tensor,
+ time: Tensor,
+ scale: float,
+ projection: ProjectedGuidance,
+) -> Tensor:
+ """APG in velocity units: ``v_main + (w - 1)(dv - (1 - parallel_weight)
+ dv_par)``, ``dv = v_main - v_ref`` and ``dv_par`` its part parallel to
+ ``x0_main = x_t - t v_main``."""
+
+ t_view = time.to(device=main.device, dtype=torch.float32).view(
+ (-1,) + (1,) * (main.dim() - 1)
+ )
+ x0_main = state.to(dtype=torch.float32) - t_view * main.to(dtype=torch.float32)
+ delta = (main - reference).to(dtype=torch.float32)
+ parallel = _parallel_part(delta, x0_main, projection)
+ update = (scale - 1.0) * (delta - (1.0 - projection.parallel_weight) * parallel)
+ return (main.to(dtype=torch.float32) + update).to(dtype=main.dtype)
+
+
+def rescale_guided_velocity(
+ *, guided: Tensor, reference: Tensor, rescale: float
+) -> Tensor:
+ """Interpolate ``guided`` toward its per-sample rescale to ``reference``'s norm."""
+
+ if rescale == 0.0:
+ return guided
+ flat = (int(guided.shape[0]), -1)
+ guided32 = guided.to(dtype=torch.float32)
+ guided_norm = guided32.reshape(flat).norm(dim=1, keepdim=True)
+ reference_norm = (
+ reference.to(dtype=torch.float32).reshape(flat).norm(dim=1, keepdim=True)
+ )
+ view = (int(guided.shape[0]),) + (1,) * (guided.dim() - 1)
+ eps = torch.finfo(torch.float32).eps
+ rescaled = guided32 * (
+ reference_norm.view(view) / guided_norm.clamp_min(eps).view(view)
+ )
+ return torch.lerp(guided32, rescaled, rescale).to(dtype=guided.dtype)
+
+
+type BranchEvaluator = Callable[[BranchCall], Tensor]
+
+
+@dataclass(frozen=True)
+class GuidancePlan:
+ """Per-schedule-point guidance of one run (``build_guidance_plan``).
+
+ Attributes:
+ steps: One ``GuidanceStep`` per schedule point, index 0 the noisy end.
+ projection: APG of the single-reference steps.
+ rescale: Guidance rescale.
+ """
+
+ steps: tuple[GuidanceStep, ...]
+ projection: ProjectedGuidance
+ rescale: float
+
+ def calls(self, index: int) -> tuple[BranchCall, ...]:
+ """The forwards point ``index`` runs, in evaluation order."""
+
+ match self.steps[index]:
+ case UnguidedStep(main=main):
+ return (main,)
+ case SingleReferenceStep(main=main, reference=reference):
+ return (main, reference)
+ case AveragedStep(main=main, cfg=cfg, pdg=None):
+ return (main, cfg)
+ case AveragedStep(main=main, cfg=cfg, pdg=BranchCall() as pdg):
+ return (main, cfg, pdg)
+ case _ as unreachable:
+ raise ValueError(f"Unsupported guidance step: {unreachable}")
+
+ def guided_velocity(
+ self, index: int, state: Tensor, time: Tensor, evaluate: BranchEvaluator
+ ) -> Tensor:
+ """Run point ``index``'s forwards through ``evaluate`` (main first) and
+ return the guided velocity in ``state``'s dtype.
+
+ Args:
+ index: Schedule point (the solver's ``step_index``).
+ state: The solver state ``x_t`` (APG reads it).
+ time: Float32 ``[B]`` times of the point.
+ evaluate: Runs one forward at ``(state, time)``.
+ """
+
+ step = self.steps[index]
+ main = evaluate(step.main)
+ match step:
+ case UnguidedStep():
+ return main.to(dtype=state.dtype)
+ case SingleReferenceStep(reference=reference, scale=scale):
+ guided = self._single(main, evaluate(reference), state, time, scale)
+ case AveragedStep() as averaged:
+ cfg = evaluate(averaged.cfg)
+ pdg = main if averaged.pdg is None else evaluate(averaged.pdg)
+ guided = main + 0.5 * (
+ averaged.cfg_scale * (main - cfg)
+ + averaged.pdg_scale * (main - pdg)
+ )
+ case _ as unreachable:
+ raise ValueError(f"Unsupported guidance step: {unreachable}")
+ if self.rescale > 0.0:
+ guided = rescale_guided_velocity(
+ guided=guided, reference=main, rescale=self.rescale
+ )
+ return guided.to(dtype=state.dtype)
+
+ def _single(
+ self, main: Tensor, reference: Tensor, state: Tensor, time: Tensor, scale: float
+ ) -> Tensor:
+ """Combine one reference with the main velocity (plain or APG)."""
+
+ if self.projection.mode is ProjectionMode.OFF:
+ return reference + scale * (main - reference)
+ return projected_guidance_velocity(
+ main=main,
+ reference=reference,
+ state=state,
+ time=time,
+ scale=scale,
+ projection=self.projection,
+ )
+
+
+def build_guidance_plan(
+ settings: GuidanceSettings,
+ *,
+ schedule: TimeSchedule,
+ log_snr_shift: float,
+ timesteps: Sequence[float],
+) -> GuidancePlan:
+ """Resolve ``settings`` for one run.
+
+ Args:
+ settings: Validated guidance settings.
+ schedule: The run's schedule family and step count.
+ log_snr_shift: The effective shift the schedule was built with.
+ timesteps: Host copy of the solver's schedule (``steps + 1`` floats,
+ with the noisy-endpoint cap if the solver uses it); the ramp reads
+ its quantiles at these times.
+
+ Returns:
+ One ``GuidanceStep`` per schedule point.
+
+ Raises:
+ ValueError: If a window does not fit, ``timesteps`` has the wrong
+ length, or CFG is on with a PDG mode that has no CFG steps and the
+ two windows overlap (PDG would silently take those steps).
+ """
+
+ steps = schedule.steps
+ if len(timesteps) != steps + 1:
+ raise ValueError(
+ f"timesteps has {len(timesteps)} points; the schedule has {steps + 1}."
+ )
+ pdg = settings.pdg
+ pdg_values = None
+ if pdg is not None:
+ match pdg.scale:
+ case EndpointPdgCurve() | BezierPdgCurve() as curve:
+ pdg_values = per_step_pdg_scales(
+ curve, schedule=schedule, log_snr_shift=log_snr_shift
+ )
+ case ConstantPdgScale() | RampPdgScale():
+ pass
+ case _ as unreachable:
+ raise ValueError(f"Unsupported PDG scale: {unreachable}")
+ cfg_window = (
+ settings.cfg.window.resolve(steps, "CFG") if settings.cfg.enabled else None
+ )
+ pdg_window = pdg.window.resolve(steps, "PDG") if pdg is not None else None
+ _reject_shadowed_cfg(settings, cfg_window, pdg_window)
+ inputs = _PlanInputs(
+ settings=settings,
+ steps=steps,
+ times=tuple(float(time) for time in timesteps),
+ cdf=ScheduleCdf(schedule, log_snr_shift),
+ pdg_values=pdg_values,
+ cfg_window=cfg_window,
+ pdg_window=pdg_window,
+ )
+ return GuidancePlan(
+ steps=tuple(_resolve_step(inputs, index) for index in range(steps + 1)),
+ projection=settings.projection,
+ rescale=settings.rescale,
+ )
+
+
+def _reject_shadowed_cfg(
+ settings: GuidanceSettings,
+ cfg_window: tuple[int, int] | None,
+ pdg_window: tuple[int, int] | None,
+) -> None:
+ """Reject CFG that a PDG mode without CFG steps would silently replace.
+
+ Raises:
+ ValueError: If CFG is on, the PDG mode runs no CFG forwards and the
+ CFG and PDG windows share a step.
+ """
+
+ pdg = settings.pdg
+ if cfg_window is None or pdg_window is None or pdg is None or pdg.mode.uses_cfg:
+ return
+ first = max(cfg_window[0], pdg_window[0])
+ last = min(cfg_window[1], pdg_window[1])
+ if first <= last:
+ raise ValueError(
+ f"CFG and PDG mode {pdg.mode.value} are both active on steps "
+ f"{first}-{last}; PDG would take those steps. Use a PDG mode that "
+ "includes CFG (combined_cfg_pdg, alternate_*, pdg_with_alternating_cfg, "
+ "cfg_to_pdg) or make the step windows disjoint."
+ )
+
+
+# The three-quarter routing keeps one token of each 2x2 latent group, so the
+# token grid needs even sides: image sides that are multiples of this.
+THREE_QUARTER_SIZE_MULTIPLE = 32
+
+
+def check_three_quarter_size(
+ settings: GuidanceSettings, width: int, height: int
+) -> None:
+ """Reject an image size the three-quarter routing cannot run at.
+
+ Raises:
+ ValueError: If PDG mode ``three_quarter`` or sparse middle steps are
+ on and a side is not a multiple of ``THREE_QUARTER_SIZE_MULTIPLE``.
+ """
+
+ three_quarter = settings.pdg is not None and (
+ settings.pdg.mode is PdgMode.THREE_QUARTER
+ )
+ if not (three_quarter or settings.sparse_middle.percent > 0.0):
+ return
+ if width % THREE_QUARTER_SIZE_MULTIPLE or height % THREE_QUARTER_SIZE_MULTIPLE:
+ raise ValueError(
+ "PDG mode three_quarter and sparse middle steps need a width and "
+ f"height that are multiples of {THREE_QUARTER_SIZE_MULTIPLE}; got "
+ f"{width}x{height}."
+ )
diff --git a/dflow/inference.py b/dflow/inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae8d9b1769f3ad66b94755edf36735e181de2ff9
--- /dev/null
+++ b/dflow/inference.py
@@ -0,0 +1,396 @@
+"""Sampling dflow latents: settings, noise and the guided solver loop.
+
+The engine joins the pieces: prompts are encoded and refined once per call,
+the guidance plan decides which forwards each schedule point runs, and the
+solver integrates from noise (``t = 1``) to the image (``t = 0``).
+
+Seeds. One integer seed fixes everything random in a call:
+
+- the initial noise is ``torch.randn`` of the latent shape from a CPU
+ generator seeded with the seed (the same noise on every GPU);
+- stochastic solvers draw from a second CPU generator with the same seed;
+- the three-quarter routing draws its kept tokens from a CUDA generator with
+ the same seed.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING
+
+import torch
+from torch import Tensor
+
+from .guidance import (
+ BranchCall,
+ BranchText,
+ GuidanceSettings,
+ build_guidance_plan,
+ check_three_quarter_size,
+)
+from .layout import compile_layout, is_compiled_layout
+from .modeling import DFlowModel, PreparedText, self_attention_gain_tensor
+from .prompt_emphasis import EmphasisSettings
+from .schedules import (
+ TRAINING_BASE_LOG_SNR_SHIFT,
+ TimeSchedule,
+ build_timesteps,
+ resolution_log_snr_shift,
+)
+from .solvers import (
+ DEFAULT_SDE_NOISE_SCALE,
+ Solver,
+ solve,
+ solver_is_stochastic,
+ solver_requires_finite_noisy_endpoint,
+)
+from .types import DFlowPath
+from .vae import LATENT_CHANNELS, LATENT_STRIDE
+
+if TYPE_CHECKING:
+ from .text_conditioning import DFlowTextEncoder
+
+DEFAULT_WIDTH = 832
+DEFAULT_HEIGHT = 1216
+MAX_SEED = 2**63 - 1
+
+LatentCallback = Callable[[Tensor, int, int], None]
+"""Receives the predicted clean latents ``[B, 96, h, w]``, the number of
+completed updates and the total after each solver update."""
+
+
+@dataclass(frozen=True)
+class SamplingSettings:
+ """Solver, schedule and timestep shift.
+
+ The log-SNR shift moves every schedule point towards the noisy end
+ (negative values). By default it is the shift the model was trained with
+ at the image size: ``base_log_snr_shift - ln(width * height / 256^2)``,
+ capped at 0 (-2.99 at 832 x 1216).
+
+ Attributes:
+ solver: Numerical method.
+ noise_scale: Noise multiplier of stochastic solvers (ignored by
+ deterministic ones).
+ schedule: Spacing and number of solver updates.
+ base_log_snr_shift: Size-independent part of the shift.
+ resolution_shift: Add the image-size term to the shift.
+
+ Raises:
+ ValueError: For a negative or non-finite noise scale or shift.
+ """
+
+ solver: Solver = Solver.ER_SDE
+ noise_scale: float = DEFAULT_SDE_NOISE_SCALE
+ schedule: TimeSchedule = field(default_factory=TimeSchedule)
+ base_log_snr_shift: float = TRAINING_BASE_LOG_SNR_SHIFT
+ resolution_shift: bool = True
+
+ def __post_init__(self) -> None:
+ """Validate the noise scale and the base shift."""
+
+ if not math.isfinite(self.noise_scale) or self.noise_scale < 0.0:
+ raise ValueError(f"noise_scale must be >= 0, got {self.noise_scale}.")
+ if not math.isfinite(self.base_log_snr_shift):
+ raise ValueError("base_log_snr_shift must be finite.")
+
+ def log_snr_shift(self, width: int, height: int) -> float:
+ """The effective shift at an image size."""
+
+ if self.resolution_shift:
+ return resolution_log_snr_shift(width, height, base=self.base_log_snr_shift)
+ return self.base_log_snr_shift
+
+ def timesteps(self, width: int, height: int, device: torch.device) -> Tensor:
+ """The descending float32 schedule at an image size."""
+
+ return build_timesteps(
+ self.schedule,
+ log_snr_shift=self.log_snr_shift(width, height),
+ finite_noisy_endpoint=solver_requires_finite_noisy_endpoint(self.solver),
+ device=device,
+ )
+
+
+@dataclass(frozen=True)
+class GenerationSettings:
+ """Everything except the prompt that fixes one generation.
+
+ Attributes:
+ width: Image width in pixels, a multiple of 16.
+ height: Image height in pixels, a multiple of 16.
+ seed: Seed of every random draw (see the module docstring).
+ sampling: Solver, schedule and shift.
+ guidance: Guidance and self-attention gains.
+ emphasis: Prompt-emphasis settings for ``(phrase:weight)`` markup, or
+ None to read prompts verbatim. Layout prompts are always verbatim.
+ negative_prompt: Text of the negative branch used by CFG and the
+ contrastive guidance modes; empty selects the learned null text.
+
+ Raises:
+ ValueError: For a size that is not a positive multiple of 16 or a
+ seed outside ``[0, 2**63 - 1]``.
+ """
+
+ width: int = DEFAULT_WIDTH
+ height: int = DEFAULT_HEIGHT
+ seed: int = 0
+ sampling: SamplingSettings = field(default_factory=SamplingSettings)
+ guidance: GuidanceSettings = field(default_factory=GuidanceSettings)
+ emphasis: EmphasisSettings | None = field(default_factory=EmphasisSettings)
+ negative_prompt: str = ""
+
+ def __post_init__(self) -> None:
+ """Validate the size and seed."""
+
+ for name, value in (("width", self.width), ("height", self.height)):
+ if value <= 0 or value % LATENT_STRIDE:
+ raise ValueError(
+ f"{name} must be a positive multiple of {LATENT_STRIDE}, "
+ f"got {value}."
+ )
+ if not 0 <= self.seed <= MAX_SEED:
+ raise ValueError(f"seed must lie in [0, {MAX_SEED}], got {self.seed}.")
+
+ @property
+ def latent_shape(self) -> tuple[int, int, int]:
+ """``(channels, height / 16, width / 16)`` of one latent."""
+
+ return (
+ LATENT_CHANNELS,
+ self.height // LATENT_STRIDE,
+ self.width // LATENT_STRIDE,
+ )
+
+
+@dataclass(frozen=True)
+class ImageToImage:
+ """Start from existing latents instead of pure noise.
+
+ The schedule is built at its full step count and sampling starts at
+ ``start_step``: the start latents are noised to that point's time with
+ the seed's noise, and the remaining ``steps - start_step`` updates run.
+ Guidance step windows count from the start step.
+
+ Attributes:
+ latents: ``[B or 1, 96, h, w]`` float32 whitened latents of the
+ generation size.
+ start_step: Index of the first schedule point, in ``[0, steps)``.
+ """
+
+ latents: Tensor
+ start_step: int
+
+
+def resolve_prompt(prompt: str, width: int, height: int) -> str:
+ """Return the text the encoder reads for a prompt at an image size.
+
+ A stored layout (the ``summary``/``frame``/``items`` JSON with 0-1000
+ boxes) is compiled to the pixel layout the model was trained on at that
+ size; an already compiled layout is returned unchanged after its panel
+ box is checked against the size. Plain prompts are returned unchanged.
+
+ Raises:
+ dflow.layout.LayoutSizeMismatchError: For a layout compiled for
+ another size.
+ dflow.layout.LayoutError: For an invalid layout.
+ """
+
+ if is_compiled_layout(prompt):
+ return compile_layout(prompt, width, height)
+ return prompt
+
+
+class DFlowEngine:
+ """Samples latents with a loaded denoiser and text encoder.
+
+ Args:
+ model: The denoiser on a CUDA device.
+ text_encoder: The prompt encoder on the same device.
+ """
+
+ def __init__(self, model: DFlowModel, text_encoder: DFlowTextEncoder) -> None:
+ self.model = model
+ self.text_encoder = text_encoder
+ self.device = next(model.parameters()).device
+
+ def prepare_texts(
+ self,
+ prompts: Sequence[str],
+ settings: GenerationSettings,
+ ) -> dict[BranchText, PreparedText]:
+ """Encode and refine the positive prompts and, when the guidance uses
+ it, the negative prompt repeated over the batch.
+
+ The negative branch never takes prompt emphasis.
+
+ Raises:
+ ValueError: If the positive prompts do not share one token count.
+ """
+
+ positives = [
+ resolve_prompt(prompt, settings.width, settings.height)
+ for prompt in prompts
+ ]
+ texts = {
+ BranchText.POSITIVE: self.model.prepare_text(
+ self.text_encoder.encode(positives, emphasis=settings.emphasis)
+ )
+ }
+ if settings.guidance.uses_negative:
+ negative = resolve_prompt(
+ settings.negative_prompt, settings.width, settings.height
+ )
+ texts[BranchText.NEGATIVE] = self.model.prepare_text(
+ self.text_encoder.encode([negative] * len(prompts), emphasis=None)
+ )
+ return texts
+
+ @torch.inference_mode()
+ def sample(
+ self,
+ prompts: Sequence[str],
+ settings: GenerationSettings,
+ *,
+ image_to_image: ImageToImage | None = None,
+ callback: LatentCallback | None = None,
+ ) -> Tensor:
+ """Sample one latent per prompt.
+
+ Args:
+ prompts: Plain prompts, stored or compiled layouts, all with the
+ same token count (repeat one prompt for several images).
+ settings: Size, seed, sampling and guidance.
+ image_to_image: Start latents and start step, or None to start
+ from noise.
+ callback: Called after each solver update with the predicted
+ clean latents.
+
+ Returns:
+ Float32 whitened latents ``[B, 96, height / 16, width / 16]``.
+
+ Raises:
+ ValueError: On an empty prompt list, unequal prompt lengths, start
+ latents of the wrong shape, or a size the three-quarter routing
+ cannot run at.
+ """
+
+ if not prompts:
+ raise ValueError("At least one prompt is required.")
+ check_three_quarter_size(settings.guidance, settings.width, settings.height)
+ batch = len(prompts)
+ texts = self.prepare_texts(prompts, settings)
+ sampling = settings.sampling
+ full = sampling.timesteps(settings.width, settings.height, self.device)
+ noise = self._initial_noise(batch, settings)
+ match image_to_image:
+ case None:
+ timesteps = full
+ state = noise
+ case ImageToImage(latents=latents, start_step=start):
+ timesteps = _slice_schedule(full, start)
+ state = _noised_start(latents, noise, timesteps[0], batch)
+ case _ as unreachable:
+ raise ValueError(f"Unsupported image_to_image: {unreachable}")
+ host_times = timesteps.tolist()
+ plan = build_guidance_plan(
+ settings.guidance,
+ schedule=TimeSchedule(
+ kind=sampling.schedule.kind,
+ steps=len(host_times) - 1,
+ beta_mean=sampling.schedule.beta_mean,
+ beta_concentration=sampling.schedule.beta_concentration,
+ ),
+ log_snr_shift=sampling.log_snr_shift(settings.width, settings.height),
+ timesteps=host_times,
+ )
+ routing = torch.Generator(device=self.device).manual_seed(settings.seed)
+ gains: dict[float, Tensor] = {}
+
+ def evaluate_at(state: Tensor, time: Tensor) -> Callable[[BranchCall], Tensor]:
+ def evaluate(call: BranchCall) -> Tensor:
+ path = call.branch.path
+ if call.self_attention_gain not in gains:
+ gains[call.self_attention_gain] = self_attention_gain_tensor(
+ call.self_attention_gain, device=self.device
+ )
+ return self.model(
+ state,
+ time,
+ texts[call.branch.text],
+ path=path,
+ self_attention_gain=gains[call.self_attention_gain],
+ suffix_caption_bias=call.suffix_caption_bias,
+ generator=routing if path is DFlowPath.THREE_QUARTER else None,
+ )
+
+ return evaluate
+
+ def velocity(state: Tensor, time: Tensor, index: int) -> Tensor:
+ return plan.guided_velocity(index, state, time, evaluate_at(state, time))
+
+ return solve(
+ velocity,
+ state,
+ timesteps,
+ solver=sampling.solver,
+ noise_scale=sampling.noise_scale,
+ generator=(
+ torch.Generator(device="cpu").manual_seed(settings.seed)
+ if solver_is_stochastic(sampling.solver)
+ else None
+ ),
+ callback=callback,
+ )
+
+ def _initial_noise(self, batch: int, settings: GenerationSettings) -> Tensor:
+ """The seed's standard normal latents on the device, channels-last."""
+
+ generator = torch.Generator(device="cpu").manual_seed(settings.seed)
+ noise = torch.randn(
+ (batch, *settings.latent_shape),
+ generator=generator,
+ dtype=torch.float32,
+ device="cpu",
+ )
+ return noise.to(device=self.device).contiguous(
+ memory_format=torch.channels_last
+ )
+
+
+def _slice_schedule(timesteps: Tensor, start_step: int) -> Tensor:
+ """The schedule from ``start_step`` on.
+
+ Raises:
+ ValueError: If ``start_step`` leaves no update.
+ """
+
+ steps = int(timesteps.shape[0]) - 1
+ if not 0 <= start_step < steps:
+ raise ValueError(f"start_step must lie in [0, {steps}), got {start_step}.")
+ return timesteps[start_step:].contiguous()
+
+
+def _noised_start(latents: Tensor, noise: Tensor, time: Tensor, batch: int) -> Tensor:
+ """``(1 - t) x0 + t noise`` at the first point of a sliced schedule.
+
+ Raises:
+ ValueError: If the latents do not match the noise's shape (a batch of
+ one is repeated over the prompts).
+ """
+
+ if latents.ndim != 4 or tuple(latents.shape[1:]) != tuple(noise.shape[1:]):
+ raise ValueError(
+ f"Start latents must have shape [B, {', '.join(map(str, noise.shape[1:]))}]"
+ f", got {tuple(latents.shape)}."
+ )
+ if int(latents.shape[0]) not in (1, batch):
+ raise ValueError(
+ f"Start latents hold {latents.shape[0]} images for {batch} prompts."
+ )
+ clean = latents.to(device=noise.device, dtype=torch.float32).expand_as(noise)
+ return ((1.0 - time) * clean + time * noise).contiguous(
+ memory_format=torch.channels_last
+ )
diff --git a/dflow/latent_rgb_preview.safetensors b/dflow/latent_rgb_preview.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..5f20312d9ff37e294280345f968ea3917c5c2952
--- /dev/null
+++ b/dflow/latent_rgb_preview.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:906560b2f308d14001203d769e9af040763fb7c3389669093990d11bb655fe3b
+size 41976
diff --git a/dflow/layout.py b/dflow/layout.py
new file mode 100644
index 0000000000000000000000000000000000000000..a241cf1bea22beed488fab40500d7ac6a37e6b3c
--- /dev/null
+++ b/dflow/layout.py
@@ -0,0 +1,387 @@
+"""Layout prompts: compile a stored layout into the prompt the model reads.
+
+A stored layout is JSON with three parts:
+
+- ``summary``: ``meta`` tags, ``canvas`` and a ``caption`` of the whole image;
+- ``frame``: ``caption``, ``tags`` and ``palette`` of the whole canvas;
+- ``items``: boxes, each with a ``label`` (character, object, text), optional
+ ``caption``, ``tags`` and ``palette``, a ``box_2d`` ``[y0, x0, y1, x1]`` on a
+ 0-1000 scale and, for text items, the exact ``text``.
+
+The model was trained on the compiled form, which depends on the image size:
+the frame becomes a full-canvas ``panel`` item and every box becomes integer
+pixels centred on the image centre (``abs_centralized``, ``yxyx``). Optional
+fields may be left out; training dropped them at random.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from collections.abc import Mapping
+from enum import StrEnum
+
+__all__ = [
+ "LAYOUT_BOX_SCALE",
+ "LayoutError",
+ "LayoutLabel",
+ "LayoutSizeMismatchError",
+ "compile_layout",
+ "is_compiled_layout",
+ "is_stored_layout",
+ "panel_box",
+]
+
+# Normalized box scale of stored layouts.
+LAYOUT_BOX_SCALE = 1000
+# Rounding applied before flooring/ceiling box edges (keeps exact edges exact).
+_BOX_EDGE_DECIMALS = 9
+# Optional descriptive fields of the frame and of every item, in compiled order.
+_ENTRY_FIELDS = ("caption", "tags", "palette")
+_SUMMARY_KEYS = frozenset({"meta", "canvas", "caption"})
+_STORED_KEYS = frozenset({"summary", "frame", "items"})
+_ITEM_KEYS = frozenset({"label", "box_2d", "text", *_ENTRY_FIELDS})
+_COORD_SPACE = "abs_centralized"
+_BOX_FORMAT = "yxyx"
+_COMPILED_KEYS = frozenset({"summary", "items", "bbox_coord_space", "bbox_format"})
+# Top-level keys every JSON prompt has; the text encoder tokenizes such prompts
+# as structured JSON (character tokens for visible text only).
+_JSON_PROMPT_KEYS = frozenset({"summary", "items"})
+
+
+class LayoutLabel(StrEnum):
+ """Item labels of a layout."""
+
+ CHARACTER = "character"
+ OBJECT = "object"
+ TEXT = "text"
+ PANEL = "panel"
+
+
+class LayoutError(ValueError):
+ """A layout is malformed."""
+
+
+class LayoutSizeMismatchError(LayoutError):
+ """A compiled layout prompt was compiled for another image size."""
+
+
+def _json_object(text: str) -> dict[str, object] | None:
+ """Return ``text`` parsed as a JSON object, or None if it is not one."""
+
+ if not text.lstrip().startswith("{"):
+ return None
+ try:
+ parsed = json.loads(text)
+ except json.JSONDecodeError:
+ return None
+ match parsed:
+ case dict():
+ return parsed
+ case _:
+ return None
+
+
+def is_compiled_layout(text: str) -> bool:
+ """Whether ``text`` is a JSON layout prompt (an object with ``summary`` and
+ ``items``).
+
+ The text encoder tokenizes such prompts as structured JSON and never parses
+ them for emphasis markup, exactly as in training. A stored (uncompiled)
+ layout also passes this test; ``is_stored_layout`` tells them apart.
+ """
+
+ parsed = _json_object(text)
+ return parsed is not None and set(parsed) >= _JSON_PROMPT_KEYS
+
+
+def is_stored_layout(text: str) -> bool:
+ """Whether ``text`` is a stored layout (``summary``, ``frame``, ``items``)
+ that still needs ``compile_layout`` before it can be encoded."""
+
+ parsed = _json_object(text)
+ return parsed is not None and set(parsed) == _STORED_KEYS
+
+
+def panel_box(width: int, height: int) -> list[int]:
+ """Return the compiled full-canvas ``panel`` box ``[y0, x0, y1, x1]``.
+
+ Raises:
+ LayoutError: If the size is not positive.
+ """
+
+ if width <= 0 or height <= 0:
+ raise LayoutError(f"Layout size must be positive, got {width}x{height}.")
+ return [-(height // 2), -(width // 2), height - height // 2, width - width // 2]
+
+
+def _four_ints(value: object, *, where: str) -> tuple[int, int, int, int]:
+ """Return ``value`` as four integers (booleans excluded).
+
+ Raises:
+ LayoutError: If it is not a list of four integers.
+ """
+
+ match value:
+ case list() if len(value) == 4 and all(
+ isinstance(item, int) and not isinstance(item, bool) for item in value
+ ):
+ a, b, c, d = (int(item) for item in value)
+ return a, b, c, d
+ case _:
+ raise LayoutError(f"{where} must be four integers, got {value!r}.")
+
+
+def _box_pixels(box: object, *, width: int, height: int, where: str) -> list[int]:
+ """Return a 0-1000 ``yxyx`` box as centred integer pixels.
+
+ Min edges are floored and max edges ceiled after rounding to 9 decimals,
+ then shifted by ``height // 2`` / ``width // 2``.
+
+ Raises:
+ LayoutError: If ``box`` is not four ordered integers in 0..1000.
+ """
+
+ y0, x0, y1, x1 = _four_ints(box, where=f"{where}.box_2d")
+ if not (0 <= y0 < y1 <= LAYOUT_BOX_SCALE and 0 <= x0 < x1 <= LAYOUT_BOX_SCALE):
+ raise LayoutError(
+ f"{where}.box_2d {box!r} must be [y0, x0, y1, x1] with "
+ f"0 <= y0 < y1 <= {LAYOUT_BOX_SCALE} and 0 <= x0 < x1 <= "
+ f"{LAYOUT_BOX_SCALE}."
+ )
+
+ def edge(value: int, size: int) -> float:
+ return round(value * size / LAYOUT_BOX_SCALE, _BOX_EDGE_DECIMALS)
+
+ return [
+ math.floor(edge(y0, height)) - height // 2,
+ math.floor(edge(x0, width)) - width // 2,
+ math.ceil(edge(y1, height)) - height // 2,
+ math.ceil(edge(x1, width)) - width // 2,
+ ]
+
+
+def _require_object(value: object, *, where: str) -> Mapping[str, object]:
+ """Return ``value`` as a JSON object.
+
+ Raises:
+ LayoutError: If it is not one.
+ """
+
+ match value:
+ case Mapping():
+ return value
+ case _:
+ raise LayoutError(f"{where} must be a JSON object.")
+
+
+def _require_keys(
+ entry: Mapping[str, object], *, allowed: frozenset[str], where: str
+) -> None:
+ """Raise unless every key of ``entry`` is in ``allowed``."""
+
+ unknown = sorted(set(entry) - allowed)
+ if unknown:
+ raise LayoutError(
+ f"{where} has unknown keys {unknown}; allowed: {sorted(allowed)}."
+ )
+
+
+def _require_string_list(value: object, *, where: str) -> None:
+ """Raise unless ``value`` is a list of strings."""
+
+ match value:
+ case list() if all(isinstance(item, str) for item in value):
+ return
+ case _:
+ raise LayoutError(f"{where} must be a list of strings.")
+
+
+def _require_string(value: object, *, where: str) -> None:
+ """Raise unless ``value`` is a string."""
+
+ if not isinstance(value, str):
+ raise LayoutError(f"{where} must be a string.")
+
+
+def _validated_entry_fields(entry: Mapping[str, object], *, where: str) -> None:
+ """Check the optional ``caption``, ``tags`` and ``palette`` fields."""
+
+ if "caption" in entry:
+ _require_string(entry["caption"], where=f"{where}.caption")
+ for key in ("tags", "palette"):
+ if key in entry:
+ _require_string_list(entry[key], where=f"{where}.{key}")
+
+
+def _validated_summary(value: object) -> Mapping[str, object]:
+ """Return the checked ``summary`` object."""
+
+ summary = _require_object(value, where="summary")
+ _require_keys(summary, allowed=_SUMMARY_KEYS, where="summary")
+ if "meta" in summary:
+ _require_string_list(summary["meta"], where="summary.meta")
+ for key in ("canvas", "caption"):
+ if key in summary:
+ _require_string(summary[key], where=f"summary.{key}")
+ return summary
+
+
+def _validated_items(value: object) -> list[Mapping[str, object]]:
+ """Return the checked ``items`` list."""
+
+ match value:
+ case list():
+ raw_items: list[object] = value
+ case _:
+ raise LayoutError("items must be a JSON list.")
+ items: list[Mapping[str, object]] = []
+ for pos, raw in enumerate(raw_items):
+ where = f"items[{pos}]"
+ item = _require_object(raw, where=where)
+ _require_keys(item, allowed=_ITEM_KEYS, where=where)
+ label = item.get("label")
+ if label not in {member.value for member in LayoutLabel}:
+ raise LayoutError(
+ f"{where}.label must be one of {[m.value for m in LayoutLabel]}, "
+ f"got {label!r}."
+ )
+ if "box_2d" not in item:
+ raise LayoutError(f"{where} needs a box_2d [y0, x0, y1, x1] on 0-1000.")
+ if label == LayoutLabel.TEXT and "text" not in item:
+ raise LayoutError(f"{where} is a text item and needs its exact 'text'.")
+ if "text" in item:
+ _require_string(item["text"], where=f"{where}.text")
+ _validated_entry_fields(item, where=where)
+ items.append(item)
+ return items
+
+
+def _compile_stored(layout: Mapping[str, object], *, width: int, height: int) -> str:
+ """Compile a stored layout at ``width`` x ``height``.
+
+ Raises:
+ LayoutError: If the layout is malformed.
+ """
+
+ if set(layout) != _STORED_KEYS:
+ raise LayoutError(
+ "A stored layout needs exactly the keys summary, frame and items; got "
+ f"{sorted(layout)}."
+ )
+ summary = _validated_summary(layout["summary"])
+ frame = _require_object(layout["frame"], where="frame")
+ _require_keys(frame, allowed=frozenset(_ENTRY_FIELDS), where="frame")
+ _validated_entry_fields(frame, where="frame")
+ items = _validated_items(layout["items"])
+ panel: dict[str, object] = {"label": LayoutLabel.PANEL.value}
+ panel.update({key: frame[key] for key in _ENTRY_FIELDS if key in frame})
+ panel["bbox"] = panel_box(width, height)
+ compiled_items: list[dict[str, object]] = [panel]
+ for pos, item in enumerate(items):
+ out: dict[str, object] = {"label": item["label"]}
+ out.update({key: item[key] for key in _ENTRY_FIELDS if key in item})
+ out["bbox"] = _box_pixels(
+ item["box_2d"], width=width, height=height, where=f"items[{pos}]"
+ )
+ if "text" in item:
+ out["text"] = item["text"]
+ compiled_items.append(out)
+ prompt = {
+ "summary": dict(summary),
+ "items": compiled_items,
+ "bbox_coord_space": _COORD_SPACE,
+ "bbox_format": _BOX_FORMAT,
+ }
+ return json.dumps(prompt, ensure_ascii=False, separators=(",", ":"))
+
+
+def _compiled_size(items: object) -> tuple[int, int] | None:
+ """Return the ``(width, height)`` a compiled prompt's panel encodes, or None."""
+
+ match items:
+ case [{"label": "panel", "bbox": list() as box}, *_]:
+ try:
+ y0, x0, y1, x1 = _four_ints(box, where="panel bbox")
+ except LayoutError:
+ return None
+ width, height = x1 - x0, y1 - y0
+ if width <= 0 or height <= 0 or box != panel_box(width, height):
+ return None
+ return width, height
+ case _:
+ return None
+
+
+def _check_compiled(parsed: Mapping[str, object], *, width: int, height: int) -> None:
+ """Check a compiled prompt's format and that its panel matches the size.
+
+ Raises:
+ LayoutSizeMismatchError: If the panel box is for another size.
+ LayoutError: If the prompt is not a compiled layout.
+ """
+
+ if set(parsed) != _COMPILED_KEYS:
+ raise LayoutError(
+ "A compiled layout needs exactly the keys summary, items, "
+ f"bbox_coord_space and bbox_format; got {sorted(parsed)}."
+ )
+ if (
+ parsed["bbox_coord_space"] != _COORD_SPACE
+ or parsed["bbox_format"] != _BOX_FORMAT
+ ):
+ raise LayoutError(
+ f"A compiled layout must use bbox_coord_space={_COORD_SPACE!r} and "
+ f"bbox_format={_BOX_FORMAT!r}."
+ )
+ size = _compiled_size(parsed["items"])
+ if size is None:
+ raise LayoutError(
+ "A compiled layout's first item must be the full-canvas panel with an "
+ "integer bbox."
+ )
+ if size != (width, height):
+ raise LayoutSizeMismatchError(
+ f"This layout prompt was compiled for {size[0]}x{size[1]} "
+ f"(width x height); the image is {width}x{height}. Compile the "
+ "stored layout again at the image size."
+ )
+
+
+def compile_layout(
+ layout_json: str | Mapping[str, object], width: int, height: int
+) -> str:
+ """Return the layout prompt the model reads for a ``width`` x ``height`` image.
+
+ Args:
+ layout_json: A stored layout (JSON text or a parsed mapping), or an
+ already compiled prompt (JSON text only), which is returned
+ verbatim after its panel box is checked against the size.
+ width: Image width in pixels.
+ height: Image height in pixels.
+
+ Returns:
+ The compiled prompt: one-line JSON, byte-identical to the training-time
+ compile of the same stored layout at this size.
+
+ Raises:
+ LayoutSizeMismatchError: If a compiled prompt is for another size.
+ LayoutError: If the layout is malformed or the size is not positive.
+ """
+
+ panel_box(width, height)
+ match layout_json:
+ case str() as text:
+ parsed = _json_object(text)
+ if parsed is None:
+ raise LayoutError("The layout is not a JSON object.")
+ # Only compiled prompts carry a coordinate space; anything else is
+ # read as a stored layout, whose own checks name a bad key.
+ if "bbox_coord_space" not in parsed:
+ return _compile_stored(parsed, width=width, height=height)
+ _check_compiled(parsed, width=width, height=height)
+ return text
+ case Mapping() as layout:
+ return _compile_stored(layout, width=width, height=height)
+ case _:
+ raise TypeError("layout_json must be JSON text or a mapping.")
diff --git a/dflow/loading.py b/dflow/loading.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e73ad6fd3a47596c4522edd1debf4f99bd7ff02
--- /dev/null
+++ b/dflow/loading.py
@@ -0,0 +1,209 @@
+"""Load the dflow_2b denoiser and text adapter weights from a release directory.
+
+A release directory holds ``model.safetensors`` (every weight, public names,
+see ``precision``), ``config.json`` (architecture constants) and
+``release.json`` (version and counts). Loading checks, before any weight
+reaches a module: the config against this package's architecture, the
+version, the tensor and parameter counts, every name (none missing, none
+extra), every shape and every storage dtype. The denoiser then loads with
+``strict=True``.
+
+Public names: ``denoiser.`` for the denoiser (``DFlowModel``'s
+own ``state_dict`` names, e.g. ``denoiser.prefix_layers.0.attn.qkv.weight``)
+and ``text_adapter.`` for the text adapter (its keys come from the text
+adapter module, ``text_conditioning.TEXT_ADAPTER_KEY_MAP``).
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import torch
+from safetensors.torch import load_file
+from torch import Tensor
+
+from .configuration import DFLOW_2B_CONFIG, DFlowConfig, read_denoiser_config
+from .modeling import DFlowModel
+from .precision import (
+ DENOISER_PREFIX,
+ TEXT_ADAPTER_PREFIX,
+ StoredDType,
+ denoiser_storage_dtype,
+ text_adapter_storage_dtypes,
+)
+from .version import MODEL_VERSION
+
+MODEL_FILENAME = "model.safetensors"
+CONFIG_FILENAME = "config.json"
+RELEASE_FILENAME = "release.json"
+
+
+def expected_denoiser_shapes(config: DFlowConfig) -> dict[str, tuple[int, ...]]:
+ """Public name -> shape of every denoiser tensor of ``config``."""
+
+ with torch.device("meta"):
+ model = DFlowModel(config)
+ return {
+ DENOISER_PREFIX + name: tuple(tensor.shape)
+ for name, tensor in model.state_dict().items()
+ }
+
+
+def expected_storage(config: DFlowConfig) -> dict[str, StoredDType]:
+ """Public name -> storage dtype of every tensor in ``model.safetensors``."""
+
+ storage = {
+ name: denoiser_storage_dtype(name) for name in expected_denoiser_shapes(config)
+ }
+ storage.update(text_adapter_storage_dtypes())
+ return storage
+
+
+def validate_public_tensors(tensors: dict[str, Tensor], config: DFlowConfig) -> None:
+ """Check names, denoiser shapes and storage dtypes of a public weight file.
+
+ Raises:
+ ValueError: If a name is missing or unexpected, a denoiser shape
+ differs from ``config``'s, or a dtype differs from the policy.
+ """
+
+ storage = expected_storage(config)
+ missing = sorted(set(storage) - set(tensors))
+ unexpected = sorted(set(tensors) - set(storage))
+ if missing or unexpected:
+ raise ValueError(
+ f"{MODEL_FILENAME} does not match this package: missing={missing}, "
+ f"unexpected={unexpected}"
+ )
+ for name, shape in expected_denoiser_shapes(config).items():
+ if tuple(tensors[name].shape) != shape:
+ raise ValueError(
+ f"{name} has shape {tuple(tensors[name].shape)}; expected {shape}"
+ )
+ for name, stored in storage.items():
+ if tensors[name].dtype != stored.torch_dtype:
+ raise ValueError(
+ f"{name} is stored as {tensors[name].dtype}; the storage policy "
+ f"requires {stored.torch_dtype}"
+ )
+
+
+def _validate_release_metadata(path: Path, tensors: dict[str, Tensor]) -> None:
+ """Check ``release.json``'s version and counts against the weight file.
+
+ Raises:
+ FileNotFoundError: If ``release.json`` is missing.
+ ValueError: If the version or a count differs.
+ """
+
+ if not path.is_file():
+ raise FileNotFoundError(f"Missing release metadata: {path}")
+ match json.loads(path.read_text(encoding="utf-8")):
+ case {
+ "version": str() as version,
+ "tensor_count": int() as tensor_count,
+ "parameter_count": int() as parameter_count,
+ }:
+ pass
+ case _:
+ raise ValueError(
+ f"{path} must hold version, tensor_count and parameter_count"
+ )
+ if version != MODEL_VERSION:
+ raise ValueError(
+ f"{path} is release {version}; this package loads {MODEL_VERSION}"
+ )
+ found_parameters = sum(tensor.numel() for tensor in tensors.values())
+ if (tensor_count, parameter_count) != (len(tensors), found_parameters):
+ raise ValueError(
+ f"{MODEL_FILENAME} holds {len(tensors)} tensors and {found_parameters} "
+ f"parameters; {RELEASE_FILENAME} declares {tensor_count} and "
+ f"{parameter_count}"
+ )
+
+
+def read_release_tensors(directory: Path, config: DFlowConfig) -> dict[str, Tensor]:
+ """Read and validate every tensor of a release directory (on the CPU).
+
+ Raises:
+ FileNotFoundError: If a release file is missing.
+ ValueError: If the config, metadata or tensors do not match.
+ """
+
+ read_denoiser_config(directory / CONFIG_FILENAME, config)
+ weights = directory / MODEL_FILENAME
+ if not weights.is_file():
+ raise FileNotFoundError(f"Missing weights: {weights}")
+ tensors = load_file(weights, device="cpu")
+ _validate_release_metadata(directory / RELEASE_FILENAME, tensors)
+ validate_public_tensors(tensors, config)
+ return tensors
+
+
+def _with_prefix(tensors: dict[str, Tensor], prefix: str) -> dict[str, Tensor]:
+ """The entries of ``tensors`` under ``prefix``, with the prefix removed."""
+
+ return {
+ name.removeprefix(prefix): tensor
+ for name, tensor in tensors.items()
+ if name.startswith(prefix)
+ }
+
+
+def load_dflow_denoiser(
+ directory: Path,
+ *,
+ device: torch.device,
+ compile_model: bool,
+ config: DFlowConfig = DFLOW_2B_CONFIG,
+) -> DFlowModel:
+ """Build the denoiser and load a release directory's weights.
+
+ Weights keep their storage dtypes on the device (bfloat16 with FP32
+ islands). With ``compile_model`` every block is compiled
+ (``DFlowModel.compile_blocks(dynamic=True)``); graphs build on first use.
+
+ Args:
+ directory: Release directory (``model.safetensors``, ``config.json``,
+ ``release.json``).
+ device: CUDA device for the model.
+ compile_model: Compile the blocks, or run eagerly.
+ config: The architecture to expect (the released model's by default).
+
+ Returns:
+ The eval-mode denoiser without gradients.
+
+ Raises:
+ FileNotFoundError: If a release file is missing.
+ ValueError: If ``device`` is not CUDA or the release does not match.
+ """
+
+ if device.type != "cuda":
+ raise ValueError(f"dflow runs on CUDA (bfloat16 autocast), got {device}")
+ tensors = read_release_tensors(directory, config)
+ with torch.device("meta"):
+ model = DFlowModel(config)
+ model.load_state_dict(
+ _with_prefix(tensors, DENOISER_PREFIX), strict=True, assign=True
+ )
+ model.to(device=device)
+ model.eval()
+ model.requires_grad_(False)
+ if compile_model:
+ model.compile_blocks(dynamic=True)
+ return model
+
+
+def load_text_adapter_tensors(
+ directory: Path, *, config: DFlowConfig = DFLOW_2B_CONFIG
+) -> dict[str, Tensor]:
+ """The text adapter's validated tensors, keyed relative to the adapter
+ module (the ``text_adapter.`` prefix removed), on the CPU.
+
+ Raises:
+ FileNotFoundError: If a release file is missing.
+ ValueError: If the release does not match.
+ """
+
+ return _with_prefix(read_release_tensors(directory, config), TEXT_ADAPTER_PREFIX)
diff --git a/dflow/modeling.py b/dflow/modeling.py
new file mode 100644
index 0000000000000000000000000000000000000000..750e4b73a4ea05fdbb7bf029d9148397425328ed
--- /dev/null
+++ b/dflow/modeling.py
@@ -0,0 +1,825 @@
+"""The dflow_2b denoiser: a single-stream text-image flow-matching transformer.
+
+Time and velocity convention
+----------------------------
+The model is trained on the linear path
+
+ x_t = (1 - t) * x_0 + t * eps, eps ~ N(0, I), t in [0, 1],
+
+where ``x_0`` is a whitened dinac3_96 latent: ``t = 1`` is pure noise and
+``t = 0`` is data. ``forward`` returns the velocity
+
+ v = dx_t / dt = eps - x_0,
+
+so an Euler step towards data is ``x_{t - h} = x_t - h * v``. The timestep
+enters as a float32 ``t`` in ``[0, 1]``; the time embedding reads
+``sin``/``cos`` of ``1000 * t * f_k`` (128 log-spaced frequencies ``f_k``
+from 1 to 1/10000). Log-SNR shifts and schedules are the sampler's business:
+the model takes the plain ``t`` of the path above.
+
+Stream and routing
+------------------
+Each sample is one sequence ``[image tokens, text tokens]`` (row-major
+``H x W`` latent grid, then the ``L`` refined prompt tokens) with joint
+self-attention in every layer. The text goes through two unmodulated refiner
+blocks once per prompt (``prepare_text``); it does not depend on the image
+size or the timestep, so one ``PreparedText`` serves every sampling step and
+size. Image layers: 6 prefix, 18 middle, a tail join, 6 suffix. ``DFlowPath``
+picks what the middle sees (``DFlowPath`` docstring); the tail join
+concatenates the prefix output ``p`` with the middle output ``m`` (the learned
+mask token where the middle did not run), scales both halves by ``1 + s(t)``,
+projects back to the width, and adds a separate projection of the scaled
+prefix at the rows the middle skipped.
+
+Precision
+---------
+Weights are bfloat16 with float32 norm weights and velocity head. Both entry
+points run under CUDA bfloat16 autocast and ``torch.no_grad``. The text
+refiner keeps a float32 residual stream (its input is float32); the joint
+stream is bfloat16. Norm weights and the velocity head are cast to their
+input's dtype at use, as in training under autocast. AdaLN scales and gates,
+RoPE and the returned velocity are float32.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, replace
+from typing import TYPE_CHECKING
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+from .blocks import DFlowBlock, RMSNorm
+from .rope3d import joint_rope_rows, text_rope_rows, validate_rope_capacity
+from .types import SUFFIX_TOKEN_COUNT, DFlowPath, TextConditioning
+
+if TYPE_CHECKING:
+ from .configuration import DFlowConfig
+
+AUTOCAST_DTYPE = torch.bfloat16
+SELF_ATTENTION_GAIN_RANGE = (-0.5, 0.1)
+"""Supported self-attention logit gains (inclusive)."""
+
+
+@dataclass(frozen=True)
+class PreparedText:
+ """A prompt batch after the text refiner, reusable across steps and sizes.
+
+ Attributes:
+ tokens: ``[B, L, width]`` refined tokens (float32).
+ key_bias: ``[B, L]`` float32 prompt-emphasis key bias, or None.
+ value_scale: ``[B, L]`` float32 prompt-emphasis value scale, or None.
+ """
+
+ tokens: Tensor
+ key_bias: Tensor | None
+ value_scale: Tensor | None
+
+ @property
+ def length(self) -> int:
+ """Tokens per prompt ``L``."""
+
+ return int(self.tokens.shape[1])
+
+
+def self_attention_gain_tensor(gain: float, *, device: torch.device) -> Tensor:
+ """The 0-dim float32 tensor ``forward`` takes as ``self_attention_gain``.
+
+ The gain ``g`` multiplies the image layers' queries by ``exp(g)`` (an
+ attention-logit temperature); 0 leaves the model unchanged.
+
+ Raises:
+ ValueError: If ``gain`` is not finite or outside
+ ``SELF_ATTENTION_GAIN_RANGE``.
+ """
+
+ low, high = SELF_ATTENTION_GAIN_RANGE
+ if not math.isfinite(gain) or not low <= gain <= high:
+ raise ValueError(
+ f"self-attention gain must be finite and within [{low}, {high}], got {gain}"
+ )
+ return torch.tensor(gain, dtype=torch.float32, device=device)
+
+
+class TimeEmbedding(nn.Module):
+ """Sinusoidal timestep features through a SiLU MLP to the AdaLN width."""
+
+ proj_in: nn.Linear
+ proj_out: nn.Linear
+ frequency_width: int
+ time_scale: float
+ max_period: float
+
+ def __init__(self, config: DFlowConfig) -> None:
+ """Build the two projections."""
+
+ super().__init__()
+ self.frequency_width = config.time_frequency_width
+ self.time_scale = config.time_scale
+ self.max_period = config.time_max_period
+ self.proj_in = nn.Linear(config.time_frequency_width, config.time_hidden_width)
+ self.proj_out = nn.Linear(config.time_hidden_width, config.time_embed_width)
+
+ def forward(self, t: Tensor) -> Tensor:
+ """Embed float32 ``t`` ``[B]`` into ``[B, time_embed_width]``."""
+
+ half = self.frequency_width // 2
+ freqs = torch.exp(
+ -math.log(self.max_period)
+ * torch.arange(half, device=t.device, dtype=torch.float32)
+ / max(float(half - 1), 1.0)
+ )
+ angles = (t.to(dtype=torch.float32) * self.time_scale)[:, None] * freqs[None]
+ features = torch.cat([torch.sin(angles), torch.cos(angles)], dim=-1)
+ hidden = F.silu(self.proj_in(features.to(dtype=self.proj_in.weight.dtype)))
+ return self.proj_out(hidden.to(dtype=self.proj_out.weight.dtype))
+
+
+class TailJoin(nn.Module):
+ """Concat join of the prefix and middle streams with time-dependent gains."""
+
+ mask_token: nn.Parameter
+ adascale: nn.Linear
+ proj: nn.Linear
+ dropped_skip_proj: nn.Linear
+
+ def __init__(self, config: DFlowConfig) -> None:
+ """Build the mask token and the three projections."""
+
+ super().__init__()
+ self.mask_token = nn.Parameter(torch.zeros(1, config.width))
+ self.adascale = nn.Linear(config.time_embed_width, 2 * config.width)
+ self.proj = nn.Linear(2 * config.width, config.width)
+ self.dropped_skip_proj = nn.Linear(config.width, config.width, bias=False)
+
+ def forward(
+ self,
+ prefix: Tensor,
+ middle: Tensor,
+ dropped: Tensor | None,
+ time_act: Tensor,
+ ) -> Tensor:
+ """Fuse ``[B, S, D]`` streams: ``W [g_p p ; g_m m] + b`` with
+ ``g = 1 + s(t)``, plus ``dropped * dropped_skip_proj(g_p p)``.
+
+ Args:
+ prefix: Prefix output.
+ middle: Middle output, the mask token where the middle did not run.
+ dropped: ``[B, S, 1]`` 1 at rows the middle skipped and 0 elsewhere;
+ None when the middle ran on every row.
+ time_act: SiLU of the timestep vector ``[B, time_embed_width]``.
+ """
+
+ batch, length, width = prefix.shape
+ concat = torch.cat([prefix, middle], dim=-1)
+ scale = self.adascale(time_act).to(dtype=torch.float32)
+ scaled = concat.to(dtype=torch.float32) * (1.0 + scale[:, None, :])
+ # Row-major [B * S, 2D] matrices: the projections see the token rows
+ # exactly as the trained model's packed stream does.
+ rows = scaled.to(dtype=concat.dtype).reshape(batch * length, 2 * width)
+ fused = self.proj(rows)
+ if dropped is not None:
+ fused = fused + dropped.reshape(batch * length, 1) * self.dropped_skip_proj(
+ rows[:, :width]
+ )
+ return fused.reshape(batch, length, width)
+
+
+@dataclass(frozen=True)
+class _StreamInputs:
+ """Per-forward inputs shared by every image layer."""
+
+ rope_sin: Tensor
+ rope_cos: Tensor
+ query_scale: Tensor
+ key_bias: Tensor | None
+ value_scale: Tensor | None
+ time_act: Tensor
+
+
+class DFlowModel(nn.Module):
+ """The denoiser (see the module docstring for conventions)."""
+
+ config: DFlowConfig
+ patch_embed: nn.Conv2d
+ time_embed: TimeEmbedding
+ text_refiner_layers: nn.ModuleList
+ prefix_layers: nn.ModuleList
+ middle_layers: nn.ModuleList
+ suffix_layers: nn.ModuleList
+ prefix_adaln: nn.ModuleList
+ middle_adaln: nn.ModuleList
+ suffix_adaln: nn.ModuleList
+ tail_join: TailJoin
+ final_norm: RMSNorm
+ final_modulation: nn.Linear
+ velocity_head: nn.Linear
+
+ def __init__(self, config: DFlowConfig) -> None:
+ """Build every module of ``config`` (weights are loaded separately)."""
+
+ super().__init__()
+ self.config = config
+ self.patch_embed = nn.Conv2d(config.latent_channels, config.width, 1)
+ self.time_embed = TimeEmbedding(config)
+ self.text_refiner_layers = _blocks(config, config.text_refiner_depth)
+ self.prefix_layers = _blocks(config, config.prefix_depth)
+ self.middle_layers = _blocks(config, config.middle_depth)
+ self.suffix_layers = _blocks(config, config.suffix_depth)
+ self.prefix_adaln = _adaln(config, config.prefix_depth)
+ self.middle_adaln = _adaln(config, config.middle_depth)
+ self.suffix_adaln = _adaln(config, config.suffix_depth)
+ self.tail_join = TailJoin(config)
+ self.final_norm = RMSNorm(config.width, eps=config.norm_eps)
+ self.final_modulation = nn.Linear(config.time_embed_width, 2 * config.width)
+ self.velocity_head = nn.Linear(config.width, config.latent_channels)
+
+ def compile_blocks(self, *, dynamic: bool) -> None:
+ """Compile every transformer block with ``torch.compile(fullgraph=True)``.
+
+ Graphs build on first use; a graph break or compiler error raises
+ then. Path, gain value and emphasis tensors stay outside the graphs.
+
+ Raises:
+ RuntimeError: If Dynamo is set to suppress errors, or a block is
+ already compiled.
+ """
+
+ if torch._dynamo.config.suppress_errors:
+ raise RuntimeError(
+ "torch._dynamo.config.suppress_errors is set: dflow compiles with "
+ "errors raised, never with an eager fallback"
+ )
+ for layers in (
+ self.text_refiner_layers,
+ self.prefix_layers,
+ self.middle_layers,
+ self.suffix_layers,
+ ):
+ for block in _block_list(layers):
+ block.compile_block(dynamic=dynamic)
+
+ @torch.no_grad()
+ def prepare_text(self, text: TextConditioning) -> PreparedText:
+ """Run the text refiner once for a prompt batch.
+
+ Args:
+ text: Encoder tokens ``[B, L, width]`` float32 and optional
+ emphasis tensors ``[B, L]`` float32, on the model's device.
+
+ Returns:
+ The refined tokens with the emphasis tensors carried along.
+
+ Raises:
+ ValueError: For wrong shapes, dtypes or devices, or a prompt too
+ long for the RoPE capacity.
+ """
+
+ self._validate_text(text)
+ batch, length, _ = text.tokens.shape
+ validate_rope_capacity(
+ self.config, text_length=length, grid_height=1, grid_width=1
+ )
+ device = text.tokens.device
+ sin, cos = text_rope_rows(self.config, length, device=device)
+ key_bias = _key_bias(text.key_bias, dtype=AUTOCAST_DTYPE)
+ value_scale = _value_scale(text.value_scale, dtype=AUTOCAST_DTYPE)
+ rope_sin = _batched(sin, batch)
+ rope_cos = _batched(cos, batch)
+ x = _owned(text.tokens)
+ with torch.autocast(device_type=device.type, dtype=AUTOCAST_DTYPE):
+ for block in _block_list(self.text_refiner_layers):
+ x = block(
+ x,
+ rope_sin=rope_sin,
+ rope_cos=rope_cos,
+ modulation=None,
+ query_scale=None,
+ key_bias=key_bias,
+ value_scale=value_scale,
+ )
+ return PreparedText(
+ tokens=x, key_bias=text.key_bias, value_scale=text.value_scale
+ )
+
+ @torch.no_grad()
+ def forward(
+ self,
+ latents: Tensor,
+ timestep: Tensor,
+ prepared: PreparedText,
+ *,
+ path: DFlowPath,
+ self_attention_gain: Tensor,
+ suffix_caption_bias: float,
+ generator: torch.Generator | None,
+ ) -> Tensor:
+ """Predict the velocity ``eps - x_0`` at ``(x_t, t)``.
+
+ Args:
+ latents: ``x_t`` ``[B, 96, H, W]`` float32 (whitened latent grid).
+ timestep: ``t`` ``[B]`` float32 in ``[0, 1]`` (1 = noise).
+ prepared: ``prepare_text`` output with batch ``B``.
+ path: Middle routing (``DFlowPath``).
+ self_attention_gain: 0-dim float32 tensor on the latents' device
+ (``self_attention_gain_tensor``); scales the image layers'
+ queries by ``exp(gain)``, never the refiner's.
+ suffix_caption_bias: Additive attention-logit bias on the prompt's
+ token keys (every text row but the learned suffix) in the six
+ suffix layers, for every query; 0 for none. The PDG reference
+ forward uses it (``PdgGuidance.suffix_caption_bias``).
+ generator: For ``THREE_QUARTER``, the CUDA generator that picks the
+ one kept token of each 2x2 group (uniformly, per sample and
+ step); it draws exactly what the training code
+ draws, so a generator seeded alike keeps the same tokens.
+ None for the other paths.
+
+ Returns:
+ Velocity ``[B, 96, H, W]`` float32.
+
+ Raises:
+ ValueError: For inconsistent shapes, dtypes or devices, a grid
+ beyond the RoPE capacity, an odd grid side with
+ ``THREE_QUARTER``, a generator given or missing for the
+ path, or a non-finite suffix caption bias.
+ """
+
+ self._validate_forward(
+ latents,
+ timestep,
+ prepared,
+ path=path,
+ self_attention_gain=self_attention_gain,
+ suffix_caption_bias=suffix_caption_bias,
+ generator=generator,
+ )
+ with torch.autocast(device_type=latents.device.type, dtype=AUTOCAST_DTYPE):
+ return self._velocity(
+ latents,
+ timestep,
+ prepared,
+ path=path,
+ self_attention_gain=self_attention_gain,
+ suffix_caption_bias=suffix_caption_bias,
+ generator=generator,
+ )
+
+ def _velocity(
+ self,
+ latents: Tensor,
+ timestep: Tensor,
+ prepared: PreparedText,
+ *,
+ path: DFlowPath,
+ self_attention_gain: Tensor,
+ suffix_caption_bias: float,
+ generator: torch.Generator | None,
+ ) -> Tensor:
+ """``forward`` after validation, inside autocast."""
+
+ batch, _, grid_height, grid_width = latents.shape
+ image = self.patch_embed(latents).flatten(2).transpose(1, 2)
+ image_count = int(image.shape[1])
+ x = torch.cat([image, prepared.tokens.to(dtype=image.dtype)], dim=1)
+ sin, cos = joint_rope_rows(
+ self.config,
+ text_length=prepared.length,
+ grid_height=grid_height,
+ grid_width=grid_width,
+ device=latents.device,
+ )
+ time_act = F.silu(self.time_embed(timestep))
+ stream = _StreamInputs(
+ rope_sin=_batched(sin, batch),
+ rope_cos=_batched(cos, batch),
+ query_scale=torch.exp(self_attention_gain.to(dtype=torch.float64)).to(
+ dtype=torch.float32
+ ),
+ key_bias=_key_bias(
+ _pad_image_rows(prepared.key_bias, image_count, fill=0.0),
+ dtype=x.dtype,
+ ),
+ value_scale=_value_scale(
+ _pad_image_rows(prepared.value_scale, image_count, fill=1.0),
+ dtype=x.dtype,
+ ),
+ time_act=time_act,
+ )
+ x = self._run_layers(x, self.prefix_layers, self.prefix_adaln, stream)
+ x = self._middle_and_join(
+ x,
+ stream,
+ path=path,
+ grid=(grid_height, grid_width),
+ image_count=image_count,
+ generator=generator,
+ )
+ suffix_stream = (
+ stream
+ if suffix_caption_bias == 0.0
+ else _with_caption_key_bias(
+ stream,
+ bias=suffix_caption_bias,
+ image_count=image_count,
+ text_length=prepared.length,
+ batch=batch,
+ dtype=x.dtype,
+ )
+ )
+ x = self._run_layers(x, self.suffix_layers, self.suffix_adaln, suffix_stream)
+ return self._final_layer(x[:, :image_count], time_act, grid_height, grid_width)
+
+ def _middle_and_join(
+ self,
+ prefix: Tensor,
+ stream: _StreamInputs,
+ *,
+ path: DFlowPath,
+ grid: tuple[int, int],
+ image_count: int,
+ generator: torch.Generator | None,
+ ) -> Tensor:
+ """Run ``path``'s middle on the prefix output and fuse it in the tail join."""
+
+ mask = self.tail_join.mask_token.to(dtype=prefix.dtype).expand_as(prefix)
+ match path:
+ case DFlowPath.FULL:
+ middle = self._run_layers(
+ prefix, self.middle_layers, self.middle_adaln, stream
+ )
+ return self.tail_join(prefix, middle, None, stream.time_act)
+ case DFlowPath.PATH_DROP:
+ dropped = prefix.new_ones(prefix.shape[0], prefix.shape[1], 1)
+ return self.tail_join(prefix, mask, dropped, stream.time_act)
+ case DFlowPath.THREE_QUARTER:
+ if generator is None:
+ raise ValueError("THREE_QUARTER needs a generator")
+ rows = three_quarter_middle_rows(
+ grid=grid,
+ image_count=image_count,
+ text_length=prefix.shape[1] - image_count,
+ batch=prefix.shape[0],
+ generator=generator,
+ device=prefix.device,
+ )
+ kept = self._run_layers(
+ _gather_rows(prefix, rows),
+ self.middle_layers,
+ self.middle_adaln,
+ _gather_stream(stream, rows),
+ )
+ middle = mask.contiguous().scatter(
+ 1, _row_index(rows, prefix.shape[-1]), kept
+ )
+ dropped = prefix.new_ones(prefix.shape[0], prefix.shape[1], 1).scatter(
+ 1, rows.unsqueeze(-1), prefix.new_zeros((*rows.shape, 1))
+ )
+ return self.tail_join(prefix, middle, dropped, stream.time_act)
+ case _ as unsupported:
+ raise ValueError(f"Unsupported DFlowPath: {unsupported}")
+
+ @staticmethod
+ def _run_layers(
+ x: Tensor, layers: nn.ModuleList, adaln: nn.ModuleList, stream: _StreamInputs
+ ) -> Tensor:
+ """Run modulated image ``layers`` with their AdaLN projections."""
+
+ for block, projection in zip(
+ _block_list(layers), _linear_list(adaln), strict=True
+ ):
+ x = block(
+ x,
+ rope_sin=stream.rope_sin,
+ rope_cos=stream.rope_cos,
+ modulation=projection(stream.time_act).to(dtype=torch.float32),
+ query_scale=stream.query_scale,
+ key_bias=stream.key_bias,
+ value_scale=stream.value_scale,
+ )
+ return x
+
+ def _final_layer(
+ self, image: Tensor, time_act: Tensor, grid_height: int, grid_width: int
+ ) -> Tensor:
+ """Final norm, timestep shift/scale and the velocity head, as a
+ float32 ``[B, C, H, W]`` grid."""
+
+ normed = self.final_norm(image)
+ shift, scale = (
+ self.final_modulation(time_act).to(dtype=torch.float32).chunk(2, dim=-1)
+ )
+ out = normed.to(dtype=torch.float32) * (1.0 + scale.unsqueeze(1))
+ out = (out + shift.unsqueeze(1)).to(dtype=normed.dtype)
+ velocity = F.linear(
+ out,
+ self.velocity_head.weight.to(dtype=out.dtype),
+ self.velocity_head.bias.to(dtype=out.dtype),
+ ).to(dtype=torch.float32)
+ batch = velocity.shape[0]
+ return velocity.transpose(1, 2).reshape(
+ batch, self.config.latent_channels, grid_height, grid_width
+ )
+
+ def _validate_text(self, text: TextConditioning) -> None:
+ """Check ``TextConditioning`` shapes, dtypes and device.
+
+ Raises:
+ ValueError: On any mismatch.
+ """
+
+ tokens = text.tokens
+ if tokens.dim() != 3 or tokens.shape[2] != self.config.width:
+ raise ValueError(
+ f"text tokens must be [B, L, {self.config.width}], got "
+ f"{tuple(tokens.shape)}"
+ )
+ if tokens.dtype != torch.float32:
+ raise ValueError(f"text tokens must be float32, got {tokens.dtype}")
+ if tokens.device != self.patch_embed.weight.device:
+ raise ValueError(
+ f"text tokens are on {tokens.device}; the model is on "
+ f"{self.patch_embed.weight.device}"
+ )
+ for name, values in (
+ ("key_bias", text.key_bias),
+ ("value_scale", text.value_scale),
+ ):
+ if values is None:
+ continue
+ if values.shape != tokens.shape[:2] or values.dtype != torch.float32:
+ raise ValueError(
+ f"text {name} must be float32 {tuple(tokens.shape[:2])}, got "
+ f"{values.dtype} {tuple(values.shape)}"
+ )
+ if values.device != tokens.device:
+ raise ValueError(f"text {name} must be on the tokens' device")
+
+ def _validate_forward(
+ self,
+ latents: Tensor,
+ timestep: Tensor,
+ prepared: PreparedText,
+ *,
+ path: DFlowPath,
+ self_attention_gain: Tensor,
+ suffix_caption_bias: float,
+ generator: torch.Generator | None,
+ ) -> None:
+ """Check ``forward``'s inputs (host-side metadata only, no device reads).
+
+ Raises:
+ ValueError: On any mismatch (see ``forward``).
+ """
+
+ config = self.config
+ if not math.isfinite(suffix_caption_bias):
+ raise ValueError(
+ f"suffix_caption_bias must be finite, got {suffix_caption_bias}"
+ )
+ if latents.dim() != 4 or latents.shape[1] != config.latent_channels:
+ raise ValueError(
+ f"latents must be [B, {config.latent_channels}, H, W], got "
+ f"{tuple(latents.shape)}"
+ )
+ batch, _, grid_height, grid_width = latents.shape
+ device = self.patch_embed.weight.device
+ expected = {
+ "latents": (
+ latents,
+ (batch, config.latent_channels, grid_height, grid_width),
+ ),
+ "timestep": (timestep, (batch,)),
+ "prepared tokens": (
+ prepared.tokens,
+ (batch, prepared.length, config.width),
+ ),
+ "self_attention_gain": (self_attention_gain, ()),
+ }
+ for name, (tensor, shape) in expected.items():
+ if tuple(tensor.shape) != shape or tensor.dtype != torch.float32:
+ raise ValueError(
+ f"{name} must be float32 {shape}, got {tensor.dtype} "
+ f"{tuple(tensor.shape)}"
+ )
+ if tensor.device != device:
+ raise ValueError(
+ f"{name} is on {tensor.device}; the model is on {device}"
+ )
+ validate_rope_capacity(
+ config,
+ text_length=prepared.length,
+ grid_height=grid_height,
+ grid_width=grid_width,
+ )
+ match path:
+ case DFlowPath.THREE_QUARTER:
+ if generator is None or not _generator_on(generator, device):
+ raise ValueError(
+ f"THREE_QUARTER needs a torch.Generator on {device}"
+ )
+ if grid_height % 2 or grid_width % 2:
+ raise ValueError(
+ "THREE_QUARTER needs even token-grid sides, got "
+ f"{grid_height}x{grid_width}"
+ )
+ case DFlowPath.FULL | DFlowPath.PATH_DROP:
+ if generator is not None:
+ raise ValueError(f"{path} draws nothing: pass generator=None")
+ case _ as unsupported:
+ raise ValueError(f"Unsupported DFlowPath: {unsupported}")
+
+
+def three_quarter_middle_rows(
+ *,
+ grid: tuple[int, int],
+ image_count: int,
+ text_length: int,
+ batch: int,
+ generator: torch.Generator,
+ device: torch.device,
+) -> Tensor:
+ """Stream rows ``[B, H * W / 4 + L]`` the THREE_QUARTER middle runs on.
+
+ One uniformly drawn token of every 2x2 group of the row-major ``H x W``
+ grid (groups in raster order), then every text row. After the group
+ choice it draws (and discards) one float64 uniform per text token, as the
+ training code does for its all-kept text subset, so a shared
+ generator advances identically.
+ """
+
+ grid_height, grid_width = grid
+ group_y = torch.arange(grid_height // 2, device=device, dtype=torch.int64)
+ group_x = torch.arange(grid_width // 2, device=device, dtype=torch.int64)
+ base = (2 * group_y.view(-1, 1) * grid_width + 2 * group_x.view(1, -1)).reshape(
+ -1, 1
+ )
+ slot = torch.arange(4, device=device, dtype=torch.int64)
+ groups = base + (slot % 2 + (slot // 2) * grid_width).view(1, 4)
+ choice = torch.randint(
+ 0, 4, (batch, groups.shape[0]), device=device, generator=generator
+ )
+ kept = groups.unsqueeze(0).expand(batch, -1, -1).gather(2, choice.unsqueeze(-1))
+ torch.rand(
+ (batch * text_length,), device=device, dtype=torch.float64, generator=generator
+ )
+ text = image_count + torch.arange(text_length, device=device, dtype=torch.int64)
+ return torch.cat([kept.squeeze(-1), text.expand(batch, -1)], dim=1)
+
+
+def _generator_on(generator: torch.Generator, device: torch.device) -> bool:
+ """Whether ``generator`` draws on ``device`` (an index-less generator
+ device means the current device of its type)."""
+
+ found = generator.device
+ if found.type != device.type:
+ return False
+ if found.index is None or device.index is None:
+ return found.index is None and (
+ device.index is None or device.index == torch.cuda.current_device()
+ )
+ return found.index == device.index
+
+
+def _row_index(rows: Tensor, width: int) -> Tensor:
+ """``rows`` ``[B, K]`` expanded to gather/scatter ``[B, K, width]``."""
+
+ return rows.unsqueeze(-1).expand(-1, -1, width)
+
+
+def _gather_rows(values: Tensor, rows: Tensor) -> Tensor:
+ """Rows ``[B, K, D]`` of ``values`` ``[B, S, D]``."""
+
+ return values.gather(1, _row_index(rows, values.shape[-1]))
+
+
+def _gather_stream(stream: _StreamInputs, rows: Tensor) -> _StreamInputs:
+ """``stream`` restricted to ``rows`` ``[B, K]``."""
+
+ batch, count = rows.shape
+ return _StreamInputs(
+ rope_sin=_gather_rows(stream.rope_sin, rows),
+ rope_cos=_gather_rows(stream.rope_cos, rows),
+ query_scale=stream.query_scale,
+ key_bias=None
+ if stream.key_bias is None
+ else stream.key_bias.gather(3, rows.view(batch, 1, 1, count)),
+ value_scale=None
+ if stream.value_scale is None
+ else stream.value_scale.gather(2, rows.view(batch, 1, count, 1)),
+ time_act=stream.time_act,
+ )
+
+
+def _with_caption_key_bias(
+ stream: _StreamInputs,
+ *,
+ bias: float,
+ image_count: int,
+ text_length: int,
+ batch: int,
+ dtype: torch.dtype,
+) -> _StreamInputs:
+ """``stream`` with ``bias`` added to the key bias of the prompt's token
+ rows: the ``text_length - SUFFIX_TOKEN_COUNT`` rows after the image rows
+ (the learned suffix rows keep their bias)."""
+
+ caption = torch.zeros(
+ (batch, image_count + text_length), dtype=dtype, device=stream.time_act.device
+ )
+ caption[:, image_count : image_count + text_length - SUFFIX_TOKEN_COUNT] = bias
+ added = caption[:, None, None, :]
+ key_bias = added if stream.key_bias is None else stream.key_bias + added
+ return replace(stream, key_bias=_owned(key_bias))
+
+
+def _pad_image_rows(
+ values: Tensor | None, image_count: int, *, fill: float
+) -> Tensor | None:
+ """``[B, L]`` text values prefixed by ``fill`` for ``image_count`` image rows."""
+
+ if values is None:
+ return None
+ pad = values.new_full((values.shape[0], image_count), fill)
+ return torch.cat([pad, values], dim=1)
+
+
+def _key_bias(values: Tensor | None, *, dtype: torch.dtype) -> Tensor | None:
+ """``[B, S]`` key bias as an additive SDPA mask ``[B, 1, 1, S]``."""
+
+ if values is None:
+ return None
+ return _owned(values.to(dtype=dtype)[:, None, None, :])
+
+
+def _value_scale(values: Tensor | None, *, dtype: torch.dtype) -> Tensor | None:
+ """``[B, S]`` value scale as ``[B, 1, S, 1]``."""
+
+ if values is None:
+ return None
+ return _owned(values.to(dtype=dtype)[:, None, :, None])
+
+
+def _owned(values: Tensor) -> Tensor:
+ """A contiguous copy of ``values`` that is not a view.
+
+ Compiled blocks guard on whether an input is a view, so every block input
+ is built as an owned tensor: one graph serves every call site.
+ """
+
+ return values.clone(memory_format=torch.contiguous_format)
+
+
+def _batched(rows: Tensor, batch: int) -> Tensor:
+ """``[N, D]`` rows repeated over a batch as an owned ``[B, N, D]`` tensor."""
+
+ return _owned(rows.unsqueeze(0).expand(batch, -1, -1))
+
+
+def _blocks(config: DFlowConfig, count: int) -> nn.ModuleList:
+ """``count`` transformer blocks."""
+
+ return nn.ModuleList(DFlowBlock(config) for _ in range(count))
+
+
+def _adaln(config: DFlowConfig, count: int) -> nn.ModuleList:
+ """``count`` AdaLN projections ``time_embed_width -> 4 * width``."""
+
+ return nn.ModuleList(
+ nn.Linear(config.time_embed_width, 4 * config.width) for _ in range(count)
+ )
+
+
+def _block_list(layers: nn.ModuleList) -> list[DFlowBlock]:
+ """The blocks of ``layers``, typed.
+
+ Raises:
+ TypeError: If an entry is not a DFlowBlock.
+ """
+
+ blocks: list[DFlowBlock] = []
+ for layer in layers:
+ match layer:
+ case DFlowBlock() as block:
+ blocks.append(block)
+ case _ as other:
+ raise TypeError(f"expected DFlowBlock, got {type(other).__name__}")
+ return blocks
+
+
+def _linear_list(layers: nn.ModuleList) -> list[nn.Linear]:
+ """The linears of ``layers``, typed.
+
+ Raises:
+ TypeError: If an entry is not an nn.Linear.
+ """
+
+ linears: list[nn.Linear] = []
+ for layer in layers:
+ match layer:
+ case nn.Linear() as linear:
+ linears.append(linear)
+ case _ as other:
+ raise TypeError(f"expected nn.Linear, got {type(other).__name__}")
+ return linears
diff --git a/dflow/pipeline.py b/dflow/pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..28c835d3911fa246877a72df9f3cc9191ce5bd4d
--- /dev/null
+++ b/dflow/pipeline.py
@@ -0,0 +1,304 @@
+"""Prompt-to-image pipeline: loading, sampling, decoding and PNG metadata."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Sequence
+from dataclasses import asdict, dataclass, field
+from enum import Enum
+from pathlib import Path
+
+import torch
+from huggingface_hub import snapshot_download
+from PIL import Image, PngImagePlugin
+from torch import Tensor
+
+from .inference import (
+ DFlowEngine,
+ GenerationSettings,
+ ImageToImage,
+ LatentCallback,
+)
+from .loading import load_dflow_denoiser, load_text_adapter_tensors
+from .preview import preview_images
+from .text_conditioning import DFlowTextEncoder, TextAdapter
+from .vae import DFlowVae
+from .version import MODEL_VERSION, __version__
+
+REPOSITORY = "data-archetype/dflow_2b"
+TEXT_ENCODER_DIRNAME = "text_encoder"
+PNG_METADATA_KEY = "dflow"
+_RELEASE_PATTERNS = (
+ "model.safetensors",
+ "config.json",
+ "release.json",
+ f"{TEXT_ENCODER_DIRNAME}/*",
+)
+
+
+def resolve_release_directory(
+ path_or_repository: str | Path,
+ *,
+ revision: str | None,
+ cache_dir: Path | None,
+) -> Path:
+ """Return a local release directory.
+
+ A ``Path`` or an existing directory is used as it is; any other string
+ with a ``/`` is a Hub repository id whose weights and text encoder are
+ downloaded.
+
+ Raises:
+ FileNotFoundError: If a ``Path`` names no directory, or a string is
+ neither a directory nor a Hub id.
+ """
+
+ if isinstance(path_or_repository, Path):
+ if not path_or_repository.is_dir():
+ raise FileNotFoundError(f"No release directory at {path_or_repository}.")
+ return path_or_repository
+ local = Path(path_or_repository).expanduser()
+ if local.is_dir():
+ return local
+ if "/" not in path_or_repository:
+ raise FileNotFoundError(
+ f"No release folder {path_or_repository!r} here; pass its path or the "
+ "Hub id data-archetype/dflow_2b."
+ )
+ return Path(
+ snapshot_download(
+ path_or_repository,
+ revision=revision,
+ allow_patterns=list(_RELEASE_PATTERNS),
+ cache_dir=None if cache_dir is None else str(cache_dir),
+ )
+ )
+
+
+@dataclass(frozen=True)
+class DFlowComponents:
+ """The loaded parts of the model.
+
+ Attributes:
+ engine: Denoiser and text encoder.
+ vae: The dinac3_96 autoencoder.
+ compiled: Whether the blocks were compiled.
+ """
+
+ engine: DFlowEngine
+ vae: DFlowVae
+ compiled: bool
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ path_or_repository: str | Path = REPOSITORY,
+ *,
+ device: torch.device | str = "cuda",
+ compile: bool = True,
+ revision: str | None = None,
+ cache_dir: Path | None = None,
+ vae_dir: Path | None = None,
+ ) -> DFlowComponents:
+ """Load the denoiser, text encoder and autoencoder.
+
+ Args:
+ path_or_repository: A local release directory or Hub repository.
+ device: CUDA device.
+ compile: ``torch.compile`` the denoiser blocks, encoder layers and
+ autoencoder. Graphs build on first use (30 to 45 seconds);
+ False runs eagerly.
+ revision: Hub revision of the release (a repository id only).
+ cache_dir: Hugging Face cache directory, or None for the default.
+ vae_dir: A local copy of ``data-archetype/dinac3_96``, or None to
+ download its pinned commit.
+
+ Raises:
+ FileNotFoundError: If release files are missing.
+ ValueError: On a non-CUDA device or a release that does not match
+ this code.
+ """
+
+ target = torch.device(device)
+ directory = resolve_release_directory(
+ path_or_repository, revision=revision, cache_dir=cache_dir
+ )
+ model = load_dflow_denoiser(directory, device=target, compile_model=compile)
+ adapter = TextAdapter()
+ adapter.load_state_dict(load_text_adapter_tensors(directory), strict=True)
+ text_encoder = DFlowTextEncoder.from_directory(
+ directory / TEXT_ENCODER_DIRNAME, adapter=adapter, device=target
+ )
+ if compile:
+ text_encoder.compile_layers()
+ vae = DFlowVae.from_pretrained(
+ device=target, compile=compile, local_dir=vae_dir, cache_dir=cache_dir
+ )
+ return cls(engine=DFlowEngine(model, text_encoder), vae=vae, compiled=compile)
+
+
+class OutputType(Enum):
+ """What ``DFlowPipeline.__call__`` returns."""
+
+ PIL = "pil"
+ TENSOR = "tensor"
+ LATENT = "latent"
+
+
+@dataclass(frozen=True)
+class DFlowOutput:
+ """Images of one call.
+
+ Attributes:
+ images: PIL images with their settings in the PNG text chunk (PIL
+ output), else empty.
+ tensors: ``[B, 3, H, W]`` float32 RGB in ``[-1, 1]`` (TENSOR output),
+ or ``[B, 96, h, w]`` latents (LATENT output), else None.
+ settings: The settings of the call.
+ """
+
+ images: list[Image.Image]
+ tensors: Tensor | None
+ settings: GenerationSettings
+
+
+@dataclass
+class DFlowPipeline:
+ """Text to image with dflow_2b.
+
+ Example::
+
+ pipe = DFlowPipeline.from_pretrained("data-archetype/dflow_2b")
+ image = pipe("A lighthouse on a cliff at dusk.").images[0]
+ image.save("lighthouse.png", pnginfo=pipe.png_info(image))
+ """
+
+ components: DFlowComponents
+ default_settings: GenerationSettings = field(default_factory=GenerationSettings)
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ path_or_repository: str | Path = REPOSITORY,
+ *,
+ device: torch.device | str = "cuda",
+ compile: bool = True,
+ revision: str | None = None,
+ cache_dir: Path | None = None,
+ vae_dir: Path | None = None,
+ ) -> DFlowPipeline:
+ """Load a pipeline (see ``DFlowComponents.from_pretrained``)."""
+
+ return cls(
+ DFlowComponents.from_pretrained(
+ path_or_repository,
+ device=device,
+ compile=compile,
+ revision=revision,
+ cache_dir=cache_dir,
+ vae_dir=vae_dir,
+ )
+ )
+
+ def __call__(
+ self,
+ prompt: str | Sequence[str],
+ settings: GenerationSettings | None = None,
+ *,
+ num_images: int = 1,
+ output_type: OutputType = OutputType.PIL,
+ image_to_image: ImageToImage | None = None,
+ callback: LatentCallback | None = None,
+ ) -> DFlowOutput:
+ """Generate images.
+
+ Args:
+ prompt: One prompt (repeated ``num_images`` times) or a list of
+ prompts with the same token count.
+ settings: Size, seed, sampling and guidance; the pipeline's
+ ``default_settings`` when None.
+ num_images: Images per prompt string (a single prompt only).
+ output_type: PIL images, RGB tensors or latents.
+ image_to_image: Start latents and start step, or None.
+ callback: Receives the predicted clean latents after each update
+ (``dflow.preview.LatentRgbPreview`` turns them into previews).
+
+ Raises:
+ ValueError: For ``num_images`` < 1 or with a prompt list.
+ """
+
+ chosen = self.default_settings if settings is None else settings
+ prompts = _prompt_list(prompt, num_images)
+ latents = self.components.engine.sample(
+ prompts, chosen, image_to_image=image_to_image, callback=callback
+ )
+ match output_type:
+ case OutputType.LATENT:
+ return DFlowOutput(images=[], tensors=latents, settings=chosen)
+ case OutputType.TENSOR:
+ rgb = self.components.vae.decode(latents).clamp(-1.0, 1.0)
+ return DFlowOutput(images=[], tensors=rgb, settings=chosen)
+ case OutputType.PIL:
+ rgb = self.components.vae.decode(latents).clamp(-1.0, 1.0)
+ images = preview_images(rgb)
+ for index, image in enumerate(images):
+ image.info[PNG_METADATA_KEY] = generation_metadata(
+ prompts[index], chosen, batch_index=index
+ )
+ return DFlowOutput(images=images, tensors=None, settings=chosen)
+ case _ as unreachable:
+ raise ValueError(f"Unsupported output type: {unreachable}")
+
+ @staticmethod
+ def png_info(image: Image.Image) -> PngImagePlugin.PngInfo:
+ """A ``PngInfo`` carrying the image's generation metadata, for
+ ``image.save(path, pnginfo=...)``.
+
+ Raises:
+ KeyError: If the image did not come from this pipeline.
+ """
+
+ info = PngImagePlugin.PngInfo()
+ info.add_text(PNG_METADATA_KEY, str(image.info[PNG_METADATA_KEY]))
+ return info
+
+
+def generation_metadata(
+ prompt: str, settings: GenerationSettings, *, batch_index: int
+) -> str:
+ """JSON text describing one generated image."""
+
+ payload = {
+ "model": f"dflow_2b {MODEL_VERSION}",
+ "package": __version__,
+ "prompt": prompt,
+ "batch_index": batch_index,
+ "settings": asdict(settings),
+ }
+ return json.dumps(payload, default=_json_value, sort_keys=True)
+
+
+def _json_value(value: object) -> object:
+ """JSON form of enums in the settings."""
+
+ match value:
+ case Enum():
+ return value.value
+ case _:
+ raise TypeError(f"Cannot serialize {type(value).__name__} to JSON.")
+
+
+def _prompt_list(prompt: str | Sequence[str], num_images: int) -> list[str]:
+ """The batch's prompts.
+
+ Raises:
+ ValueError: For ``num_images`` < 1, or ``num_images`` > 1 with a list.
+ """
+
+ if num_images < 1:
+ raise ValueError(f"num_images must be >= 1, got {num_images}.")
+ if isinstance(prompt, str):
+ return [prompt] * num_images
+ if num_images != 1:
+ raise ValueError("num_images applies to a single prompt string only.")
+ return list(prompt)
diff --git a/dflow/precision.py b/dflow/precision.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdcb6c10f6cc75a70131aae75b2d9df7261eef14
--- /dev/null
+++ b/dflow/precision.py
@@ -0,0 +1,125 @@
+"""Storage dtypes of the public ``model.safetensors``: bfloat16 with FP32 islands.
+
+Every tensor name in the file matches exactly one rule. The FP32 islands are
+the tensors whose rounding would change results: norm affine weights (some
+see a float32 residual stream), the velocity head, the text adapter's learned
+tokens and tap statistics. The rest is bfloat16. The same
+policy writes the file (``export_release.py``) and checks it on load; a
+tensor stored in another dtype fails loading.
+"""
+
+from __future__ import annotations
+
+import re
+from enum import Enum
+
+import torch
+
+from .text_conditioning import TEXT_ADAPTER_KEY_MAP
+
+DENOISER_PREFIX = "denoiser."
+TEXT_ADAPTER_PREFIX = "text_adapter."
+
+
+class StoredDType(Enum):
+ """The dtype one public tensor is stored in."""
+
+ BFLOAT16 = "bfloat16"
+ FLOAT32 = "float32"
+
+ @property
+ def torch_dtype(self) -> torch.dtype:
+ """The matching torch dtype."""
+
+ match self:
+ case StoredDType.BFLOAT16:
+ return torch.bfloat16
+ case StoredDType.FLOAT32:
+ return torch.float32
+ case _ as unreachable:
+ raise RuntimeError(f"Unsupported stored dtype: {unreachable}")
+
+
+_LAYER = r"denoiser\.(?:text_refiner|prefix|middle|suffix)_layers\.\d+\."
+_NORMS = r"(?:attn_norm1|attn_norm2|mlp_norm1|mlp_norm2|attn\.q_norm|attn\.k_norm)"
+
+_STORAGE_RULES: tuple[tuple[re.Pattern[str], StoredDType], ...] = (
+ (re.compile(_LAYER + _NORMS + r"\.weight"), StoredDType.FLOAT32),
+ (
+ re.compile(
+ _LAYER
+ + r"(?:attn\.(?:qkv|proj_out)\.weight|mlp\.(?:up|down)\.(?:weight|bias))"
+ ),
+ StoredDType.BFLOAT16,
+ ),
+ (
+ re.compile(r"denoiser\.(?:prefix|middle|suffix)_adaln\.\d+\.(?:weight|bias)"),
+ StoredDType.BFLOAT16,
+ ),
+ (
+ re.compile(
+ r"denoiser\.(?:patch_embed|time_embed\.proj_in|time_embed\.proj_out"
+ r"|tail_join\.adascale|tail_join\.proj|final_modulation)"
+ r"\.(?:weight|bias)"
+ ),
+ StoredDType.BFLOAT16,
+ ),
+ (
+ re.compile(r"denoiser\.tail_join\.(?:mask_token|dropped_skip_proj\.weight)"),
+ StoredDType.BFLOAT16,
+ ),
+ (
+ re.compile(r"denoiser\.(?:final_norm\.weight|velocity_head\.(?:weight|bias))"),
+ StoredDType.FLOAT32,
+ ),
+)
+
+
+def denoiser_storage_dtype(name: str) -> StoredDType:
+ """Storage dtype of one public ``denoiser.*`` tensor.
+
+ Raises:
+ RuntimeError: If ``name`` matches no rule or several.
+ """
+
+ matches = {
+ storage for pattern, storage in _STORAGE_RULES if pattern.fullmatch(name)
+ }
+ if len(matches) != 1:
+ raise RuntimeError(
+ f"Public tensor {name!r} matches storage rules "
+ f"{sorted(storage.value for storage in matches)}; it needs exactly one"
+ )
+ return matches.pop()
+
+
+# Storage of each training text adapter tensor; the public key of each is
+# ``text_adapter.`` + ``TEXT_ADAPTER_KEY_MAP[training key]`` (text_conditioning).
+_TEXT_ADAPTER_STORAGE: dict[str, StoredDType] = {
+ "conditioning._encoder._proj_lo.weight": StoredDType.BFLOAT16,
+ "conditioning._encoder._proj_mid.weight": StoredDType.BFLOAT16,
+ "conditioning._encoder._proj_hi.weight": StoredDType.BFLOAT16,
+ "conditioning._encoder._tap_statistics.mean": StoredDType.FLOAT32,
+ "conditioning._encoder._tap_statistics.std": StoredDType.FLOAT32,
+ "conditioning.learned_padding_tokens": StoredDType.FLOAT32,
+ "conditioning.uncond_token": StoredDType.FLOAT32,
+}
+
+
+def text_adapter_storage_dtypes() -> dict[str, StoredDType]:
+ """Storage dtype of every public text adapter tensor, keyed by its full
+ public name (``text_adapter.``).
+
+ Raises:
+ RuntimeError: If the adapter's key map and the storage rules differ.
+ """
+
+ if set(TEXT_ADAPTER_KEY_MAP) != set(_TEXT_ADAPTER_STORAGE):
+ raise RuntimeError(
+ "Text adapter keys and storage rules differ: "
+ f"{sorted(set(TEXT_ADAPTER_KEY_MAP) ^ set(_TEXT_ADAPTER_STORAGE))}"
+ )
+ return {
+ TEXT_ADAPTER_PREFIX + public: _TEXT_ADAPTER_STORAGE[internal]
+ for internal, public in TEXT_ADAPTER_KEY_MAP.items()
+ }
diff --git a/dflow/preview.py b/dflow/preview.py
new file mode 100644
index 0000000000000000000000000000000000000000..9252ce167fd898dfaaefe525805641ffe4b31321
--- /dev/null
+++ b/dflow/preview.py
@@ -0,0 +1,148 @@
+"""Fast latent-to-RGB previews for dinac3_96 latents.
+
+A fitted linear readout: a 3x3 convolution from the 96 whitened latent
+channels to a 2x2 cell of RGB values per latent token, pixel-shuffled to 1/8
+of the image resolution. It is meant for live previews during sampling; the
+final image always comes from the VAE decoder.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+
+import torch
+import torch.nn.functional as F
+from PIL import Image
+from safetensors import safe_open
+from safetensors.torch import load_file
+from torch import Tensor
+
+LATENT_RGB_PREVIEW_FILENAME = "latent_rgb_preview.safetensors"
+_METADATA_KEY = "dflow"
+_FORMAT = "dflow.latent_rgb_preview.v1"
+_WEIGHT_KEY = "projection.weight"
+_BIAS_KEY = "projection.bias"
+_LATENT_CHANNELS = 96
+_RGB_CHANNELS = 3
+_EXPANSION = 2
+
+
+@dataclass(frozen=True)
+class LatentRgbPreview:
+ """The fitted projection, as float32 tensors on one device.
+
+ Attributes:
+ weight: ``[12, 96, k, k]`` convolution weight (k odd).
+ bias: ``[12]`` bias.
+ """
+
+ weight: Tensor
+ bias: Tensor
+
+ @classmethod
+ def from_file(cls, path: Path) -> LatentRgbPreview:
+ """Load a projection file and check its metadata and shapes.
+
+ Raises:
+ ValueError: If the metadata, tensor names, shapes or dtypes do not
+ match the dinac3_96 preview format.
+ """
+
+ _check_metadata(path)
+ tensors = load_file(str(path), device="cpu")
+ if set(tensors) != {_WEIGHT_KEY, _BIAS_KEY}:
+ raise ValueError(
+ f"{path} must hold exactly {_WEIGHT_KEY} and {_BIAS_KEY}, "
+ f"got {sorted(tensors)}."
+ )
+ weight = tensors[_WEIGHT_KEY]
+ bias = tensors[_BIAS_KEY]
+ cells = _RGB_CHANNELS * _EXPANSION**2
+ kernel = int(weight.shape[-1])
+ if (
+ weight.ndim != 4
+ or tuple(weight.shape[:2]) != (cells, _LATENT_CHANNELS)
+ or int(weight.shape[2]) != kernel
+ or kernel % 2 != 1
+ or tuple(bias.shape) != (cells,)
+ ):
+ raise ValueError(
+ f"{path}: expected weight [{cells}, {_LATENT_CHANNELS}, k, k] with "
+ f"odd k and bias [{cells}], got {tuple(weight.shape)} and "
+ f"{tuple(bias.shape)}."
+ )
+ if weight.dtype != torch.float32 or bias.dtype != torch.float32:
+ raise ValueError(f"{path}: the projection must be stored in float32.")
+ return cls(weight=weight.contiguous(), bias=bias.contiguous())
+
+ @classmethod
+ def bundled(cls) -> LatentRgbPreview:
+ """Load the projection shipped with the package."""
+
+ return cls.from_file(Path(__file__).with_name(LATENT_RGB_PREVIEW_FILENAME))
+
+ def to(self, device: torch.device) -> LatentRgbPreview:
+ """Return a copy on ``device``."""
+
+ return LatentRgbPreview(self.weight.to(device), self.bias.to(device))
+
+ def project(self, latents: Tensor) -> Tensor:
+ """Project whitened latents ``[B, 96, h, w]`` to RGB ``[B, 3, 2h, 2w]``
+ in ``[-1, 1]`` (float32, on the latents' device).
+
+ The latents are padded by replication so the output keeps the latent
+ grid's size.
+ """
+
+ pad = int(self.weight.shape[-1]) // 2
+ with torch.autocast(device_type=latents.device.type, enabled=False):
+ padded = F.pad(latents.float(), (pad, pad, pad, pad), mode="replicate")
+ cells = F.conv2d(padded, self.weight, self.bias)
+ return F.pixel_shuffle(cells, _EXPANSION).clamp(-1.0, 1.0)
+
+
+def preview_images(rgb: Tensor) -> list[Image.Image]:
+ """Convert ``[B, 3, H, W]`` RGB in ``[-1, 1]`` to PIL images."""
+
+ pixels = (
+ rgb.detach()
+ .float()
+ .add(1.0)
+ .mul(127.5)
+ .round()
+ .clamp(0.0, 255.0)
+ .to(torch.uint8)
+ .permute(0, 2, 3, 1)
+ .cpu()
+ .numpy()
+ )
+ return [Image.fromarray(image, mode="RGB") for image in pixels]
+
+
+def _check_metadata(path: Path) -> None:
+ """Require the dflow preview format in the file's metadata.
+
+ Raises:
+ ValueError: If the metadata is missing or describes another format.
+ """
+
+ with safe_open(str(path), framework="pt", device="cpu") as handle:
+ header = handle.metadata()
+ if header is None or _METADATA_KEY not in header:
+ raise ValueError(f"{path} has no '{_METADATA_KEY}' metadata.")
+ metadata: dict[str, str] = json.loads(header[_METADATA_KEY])
+ expected = {
+ "format": _FORMAT,
+ "latent_channels": str(_LATENT_CHANNELS),
+ "rgb_channels": str(_RGB_CHANNELS),
+ "spatial_expansion_factor": str(_EXPANSION),
+ }
+ wrong = {
+ key: (metadata.get(key), value)
+ for key, value in expected.items()
+ if metadata.get(key) != value
+ }
+ if wrong:
+ raise ValueError(f"{path}: incompatible preview metadata {wrong}.")
diff --git a/dflow/prompt_emphasis.py b/dflow/prompt_emphasis.py
new file mode 100644
index 0000000000000000000000000000000000000000..d650cdc60bb8633a985d6bf4d5d31507bfbfa14b
--- /dev/null
+++ b/dflow/prompt_emphasis.py
@@ -0,0 +1,317 @@
+r"""Prompt emphasis: ``(phrase:weight)`` markup applied through attention.
+
+Markup (the grammar of the ComfyUI ``MOSSImagePromptWeight`` node):
+
+- the prompt is NFC-normalized first;
+- a balanced ``(...)`` group whose text after its last colon is a number
+ (``2``, ``.5``, ``-1``) weights the phrase before that colon; the phrase may
+ hold colons, and groups nest (an inner weight overrides its outer group);
+- any other group, and an unmatched parenthesis, stays literal text;
+- ``\(`` and ``\)`` are literal parentheses.
+
+Weights reach the model per token: a token takes the weight of the last group
+whose phrase its characters overlap; weight 1 changes nothing.
+
+- Weight > 0: an additive bias on the token's attention key logits,
+ ``strength * log(w)`` (``LOG``: the token's share of attention is
+ multiplied by ``w``) or ``strength * 2 * (w - 1)`` (``LINEAR``).
+- Weight <= 0: the token's attention value is scaled by
+ ``1 + strength * (w - 1)`` (0 mutes it, -1 subtracts it).
+
+The bias and scale act in every joint attention of the weighted prompt's
+forward passes and, with ``EmphasisSettings.encoder``, inside the text
+encoder's self-attention too. JSON layout prompts are never parsed.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+import unicodedata
+from collections.abc import Sequence
+from dataclasses import dataclass
+from enum import StrEnum
+
+__all__ = [
+ "EmphasisMapping",
+ "EmphasisSettings",
+ "ParsedPrompt",
+ "TokenEmphasis",
+ "WeightedTerm",
+ "parse_prompt_weights",
+ "token_emphasis",
+ "token_weights",
+]
+
+# A group's weight: the text after its last colon, matched in full.
+_WEIGHT = re.compile(r"-?\d*\.?\d+")
+# One-character stand-ins for escaped parentheses (positions do not move).
+_ESCAPED = {"(": "\x01", ")": "\x02"}
+_UNESCAPED = {value: key for key, value in _ESCAPED.items()}
+_NEUTRAL_WEIGHT = 1.0
+_NEUTRAL_BIAS = 0.0
+_NEUTRAL_SCALE = 1.0
+
+
+class EmphasisMapping(StrEnum):
+ """How a positive weight becomes an attention-logit bias.
+
+ LOG: ``log(w)``; ``(x:2)`` gets exactly twice the attention mass.
+ LINEAR: ``2 * (w - 1)``; ``(x:2)`` gets about 7 times the mass.
+ """
+
+ LOG = "log"
+ LINEAR = "linear"
+
+
+@dataclass(frozen=True)
+class EmphasisSettings:
+ """Prompt-emphasis settings.
+
+ The defaults are the ComfyUI ``MOSSImagePromptWeight`` node's: ``LINEAR``
+ mapping, strength 1, encoder weighting on.
+
+ Attributes:
+ mapping: Positive-weight to logit-bias mapping.
+ strength: Multiplier on every bias and value-scale offset.
+ encoder: Also apply the weights inside the text encoder.
+
+ Raises:
+ ValueError: If ``strength`` is negative or not finite.
+ """
+
+ mapping: EmphasisMapping = EmphasisMapping.LINEAR
+ strength: float = 1.0
+ encoder: bool = True
+
+ def __post_init__(self) -> None:
+ """Validate the strength."""
+
+ if not math.isfinite(self.strength) or self.strength < 0.0:
+ raise ValueError(f"strength must be finite and >= 0, got {self.strength}.")
+
+ def key_bias(self, weight: float) -> float:
+ """Return the key-logit bias of a token with weight > 0."""
+
+ match self.mapping:
+ case EmphasisMapping.LOG:
+ return self.strength * math.log(weight)
+ case EmphasisMapping.LINEAR:
+ return self.strength * 2.0 * (weight - 1.0)
+ case _ as unreachable:
+ raise ValueError(f"Unsupported emphasis mapping: {unreachable}")
+
+ def value_scale(self, weight: float) -> float:
+ """Return the value multiplier of a token with weight <= 0."""
+
+ return 1.0 + self.strength * (weight - 1.0)
+
+
+@dataclass(frozen=True)
+class WeightedTerm:
+ """One weighted group of a prompt.
+
+ Attributes:
+ start, end: The phrase in the clean text, surrounding spaces excluded.
+ weight: Its weight (any real number; 1 changes nothing).
+ raw_start, raw_end: The whole ``(...:w)`` group in the NFC-normalized
+ prompt as typed (for highlighting it).
+ """
+
+ start: int
+ end: int
+ weight: float
+ raw_start: int
+ raw_end: int
+
+
+@dataclass(frozen=True)
+class ParsedPrompt:
+ """A prompt with its emphasis markup removed.
+
+ Attributes:
+ clean_text: What the text encoder reads.
+ terms: Weighted groups, each outer group before the groups nested in
+ it (a later term overrides an earlier one on shared tokens).
+ """
+
+ clean_text: str
+ terms: tuple[WeightedTerm, ...]
+
+
+def parse_prompt_weights(text: str) -> ParsedPrompt:
+ """Parse ``(phrase:weight)`` markup (grammar in the module docstring)."""
+
+ normalized = unicodedata.normalize("NFC", text)
+ escaped, raw_at = _escape(normalized)
+ terms: list[WeightedTerm | None] = []
+ clean = _strip_weights(escaped, 0, len(escaped), terms=terms, base=0, raw_at=raw_at)
+ return ParsedPrompt(
+ clean_text="".join(_UNESCAPED.get(char, char) for char in clean),
+ terms=tuple(term for term in terms if term is not None),
+ )
+
+
+def _escape(text: str) -> tuple[str, list[int]]:
+ """Replace ``\\(`` / ``\\)`` by one-character stand-ins; return the raw
+ index of each character (plus the end)."""
+
+ out: list[str] = []
+ raw_at: list[int] = []
+ pos = 0
+ while pos < len(text):
+ pair = text[pos : pos + 2]
+ if len(pair) == 2 and pair[0] == "\\" and pair[1] in _ESCAPED:
+ out.append(_ESCAPED[pair[1]])
+ raw_at.append(pos)
+ pos += 2
+ else:
+ out.append(text[pos])
+ raw_at.append(pos)
+ pos += 1
+ raw_at.append(len(text))
+ return "".join(out), raw_at
+
+
+def _groups(text: str, lo: int, hi: int) -> list[tuple[int, int]]:
+ """Split ``text[lo:hi]`` into text runs and balanced ``(...)`` groups."""
+
+ out: list[tuple[int, int]] = []
+ depth, start = 0, lo
+ for pos in range(lo, hi):
+ if text[pos] == "(":
+ if depth == 0:
+ out.append((start, pos))
+ start = pos
+ depth += 1
+ elif text[pos] == ")" and depth:
+ depth -= 1
+ if depth == 0:
+ out.append((start, pos + 1))
+ start = pos + 1
+ if depth:
+ # An unmatched "(" stays text; what follows it is split again.
+ return [*out, (start, start + 1), *_groups(text, start + 1, hi)]
+ return [*out, (start, hi)]
+
+
+def _strip_weights(
+ text: str,
+ lo: int,
+ hi: int,
+ *,
+ terms: list[WeightedTerm | None],
+ base: int,
+ raw_at: Sequence[int],
+) -> str:
+ """Return ``text[lo:hi]`` without weight markup, recording the terms.
+
+ ``base`` is where the returned text starts in the whole clean text.
+ """
+
+ out = ""
+ for a, b in _groups(text, lo, hi):
+ if b - a < 2 or text[a] != "(" or text[b - 1] != ")":
+ out += text[a:b]
+ continue
+ colon = text.rfind(":", a + 1, b - 1)
+ weight = text[colon + 1 : b - 1].strip() if colon >= 0 else ""
+ if (
+ colon < 0
+ or text[a + 1 : colon].strip() == ""
+ or _WEIGHT.fullmatch(weight) is None
+ ):
+ inner = _strip_weights(
+ text, a + 1, b - 1, terms=terms, base=base + len(out) + 1, raw_at=raw_at
+ )
+ out += "(" + inner + ")"
+ continue
+ index = len(terms)
+ terms.append(None) # the outer group first, so nested groups override it
+ start = base + len(out)
+ phrase = _strip_weights(
+ text, a + 1, colon, terms=terms, base=start, raw_at=raw_at
+ )
+ terms[index] = WeightedTerm(
+ start=start + len(phrase) - len(phrase.lstrip()),
+ end=start + len(phrase.rstrip()),
+ weight=float(weight),
+ raw_start=raw_at[a],
+ raw_end=raw_at[b - 1] + 1,
+ )
+ out += phrase
+ return out
+
+
+def token_weights(
+ terms: Sequence[WeightedTerm], offsets: Sequence[tuple[int, int]]
+) -> list[float]:
+ """Return each token's weight: that of the last term its span overlaps.
+
+ Args:
+ terms: The prompt's weighted terms, outer groups first.
+ offsets: Per token, its ``(start, end)`` span in the clean text
+ (``(0, 0)`` for special tokens, which never overlap a term).
+ """
+
+ weights = [_NEUTRAL_WEIGHT] * len(offsets)
+ for term in terms:
+ for pos, (lo, hi) in enumerate(offsets):
+ if lo < term.end and hi > term.start:
+ weights[pos] = term.weight
+ return weights
+
+
+@dataclass(frozen=True)
+class TokenEmphasis:
+ """Per-token attention bias and value scale of one prompt.
+
+ Attributes:
+ key_bias: Additive key-logit bias per token (0: unchanged).
+ value_scale: Value multiplier per token (1: unchanged).
+ """
+
+ key_bias: tuple[float, ...]
+ value_scale: tuple[float, ...]
+
+ def has_key_bias(self) -> bool:
+ """Whether any token's key bias differs from 0."""
+
+ return any(value != _NEUTRAL_BIAS for value in self.key_bias)
+
+ def has_value_scale(self) -> bool:
+ """Whether any token's value scale differs from 1."""
+
+ return any(value != _NEUTRAL_SCALE for value in self.value_scale)
+
+
+def token_emphasis(
+ parsed: ParsedPrompt,
+ offsets: Sequence[tuple[int, int]],
+ settings: EmphasisSettings,
+) -> TokenEmphasis | None:
+ """Map a parsed prompt's weights onto its tokens.
+
+ Args:
+ parsed: The parsed prompt.
+ offsets: Per token of ``parsed.clean_text``, its character span.
+ settings: The mapping and strength.
+
+ Returns:
+ The token bias and scale, or None when no token is weighted.
+ """
+
+ if not parsed.terms:
+ return None
+ weights = token_weights(parsed.terms, offsets)
+ if all(weight == _NEUTRAL_WEIGHT for weight in weights):
+ return None
+ return TokenEmphasis(
+ key_bias=tuple(
+ settings.key_bias(w) if w > 0.0 and w != _NEUTRAL_WEIGHT else _NEUTRAL_BIAS
+ for w in weights
+ ),
+ value_scale=tuple(
+ settings.value_scale(w) if w <= 0.0 else _NEUTRAL_SCALE for w in weights
+ ),
+ )
diff --git a/dflow/rope3d.py b/dflow/rope3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd26943f2fef07b3e96aaf2aa60e2b608ac3cca7
--- /dev/null
+++ b/dflow/rope3d.py
@@ -0,0 +1,174 @@
+"""Centred three-axis rotary position embedding of the joint text-image stream.
+
+Every token has a 3-axis position ``(a, y, x)``; each axis rotates its own
+channel pairs of every attention head (``rope_axes_dims`` channels, adjacent
+pairs). Text token ``i`` (1-based) of an ``L``-token prompt sits at
+``(i, 0, 0)``. Image token ``(row, col)`` of an ``H x W`` grid sits at
+``(L + 1, row - (H - 1) / 2, col - (W - 1) / 2)``: the grid is centred on the
+text, so its spatial positions are half-integers on even sides. Angles are
+``position * theta^(-2k / dim)`` computed in float64 and rounded to float32
+before the sine and cosine; nothing in this module passes through bfloat16.
+
+Two evaluation paths reproduce the trained model bit for bit:
+
+- the text refiner reads rows of a per-axis table built on the CPU with
+ ``torch.polar`` (``text_rope_rows``);
+- the joint stream evaluates its real-valued positions directly on the
+ positions' device (``joint_rope_rows``).
+"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+from typing import TYPE_CHECKING
+
+import torch
+from torch import Tensor
+
+if TYPE_CHECKING:
+ from .configuration import DFlowConfig
+
+RopeRows = tuple[Tensor, Tensor]
+"""``(sin, cos)``, each ``[N, head_width]`` float32, adjacent-pair layout."""
+
+
+def validate_rope_capacity(
+ config: DFlowConfig, *, text_length: int, grid_height: int, grid_width: int
+) -> None:
+ """Check a prompt length and token grid fit the RoPE capacity.
+
+ Raises:
+ ValueError: If the text or image axis-0 position (``L + 1``) reaches
+ ``rope_axes_lens[0]``, a grid side exceeds its axis capacity, or a
+ size is not positive.
+ """
+
+ axis0, axis1, axis2 = config.rope_axes_lens
+ if text_length <= 0 or grid_height <= 0 or grid_width <= 0:
+ raise ValueError(
+ "text length and token grid must be positive, got "
+ f"L={text_length}, grid={grid_height}x{grid_width}"
+ )
+ if text_length + 1 >= axis0:
+ raise ValueError(
+ f"A {text_length}-token prompt exceeds the RoPE text capacity: the "
+ f"image sits at axis-0 position {text_length + 1}, which must stay "
+ f"below {axis0}"
+ )
+ if grid_height > axis1 or grid_width > axis2:
+ raise ValueError(
+ f"Token grid {grid_height}x{grid_width} exceeds the RoPE spatial "
+ f"capacity {axis1}x{axis2}"
+ )
+
+
+def _axis_frequencies(*, dim: int, theta: float, device: torch.device) -> Tensor:
+ """One axis's float64 rotation frequencies ``theta^(-2k / dim)``."""
+
+ exponents = torch.arange(0, dim, 2, dtype=torch.float64, device=device)
+ return 1.0 / (theta ** (exponents / float(dim)))
+
+
+def text_position_ids(length: int, *, device: torch.device) -> Tensor:
+ """Int64 positions ``(1..L, 0, 0)`` ``[L, 3]`` of an ``L``-token prompt."""
+
+ axis0 = torch.arange(1, length + 1, dtype=torch.int64, device=device)
+ zeros = torch.zeros_like(axis0)
+ return torch.stack((axis0, zeros, zeros), dim=-1)
+
+
+def image_position_ids(
+ *, text_length: int, grid_height: int, grid_width: int, device: torch.device
+) -> Tensor:
+ """Float64 centred positions ``[H * W, 3]`` of a row-major token grid after
+ an ``L``-token prompt: ``(L + 1, row - (H - 1) / 2, col - (W - 1) / 2)``."""
+
+ local = torch.arange(grid_height * grid_width, dtype=torch.int64, device=device)
+ row = local // grid_width
+ col = local - row * grid_width
+ ids = torch.stack((torch.full_like(local, text_length + 1), row, col), dim=-1)
+ centred = ids.to(torch.float64)
+ centred[:, 1] -= (grid_height - 1) / 2
+ centred[:, 2] -= (grid_width - 1) / 2
+ return centred
+
+
+def rope_rows_at(config: DFlowConfig, positions: Tensor) -> RopeRows:
+ """RoPE rows of real-valued positions ``[N, 3]`` on their own device.
+
+ Angles are ``position * frequency`` in float64, then float32; sine and
+ cosine run in float32 and repeat over each adjacent channel pair.
+ """
+
+ sins: list[Tensor] = []
+ coses: list[Tensor] = []
+ for axis, dim in enumerate(config.rope_axes_dims):
+ freqs = _axis_frequencies(
+ dim=dim, theta=config.rope_theta, device=positions.device
+ )
+ angles = torch.outer(positions[:, axis].to(torch.float64), freqs).float()
+ sins.append(torch.sin(angles).repeat_interleave(2, dim=-1))
+ coses.append(torch.cos(angles).repeat_interleave(2, dim=-1))
+ return torch.cat(sins, dim=-1), torch.cat(coses, dim=-1)
+
+
+@lru_cache(maxsize=4)
+def _axis_tables(config: DFlowConfig) -> tuple[RopeRows, ...]:
+ """Per-axis CPU tables ``(sin, cos)`` ``[axis_len, dim]`` of integer
+ positions, from ``torch.polar`` of the float32-rounded float64 angles."""
+
+ cpu = torch.device("cpu")
+ tables: list[RopeRows] = []
+ for dim, length in zip(config.rope_axes_dims, config.rope_axes_lens, strict=True):
+ timestep = torch.arange(length, dtype=torch.float64, device=cpu)
+ freqs = _axis_frequencies(dim=dim, theta=config.rope_theta, device=cpu)
+ angles = torch.outer(timestep, freqs).float()
+ rotation = torch.polar(torch.ones_like(angles), angles)
+ tables.append(
+ (
+ rotation.imag.repeat_interleave(2, dim=-1).float(),
+ rotation.real.repeat_interleave(2, dim=-1).float(),
+ )
+ )
+ return tuple(tables)
+
+
+def text_rope_rows(
+ config: DFlowConfig, length: int, *, device: torch.device
+) -> RopeRows:
+ """RoPE rows ``[L, head_width]`` of an ``L``-token prompt for the text
+ refiner: rows of the CPU integer-position tables, moved to ``device``."""
+
+ ids = text_position_ids(length, device=torch.device("cpu"))
+ sins: list[Tensor] = []
+ coses: list[Tensor] = []
+ for axis, (sin_table, cos_table) in enumerate(_axis_tables(config)):
+ sins.append(sin_table.index_select(0, ids[:, axis]))
+ coses.append(cos_table.index_select(0, ids[:, axis]))
+ return torch.cat(sins, dim=-1).to(device), torch.cat(coses, dim=-1).to(device)
+
+
+def joint_rope_rows(
+ config: DFlowConfig,
+ *,
+ text_length: int,
+ grid_height: int,
+ grid_width: int,
+ device: torch.device,
+) -> RopeRows:
+ """RoPE rows ``[H * W + L, head_width]`` of the joint stream
+ ``[image tokens, text tokens]``, evaluated on ``device``."""
+
+ positions = torch.cat(
+ (
+ image_position_ids(
+ text_length=text_length,
+ grid_height=grid_height,
+ grid_width=grid_width,
+ device=device,
+ ),
+ text_position_ids(text_length, device=device).to(torch.float64),
+ ),
+ dim=0,
+ )
+ return rope_rows_at(config, positions)
diff --git a/dflow/schedules.py b/dflow/schedules.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b3217f6144d607b244730c5f7d77fbea865e6c1
--- /dev/null
+++ b/dflow/schedules.py
@@ -0,0 +1,286 @@
+"""Flow-matching timestep schedules, the log-SNR shift and the schedule CDF.
+
+Time convention (shared with ``solvers`` and ``guidance``): the flow path is
+``x_t = (1 - t) x_0 + t noise`` with ``t = 1`` pure noise and ``t = 0`` clean.
+A schedule is a strictly descending float32 tensor of ``steps + 1`` times,
+noisy end first. The model predicts the velocity ``v = dx_t/dt = noise - x_0``,
+so the clean estimate at time ``t`` is ``x_0 = x_t - t v``.
+
+The log-SNR of time ``t`` is ``-2 logit(t)``. An additive log-SNR shift ``s``
+moves every interior time to ``sigmoid(logit(t) - s / 2)``; a negative shift
+spends more steps near the noisy end. The model was trained with
+``s = min(0, -0.25 - ln(width * height / 256^2))``.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from enum import StrEnum
+
+import numpy as np
+import torch
+from scipy import special, stats
+from torch import Tensor
+
+# Resolution-shift constants: base shift and reference side in pixels.
+TRAINING_BASE_LOG_SNR_SHIFT = -0.25
+RESOLUTION_SHIFT_REFERENCE = 256
+# Shifts at or below this magnitude leave the schedule unchanged.
+_SHIFT_NO_OP_TOLERANCE = 1.0e-9
+# The noisy endpoint t = 1 becomes 1 - this for solvers that evaluate log-SNR.
+FINITE_NOISY_ENDPOINT_EPSILON = 1.0e-4
+BETA_0_6_SHAPE = 0.6
+BETA_1_25_SHAPE = 1.25
+DEFAULT_CUSTOM_BETA_MEAN = 0.5
+DEFAULT_CUSTOM_BETA_CONCENTRATION = 0.6
+
+
+class ScheduleKind(StrEnum):
+ """Spacing of the schedule's points before the log-SNR shift.
+
+ LINEAR: evenly spaced times.
+ BETA_0_6: equal-probability quantiles of Beta(0.6, 0.6) (dense at both ends).
+ BETA_1_25: quantiles of Beta(1.25, 1.25) (slightly dense in the middle).
+ CUSTOM_BETA: quantiles of Beta(mean * concentration,
+ (1 - mean) * concentration).
+ """
+
+ LINEAR = "linear"
+ BETA_0_6 = "beta_0_6"
+ BETA_1_25 = "beta_1_25"
+ CUSTOM_BETA = "custom_beta"
+
+
+@dataclass(frozen=True)
+class TimeSchedule:
+ """A schedule family and its step count.
+
+ Attributes:
+ kind: Point spacing.
+ steps: Solver updates; the schedule has ``steps + 1`` points.
+ beta_mean: Mean of the CUSTOM_BETA distribution, in (0, 1).
+ beta_concentration: Concentration (alpha + beta) of CUSTOM_BETA, > 0.
+
+ Raises:
+ TypeError: For a non-int step count.
+ ValueError: For a non-positive step count or invalid beta parameters.
+ """
+
+ kind: ScheduleKind = ScheduleKind.BETA_1_25
+ steps: int = 50
+ beta_mean: float = DEFAULT_CUSTOM_BETA_MEAN
+ beta_concentration: float = DEFAULT_CUSTOM_BETA_CONCENTRATION
+
+ def __post_init__(self) -> None:
+ """Validate the step count and the custom beta parameters."""
+
+ if isinstance(self.steps, bool) or not isinstance(self.steps, int):
+ raise TypeError("TimeSchedule.steps must be an int.")
+ if self.steps < 1:
+ raise ValueError(f"TimeSchedule.steps must be >= 1, got {self.steps}.")
+ if not (math.isfinite(self.beta_mean) and 0.0 < self.beta_mean < 1.0):
+ raise ValueError(
+ f"TimeSchedule.beta_mean must lie in (0, 1), got {self.beta_mean}."
+ )
+ if not (math.isfinite(self.beta_concentration) and self.beta_concentration > 0):
+ raise ValueError(
+ "TimeSchedule.beta_concentration must be finite and > 0, got "
+ f"{self.beta_concentration}."
+ )
+
+ @property
+ def beta_parameters(self) -> tuple[float, float] | None:
+ """Return (alpha, beta) of a beta spacing, or None for LINEAR."""
+
+ match self.kind:
+ case ScheduleKind.LINEAR:
+ return None
+ case ScheduleKind.BETA_0_6:
+ return BETA_0_6_SHAPE, BETA_0_6_SHAPE
+ case ScheduleKind.BETA_1_25:
+ return BETA_1_25_SHAPE, BETA_1_25_SHAPE
+ case ScheduleKind.CUSTOM_BETA:
+ return (
+ self.beta_mean * self.beta_concentration,
+ (1.0 - self.beta_mean) * self.beta_concentration,
+ )
+ case _ as unreachable:
+ raise ValueError(f"Unsupported schedule kind: {unreachable}")
+
+
+def resolution_log_snr_shift(
+ width: int,
+ height: int,
+ *,
+ base: float = TRAINING_BASE_LOG_SNR_SHIFT,
+ reference: int = RESOLUTION_SHIFT_REFERENCE,
+) -> float:
+ """Return ``min(0, base - ln(width * height / reference^2))``.
+
+ This is the timestep shift the model was trained with at a given image
+ size (-2.99 at 832 x 1216 with the defaults).
+
+ Args:
+ width: Image width in pixels.
+ height: Image height in pixels.
+ base: Size-independent part of the shift.
+ reference: Side in pixels of the square whose area has no size term.
+
+ Raises:
+ ValueError: For a non-positive size or reference, or a non-finite base.
+ """
+
+ if width <= 0 or height <= 0 or reference <= 0:
+ raise ValueError(
+ "width, height and reference must be positive, got "
+ f"{width} x {height}, reference {reference}."
+ )
+ if not math.isfinite(base):
+ raise ValueError(f"base must be finite, got {base}.")
+ resolution_term = -math.log((width * height) / float(reference * reference))
+ return min(0.0, float(base) + resolution_term)
+
+
+def apply_log_snr_shift(timesteps: Tensor, shift: float) -> Tensor:
+ """Shift interior times by ``shift`` in log-SNR; keep exact 0 and 1.
+
+ Args:
+ timesteps: Float tensor of times in [0, 1].
+ shift: Additive log-SNR shift; |shift| <= 1e-9 returns the input.
+
+ Raises:
+ ValueError: For a non-finite shift.
+ """
+
+ if not math.isfinite(shift):
+ raise ValueError(f"log_snr_shift must be finite, got {shift}.")
+ if abs(shift) <= _SHIFT_NO_OP_TOLERANCE:
+ return timesteps
+ finfo = torch.finfo(timesteps.dtype)
+ clamped = timesteps.clamp(max(float(finfo.tiny), 1.0e-12), 1.0 - float(finfo.eps))
+ shifted = torch.sigmoid(torch.logit(clamped) - 0.5 * shift)
+ shifted = torch.where(timesteps == 0.0, torch.zeros_like(shifted), shifted)
+ return torch.where(timesteps == 1.0, torch.ones_like(shifted), shifted)
+
+
+def _beta_quantiles(points: int, *, alpha: float, beta: float) -> Tensor:
+ """Return Beta(alpha, beta) quantiles of a float32 probability grid, in float32.
+
+ Raises:
+ RuntimeError: If SciPy returns non-finite quantiles.
+ """
+
+ probabilities = torch.linspace(0.0, 1.0, points, dtype=torch.float32, device="cpu")
+ values = np.asarray(
+ stats.beta.ppf(probabilities.to(torch.float64).numpy(), alpha, beta),
+ dtype=np.float32,
+ )
+ if not bool(np.isfinite(values).all()):
+ raise RuntimeError(f"Beta({alpha}, {beta}) quantiles are not finite.")
+ return torch.from_numpy(values)
+
+
+def _ascending_base(schedule: TimeSchedule) -> Tensor:
+ """Return the unshifted ascending float32 CPU grid of ``steps + 1`` points."""
+
+ points = schedule.steps + 1
+ parameters = schedule.beta_parameters
+ if parameters is None:
+ return torch.linspace(0.0, 1.0, points, dtype=torch.float32, device="cpu")
+ alpha, beta = parameters
+ return _beta_quantiles(points, alpha=alpha, beta=beta)
+
+
+def _cap_noisy_endpoint(descending: Tensor) -> Tensor:
+ """Replace an exact ``t = 1`` first point by ``1 - 1e-4`` (or the next float
+ above its neighbour when that neighbour is already closer to 1).
+
+ Raises:
+ ValueError: If no float32 lies strictly between the neighbour and 1.
+ """
+
+ if float(descending[0]) != 1.0:
+ return descending
+ one = torch.ones((), dtype=descending.dtype, device=descending.device)
+ candidate = torch.tensor(
+ 1.0 - FINITE_NOISY_ENDPOINT_EPSILON,
+ dtype=descending.dtype,
+ device=descending.device,
+ )
+ neighbour = descending[1]
+ if float(neighbour) >= float(candidate):
+ candidate = torch.nextafter(neighbour, one)
+ if float(candidate) >= 1.0:
+ raise ValueError(
+ "No finite noisy endpoint fits between the second schedule point "
+ "and t = 1; lower the step count or the log-SNR shift magnitude."
+ )
+ capped = descending.clone()
+ capped[0] = candidate
+ return capped
+
+
+def build_timesteps(
+ schedule: TimeSchedule,
+ *,
+ log_snr_shift: float,
+ finite_noisy_endpoint: bool,
+ device: torch.device,
+) -> Tensor:
+ """Build the descending float32 schedule the solver integrates over.
+
+ Order of operations (as the training code): unshifted ascending grid,
+ moved to ``device``, log-SNR shift there, flip to descending, then, when
+ ``finite_noisy_endpoint``, replace the exact ``t = 1`` start by
+ ``1 - 1e-4``. Log-SNR solvers
+ (``solvers.solver_requires_finite_noisy_endpoint``) need that finite start.
+ The shift runs on ``device`` because CPU and CUDA ``logit``/``sigmoid`` can
+ differ in the last bit.
+
+ Args:
+ schedule: Spacing and step count.
+ log_snr_shift: Effective shift (e.g. ``resolution_log_snr_shift``).
+ finite_noisy_endpoint: Whether to cap the noisy endpoint below 1.
+ device: Device of the returned tensor.
+
+ Returns:
+ Float32 tensor ``[steps + 1]``, strictly descending, ending at 0.
+
+ Raises:
+ ValueError: For a non-finite shift or an impossible endpoint cap.
+ """
+
+ base = _ascending_base(schedule).to(device=device)
+ descending = torch.flip(apply_log_snr_shift(base, log_snr_shift), dims=(0,))
+ if finite_noisy_endpoint:
+ descending = _cap_noisy_endpoint(descending)
+ return descending.contiguous()
+
+
+@dataclass(frozen=True)
+class ScheduleCdf:
+ """CDF of a shifted schedule's time distribution: 1 at the noisy end, 0 clean.
+
+ Step ``i`` of an ``N``-step standard schedule sits at quantile ``1 - i / N``
+ before the endpoint cap; the guidance ramp is defined in this coordinate.
+ Evaluated on the host from Python floats (no device work).
+ """
+
+ schedule: TimeSchedule
+ log_snr_shift: float
+
+ def quantile_at_time(self, time: float) -> float:
+ """Return the CDF value of the unshifted distribution at a solver time."""
+
+ if time <= 0.0:
+ return 0.0
+ if time >= 1.0:
+ return 1.0
+ logit = math.log(time) - math.log1p(-time)
+ base_time = float(special.expit(logit + 0.5 * self.log_snr_shift))
+ parameters = self.schedule.beta_parameters
+ if parameters is None:
+ return base_time
+ alpha, beta = parameters
+ return float(special.betainc(alpha, beta, base_time))
diff --git a/dflow/solvers.py b/dflow/solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..aace34d1cb454ce15b59ccd18df2fad5808fefcc
--- /dev/null
+++ b/dflow/solvers.py
@@ -0,0 +1,638 @@
+"""Float32 solvers for the linear flow-matching path.
+
+Conventions (see ``schedules``): ``x_t = (1 - t) x_0 + t noise``, times run
+from the noisy end (``t`` near 1) to ``t = 0``, and the velocity callable
+returns ``v = noise - x_0`` at ``(x_t, t)``, so ``x_0 = x_t - t v`` and an Euler
+step is ``x + (t_next - t) v``. The solver state is float32.
+
+Every solver calls ``velocity(state, time, step_index)`` where ``time`` is a
+float32 ``[B]`` tensor holding ``timesteps[step_index]``: each evaluation sits
+exactly on a schedule point, and ``step_index`` is that point's index
+(``0 .. steps``; ABM2 also evaluates the last point). Guidance uses the index to
+look up its per-step plan.
+
+The schedule is read to the host once before the loop; the per-step code has
+no host synchronisation.
+"""
+
+from __future__ import annotations
+
+import itertools
+import math
+from dataclasses import dataclass
+from enum import StrEnum
+from typing import Protocol
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import Tensor
+
+from .brownian_noise import BrownianIntervalNormal, standard_normal
+
+DEFAULT_SDE_NOISE_SCALE = 1.0
+DEFAULT_DPMPP_2M_SDE_ETA = 0.5
+# Floor of t in Euler-Maruyama's velocity-to-score conversion.
+_SCORE_TIME_FLOOR = 1.0e-4
+_ER_MAX_STAGE = 3
+_ER_QUADRATURE_POINTS = 16
+_ER_NOISE_EXPONENT = 0.3
+_ER_NOISE_OFFSET = 10.0
+
+
+class Solver(StrEnum):
+ """Numerical solvers.
+
+ EULER: first-order ODE.
+ EULER_MARUYAMA: first-order reverse SDE (noise scale 1 is the SDE's own).
+ ER_SDE: third-stage extended reverse-time SDE with independent normals.
+ ER_SDE_BT: ER_SDE with Brownian-tree noise (schedule-consistent paths).
+ DPMPP_2M: second-order multistep ODE in half-log-SNR.
+ DPMPP_2M_SDE: DPM++ 2M SDE midpoint method (noise scale is eta).
+ ABM2: Adams-Bashforth-Moulton predictor-corrector (two evaluations a step).
+ """
+
+ EULER = "euler"
+ EULER_MARUYAMA = "euler_maruyama"
+ ER_SDE = "er_sde"
+ ER_SDE_BT = "er_sde_bt"
+ DPMPP_2M = "dpmpp_2m"
+ DPMPP_2M_SDE = "dpmpp_2m_sde"
+ ABM2 = "abm2"
+
+
+def default_noise_scale(solver: Solver) -> float:
+ """Return the recommended noise scale (eta for DPM++ 2M SDE) of a solver."""
+
+ match solver:
+ case Solver.DPMPP_2M_SDE:
+ return DEFAULT_DPMPP_2M_SDE_ETA
+ case (
+ Solver.EULER
+ | Solver.EULER_MARUYAMA
+ | Solver.ER_SDE
+ | Solver.ER_SDE_BT
+ | Solver.DPMPP_2M
+ | Solver.ABM2
+ ):
+ return DEFAULT_SDE_NOISE_SCALE
+ case _ as unreachable:
+ raise ValueError(f"Unsupported solver: {unreachable}")
+
+
+def solver_is_stochastic(solver: Solver) -> bool:
+ """Return whether a solver injects noise (and needs a generator)."""
+
+ match solver:
+ case (
+ Solver.EULER_MARUYAMA
+ | Solver.ER_SDE
+ | Solver.ER_SDE_BT
+ | Solver.DPMPP_2M_SDE
+ ):
+ return True
+ case Solver.EULER | Solver.DPMPP_2M | Solver.ABM2:
+ return False
+ case _ as unreachable:
+ raise ValueError(f"Unsupported solver: {unreachable}")
+
+
+def solver_requires_finite_noisy_endpoint(solver: Solver) -> bool:
+ """Return whether a solver evaluates log-SNR at the first point (needs t < 1)."""
+
+ match solver:
+ case Solver.ER_SDE | Solver.ER_SDE_BT | Solver.DPMPP_2M | Solver.DPMPP_2M_SDE:
+ return True
+ case Solver.EULER | Solver.EULER_MARUYAMA | Solver.ABM2:
+ return False
+ case _ as unreachable:
+ raise ValueError(f"Unsupported solver: {unreachable}")
+
+
+class VelocityFunction(Protocol):
+ """The velocity at one schedule point."""
+
+ def __call__(self, state: Tensor, time: Tensor, step_index: int, /) -> Tensor:
+ """Return ``v`` like ``state`` for float32 times ``[B]`` at ``step_index``."""
+
+ ...
+
+
+class SolverCallback(Protocol):
+ """Observer of each completed solver update."""
+
+ def __call__(self, predicted_x0: Tensor, completed: int, total: int, /) -> None:
+ """Receive the latest clean estimate after ``completed`` of ``total``."""
+
+ ...
+
+
+@dataclass(frozen=True)
+class _Run:
+ """Validated per-solve inputs shared by every solver loop."""
+
+ velocity: VelocityFunction
+ times: Tensor
+ host_times: tuple[float, ...]
+ callback: SolverCallback | None
+
+ @property
+ def intervals(self) -> int:
+ """Number of solver updates."""
+
+ return len(self.host_times) - 1
+
+ def time_batch(self, index: int, batch: int) -> Tensor:
+ """Return ``times[index]`` as a float32 ``[batch]`` vector."""
+
+ return self.times[index].expand(batch)
+
+ def evaluate(self, state: Tensor, index: int) -> Tensor:
+ """Evaluate the velocity at schedule point ``index``, cast like ``state``."""
+
+ time = self.time_batch(index, int(state.shape[0]))
+ return self.velocity(state, time, index).to(dtype=state.dtype)
+
+ def report(self, state: Tensor, velocity: Tensor, index: int, done: int) -> None:
+ """Send ``state - t_index v`` to the callback when one is set."""
+
+ if self.callback is not None:
+ self.callback(state - self.times[index] * velocity, done, self.intervals)
+
+
+def _validate(state: Tensor, timesteps: Tensor) -> tuple[float, ...]:
+ """Check state and schedule invariants once; return the host times.
+
+ Raises:
+ ValueError: For a non-float32 or non-4D state, or a schedule that is not
+ a strictly descending finite float32 vector in [0, 1] of length >= 2.
+ """
+
+ if state.dim() != 4 or state.dtype != torch.float32:
+ raise ValueError(
+ f"The solver state must be float32 [B, C, H, W]; got {state.dtype} "
+ f"with shape {tuple(state.shape)}."
+ )
+ if timesteps.dim() != 1 or timesteps.dtype != torch.float32:
+ raise ValueError("timesteps must be a float32 vector.")
+ if timesteps.device != state.device:
+ raise ValueError(
+ f"timesteps are on {timesteps.device} but the state is on {state.device}."
+ )
+ host = tuple(float(value) for value in timesteps.cpu().tolist())
+ if len(host) < 2 or not all(math.isfinite(value) for value in host):
+ raise ValueError("timesteps need at least two finite points.")
+ if any(value < 0.0 or value > 1.0 for value in host):
+ raise ValueError("timesteps must lie in [0, 1].")
+ if any(a <= b for a, b in itertools.pairwise(host)):
+ raise ValueError("timesteps must be strictly descending.")
+ return host
+
+
+def _require_finite_log_snr(host_times: tuple[float, ...], solver: Solver) -> None:
+ """Require evaluation times in (0, 1) for a log-SNR solver.
+
+ Raises:
+ ValueError: If a model-evaluation time is 0 or 1.
+ """
+
+ if any(value <= 0.0 or value >= 1.0 for value in host_times[:-1]):
+ raise ValueError(
+ f"{solver.value} evaluates log-SNR: every point but the last must lie "
+ "in (0, 1). Build the schedule with finite_noisy_endpoint=True."
+ )
+
+
+def _euler(run: _Run, state: Tensor) -> Tensor:
+ """First-order Euler; the step is the float32 difference of the points."""
+
+ deltas = (run.times[1:] - run.times[:-1]).cpu().tolist()
+ for index in range(run.intervals):
+ velocity = run.evaluate(state, index)
+ run.report(state, velocity, index, index + 1)
+ state = state + float(deltas[index]) * velocity
+ return state
+
+
+def _euler_maruyama(
+ run: _Run, state: Tensor, *, noise_scale: float, generator: torch.Generator
+) -> Tensor:
+ """Reverse-SDE Euler-Maruyama: drift ``v - t score``, diffusion ``2 t``.
+
+ The score is ``-((1 - t) v + x) / max(t, 1e-4)``. A final step to t = 0
+ returns ``x - t v``.
+ """
+
+ deltas = (run.times[1:] - run.times[:-1]).cpu().tolist()
+ batch = int(state.shape[0])
+ for index in range(run.intervals):
+ t0 = run.host_times[index]
+ dt = float(deltas[index])
+ time = torch.full((batch,), t0, device=state.device, dtype=torch.float32)
+ velocity = run.velocity(state, time, index).to(dtype=state.dtype)
+ run.report(state, velocity, index, index + 1)
+ if index == run.intervals - 1 and run.host_times[index + 1] == 0.0:
+ state = state - t0 * velocity
+ continue
+ noise = standard_normal(
+ tuple(state.shape), generator=generator, device=state.device
+ )
+ time_view = time.view(batch, 1, 1, 1)
+ safe_time = time_view.clamp(min=_SCORE_TIME_FLOOR)
+ score = -(((1.0 - safe_time) * velocity) + state) / safe_time
+ drift = velocity - time_view * score
+ scale = noise_scale * math.sqrt(2.0 * t0) * math.sqrt(abs(dt))
+ state = state + dt * drift + scale * noise
+ return state
+
+
+def _half_log_snr_float64(times: Tensor) -> Tensor:
+ """Return ``log((1 - t) / t)`` in float64 (t clamped above 0)."""
+
+ times64 = times.clamp(min=torch.finfo(times.dtype).tiny).to(dtype=torch.float64)
+ return torch.log1p(-times64) - torch.log(times64)
+
+
+def _require_increasing(lambdas: Tensor, host_times: tuple[float, ...]) -> None:
+ """Require half-log-SNR to rise over every step that does not end at 0.
+
+ Raises:
+ ValueError: Otherwise.
+ """
+
+ values = lambdas.cpu().tolist()
+ for index, (current, following) in enumerate(itertools.pairwise(values)):
+ if host_times[index + 1] != 0.0 and following - current <= 0.0:
+ raise ValueError("The schedule must raise half-log-SNR over every step.")
+
+
+def _dpmpp_2m_update(
+ state: Tensor,
+ denoised: Tensor,
+ previous: tuple[Tensor, Tensor] | None,
+ current_lambda: Tensor,
+ next_lambda: Tensor,
+) -> Tensor:
+ """One DPM++ 2M update; ``previous`` is (denoised, lambda) of the last step."""
+
+ step = next_lambda - current_lambda
+ if previous is None:
+ extrapolated = denoised
+ else:
+ previous_denoised, previous_lambda = previous
+ ratio = (current_lambda - previous_lambda) / step
+ extrapolated = (1.0 + 1.0 / (2.0 * ratio)) * denoised - (
+ 1.0 / (2.0 * ratio)
+ ) * previous_denoised
+ log_sigma_ratio = F.logsigmoid(-next_lambda) - F.logsigmoid(-current_lambda)
+ sigma_ratio = torch.exp(log_sigma_ratio).to(dtype=state.dtype)
+ alpha_next = torch.sigmoid(next_lambda).to(dtype=state.dtype)
+ coefficient = (alpha_next * (-torch.expm1(-step))).to(dtype=state.dtype)
+ return sigma_ratio * state + coefficient * extrapolated
+
+
+def _dpmpp_2m(run: _Run, state: Tensor) -> Tensor:
+ """DPM++ 2M in half-log-SNR; a final step to t = 0 returns ``x - t v``."""
+
+ lambdas = _half_log_snr_float64(run.times)
+ _require_increasing(lambdas, run.host_times)
+ previous: tuple[Tensor, Tensor] | None = None
+ for index in range(run.intervals):
+ velocity = run.evaluate(state, index)
+ denoised = state - run.times[index] * velocity
+ run.report(state, velocity, index, index + 1)
+ if run.host_times[index + 1] == 0.0:
+ state = denoised
+ else:
+ state = _dpmpp_2m_update(
+ state, denoised, previous, lambdas[index], lambdas[index + 1]
+ )
+ previous = (denoised, lambdas[index])
+ return state
+
+
+@dataclass(frozen=True)
+class _SdeStep:
+ """One DPM++ 2M SDE interval: times, half-log-SNR step and eta."""
+
+ current_time: Tensor
+ next_time: Tensor
+ step: Tensor
+ eta: float
+
+
+def _dpmpp_2m_sde_update(
+ state: Tensor,
+ denoised: Tensor,
+ previous: tuple[Tensor, Tensor] | None,
+ interval: _SdeStep,
+ generator: torch.Generator,
+) -> Tensor:
+ """One DPM++ 2M SDE midpoint update; ``previous`` is (denoised, step)."""
+
+ eta = interval.eta
+ stochastic_step = interval.step * (1.0 + eta)
+ sigma_ratio = (interval.next_time / interval.current_time) * torch.exp(
+ -interval.step * eta
+ )
+ coefficient = (1.0 - interval.next_time) * (-torch.expm1(-stochastic_step))
+ result = sigma_ratio.to(state.dtype) * state
+ result = result + coefficient.to(state.dtype) * denoised
+ if previous is not None:
+ previous_denoised, previous_step = previous
+ ratio = previous_step / interval.step
+ result = result + (
+ 0.5
+ * coefficient.to(state.dtype)
+ / ratio.to(state.dtype)
+ * (denoised - previous_denoised)
+ )
+ if eta == 0.0:
+ return result
+ normal = standard_normal(
+ tuple(state.shape), generator=generator, device=state.device
+ )
+ noise_scale = interval.next_time * torch.sqrt(
+ -torch.expm1(-2.0 * interval.step * eta)
+ )
+ return result + noise_scale.to(state.dtype) * normal
+
+
+def _dpmpp_2m_sde(
+ run: _Run, state: Tensor, *, eta: float, generator: torch.Generator
+) -> Tensor:
+ """DPM++ 2M SDE (eta 0 is the deterministic midpoint method)."""
+
+ lambdas = _half_log_snr_float64(run.times)
+ _require_increasing(lambdas, run.host_times)
+ previous_denoised: Tensor | None = None
+ previous_step: Tensor | None = None
+ for index in range(run.intervals):
+ velocity = run.evaluate(state, index)
+ denoised = state - run.times[index] * velocity
+ run.report(state, velocity, index, index + 1)
+ if run.host_times[index + 1] == 0.0:
+ state = denoised
+ else:
+ step = lambdas[index + 1] - lambdas[index]
+ previous = (
+ None
+ if previous_denoised is None or previous_step is None
+ else (previous_denoised, previous_step)
+ )
+ interval = _SdeStep(run.times[index], run.times[index + 1], step, eta)
+ state = _dpmpp_2m_sde_update(state, denoised, previous, interval, generator)
+ previous_step = step
+ previous_denoised = denoised
+ return state
+
+
+def _er_noise_scaler(er_lambda: Tensor) -> Tensor:
+ """ER-SDE noise-scaling function ``l (exp(l^0.3) + 10)``."""
+
+ return er_lambda * (torch.exp(er_lambda.pow(_ER_NOISE_EXPONENT)) + _ER_NOISE_OFFSET)
+
+
+def _er_stochastic_time(er_lambda: Tensor) -> Tensor:
+ """ER Brownian clock ``1 / (exp(l^0.3) + 10)^2``."""
+
+ denominator = torch.exp(er_lambda.pow(_ER_NOISE_EXPONENT)) + _ER_NOISE_OFFSET
+ return denominator.square().reciprocal()
+
+
+@dataclass(frozen=True)
+class _ErSdeContext:
+ """Per-solve ER-SDE constants: lambdas, quadrature rule and noise source."""
+
+ times: Tensor
+ er_lambdas: Tensor
+ nodes: Tensor
+ weights: Tensor
+ noise_scale: float
+ generator: torch.Generator
+ tree: BrownianIntervalNormal | None
+ # Host Brownian-clock time per point (read once; BT only).
+ clock: tuple[float, ...]
+
+
+def _er_context(
+ run: _Run,
+ state: Tensor,
+ *,
+ noise_scale: float,
+ generator: torch.Generator,
+ brownian: bool,
+) -> _ErSdeContext:
+ """Prepare ER-SDE constants (and the Brownian tree) before the loop."""
+
+ times = run.times
+ half_log_snr = torch.log1p(-times) - torch.log(times)
+ er_lambdas = torch.exp(-half_log_snr)
+ nodes_np, weights_np = np.polynomial.legendre.leggauss(_ER_QUADRATURE_POINTS)
+ nodes = torch.as_tensor(nodes_np, device=times.device, dtype=torch.float32)
+ weights = torch.as_tensor(weights_np, device=times.device, dtype=torch.float32)
+ tree: BrownianIntervalNormal | None = None
+ clock: tuple[float, ...] = ()
+ if brownian and noise_scale > 0.0:
+ tree = BrownianIntervalNormal(
+ state=state,
+ start=0.0,
+ end=1.0 / (1.0 + _ER_NOISE_OFFSET) ** 2,
+ generator=generator,
+ )
+ clock = tuple(
+ float(_er_stochastic_time(er_lambdas[index]).item())
+ for index in range(len(run.host_times))
+ )
+ return _ErSdeContext(
+ times, er_lambdas, nodes, weights, noise_scale, generator, tree, clock
+ )
+
+
+def _er_quadrature(
+ context: _ErSdeContext, lambda_s: Tensor, lambda_t: Tensor
+) -> tuple[Tensor, Tensor]:
+ """Gauss-Legendre ER-SDE correction integrals over one interval."""
+
+ midpoint = (lambda_s + lambda_t) / 2.0
+ half_span = (lambda_s - lambda_t) / 2.0
+ positions = midpoint + half_span * context.nodes
+ scaled = _er_noise_scaler(positions)
+ second = half_span * torch.sum(context.weights / scaled)
+ third = half_span * torch.sum(context.weights * (positions - lambda_s) / scaled)
+ return second, third
+
+
+@dataclass(frozen=True)
+class _ErHistory:
+ """Clean estimate and its first divided difference from the last step."""
+
+ denoised: Tensor
+ derivative: Tensor | None
+
+
+def _er_sde_step(
+ context: _ErSdeContext,
+ state: Tensor,
+ denoised: Tensor,
+ history: _ErHistory | None,
+ index: int,
+) -> tuple[Tensor, Tensor | None]:
+ """One non-terminal ER-SDE update; returns the state and the derivative."""
+
+ lambdas = context.er_lambdas
+ lambda_s, lambda_t = lambdas[index], lambdas[index + 1]
+ alpha_s = context.times[index] / lambda_s
+ alpha_t = context.times[index + 1] / lambda_t
+ noise_t = _er_noise_scaler(lambda_t)
+ ratio = noise_t / _er_noise_scaler(lambda_s)
+ next_state = (alpha_t / alpha_s) * ratio * state
+ next_state = next_state + alpha_t * (1.0 - ratio) * denoised
+ derivative: Tensor | None = None
+ stage = min(_ER_MAX_STAGE, index + 1)
+ if stage >= 2 and history is not None:
+ second, third = _er_quadrature(context, lambda_s, lambda_t)
+ delta = lambda_t - lambda_s
+ derivative = (denoised - history.denoised) / (lambda_s - lambdas[index - 1])
+ next_state = next_state + alpha_t * (delta + second * noise_t) * derivative
+ if stage >= 3 and history.derivative is not None:
+ span = (lambda_s - lambdas[index - 2]) / 2.0
+ second_derivative = (derivative - history.derivative) / span
+ next_state = (
+ next_state
+ + alpha_t * (delta.square() / 2.0 + third * noise_t) * second_derivative
+ )
+ if context.noise_scale > 0.0:
+ if context.tree is None:
+ noise = standard_normal(
+ tuple(state.shape), generator=context.generator, device=state.device
+ )
+ else:
+ noise = context.tree.sample(
+ state=state,
+ start=context.clock[index],
+ end=context.clock[index + 1],
+ )
+ variance = lambda_t.square() - lambda_s.square() * ratio.square()
+ stochastic = alpha_t * torch.sqrt(torch.clamp(variance, min=0.0))
+ next_state = next_state + context.noise_scale * stochastic * noise
+ return next_state.to(dtype=state.dtype), derivative
+
+
+def _er_sde(run: _Run, state: Tensor, context: _ErSdeContext) -> Tensor:
+ """Third-stage VP ER-SDE; a final step to t = 0 returns ``x - t v``."""
+
+ history: _ErHistory | None = None
+ for index in range(run.intervals):
+ velocity = run.evaluate(state, index)
+ denoised = state - run.times[index] * velocity
+ run.report(state, velocity, index, index + 1)
+ derivative: Tensor | None = None
+ if run.host_times[index + 1] == 0.0:
+ state = denoised
+ else:
+ state, derivative = _er_sde_step(context, state, denoised, history, index)
+ history = _ErHistory(denoised, derivative)
+ return state
+
+
+def _abm2(run: _Run, state: Tensor) -> Tensor:
+ """ABM2: Euler bootstrap, then AB2 predictor and trapezoidal corrector,
+ re-evaluating the velocity at the corrected state."""
+
+ times = run.times
+ previous_velocity = run.evaluate(state, 0)
+ state = state + (times[1] - times[0]) * previous_velocity
+ current_velocity = run.evaluate(state, 1)
+ run.report(state, current_velocity, 1, 1)
+ for index in range(1, run.intervals):
+ previous_step = times[index] - times[index - 1]
+ current_step = times[index + 1] - times[index]
+ ratio = current_step / previous_step
+ predicted = state + current_step * (
+ (1.0 + 0.5 * ratio) * current_velocity + (-0.5 * ratio) * previous_velocity
+ )
+ predicted_velocity = run.evaluate(predicted, index + 1)
+ state = state + 0.5 * current_step * (current_velocity + predicted_velocity)
+ previous_velocity = current_velocity
+ current_velocity = run.evaluate(state, index + 1)
+ run.report(state, current_velocity, index + 1, index + 1)
+ return state
+
+
+def _validate_noise(solver: Solver, noise_scale: float, generator: object) -> None:
+ """Check the noise scale, and that stochastic solvers have a generator.
+
+ Raises:
+ ValueError: For a negative or non-finite scale, or a missing generator.
+ """
+
+ if not math.isfinite(noise_scale) or noise_scale < 0.0:
+ raise ValueError(f"noise_scale must be finite and >= 0, got {noise_scale}.")
+ if solver_is_stochastic(solver) and generator is None:
+ raise ValueError(f"{solver.value} injects noise: pass a torch.Generator.")
+
+
+def solve(
+ velocity: VelocityFunction,
+ initial_state: Tensor,
+ timesteps: Tensor,
+ *,
+ solver: Solver,
+ noise_scale: float,
+ generator: torch.Generator | None,
+ callback: SolverCallback | None = None,
+) -> Tensor:
+ """Integrate from ``timesteps[0]`` to ``timesteps[-1]``.
+
+ Args:
+ velocity: ``(state, time [B], step_index) -> v``; see the module docstring.
+ initial_state: Float32 ``[B, C, H, W]`` state at ``timesteps[0]``.
+ timesteps: Descending float32 schedule on the state's device
+ (``schedules.build_timesteps``; log-SNR solvers need a first point
+ below 1).
+ solver: Numerical method.
+ noise_scale: SDE noise multiplier (eta for DPM++ 2M SDE); deterministic
+ solvers ignore it.
+ generator: Source of the injected noise (a CPU generator gives the same
+ noise on every GPU); required by stochastic solvers.
+ callback: Receives ``x_t - t v`` of each evaluated point after each update.
+
+ Returns:
+ The float32 state at ``timesteps[-1]``.
+
+ Raises:
+ ValueError: For an invalid state, schedule, noise scale or generator.
+ """
+
+ host_times = _validate(initial_state, timesteps)
+ _validate_noise(solver, noise_scale, generator)
+ if solver_requires_finite_noisy_endpoint(solver):
+ _require_finite_log_snr(host_times, solver)
+ run = _Run(velocity, timesteps, host_times, callback)
+ match solver, generator:
+ case Solver.EULER, _:
+ return _euler(run, initial_state)
+ case Solver.EULER_MARUYAMA, torch.Generator() as noise:
+ return _euler_maruyama(
+ run, initial_state, noise_scale=noise_scale, generator=noise
+ )
+ case (
+ Solver.ER_SDE | Solver.ER_SDE_BT
+ ) as er_solver, torch.Generator() as noise:
+ context = _er_context(
+ run,
+ initial_state,
+ noise_scale=noise_scale,
+ generator=noise,
+ brownian=er_solver is Solver.ER_SDE_BT,
+ )
+ return _er_sde(run, initial_state, context)
+ case Solver.DPMPP_2M, _:
+ return _dpmpp_2m(run, initial_state)
+ case Solver.DPMPP_2M_SDE, torch.Generator() as noise:
+ return _dpmpp_2m_sde(run, initial_state, eta=noise_scale, generator=noise)
+ case Solver.ABM2, _:
+ return _abm2(run, initial_state)
+ case _ as unreachable:
+ raise ValueError(f"Unsupported solver call: {unreachable}")
diff --git a/dflow/text_conditioning.py b/dflow/text_conditioning.py
new file mode 100644
index 0000000000000000000000000000000000000000..a070c28beb3cde07f6e17e693f2974abcd00049c
--- /dev/null
+++ b/dflow/text_conditioning.py
@@ -0,0 +1,395 @@
+"""Prompts to ``TextConditioning``: tokenize, encode, standardize, project.
+
+For a prompt the model receives ``L + 3`` tokens of width 2304:
+
+1. the T5Gemma2 hidden states after layers 2, 6 and 12 (``text_encoder``),
+ each standardized per channel with fixed statistics (FP32);
+2. three linear maps 640 -> 2304, one per tap, summed in FP32;
+3. three learned suffix tokens appended.
+
+A blank prompt (empty or whitespace only) is the learned unconditional
+sequence: the unconditional token followed by the same three suffix tokens.
+This is the null text used for CFG and for an empty negative prompt.
+
+Batching rule: the denoiser runs each batch as one dense attention forward
+without padding, so every prompt of a batch must have the same token count.
+``DFlowTextEncoder.encode`` raises on unequal counts;
+``DFlowTextEncoder.encode_grouped`` splits a list into equal-length groups.
+A prompt repeated over a batch always qualifies.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+from .layout import is_compiled_layout, is_stored_layout
+from .prompt_emphasis import (
+ EmphasisSettings,
+ TokenEmphasis,
+ parse_prompt_weights,
+ token_emphasis,
+)
+from .text_encoder import (
+ COMPUTE_DTYPE,
+ ENCODER_CONFIG,
+ EncoderTaps,
+ EncoderWeighting,
+ T5Gemma2Encoder,
+)
+from .tokenization import PromptTokenizer
+from .types import SUFFIX_TOKEN_COUNT, TextConditioning
+
+__all__ = [
+ "SUFFIX_TOKEN_COUNT",
+ "TEXT_ADAPTER_KEY_MAP",
+ "TEXT_ADAPTER_REQUIRED_FLAGS",
+ "TEXT_WIDTH",
+ "DFlowTextEncoder",
+ "TextAdapter",
+ "TextConditioningGroup",
+]
+
+TEXT_WIDTH = 2304
+_TAP_COUNT = 3
+
+# Training checkpoint key -> key relative to ``TextAdapter`` (the public file adds
+# the prefix ``text_adapter.``).
+TEXT_ADAPTER_KEY_MAP: dict[str, str] = {
+ "conditioning._encoder._proj_lo.weight": "proj_lo.weight",
+ "conditioning._encoder._proj_mid.weight": "proj_mid.weight",
+ "conditioning._encoder._proj_hi.weight": "proj_hi.weight",
+ "conditioning._encoder._tap_statistics.mean": "tap_mean",
+ "conditioning._encoder._tap_statistics.std": "tap_std",
+ "conditioning.uncond_token": "uncond_token",
+ "conditioning.learned_padding_tokens": "suffix_tokens",
+}
+# Training checkpoint keys that are not published: each must hold this value.
+TEXT_ADAPTER_REQUIRED_FLAGS: dict[str, bool] = {
+ "conditioning._encoder._tap_statistics.calibrated": True,
+}
+
+
+class TextAdapter(nn.Module):
+ """Tap standardization, the three projections and the learned tokens.
+
+ Projection weights are bf16 (as published); statistics and learned tokens
+ stay FP32 across ``.to(dtype)`` moves.
+ """
+
+ tap_mean: Tensor
+ tap_std: Tensor
+ uncond_token: Tensor
+ suffix_tokens: Tensor
+
+ def __init__(self) -> None:
+ super().__init__()
+ hidden = ENCODER_CONFIG.hidden_size
+ self.proj_lo = nn.Linear(hidden, TEXT_WIDTH, bias=False, dtype=COMPUTE_DTYPE)
+ self.proj_mid = nn.Linear(hidden, TEXT_WIDTH, bias=False, dtype=COMPUTE_DTYPE)
+ self.proj_hi = nn.Linear(hidden, TEXT_WIDTH, bias=False, dtype=COMPUTE_DTYPE)
+ self.register_buffer("tap_mean", torch.zeros(_TAP_COUNT, hidden))
+ self.register_buffer("tap_std", torch.ones(_TAP_COUNT, hidden))
+ self.register_buffer("uncond_token", torch.zeros(1, TEXT_WIDTH))
+ self.register_buffer(
+ "suffix_tokens", torch.zeros(SUFFIX_TOKEN_COUNT, TEXT_WIDTH)
+ )
+
+ def _apply(self, fn: Callable[[Tensor], Tensor], recurse: bool = True) -> nn.Module:
+ """Apply device moves without rounding the FP32 tensors."""
+
+ kept = {
+ name: tensor.detach().float()
+ for name, tensor in self.named_buffers(recurse=False)
+ }
+ super()._apply(fn, recurse=recurse)
+ for name, tensor in self.named_buffers(recurse=False):
+ tensor.data = kept[name].to(device=tensor.device)
+ return self
+
+ def project(self, taps: EncoderTaps) -> Tensor:
+ """Return the summed projections ``[B, L, 2304]`` FP32 of three taps.
+
+ Each tap is standardized per channel in FP32; each projection runs
+ under bf16 autocast and is summed in FP32.
+ """
+
+ total: Tensor | None = None
+ projections = (self.proj_lo, self.proj_mid, self.proj_hi)
+ tap_values = (taps.low, taps.middle, taps.high)
+ device = taps.low.device
+ with torch.autocast(device_type=device.type, dtype=COMPUTE_DTYPE):
+ for slot, (projection, tap) in enumerate(
+ zip(projections, tap_values, strict=True)
+ ):
+ normalized = (tap.float() - self.tap_mean[slot]) / self.tap_std[slot]
+ projected = F.linear(normalized, projection.weight).float()
+ total = projected if total is None else total + projected
+ if total is None:
+ raise RuntimeError("TextAdapter has no projections.")
+ return total
+
+ def conditioning_tokens(self, taps: EncoderTaps) -> Tensor:
+ """Return ``[B, L + 3, 2304]`` FP32: projected taps, then the suffix."""
+
+ projected = self.project(taps)
+ suffix = self.suffix_tokens.float().expand(projected.shape[0], -1, -1)
+ return torch.cat((projected, suffix), dim=1)
+
+ def unconditional_tokens(self, batch: int) -> Tensor:
+ """Return the null text ``[batch, 4, 2304]`` FP32: unconditional token,
+ then the suffix."""
+
+ sequence = torch.cat((self.uncond_token, self.suffix_tokens), dim=0).float()
+ return sequence.unsqueeze(0).expand(batch, -1, -1).contiguous()
+
+
+@dataclass(frozen=True)
+class _PreparedPrompt:
+ """One prompt ready to encode.
+
+ Attributes:
+ ids: Token ids, or None for the null text.
+ emphasis: Per-token emphasis over ``ids``, or None.
+ """
+
+ ids: tuple[int, ...] | None
+ emphasis: TokenEmphasis | None
+
+ @property
+ def length(self) -> int:
+ """Return the conditioning token count (suffix included)."""
+
+ if self.ids is None:
+ return 1 + SUFFIX_TOKEN_COUNT
+ return len(self.ids) + SUFFIX_TOKEN_COUNT
+
+
+@dataclass(frozen=True)
+class TextConditioningGroup:
+ """Prompts of equal token count and their conditioning.
+
+ Attributes:
+ indices: Positions of the group's prompts in the input list.
+ conditioning: Their conditioning, rows in ``indices`` order.
+ """
+
+ indices: tuple[int, ...]
+ conditioning: TextConditioning
+
+
+class DFlowTextEncoder(nn.Module):
+ """Prompts to ``TextConditioning`` with the bundled T5Gemma2 encoder.
+
+ Args:
+ tokenizer: The prompt tokenizer.
+ encoder: The 12-layer T5Gemma2 encoder.
+ adapter: The trained tap projections and learned tokens.
+ """
+
+ def __init__(
+ self,
+ *,
+ tokenizer: PromptTokenizer,
+ encoder: T5Gemma2Encoder,
+ adapter: TextAdapter,
+ ) -> None:
+ super().__init__()
+ self.tokenizer = tokenizer
+ self.encoder = encoder
+ self.adapter = adapter
+
+ @classmethod
+ def from_directory(
+ cls, directory: str | Path, *, adapter: TextAdapter, device: torch.device
+ ) -> DFlowTextEncoder:
+ """Load the tokenizer and encoder of a ``text_encoder/`` folder.
+
+ Args:
+ directory: The bundled ``text_encoder/`` folder.
+ adapter: The loaded ``text_adapter`` of the model weights.
+ device: Execution device.
+ """
+
+ return cls(
+ tokenizer=PromptTokenizer.from_directory(directory),
+ encoder=T5Gemma2Encoder.from_directory(directory, device=device),
+ adapter=adapter.to(device=device),
+ )
+
+ def compile_layers(self) -> None:
+ """Compile the encoder layers (``T5Gemma2Encoder.compile_layers``)."""
+
+ self.encoder.compile_layers()
+
+ def _prepare(
+ self, prompt: str, emphasis: EmphasisSettings | None
+ ) -> _PreparedPrompt:
+ """Tokenize one prompt and map its emphasis onto the tokens.
+
+ Raises:
+ ValueError: For a stored (uncompiled) layout.
+ PromptTooLongError: If the prompt is too long.
+ """
+
+ if not prompt.strip():
+ return _PreparedPrompt(ids=None, emphasis=None)
+ if is_compiled_layout(prompt):
+ if is_stored_layout(prompt):
+ raise ValueError(
+ "This is a stored layout; compile it at the image size first "
+ "with dflow.layout.compile_layout(layout, width, height)."
+ )
+ return _PreparedPrompt(
+ ids=self.tokenizer.tokenize(prompt).ids, emphasis=None
+ )
+ if emphasis is None:
+ return _PreparedPrompt(
+ ids=self.tokenizer.tokenize(prompt).ids, emphasis=None
+ )
+ parsed = parse_prompt_weights(prompt)
+ tokenized = self.tokenizer.tokenize(parsed.clean_text)
+ return _PreparedPrompt(
+ ids=tokenized.ids,
+ emphasis=token_emphasis(parsed, tokenized.offsets, emphasis),
+ )
+
+ def encode(
+ self, prompts: Sequence[str], *, emphasis: EmphasisSettings | None
+ ) -> TextConditioning:
+ """Encode prompts of equal token count as one batch.
+
+ Args:
+ prompts: Prompts in batch order: plain text, compiled layout JSON,
+ or blank for the null text.
+ emphasis: Settings to parse and apply ``(phrase:weight)`` markup
+ in plain prompts, or None to encode them verbatim.
+
+ Raises:
+ ValueError: If the prompts have different token counts (use
+ ``encode_grouped``), the list is empty or a prompt is invalid.
+ PromptTooLongError: If a prompt is too long.
+ """
+
+ if not prompts:
+ raise ValueError("At least one prompt is required.")
+ prepared = [self._prepare(prompt, emphasis) for prompt in prompts]
+ lengths = sorted({row.length for row in prepared})
+ if len(lengths) != 1:
+ raise ValueError(
+ "Prompts of one batch must have the same token count; got "
+ f"{[row.length for row in prepared]}. Use encode_grouped."
+ )
+ return self._encode_prepared(prepared, emphasis=emphasis)
+
+ def encode_grouped(
+ self, prompts: Sequence[str], *, emphasis: EmphasisSettings | None
+ ) -> list[TextConditioningGroup]:
+ """Encode prompts in groups of equal token count (first-seen order).
+
+ Raises:
+ ValueError: If the list is empty or a prompt is invalid.
+ PromptTooLongError: If a prompt is too long.
+ """
+
+ if not prompts:
+ raise ValueError("At least one prompt is required.")
+ prepared = [self._prepare(prompt, emphasis) for prompt in prompts]
+ groups: dict[int, list[int]] = {}
+ for index, row in enumerate(prepared):
+ groups.setdefault(row.length, []).append(index)
+ return [
+ TextConditioningGroup(
+ indices=tuple(indices),
+ conditioning=self._encode_prepared(
+ [prepared[index] for index in indices], emphasis=emphasis
+ ),
+ )
+ for indices in groups.values()
+ ]
+
+ def _device(self) -> torch.device:
+ """Return the adapter's device."""
+
+ return self.adapter.uncond_token.device
+
+ @torch.no_grad()
+ def _encode_prepared(
+ self, prepared: Sequence[_PreparedPrompt], *, emphasis: EmphasisSettings | None
+ ) -> TextConditioning:
+ """Encode equal-length prepared prompts."""
+
+ device = self._device()
+ length = prepared[0].length
+ tokens = torch.empty(
+ (len(prepared), length, TEXT_WIDTH), device=device, dtype=torch.float32
+ )
+ null_rows = [pos for pos, row in enumerate(prepared) if row.ids is None]
+ text_rows = [pos for pos, row in enumerate(prepared) if row.ids is not None]
+ if null_rows:
+ tokens[null_rows] = self.adapter.unconditional_tokens(len(null_rows))
+ if text_rows:
+ rows = [prepared[pos] for pos in text_rows]
+ tokens[text_rows] = self._encode_text(rows, emphasis=emphasis)
+ key_bias, value_scale = _emphasis_tensors(prepared, device=device)
+ return TextConditioning(
+ tokens=tokens, key_bias=key_bias, value_scale=value_scale
+ )
+
+ def _encode_text(
+ self, rows: Sequence[_PreparedPrompt], *, emphasis: EmphasisSettings | None
+ ) -> Tensor:
+ """Run the encoder and adapter on text rows of equal length."""
+
+ device = self._device()
+ ids = torch.tensor(
+ [row.ids for row in rows if row.ids is not None],
+ dtype=torch.int64,
+ device=device,
+ )
+ weighting = None
+ if emphasis is not None and emphasis.encoder:
+ key_bias, value_scale = _emphasis_tensors(rows, device=device, suffix=False)
+ if key_bias is not None or value_scale is not None:
+ weighting = EncoderWeighting(key_bias=key_bias, value_scale=value_scale)
+ return self.adapter.conditioning_tokens(self.encoder(ids, weighting=weighting))
+
+
+def _emphasis_tensors(
+ rows: Sequence[_PreparedPrompt], *, device: torch.device, suffix: bool = True
+) -> tuple[Tensor | None, Tensor | None]:
+ """Return FP32 ``[B, L]`` key bias and value scale, each None if neutral.
+
+ ``suffix`` appends the neutral suffix positions (conditioning tokens);
+ without it the rows cover the encoder tokens only.
+ """
+
+ if all(row.emphasis is None for row in rows):
+ return None, None
+ extra = SUFFIX_TOKEN_COUNT if suffix else 0
+ biases: list[list[float]] = []
+ scales: list[list[float]] = []
+ for row in rows:
+ width = row.length - SUFFIX_TOKEN_COUNT + extra
+ match row.emphasis:
+ case TokenEmphasis() as weights:
+ biases.append([*weights.key_bias, *([0.0] * extra)])
+ scales.append([*weights.value_scale, *([1.0] * extra)])
+ case None:
+ biases.append([0.0] * width)
+ scales.append([1.0] * width)
+ has_bias = any(
+ row.emphasis is not None and row.emphasis.has_key_bias() for row in rows
+ )
+ has_scale = any(
+ row.emphasis is not None and row.emphasis.has_value_scale() for row in rows
+ )
+ return (
+ torch.tensor(biases, dtype=torch.float32, device=device) if has_bias else None,
+ torch.tensor(scales, dtype=torch.float32, device=device) if has_scale else None,
+ )
diff --git a/dflow/text_encoder.py b/dflow/text_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..653e497c89046b57a7ad57f27abd8b04a0da72cf
--- /dev/null
+++ b/dflow/text_encoder.py
@@ -0,0 +1,627 @@
+"""Dense T5Gemma2-270M text encoder, layers 1-12, with three hidden-state taps.
+
+The bundled ``text_encoder/`` folder holds the tokenizer and the used subset
+of Google's ``t5gemma-2-270m-270m`` encoder: the token embeddings and the first
+12 layers (the model reads hidden states after layers 2, 6 and 12, so later
+layers never run). Each layer is a Gemma 3 block with bidirectional attention:
+
+- embeddings scaled by ``sqrt(640)``; the end-of-image id uses its own vector;
+- Gemma RMSNorm ``x * rsqrt(mean(x^2) + eps) * (1 + w)`` in FP32, four per layer
+ (before and after attention and the MLP);
+- 4 query heads and 1 key/value head of width 256, per-head RMSNorm on queries
+ and keys, then RoPE; logits scaled by ``256 ** -0.5``;
+- sliding layers see keys within ``-256 <= key - query <= 255`` positions
+ (window 512); layers 6 and 12 see every token; each kind has its own RoPE;
+- GeGLU MLP (tanh GELU), width 2048.
+
+Precision: the residual stream stays FP32 (Gemma has massive-activation
+channels); matrix multiplies and attention run under CUDA bf16 autocast; the
+taps are FP32.
+
+Prompt emphasis may add a per-key logit bias and a per-token value scale in
+every layer's attention; both are explicit tensor inputs.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from enum import StrEnum
+from pathlib import Path
+
+import torch
+import torch.nn.functional as F
+from safetensors.torch import load_file
+from torch import Tensor, nn
+
+__all__ = [
+ "COMPUTE_DTYPE",
+ "ENCODER_CONFIG",
+ "EncoderTaps",
+ "EncoderWeighting",
+ "LayerKind",
+ "T5Gemma2Encoder",
+ "T5Gemma2EncoderConfig",
+]
+
+# Matrix-multiply and attention dtype (autocast); the residual stream is FP32.
+COMPUTE_DTYPE = torch.bfloat16
+CONFIG_FILENAME = "config.json"
+WEIGHTS_FILENAME = "model.safetensors"
+# Stored dtype of every bundled tensor (the source checkpoint's dtype).
+STORAGE_DTYPE = torch.bfloat16
+
+
+class LayerKind(StrEnum):
+ """Attention span of one encoder layer."""
+
+ SLIDING = "sliding_attention"
+ FULL = "full_attention"
+
+
+class RopeType(StrEnum):
+ """RoPE frequency schedules of the two layer kinds."""
+
+ DEFAULT = "default"
+ LINEAR = "linear"
+
+
+@dataclass(frozen=True)
+class RopeSettings:
+ """RoPE frequencies of one layer kind.
+
+ Attributes:
+ theta: Base period.
+ rope_type: ``DEFAULT``, or ``LINEAR`` (frequencies divided by ``factor``).
+ factor: Linear scaling factor (1 for ``DEFAULT``).
+ """
+
+ theta: float
+ rope_type: RopeType
+ factor: float
+
+
+@dataclass(frozen=True)
+class T5Gemma2EncoderConfig:
+ """Architecture of the bundled encoder subset (``text_encoder/config.json``)."""
+
+ vocab_size: int
+ hidden_size: int
+ intermediate_size: int
+ num_attention_heads: int
+ num_key_value_heads: int
+ head_dim: int
+ query_pre_attn_scalar: float
+ rms_norm_eps: float
+ sliding_window: int
+ layer_types: tuple[LayerKind, ...]
+ sliding_rope: RopeSettings
+ full_rope: RopeSettings
+ embed_scale: float
+ eoi_token_index: int
+ tap_layers: tuple[int, int, int]
+
+ @property
+ def num_layers(self) -> int:
+ """Return the number of bundled layers."""
+
+ return len(self.layer_types)
+
+ def rope(self, kind: LayerKind) -> RopeSettings:
+ """Return the RoPE settings of ``kind``."""
+
+ match kind:
+ case LayerKind.SLIDING:
+ return self.sliding_rope
+ case LayerKind.FULL:
+ return self.full_rope
+ case _ as unreachable:
+ raise ValueError(f"Unsupported layer kind: {unreachable}")
+
+ def to_json_dict(self) -> dict[str, object]:
+ """Return the JSON form written to ``text_encoder/config.json``."""
+
+ def rope(settings: RopeSettings) -> dict[str, object]:
+ return {
+ "theta": settings.theta,
+ "rope_type": settings.rope_type.value,
+ "factor": settings.factor,
+ }
+
+ return {
+ "vocab_size": self.vocab_size,
+ "hidden_size": self.hidden_size,
+ "intermediate_size": self.intermediate_size,
+ "num_attention_heads": self.num_attention_heads,
+ "num_key_value_heads": self.num_key_value_heads,
+ "head_dim": self.head_dim,
+ "query_pre_attn_scalar": self.query_pre_attn_scalar,
+ "rms_norm_eps": self.rms_norm_eps,
+ "sliding_window": self.sliding_window,
+ "layer_types": [kind.value for kind in self.layer_types],
+ "sliding_rope": rope(self.sliding_rope),
+ "full_rope": rope(self.full_rope),
+ "embed_scale": self.embed_scale,
+ "eoi_token_index": self.eoi_token_index,
+ "tap_layers": list(self.tap_layers),
+ }
+
+
+# The used subset of google/t5gemma-2-270m-270m: embeddings and layers 1-12.
+ENCODER_CONFIG = T5Gemma2EncoderConfig(
+ vocab_size=262_144,
+ hidden_size=640,
+ intermediate_size=2048,
+ num_attention_heads=4,
+ num_key_value_heads=1,
+ head_dim=256,
+ query_pre_attn_scalar=256.0,
+ rms_norm_eps=1e-6,
+ sliding_window=512,
+ layer_types=(
+ *(LayerKind.SLIDING,) * 5,
+ LayerKind.FULL,
+ *(LayerKind.SLIDING,) * 5,
+ LayerKind.FULL,
+ ),
+ sliding_rope=RopeSettings(theta=10_000.0, rope_type=RopeType.DEFAULT, factor=1.0),
+ full_rope=RopeSettings(theta=1_000_000.0, rope_type=RopeType.LINEAR, factor=8.0),
+ embed_scale=640**0.5,
+ eoi_token_index=256_000,
+ tap_layers=(2, 6, 12),
+)
+
+
+def _check_config_file(path: Path) -> None:
+ """Raise unless ``path`` holds exactly ``ENCODER_CONFIG`` (plus provenance).
+
+ Raises:
+ ValueError: On any architecture mismatch.
+ """
+
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(raw, dict):
+ raise ValueError(f"{path} must hold a JSON object.")
+ expected = ENCODER_CONFIG.to_json_dict()
+ mismatched = [key for key, value in expected.items() if raw.get(key) != value]
+ if mismatched:
+ raise ValueError(
+ f"{path} does not describe the bundled T5Gemma2 encoder subset; "
+ f"mismatched keys: {mismatched}."
+ )
+
+
+def _rope_inv_freq(settings: RopeSettings, head_dim: int) -> Tensor:
+ """Return FP32 RoPE inverse frequencies ``[head_dim // 2]``, computed on the
+ CPU (as the reference) so every device sees the same values."""
+
+ exponents = torch.arange(0, head_dim, 2, dtype=torch.int64, device="cpu").to(
+ torch.float32
+ )
+ inv_freq = 1.0 / (settings.theta ** (exponents / float(head_dim)))
+ match settings.rope_type:
+ case RopeType.DEFAULT:
+ return inv_freq
+ case RopeType.LINEAR:
+ return inv_freq / settings.factor
+ case _ as unreachable:
+ raise ValueError(f"Unsupported RoPE type: {unreachable}")
+
+
+def _rotate_half(values: Tensor) -> Tensor:
+ """Half-split rotary permutation ``[-x2, x1]``."""
+
+ half = values.shape[-1] // 2
+ return torch.cat((-values[..., half:], values[..., :half]), dim=-1)
+
+
+class _Float32Module(nn.Module):
+ """A module whose listed tensors stay FP32 across ``.to(dtype)`` moves."""
+
+ _fp32_names: tuple[str, ...] = ()
+
+ def _apply(self, fn: Callable[[Tensor], Tensor], recurse: bool = True) -> nn.Module:
+ """Apply device moves without rounding the FP32 tensors."""
+
+ kept = {
+ name: tensor.detach().to(dtype=torch.float32)
+ for name, tensor in self._named_fp32()
+ }
+ super()._apply(fn, recurse=recurse)
+ for name, tensor in self._named_fp32():
+ tensor.data = kept[name].to(device=tensor.device)
+ return self
+
+ def _named_fp32(self) -> list[tuple[str, Tensor]]:
+ """Return the FP32 tensors by name."""
+
+ named: dict[str, Tensor] = dict(self.named_parameters(recurse=False))
+ named.update(dict(self.named_buffers(recurse=False)))
+ return [(name, named[name]) for name in self._fp32_names]
+
+
+class GemmaRMSNorm(_Float32Module):
+ """Gemma RMSNorm with an FP32 ``(1 + w)`` affine; returns the input dtype."""
+
+ _fp32_names = ("weight",)
+
+ def __init__(self, width: int, *, eps: float) -> None:
+ super().__init__()
+ self.weight = nn.Parameter(torch.zeros(width, dtype=torch.float32))
+ self.eps = eps
+
+ def forward(self, values: Tensor) -> Tensor:
+ """Normalize in FP32 and return the input dtype."""
+
+ normed = values.to(dtype=torch.float32)
+ normed = normed * torch.rsqrt(
+ normed.pow(2).mean(dim=-1, keepdim=True) + self.eps
+ )
+ return (normed * (1.0 + self.weight)).to(dtype=values.dtype)
+
+
+class ScaledEmbedding(_Float32Module):
+ """FP32 token embeddings scaled by ``embed_scale``, with the end-of-image
+ token's own vector."""
+
+ _fp32_names = ("weight", "eoi_embedding")
+
+ def __init__(self, config: T5Gemma2EncoderConfig) -> None:
+ super().__init__()
+ self.weight = nn.Parameter(
+ torch.zeros(config.vocab_size, config.hidden_size, dtype=torch.float32)
+ )
+ self.eoi_embedding = nn.Parameter(
+ torch.zeros(config.hidden_size, dtype=torch.float32)
+ )
+ self.embed_scale = config.embed_scale
+ self.eoi_token_index = config.eoi_token_index
+
+ def forward(self, ids: Tensor) -> Tensor:
+ """Embed ``[B, L]`` ids as FP32 ``[B, L, hidden]``."""
+
+ values = F.embedding(ids, self.weight) * self.embed_scale
+ is_eoi = (ids == self.eoi_token_index).unsqueeze(-1)
+ return torch.where(is_eoi, self.eoi_embedding.to(values.dtype), values)
+
+
+class EncoderAttention(nn.Module):
+ """Bidirectional grouped-query attention of one layer."""
+
+ def __init__(self, config: T5Gemma2EncoderConfig) -> None:
+ super().__init__()
+ width, heads = config.hidden_size, config.num_attention_heads
+ kv_heads, head_dim = config.num_key_value_heads, config.head_dim
+ self.q_proj = nn.Linear(width, heads * head_dim, bias=False)
+ self.k_proj = nn.Linear(width, kv_heads * head_dim, bias=False)
+ self.v_proj = nn.Linear(width, kv_heads * head_dim, bias=False)
+ self.o_proj = nn.Linear(heads * head_dim, width, bias=False)
+ self.q_norm = GemmaRMSNorm(head_dim, eps=config.rms_norm_eps)
+ self.k_norm = GemmaRMSNorm(head_dim, eps=config.rms_norm_eps)
+ self.heads, self.kv_heads, self.head_dim = heads, kv_heads, head_dim
+ self.scale = config.query_pre_attn_scalar**-0.5
+
+ def forward(
+ self,
+ values: Tensor,
+ *,
+ cos: Tensor,
+ sin: Tensor,
+ attn_bias: Tensor | None,
+ value_scale: Tensor | None,
+ ) -> Tensor:
+ """Attend over ``[B, L, hidden]`` values.
+
+ Args:
+ values: Normalized layer input.
+ cos, sin: FP32 RoPE tables ``[L, 1, head_dim]`` of this layer kind.
+ attn_bias: Additive logit bias broadcastable to ``[B, 1, L, L]``
+ (window mask and emphasis key bias) in the compute dtype, or
+ None.
+ value_scale: Per-token value multiplier ``[B, L, 1, 1]``, or None.
+ """
+
+ batch, length, _ = values.shape
+ q = self.q_proj(values).view(batch, length, self.heads, self.head_dim)
+ k = self.k_proj(values).view(batch, length, self.kv_heads, self.head_dim)
+ v = self.v_proj(values).view(batch, length, self.kv_heads, self.head_dim)
+ q, k = self.q_norm(q), self.k_norm(k)
+ if value_scale is not None:
+ v = v * value_scale.to(dtype=v.dtype)
+ cos_q, sin_q = cos.to(dtype=q.dtype), sin.to(dtype=q.dtype)
+ q = q * cos_q + _rotate_half(q) * sin_q
+ k = k * cos_q + _rotate_half(k) * sin_q
+ groups = self.heads // self.kv_heads
+ out = F.scaled_dot_product_attention(
+ q.transpose(1, 2),
+ k.repeat_interleave(groups, dim=2).transpose(1, 2),
+ v.repeat_interleave(groups, dim=2).transpose(1, 2),
+ attn_mask=attn_bias,
+ scale=self.scale,
+ )
+ out = out.transpose(1, 2).reshape(batch, length, self.heads * self.head_dim)
+ return self.o_proj(out)
+
+
+class EncoderMLP(nn.Module):
+ """GeGLU feed-forward block (tanh GELU)."""
+
+ def __init__(self, config: T5Gemma2EncoderConfig) -> None:
+ super().__init__()
+ width, hidden = config.hidden_size, config.intermediate_size
+ self.gate_proj = nn.Linear(width, hidden, bias=False)
+ self.up_proj = nn.Linear(width, hidden, bias=False)
+ self.down_proj = nn.Linear(hidden, width, bias=False)
+
+ def forward(self, values: Tensor) -> Tensor:
+ """Apply the gated projection."""
+
+ gate = F.gelu(self.gate_proj(values), approximate="tanh")
+ return self.down_proj(gate * self.up_proj(values))
+
+
+class EncoderLayer(nn.Module):
+ """One sandwich-normed Gemma 3 encoder block."""
+
+ def __init__(self, config: T5Gemma2EncoderConfig, kind: LayerKind) -> None:
+ super().__init__()
+ eps = config.rms_norm_eps
+ self.pre_self_attn_layernorm = GemmaRMSNorm(config.hidden_size, eps=eps)
+ self.self_attn = EncoderAttention(config)
+ self.post_self_attn_layernorm = GemmaRMSNorm(config.hidden_size, eps=eps)
+ self.pre_feedforward_layernorm = GemmaRMSNorm(config.hidden_size, eps=eps)
+ self.mlp = EncoderMLP(config)
+ self.post_feedforward_layernorm = GemmaRMSNorm(config.hidden_size, eps=eps)
+ self.kind = kind
+ self._compiled: Callable[..., Tensor] | None = None
+
+ def compile_layer(self) -> None:
+ """Compile this layer's forward (full graph, dynamic sequence length).
+
+ Raises:
+ RuntimeError: If the layer is already compiled.
+ """
+
+ if self._compiled is not None:
+ raise RuntimeError("EncoderLayer is already compiled.")
+ self._compiled = torch.compile(self._forward_impl, fullgraph=True, dynamic=True)
+
+ def forward(
+ self,
+ values: Tensor,
+ *,
+ cos: Tensor,
+ sin: Tensor,
+ attn_bias: Tensor | None,
+ value_scale: Tensor | None,
+ ) -> Tensor:
+ """Apply the block to the FP32 residual stream ``[B, L, hidden]``."""
+
+ call = self._forward_impl if self._compiled is None else self._compiled
+ return call(
+ values, cos=cos, sin=sin, attn_bias=attn_bias, value_scale=value_scale
+ )
+
+ def _forward_impl(
+ self,
+ values: Tensor,
+ *,
+ cos: Tensor,
+ sin: Tensor,
+ attn_bias: Tensor | None,
+ value_scale: Tensor | None,
+ ) -> Tensor:
+ """Attention and MLP residual updates."""
+
+ attn = self.self_attn(
+ self.pre_self_attn_layernorm(values),
+ cos=cos,
+ sin=sin,
+ attn_bias=attn_bias,
+ value_scale=value_scale,
+ )
+ values = values + self.post_self_attn_layernorm(attn)
+ mlp = self.mlp(self.pre_feedforward_layernorm(values))
+ return values + self.post_feedforward_layernorm(mlp)
+
+
+@dataclass(frozen=True)
+class EncoderTaps:
+ """FP32 hidden states ``[B, L, 640]`` after layers 2, 6 and 12."""
+
+ low: Tensor
+ middle: Tensor
+ high: Tensor
+
+
+@dataclass(frozen=True)
+class EncoderWeighting:
+ """Prompt emphasis inside the encoder's attention.
+
+ Attributes:
+ key_bias: FP32 ``[B, L]`` additive logit bias on each token's key, or
+ None.
+ value_scale: FP32 ``[B, L]`` multiplier on each token's value, or None.
+ """
+
+ key_bias: Tensor | None
+ value_scale: Tensor | None
+
+
+class T5Gemma2Encoder(_Float32Module):
+ """Embeddings and the first 12 T5Gemma2 encoder layers, returning three taps.
+
+ Args:
+ config: The architecture (``ENCODER_CONFIG``).
+ """
+
+ _fp32_names = ("sliding_inv_freq", "full_inv_freq")
+ sliding_inv_freq: Tensor
+ full_inv_freq: Tensor
+
+ def __init__(self, config: T5Gemma2EncoderConfig = ENCODER_CONFIG) -> None:
+ super().__init__()
+ self.config = config
+ self.embed_tokens = ScaledEmbedding(config)
+ self.layers = nn.ModuleList(
+ EncoderLayer(config, kind) for kind in config.layer_types
+ )
+ for kind, name in ((LayerKind.SLIDING, "sliding"), (LayerKind.FULL, "full")):
+ self.register_buffer(
+ f"{name}_inv_freq",
+ _rope_inv_freq(config.rope(kind), config.head_dim),
+ persistent=False,
+ )
+ self._compiled = False
+
+ @classmethod
+ def from_directory(
+ cls, directory: str | Path, *, device: torch.device
+ ) -> T5Gemma2Encoder:
+ """Load the bundled weights of a ``text_encoder/`` folder onto ``device``.
+
+ Linear weights stay in their stored bf16 (the dtype autocast feeds the
+ matrix multiplies); embeddings and norms are FP32 copies.
+
+ Raises:
+ FileNotFoundError: If the weights are missing.
+ ValueError: If the config or any tensor name, shape or dtype differs.
+ """
+
+ path = Path(directory)
+ _check_config_file(path / CONFIG_FILENAME)
+ weights_path = path / WEIGHTS_FILENAME
+ if not weights_path.is_file():
+ raise FileNotFoundError(f"No {WEIGHTS_FILENAME} in {path}.")
+ state = load_file(str(weights_path), device="cpu")
+ bad_dtypes = sorted(k for k, t in state.items() if t.dtype != STORAGE_DTYPE)
+ if bad_dtypes:
+ raise ValueError(
+ f"{weights_path} tensors must be {STORAGE_DTYPE}; not: {bad_dtypes}."
+ )
+ with torch.device(device):
+ encoder = cls(ENCODER_CONFIG)
+ encoder._cast_linears(STORAGE_DTYPE)
+ encoder.load_state_dict(state, strict=True)
+ return encoder.to(device=device).eval().requires_grad_(False)
+
+ def _cast_linears(self, dtype: torch.dtype) -> None:
+ """Store every linear weight in ``dtype``."""
+
+ for module in self.modules():
+ match module:
+ case nn.Linear():
+ module.weight.data = module.weight.data.to(dtype=dtype)
+ case _:
+ pass
+
+ def _layers(self) -> list[tuple[int, EncoderLayer]]:
+ """Return ``(1-based index, layer)`` pairs."""
+
+ out: list[tuple[int, EncoderLayer]] = []
+ for index, module in enumerate(self.layers, start=1):
+ match module:
+ case EncoderLayer():
+ out.append((index, module))
+ case _:
+ raise TypeError("T5Gemma2Encoder.layers must hold EncoderLayer.")
+ return out
+
+ def compile_layers(self) -> None:
+ """Compile every layer separately (``torch.compile``, full graph,
+ dynamic sequence length).
+
+ Raises:
+ RuntimeError: If the layers are already compiled.
+ """
+
+ if self._compiled:
+ raise RuntimeError("T5Gemma2Encoder layers are already compiled.")
+ for _, layer in self._layers():
+ layer.compile_layer()
+ self._compiled = True
+
+ def _rope_tables(
+ self, *, length: int, device: torch.device
+ ) -> dict[LayerKind, tuple[Tensor, Tensor]]:
+ """Return each layer kind's FP32 ``(cos, sin)`` ``[L, 1, head_dim]``."""
+
+ positions = torch.arange(length, device=device, dtype=torch.int64)
+ positions = positions.to(dtype=torch.float32).unsqueeze(1)
+ tables: dict[LayerKind, tuple[Tensor, Tensor]] = {}
+ for kind, inv_freq in (
+ (LayerKind.SLIDING, self.sliding_inv_freq),
+ (LayerKind.FULL, self.full_inv_freq),
+ ):
+ freqs = positions * inv_freq.view(1, -1)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ tables[kind] = (emb.cos().unsqueeze(1), emb.sin().unsqueeze(1))
+ return tables
+
+ def _attention_biases(
+ self, *, length: int, key_bias: Tensor | None, device: torch.device
+ ) -> dict[LayerKind, Tensor | None]:
+ """Return each layer kind's additive attention bias in the compute dtype.
+
+ Sliding layers mask keys outside the window when the prompt is longer
+ than it; the emphasis key bias is added for both kinds.
+ """
+
+ key = (
+ None
+ if key_bias is None
+ else key_bias.to(dtype=COMPUTE_DTYPE)[:, None, None, :]
+ )
+ window = self.config.sliding_window
+ left, right = (window + 1) // 2 - 1, window // 2
+ sliding = key
+ if length - 1 > min(left, right):
+ steps = torch.arange(length, device=device)
+ delta = steps.view(-1, 1) - steps.view(1, -1)
+ outside = (delta > left) | (-delta > right)
+ mask = torch.zeros((length, length), device=device, dtype=COMPUTE_DTYPE)
+ mask = mask.masked_fill(outside, -math.inf)[None, None]
+ sliding = mask if key is None else mask + key
+ return {LayerKind.SLIDING: sliding, LayerKind.FULL: key}
+
+ def forward(
+ self, token_ids: Tensor, *, weighting: EncoderWeighting | None
+ ) -> EncoderTaps:
+ """Encode an unpadded ``[B, L]`` id batch on the encoder's device.
+
+ Args:
+ token_ids: int64 token ids, every row a full prompt (no padding).
+ weighting: Prompt emphasis inside attention, or None.
+
+ Returns:
+ The FP32 hidden states after layers 2, 6 and 12.
+ """
+
+ device = token_ids.device
+ length = int(token_ids.shape[1])
+ key_bias = None if weighting is None else weighting.key_bias
+ value_scale = (
+ None
+ if weighting is None or weighting.value_scale is None
+ else weighting.value_scale[:, :, None, None]
+ )
+ biases = self._attention_biases(length=length, key_bias=key_bias, device=device)
+ ropes = self._rope_tables(length=length, device=device)
+ taps: dict[int, Tensor] = {}
+ with torch.autocast(device_type=device.type, dtype=COMPUTE_DTYPE):
+ values = self.embed_tokens(token_ids)
+ for index, layer in self._layers():
+ cos, sin = ropes[layer.kind]
+ values = layer(
+ values,
+ cos=cos,
+ sin=sin,
+ attn_bias=biases[layer.kind],
+ value_scale=value_scale,
+ )
+ if index in self.config.tap_layers:
+ taps[index] = values
+ low, middle, high = (taps[index] for index in self.config.tap_layers)
+ return EncoderTaps(low=low, middle=middle, high=high)
diff --git a/dflow/tokenization.py b/dflow/tokenization.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4c3664219f5c5de21ee6c2aa76639a35970f69c
--- /dev/null
+++ b/dflow/tokenization.py
@@ -0,0 +1,311 @@
+"""Prompt tokenization for the T5Gemma2 text encoder, exactly as in training.
+
+- The tokenizer's special-token frame (````) wraps every prompt.
+- Text the image should show is tokenized one character at a time, so its
+ spelling becomes token identity: in a plain prompt every straight
+ (``"..."``) or curly (``“...”``) double-quoted span on one line, quote marks
+ included; in a JSON layout prompt the string value of every ``"text"`` key
+ and every escaped-quote (``\\"...\\"``) span inside other string values.
+- Everything else is tokenized normally.
+- A prompt over ``MAX_PROMPT_TOKENS`` tokens (frame included) raises; prompts
+ are never truncated.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path
+
+from transformers import AutoTokenizer, PreTrainedTokenizerBase
+
+from .layout import is_compiled_layout
+
+__all__ = [
+ "MAX_PROMPT_TOKENS",
+ "PromptTokenizer",
+ "PromptTooLongError",
+ "TokenizedPrompt",
+ "quoted_segments",
+ "structured_segments",
+]
+
+# The longest prompt the model was trained on, in tokens (special tokens included).
+MAX_PROMPT_TOKENS = 6144
+
+_QUOTED_SPAN = re.compile(r"\"[^\"\n]*\"|“[^”\n]*”")
+# A JSON string literal (quote marks included) and one escape sequence in it.
+_JSON_STRING = re.compile(r"\"(?:[^\"\\]|\\.)*\"")
+_JSON_ESCAPE = re.compile(r"\\.")
+_JSON_KEY_COLON = re.compile(r"\s*:")
+_JSON_ESCAPED_QUOTE = '\\"'
+# The JSON key whose string value is visible text (a layout item's ``text``).
+_VISIBLE_TEXT_KEY = '"text"'
+# Probe text used to find the special tokens the tokenizer adds around text.
+_FRAME_PROBE = "a"
+
+type Segment = tuple[int, int, bool]
+type Offset = tuple[int, int]
+
+
+class PromptTooLongError(ValueError):
+ """A prompt has more tokens than the model was trained on."""
+
+
+@dataclass(frozen=True)
+class TokenizedPrompt:
+ """Token ids of one prompt and each token's character span in it.
+
+ Attributes:
+ ids: Token ids, special tokens included.
+ offsets: Per token, its ``(start, end)`` character span in the prompt;
+ ``(0, 0)`` for special tokens.
+ """
+
+ ids: tuple[int, ...]
+ offsets: tuple[Offset, ...]
+
+
+def _segments_from_spans(text: str, spans: Sequence[Offset]) -> list[Segment]:
+ """Cover ``text`` with ``(start, end, in_span)`` segments for ordered,
+ non-overlapping ``spans``."""
+
+ segments: list[Segment] = []
+ cursor = 0
+ for start, end in spans:
+ if start > cursor:
+ segments.append((cursor, start, False))
+ segments.append((start, end, True))
+ cursor = end
+ if cursor < len(text):
+ segments.append((cursor, len(text), False))
+ return segments
+
+
+def quoted_segments(text: str) -> list[Segment]:
+ """Split a plain prompt into ``(start, end, is_quoted)`` segments covering it.
+
+ Quoted segments are balanced straight or curly double quotes on one line,
+ quote marks included. Single quotes are not quotes (apostrophes).
+ """
+
+ return _segments_from_spans(
+ text, [match.span() for match in _QUOTED_SPAN.finditer(text)]
+ )
+
+
+def _escaped_quote_spans(literal: str, *, offset: int) -> list[Offset]:
+ """Spans of balanced ``\\"...\\"`` pairs inside one JSON string literal,
+ shifted by ``offset``; an unpaired last escaped quote is ignored."""
+
+ quotes = [
+ match.start()
+ for match in _JSON_ESCAPE.finditer(literal)
+ if match.group(0) == _JSON_ESCAPED_QUOTE
+ ]
+ return [
+ (offset + quotes[pos], offset + quotes[pos + 1] + len(_JSON_ESCAPED_QUOTE))
+ for pos in range(0, len(quotes) - 1, 2)
+ ]
+
+
+def structured_segments(text: str) -> list[Segment]:
+ """Split a JSON layout prompt into ``(start, end, is_visible_text)`` segments.
+
+ Visible text is the string value of every ``"text"`` key (quote marks
+ included) and each balanced ``\\"...\\"`` span inside any other string
+ value. String literals are lexed whole.
+
+ Raises:
+ ValueError: If ``text`` has a double quote outside a string literal.
+ """
+
+ spans: list[Offset] = []
+ cursor = 0
+ after_text_key = False
+ for match in _JSON_STRING.finditer(text):
+ start, end = match.span()
+ between = text[cursor:start]
+ if '"' in between:
+ raise ValueError(
+ f"Layout prompt has an unterminated string at {cursor}: {text[:120]!r}"
+ )
+ if _JSON_KEY_COLON.match(text, end) is not None:
+ after_text_key = match.group(0) == _VISIBLE_TEXT_KEY
+ elif after_text_key and between.strip() == ":":
+ spans.append((start, end))
+ after_text_key = False
+ else:
+ spans.extend(_escaped_quote_spans(match.group(0), offset=start))
+ after_text_key = False
+ cursor = end
+ if '"' in text[cursor:]:
+ raise ValueError(
+ f"Layout prompt has an unterminated string at {cursor}: {text[:120]!r}"
+ )
+ return _segments_from_spans(text, spans)
+
+
+def _int_rows(raw: object, *, name: str) -> list[list[int]]:
+ """Return a tokenizer output field as integer rows.
+
+ Raises:
+ TypeError: If the field is not a list of integer lists.
+ """
+
+ match raw:
+ case list() if all(
+ isinstance(row, list) and all(isinstance(v, int) for v in row)
+ for row in raw
+ ):
+ return [[int(v) for v in row] for row in raw]
+ case _:
+ raise TypeError(f"Tokenizer {name} must be a list of integer lists.")
+
+
+def _offset_rows(raw: object) -> list[list[Offset]]:
+ """Return tokenizer offset mappings as ``(start, end)`` rows.
+
+ Raises:
+ TypeError: If the field is not a list of integer-pair lists.
+ """
+
+ match raw:
+ case list():
+ rows: list[list[Offset]] = []
+ for row in raw:
+ match row:
+ case list():
+ pairs: list[Offset] = []
+ for pair in row:
+ match pair:
+ case (int() as start, int() as end):
+ pairs.append((start, end))
+ case [int() as start, int() as end]:
+ pairs.append((start, end))
+ case _:
+ raise TypeError(
+ "Tokenizer offsets must be integer pairs."
+ )
+ rows.append(pairs)
+ case _:
+ raise TypeError("Tokenizer offsets must be rows of pairs.")
+ return rows
+ case _:
+ raise TypeError("Tokenizer offset_mapping must be a list of rows.")
+
+
+class PromptTokenizer:
+ """The T5Gemma2 tokenizer with the training-time prompt rules.
+
+ Args:
+ tokenizer: The fast T5Gemma2 tokenizer.
+ max_tokens: The longest allowed prompt in tokens.
+
+ Raises:
+ RuntimeError: If the special-token frame cannot be located.
+ """
+
+ def __init__(
+ self, tokenizer: PreTrainedTokenizerBase, *, max_tokens: int = MAX_PROMPT_TOKENS
+ ) -> None:
+ if max_tokens <= 0:
+ raise ValueError(f"max_tokens must be positive, got {max_tokens}.")
+ self.tokenizer = tokenizer
+ self.max_tokens = max_tokens
+ self.prefix_ids, self.suffix_ids = self._special_token_frame()
+
+ @classmethod
+ def from_directory(cls, directory: str | Path) -> PromptTokenizer:
+ """Load the tokenizer files of a bundled ``text_encoder/`` folder.
+
+ Raises:
+ FileNotFoundError: If ``tokenizer.json`` is missing.
+ """
+
+ path = Path(directory)
+ if not (path / "tokenizer.json").is_file():
+ raise FileNotFoundError(f"No tokenizer.json in {path}.")
+ # The folder's config.json is ours (no transformers version), which
+ # transformers would otherwise take for an old Mistral checkpoint.
+ loaded = AutoTokenizer.from_pretrained(
+ str(path), local_files_only=True, fix_mistral_regex=False
+ )
+ if not isinstance(loaded, PreTrainedTokenizerBase) or not loaded.is_fast:
+ raise TypeError(f"{path} does not hold a fast tokenizer.")
+ return cls(loaded)
+
+ def _encode(self, texts: Sequence[str], *, special: bool) -> list[list[int]]:
+ """Return the plain token ids of each text."""
+
+ encoded = self.tokenizer(
+ list(texts),
+ padding=False,
+ truncation=False,
+ add_special_tokens=special,
+ )
+ return _int_rows(encoded["input_ids"], name="input_ids")
+
+ def _special_token_frame(self) -> tuple[tuple[int, ...], tuple[int, ...]]:
+ """Return the special-token ids the tokenizer adds before and after text.
+
+ Raises:
+ RuntimeError: If the plain ids are not a run inside the framed ids.
+ """
+
+ plain = self._encode([_FRAME_PROBE], special=False)[0]
+ framed = self._encode([_FRAME_PROBE], special=True)[0]
+ width = len(plain)
+ for start in range(len(framed) - width + 1):
+ if framed[start : start + width] == plain:
+ return tuple(framed[:start]), tuple(framed[start + width :])
+ raise RuntimeError("Could not locate plain tokens inside the special frame.")
+
+ def tokenize(self, text: str) -> TokenizedPrompt:
+ """Tokenize one prompt (plain or a compiled JSON layout prompt).
+
+ Raises:
+ PromptTooLongError: If the prompt exceeds ``max_tokens``.
+ ValueError: If a JSON layout prompt has an unterminated string.
+ """
+
+ segments = (
+ structured_segments(text)
+ if is_compiled_layout(text)
+ else quoted_segments(text)
+ )
+ pieces: list[str] = []
+ starts: list[int] = []
+ for start, end, by_character in segments:
+ if by_character:
+ pieces.extend(text[start:end])
+ starts.extend(range(start, end))
+ else:
+ pieces.append(text[start:end])
+ starts.append(start)
+ ids: list[int] = list(self.prefix_ids)
+ offsets: list[Offset] = [(0, 0)] * len(self.prefix_ids)
+ if pieces:
+ encoded = self.tokenizer(
+ pieces,
+ padding=False,
+ truncation=False,
+ add_special_tokens=False,
+ return_offsets_mapping=True,
+ )
+ id_rows = _int_rows(encoded["input_ids"], name="input_ids")
+ offset_rows = _offset_rows(encoded["offset_mapping"])
+ for base, row_ids, row_offsets in zip(
+ starts, id_rows, offset_rows, strict=True
+ ):
+ ids.extend(row_ids)
+ offsets.extend((base + lo, base + hi) for lo, hi in row_offsets)
+ ids.extend(self.suffix_ids)
+ offsets.extend([(0, 0)] * len(self.suffix_ids))
+ if len(ids) > self.max_tokens:
+ raise PromptTooLongError(
+ f"The prompt has {len(ids)} tokens; the model takes at most "
+ f"{self.max_tokens}. Shorten it: {text[:120]!r}"
+ )
+ return TokenizedPrompt(ids=tuple(ids), offsets=tuple(offsets))
diff --git a/dflow/types.py b/dflow/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..51ba56f029a4290fc291fc279361931edb7cd1fa
--- /dev/null
+++ b/dflow/types.py
@@ -0,0 +1,59 @@
+"""Types shared between the text path, the denoiser and the sampler.
+
+These are the contracts between modules: the text path produces
+``TextConditioning``; the denoiser consumes it and runs one of the
+``DFlowPath`` routings per forward.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import StrEnum
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from torch import Tensor
+
+
+# Learned suffix tokens appended to every prompt's text tokens.
+SUFFIX_TOKEN_COUNT = 3
+
+
+class DFlowPath(StrEnum):
+ """Which trained routing of the 18 middle layers a forward runs.
+
+ FULL: every token through all 30 image layers (the main prediction).
+ PATH_DROP: the middle is skipped for every token (the weak pass of
+ path-drop guidance).
+ THREE_QUARTER: one image token per 2x2 group (and every text token) goes
+ through the middle; the rest skip it.
+ """
+
+ FULL = "full"
+ PATH_DROP = "path_drop"
+ THREE_QUARTER = "three_quarter"
+
+
+@dataclass(frozen=True)
+class TextConditioning:
+ """Text tokens for a prompt batch, ready for the denoiser's text refiner.
+
+ All prompts in a batch have the same token count ``L`` (the dense
+ attention path has no padding); batches of different lengths run as
+ separate forwards.
+
+ Attributes:
+ tokens: ``[B, L, 2304]`` float32: the summed projected encoder taps
+ followed by the learned suffix tokens (or the learned
+ unconditional token and the suffix for an empty prompt).
+ key_bias: ``[B, L]`` float32 additive attention-logit bias on each
+ text token's key (prompt emphasis with weight > 0), or None when no
+ token is weighted.
+ value_scale: ``[B, L]`` float32 multiplier on each text token's value
+ (prompt emphasis with weight <= 0), or None when no token is
+ weighted.
+ """
+
+ tokens: Tensor
+ key_bias: Tensor | None
+ value_scale: Tensor | None
diff --git a/dflow/vae.py b/dflow/vae.py
new file mode 100644
index 0000000000000000000000000000000000000000..18eb319ab6422be5d6cf702dfdad33e3ff2dd883
--- /dev/null
+++ b/dflow/vae.py
@@ -0,0 +1,210 @@
+"""The dinac3_96 autoencoder that maps between images and dflow latents.
+
+dflow_2b generates whitened dinac3_96 latents: 96 channels at 1/16 of the
+image resolution. The autoencoder is a separate repository; it is
+downloaded at a pinned commit and its own Python package (``dinac3/`` in that
+repository) is imported from the download under a private module name, so it
+never clashes with an installed copy.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+import threading
+from pathlib import Path
+from types import ModuleType
+from typing import Protocol, cast
+
+import torch
+from huggingface_hub import snapshot_download
+from torch import Tensor
+
+VAE_REPOSITORY = "data-archetype/dinac3_96"
+# dinac3_96 v1.0 with its final documentation commit.
+VAE_REVISION = "d0ca36daa3e429a510ba465a5f7f8139c66d2f82"
+LATENT_CHANNELS = 96
+LATENT_STRIDE = 16
+_PACKAGE_DIR = "dinac3"
+_PRIVATE_MODULE = "_dflow_dinac3"
+_DOWNLOAD_PATTERNS = ("config.json", "model.safetensors", f"{_PACKAGE_DIR}/*.py")
+_IMPORT_LOCK = threading.Lock()
+
+
+class _Dinac3Model(Protocol):
+ """The part of ``dinac3.Dinac3`` dflow uses."""
+
+ def encode(self, images: Tensor) -> Tensor:
+ """Whitened float32 latents of ``[-1, 1]`` images."""
+ ...
+
+ def decode(self, latents: Tensor, height: int, width: int) -> Tensor:
+ """Float32 RGB (unclamped, about ``[-1, 1]``) of whitened latents."""
+ ...
+
+
+class _Dinac3Factory(Protocol):
+ """``dinac3.Dinac3.from_pretrained``."""
+
+ def from_pretrained(
+ self,
+ path_or_repo: str | Path,
+ *,
+ device: torch.device | str,
+ dtype: torch.dtype,
+ compile_encoder: bool,
+ compile_decoder: bool,
+ revision: str | None,
+ ) -> _Dinac3Model:
+ """Load and prepare the autoencoder."""
+ ...
+
+
+class DFlowVae:
+ """Encode images to and decode them from dflow latents.
+
+ Images are ``[B, 3, H, W]`` float32 RGB in ``[-1, 1]`` with H and W
+ multiples of 16; latents are ``[B, 96, H/16, W/16]`` float32, whitened.
+ """
+
+ def __init__(self, model: _Dinac3Model, *, revision: str) -> None:
+ """Wrap a loaded autoencoder; ``revision`` records the commit it came from."""
+
+ self.model = model
+ self.revision = revision
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ *,
+ device: torch.device,
+ compile: bool,
+ local_dir: Path | None = None,
+ revision: str = VAE_REVISION,
+ cache_dir: Path | None = None,
+ ) -> DFlowVae:
+ """Download (or reuse) the pinned dinac3_96 release and load it in bf16.
+
+ Args:
+ device: CUDA device.
+ compile: ``torch.compile`` the encoder and decoder (dynamic shapes).
+ local_dir: An existing local copy of the repository to load from
+ instead of the Hub (offline use).
+ revision: Hub commit to download; the pinned release by default.
+ cache_dir: Hugging Face cache directory, or None for the default.
+
+ Raises:
+ FileNotFoundError: If ``local_dir`` lacks the package or weights.
+ ValueError: On a non-CUDA device.
+ """
+
+ if device.type != "cuda":
+ raise ValueError(f"dflow inference needs a CUDA device, got {device}.")
+ root = (
+ local_dir
+ if local_dir is not None
+ else Path(
+ snapshot_download(
+ VAE_REPOSITORY,
+ revision=revision,
+ allow_patterns=list(_DOWNLOAD_PATTERNS),
+ cache_dir=None if cache_dir is None else str(cache_dir),
+ )
+ )
+ )
+ factory = _import_factory(root)
+ model = factory.from_pretrained(
+ root,
+ device=device,
+ dtype=torch.bfloat16,
+ compile_encoder=compile,
+ compile_decoder=compile,
+ revision=None,
+ )
+ return cls(model, revision=revision)
+
+ def decode(self, latents: Tensor) -> Tensor:
+ """Decode whitened latents to float32 RGB ``[B, 3, 16h, 16w]``, unclamped."""
+
+ height = int(latents.shape[-2]) * LATENT_STRIDE
+ width = int(latents.shape[-1]) * LATENT_STRIDE
+ return self.model.decode(latents.float(), height, width)
+
+ def encode(self, images: Tensor) -> Tensor:
+ """Encode ``[-1, 1]`` RGB images to whitened float32 latents.
+
+ Raises:
+ ValueError: If the image height or width is not a multiple of 16.
+ """
+
+ height, width = int(images.shape[-2]), int(images.shape[-1])
+ if height % LATENT_STRIDE or width % LATENT_STRIDE:
+ raise ValueError(
+ f"Image size {width}x{height} must be a multiple of {LATENT_STRIDE} "
+ "on both sides."
+ )
+ return self.model.encode(images.float())
+
+
+def _import_factory(root: Path) -> _Dinac3Factory:
+ """Import ``root/dinac3`` under a private module name and return ``Dinac3``.
+
+ Raises:
+ FileNotFoundError: If the package or weights are missing under ``root``.
+ """
+
+ package_init = root / _PACKAGE_DIR / "__init__.py"
+ missing = [
+ path
+ for path in (package_init, root / "config.json", root / "model.safetensors")
+ if not path.is_file()
+ ]
+ if missing:
+ raise FileNotFoundError(
+ f"Incomplete {VAE_REPOSITORY} download at {root}: missing {missing}."
+ )
+ with _IMPORT_LOCK:
+ module = sys.modules.get(_PRIVATE_MODULE)
+ if module is None or Path(module.__file__ or "") != package_init:
+ module = _load_package(package_init)
+ return cast("_Dinac3Factory", module.Dinac3)
+
+
+def _load_package(package_init: Path) -> ModuleType:
+ """Execute a package from its ``__init__.py`` under the private name,
+ replacing any earlier copy and its submodules.
+
+ Raises:
+ ImportError: If Python cannot build a module spec for the file, or the
+ package fails to import (a missing dependency). The partly
+ imported modules are removed first, so a retry imports afresh.
+ """
+
+ spec = importlib.util.spec_from_file_location(
+ _PRIVATE_MODULE,
+ package_init,
+ submodule_search_locations=[str(package_init.parent)],
+ )
+ if spec is None or spec.loader is None:
+ raise ImportError(f"Cannot import the autoencoder package at {package_init}.")
+ _drop_private_modules()
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[_PRIVATE_MODULE] = module
+ try:
+ spec.loader.exec_module(module)
+ except ImportError:
+ _drop_private_modules()
+ raise
+ return module
+
+
+def _drop_private_modules() -> None:
+ """Remove the private autoencoder package and its submodules from
+ ``sys.modules``."""
+
+ for name in [
+ name
+ for name in sys.modules
+ if name == _PRIVATE_MODULE or name.startswith(f"{_PRIVATE_MODULE}.")
+ ]:
+ del sys.modules[name]
diff --git a/dflow/version.py b/dflow/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc4842520efc4d8d562118bfee3167bd84fbd843
--- /dev/null
+++ b/dflow/version.py
@@ -0,0 +1,4 @@
+"""Package and model version."""
+
+__version__ = "0.2.0"
+MODEL_VERSION = "0.2"
diff --git a/model.safetensors b/model.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..3e93eda61ab2c318735b796d05968379dc403069
--- /dev/null
+++ b/model.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:78e4a30c1c48e81693e84125bd1e3ccbc5e7fe92a31e63a47b981ee44c5f56f8
+size 4268864440
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..37ca416166e6d7ab941786a7042a040f94cfc088
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,31 @@
+[build-system]
+requires = ["hatchling>=1.28,<2"]
+build-backend = "hatchling.build"
+
+[project]
+name = "dflow"
+dynamic = ["version"]
+description = "Inference package for the dflow_2b text-to-image model"
+readme = "README.md"
+requires-python = ">=3.12"
+license = { file = "LICENSE" }
+dependencies = [
+ "torch>=2.13",
+ "huggingface-hub>=1.15,<2",
+ "numpy>=2,<3",
+ "pillow>=12,<13",
+ "safetensors>=0.7",
+ "scipy>=1.17,<2",
+ "timm==1.0.26",
+ "torchsde==0.2.6",
+ "transformers>=5.12,<6",
+]
+
+[project.optional-dependencies]
+diffusers = ["diffusers>=0.40"]
+
+[tool.hatch.build.targets.wheel]
+packages = ["dflow"]
+
+[tool.hatch.version]
+path = "dflow/version.py"
diff --git a/release.json b/release.json
new file mode 100644
index 0000000000000000000000000000000000000000..2ecb1e87e71355c5a408a044a9871c0c56e6476f
--- /dev/null
+++ b/release.json
@@ -0,0 +1,9 @@
+{
+ "dtype": "bfloat16",
+ "license": "mg-by-nc-2.0",
+ "parameter_count": 2133866592,
+ "tensor_count": 468,
+ "text_encoder_repository": "google/t5gemma-2-270m-270m",
+ "vae_repository": "data-archetype/dinac3_96",
+ "version": "0.2"
+}
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..2f8598fc2a431f49044931ae7b250f77ff1b872a
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,9 @@
+torch>=2.13
+huggingface-hub>=1.15,<2
+numpy>=2,<3
+pillow>=12,<13
+safetensors>=0.7
+scipy>=1.17,<2
+timm==1.0.26
+torchsde==0.2.6
+transformers>=5.12,<6
diff --git a/text_encoder/LICENSE-GEMMA.md b/text_encoder/LICENSE-GEMMA.md
new file mode 100644
index 0000000000000000000000000000000000000000..b77396904660b7c023a7c4661cbbd29fb2bf3ba3
--- /dev/null
+++ b/text_encoder/LICENSE-GEMMA.md
@@ -0,0 +1,173 @@
+# Gemma Terms of Use for the bundled text encoder
+
+Gemma is provided under and subject to the Gemma Terms of Use found at
+gemma.ai/resources/terms
+
+The same terms were previously published at ai.google.dev/gemma/terms, which
+now redirects to the address above. Earlier versions of the terms worded this
+notice as: "Gemma is provided under and subject to the Gemma Terms of Use found
+at ai.google.dev/gemma/terms".
+
+## Modification notice
+
+**The files in this folder have been modified from the original.** They are
+derived from
+[`google/t5gemma-2-270m-270m`](https://huggingface.co/google/t5gemma-2-270m-270m)
+at revision `7c38f16641f455ef0685b18431faf1b17722d5a1`. Data Archetype made the
+following changes in November 2026:
+
+- `model.safetensors` is a trimmed copy of the original weights. It keeps the
+ token embeddings and encoder layers 1 to 12. The remaining encoder layers and
+ the whole decoder were removed. The kept weights are stored in bfloat16 with
+ shortened tensor names.
+- `config.json` was rewritten to describe the trimmed encoder and to record the
+ source repository and revision.
+- The tokenizer files are unchanged.
+
+## Use restrictions
+
+Use of these files is subject to the use restrictions in Section 3.2 of the
+Gemma Terms of Use below. You must not use them:
+
+- for the restricted uses set forth in the Gemma Prohibited Use Policy at
+ [gemma.ai/resources/prohibited_use_policy](https://gemma.ai/resources/prohibited_use_policy),
+ which the terms incorporate by reference; or
+- in violation of applicable laws and regulations.
+
+If you distribute these files or a model derived from them, the Gemma Terms of
+Use require you to pass on the same restrictions, a copy of the terms, the
+notice at the top of this file and a notice of any modifications you make. See
+Section 3.1 below.
+
+## Gemma Terms of Use
+
+The text below is a copy of the terms as published at
+[gemma.ai/resources/terms](https://gemma.ai/resources/terms), retrieved on
+18 November 2026. The published page is the authoritative version.
+
+---
+
+Last modified: April 1, 2026
+
+By using, reproducing, modifying, distributing, performing or displaying any portion or element of Gemma, Model Derivatives including via any Hosted Service, (each as defined below) (collectively, the "Gemma Services") or otherwise accepting the terms of this Agreement, you agree to be bound by this Agreement.
+
+### Section 1: DEFINITIONS
+
+#### 1.1 Definitions
+
+(a) "Agreement" or "Gemma Terms of Use" means these terms and conditions that govern the use, reproduction, Distribution or modification of the Gemma Services and any terms and conditions incorporated by reference.
+
+(b) "Distribution" or "Distribute" means any transmission, publication, or other sharing of Gemma or Model Derivatives to a third party, including by providing or making Gemma or its functionality available as a hosted service via API, web access, or any other electronic or remote means ("Hosted Service").
+
+(c) "Gemma" means the set of machine learning language models, trained model weights and parameters identified in the Appendix, regardless of the source that you obtained it from.
+
+(d) "Google" means Google LLC.
+
+(e) "Model Derivatives" means all (i) modifications to Gemma, (ii) works based on Gemma, or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Gemma, to that model in order to cause that model to perform similarly to Gemma, including distillation methods that use intermediate data representations or methods based on the generation of synthetic data Outputs by Gemma for training that model. For clarity, Outputs are not deemed Model Derivatives.
+
+(f) "Output" means the information content output of Gemma or a Model Derivative that results from operating or otherwise using Gemma or the Model Derivative, including via a Hosted Service.
+
+#### 1.2
+
+As used in this Agreement, "including" means "including without limitation".
+
+### Section 2: ELIGIBILITY AND USAGE
+
+#### 2.1 Eligibility
+
+You represent and warrant that you have the legal capacity to enter into this Agreement (including being of sufficient age of consent). If you are accessing or using any of the Gemma Services for or on behalf of a legal entity, (a) you are entering into this Agreement on behalf of yourself and that legal entity, (b) you represent and warrant that you have the authority to act on behalf of and bind that entity to this Agreement and (c) references to "you" or "your" in the remainder of this Agreement refers to both you (as an individual) and that entity.
+
+#### 2.2 Use
+
+You may use, reproduce, modify, Distribute, perform or display any of the Gemma Services only in accordance with the terms of this Agreement, and must not violate (or encourage or permit anyone else to violate) any term of this Agreement.
+
+### Section 3: DISTRIBUTION AND RESTRICTIONS
+
+#### 3.1 Distribution and Redistribution
+
+You may reproduce or Distribute copies of Gemma or Model Derivatives if you meet all of the following conditions:
+
+1. You must include the use restrictions referenced in Section 3.2 as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Gemma or Model Derivatives and you must provide notice to subsequent users you Distribute to that Gemma or Model Derivatives are subject to the use restrictions in Section 3.2.
+2. You must provide all third party recipients of Gemma or Model Derivatives a copy of this Agreement.
+3. You must cause any modified files to carry prominent notices stating that you modified the files.
+4. All Distributions (other than through a Hosted Service) must be accompanied by a "Notice" text file that contains the following notice: "Gemma is provided under and subject to the Gemma Terms of Use found at gemma.ai/resources/terms".
+
+You may add your own intellectual property statement to your modifications and, except as set forth in this Section, may provide additional or different terms and conditions for use, reproduction, or Distribution of your modifications, or for any such Model Derivatives as a whole, provided your use, reproduction, modification, Distribution, performance, and display of Gemma otherwise complies with the terms and conditions of this Agreement. Any additional or different terms and conditions you impose must not conflict with the terms of this Agreement.
+
+#### 3.2 Use Restrictions
+
+You must not use any of the Gemma Services:
+
+1. for the restricted uses set forth in the Gemma Prohibited Use Policy at gemma.ai/resources/prohibited_use_policy ("Prohibited Use Policy"), which is hereby incorporated by reference into this Agreement; or
+2. in violation of applicable laws and regulations.
+
+To the maximum extent permitted by law, Google reserves the right to restrict (remotely or otherwise) usage of any of the Gemma Services that Google reasonably believes are in violation of this Agreement.
+
+#### 3.3 Generated Output
+
+Google claims no rights in Outputs you generate using Gemma. You and your users are solely responsible for Outputs and their subsequent uses.
+
+### Section 4: ADDITIONAL PROVISIONS
+
+#### 4.1 Updates
+
+Google may update Gemma from time to time.
+
+#### 4.2 Trademarks
+
+Nothing in this Agreement grants you any rights to use Google's trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between you and Google. Google reserves any rights not expressly granted herein.
+
+#### 4.3 DISCLAIMER OF WARRANTY
+
+UNLESS REQUIRED BY APPLICABLE LAW, THE GEMMA SERVICES, AND OUTPUTS, ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE GEMMA SERVICES OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR USE OR DISTRIBUTION OF ANY OF THE GEMMA SERVICES OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.
+
+#### 4.4 LIMITATION OF LIABILITY
+
+TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY, CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW, SHALL GOOGLE OR ITS AFFILIATES BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO, ANY OF THE GEMMA SERVICES OR OUTPUTS EVEN IF GOOGLE OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+#### 4.5 Term, Termination, and Survival
+
+The term of this Agreement will commence upon your acceptance of this Agreement (including acceptance by your use, modification, or Distribution, reproduction, performance or display of any portion or element of the Gemma Services) and will continue in full force and effect until terminated in accordance with the terms of this Agreement. Google may terminate this Agreement if you are in breach of any term of this Agreement. Upon termination of this Agreement, you must delete and cease use and Distribution of all copies of Gemma and Model Derivatives in your possession or control. Sections 1, 2.1, 3.3, 4.2 to 4.9 shall survive the termination of this Agreement.
+
+#### 4.6 Governing Law and Jurisdiction
+
+This Agreement will be governed by the laws of the State of California without regard to choice of law principles. The UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The state and federal courts of Santa Clara County, California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
+
+#### 4.7 Severability
+
+If any provision of this Agreement is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
+
+#### 4.8 Entire Agreement
+
+This Agreement states all the terms agreed between the parties and supersedes all other agreements between the parties as of the date of acceptance relating to its subject matter.
+
+#### 4.9 No Waiver
+
+Google will not be treated as having waived any rights by not exercising (or delaying the exercise of) any rights under this Agreement.
+
+### Appendix
+
+- Gemma 1
+- Gemma 1.1
+- Gemma 2
+- Gemma 3
+- Gemma 3n
+- FunctionGemma
+- EmbeddingGemma
+- PaliGemma
+- PaliGemma 2
+- ShieldGemma
+- ShieldGemma 2
+- CodeGemma
+- CodeGemma 1.1
+- Gemma 2 JPN
+- DataGemma RIG
+- DataGemma RAG
+- RecurrentGemma
+- Gemma Scope
+- Gemma-APS
+- T5Gemma
+- VaultGemma
+- FunctionGemma
+- T5Gemma 2
+- TranslateGemma
diff --git a/text_encoder/NOTICE b/text_encoder/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..8a823c4c8f39e948dcf06ceb707890f38b631644
--- /dev/null
+++ b/text_encoder/NOTICE
@@ -0,0 +1,9 @@
+Gemma is provided under and subject to the Gemma Terms of Use found at
+gemma.ai/resources/terms
+
+The files in this folder are a modified copy of part of
+google/t5gemma-2-270m-270m (revision
+7c38f16641f455ef0685b18431faf1b17722d5a1). Data Archetype modified them in
+November 2026: only the tokenizer, the token embeddings and encoder layers
+1 to 12 are kept, and the weights are stored in bfloat16. See
+LICENSE-GEMMA.md in this folder for the terms and the use restrictions.
diff --git a/text_encoder/config.json b/text_encoder/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..5f0223e97f7e07cdaf470d3711f72bfa7737164e
--- /dev/null
+++ b/text_encoder/config.json
@@ -0,0 +1,46 @@
+{
+ "vocab_size": 262144,
+ "hidden_size": 640,
+ "intermediate_size": 2048,
+ "num_attention_heads": 4,
+ "num_key_value_heads": 1,
+ "head_dim": 256,
+ "query_pre_attn_scalar": 256.0,
+ "rms_norm_eps": 1e-06,
+ "sliding_window": 512,
+ "layer_types": [
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention"
+ ],
+ "sliding_rope": {
+ "theta": 10000.0,
+ "rope_type": "default",
+ "factor": 1.0
+ },
+ "full_rope": {
+ "theta": 1000000.0,
+ "rope_type": "linear",
+ "factor": 8.0
+ },
+ "embed_scale": 25.298221281347036,
+ "eoi_token_index": 256000,
+ "tap_layers": [
+ 2,
+ 6,
+ 12
+ ],
+ "dtype": "bfloat16",
+ "source_repository": "google/t5gemma-2-270m-270m",
+ "source_revision": "7c38f16641f455ef0685b18431faf1b17722d5a1",
+ "source_layers_used": "token embeddings and encoder layers 1-12 of 18"
+}
diff --git a/text_encoder/model.safetensors b/text_encoder/model.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..578d6836331e7335d2629901f2fcf05b4715e418
--- /dev/null
+++ b/text_encoder/model.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5ac6e442a6e35df2fc2bf3dae6eb4bd8cdd6995e23742df85cd6688469f5aa70
+size 469329848
diff --git a/text_encoder/special_tokens_map.json b/text_encoder/special_tokens_map.json
new file mode 100644
index 0000000000000000000000000000000000000000..1a6193244714d3d78be48666cb02cdbfac62ad86
--- /dev/null
+++ b/text_encoder/special_tokens_map.json
@@ -0,0 +1,33 @@
+{
+ "boi_token": "",
+ "bos_token": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ },
+ "eoi_token": "",
+ "eos_token": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ },
+ "image_token": "",
+ "pad_token": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ },
+ "unk_token": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ }
+}
diff --git a/text_encoder/tokenizer.json b/text_encoder/tokenizer.json
new file mode 100644
index 0000000000000000000000000000000000000000..8f149029a8e2a286d3244e2ffbfbbf29777d482b
--- /dev/null
+++ b/text_encoder/tokenizer.json
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4c76318660cc87c3029535cc1596717df67132d231ce4ecf088ba2a8ec07c098
+size 33384388
diff --git a/text_encoder/tokenizer_config.json b/text_encoder/tokenizer_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..b5986b139db26d501be78ce7f6ad853d52291c16
--- /dev/null
+++ b/text_encoder/tokenizer_config.json
@@ -0,0 +1,28 @@
+{
+ "add_bos_token": true,
+ "add_eos_token": false,
+ "additional_special_tokens": null,
+ "backend": "tokenizers",
+ "boi_token": "",
+ "bos_token": "",
+ "clean_up_tokenization_spaces": false,
+ "eoi_token": "",
+ "eos_token": "",
+ "image_token": "",
+ "is_local": true,
+ "mask_token": "",
+ "model_max_length": 1000000000000000019884624838656,
+ "model_specific_special_tokens": {
+ "boi_token": "",
+ "eoi_token": "",
+ "image_token": ""
+ },
+ "pad_token": "",
+ "padding_side": "right",
+ "processor_class": "Gemma3Processor",
+ "sp_model_kwargs": null,
+ "spaces_between_special_tokens": false,
+ "tokenizer_class": "GemmaTokenizer",
+ "unk_token": "",
+ "use_default_system_prompt": false
+}