diff --git a/README.md b/README.md index f36a435e8d..c3aa85b26a 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ API and command-line option may change frequently.*** - [Ming-Image Design](./docs/models/ming_image.md) - [PixArt](./docs/models/pixart.md) - [Iris-3B](./docs/models/iris.md) + - [RD Flow 64](./docs/models/rd_flow_64.md) - [Image Edit Models](./docs/guides/edit.md) - [FLUX.1-Kontext-dev](./docs/models/kontext.md) - [Qwen Image Edit series](./docs/models/qwen_image_edit.md) diff --git a/assets/rd_flow_64/dgl_output.png b/assets/rd_flow_64/dgl_output.png new file mode 100644 index 0000000000..16caa49b61 Binary files /dev/null and b/assets/rd_flow_64/dgl_output.png differ diff --git a/assets/rd_flow_64/dgl_palette.png b/assets/rd_flow_64/dgl_palette.png new file mode 100644 index 0000000000..cd91ff0267 Binary files /dev/null and b/assets/rd_flow_64/dgl_palette.png differ diff --git a/assets/rd_flow_64/dgl_tokens.png b/assets/rd_flow_64/dgl_tokens.png new file mode 100644 index 0000000000..8ec0b90df0 Binary files /dev/null and b/assets/rd_flow_64/dgl_tokens.png differ diff --git a/assets/rd_flow_64/lighthouse.png b/assets/rd_flow_64/lighthouse.png new file mode 100644 index 0000000000..9d7baa0318 Binary files /dev/null and b/assets/rd_flow_64/lighthouse.png differ diff --git a/assets/rd_flow_64/locked_palette.png b/assets/rd_flow_64/locked_palette.png new file mode 100644 index 0000000000..56e62788ef Binary files /dev/null and b/assets/rd_flow_64/locked_palette.png differ diff --git a/assets/rd_flow_64/locked_palette_strip.png b/assets/rd_flow_64/locked_palette_strip.png new file mode 100644 index 0000000000..5421e37fb0 Binary files /dev/null and b/assets/rd_flow_64/locked_palette_strip.png differ diff --git a/assets/rd_flow_64/max_colours_8.png b/assets/rd_flow_64/max_colours_8.png new file mode 100644 index 0000000000..75f5f33bab Binary files /dev/null and b/assets/rd_flow_64/max_colours_8.png differ diff --git a/assets/rd_flow_64/opaque.png b/assets/rd_flow_64/opaque.png new file mode 100644 index 0000000000..bbd9856e2c Binary files /dev/null and b/assets/rd_flow_64/opaque.png differ diff --git a/assets/rd_flow_64/sprite.png b/assets/rd_flow_64/sprite.png new file mode 100644 index 0000000000..16caa49b61 Binary files /dev/null and b/assets/rd_flow_64/sprite.png differ diff --git a/docs/dgl-builtins.md b/docs/dgl-builtins.md index c9a830bc14..26647d943c 100644 --- a/docs/dgl-builtins.md +++ b/docs/dgl-builtins.md @@ -75,6 +75,7 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn | `pulid::apply` | `condition: dict`, `pulid: pulid`, `embedding: tensor`, `strength?: number = 1`, `start_sigma?: number`, `end_sigma?: number` | same type as `condition`
`pulid: pulid_bindings` | | `pulid::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `pulid` | | `pulid::load_embedding` | `path: string` | `tensor` | +| `rd_flow::sample` | `start: tensor`, `predict: predictor`, `steps?: int = 16`, `guidance?: number = 4.0`, `interval_lo?: number = 0.0`, `interval_hi?: number = 0.9`, `shift?: number = 3.0`, `palette_at?: number = 0.6`, `pointer_from?: number = 0.35`, `commit_from?: number = 0.55`, `commit_thresh?: number = 0.9`, `max_colours?: int = 64`, `merge?: number = 0.05`, `background?: string = "transparent"`, `source?: int = 6`, `palette?: string = ""` | `dict`
`image: tensor`
`palette: tensor`
`tokens: tensor` | | `regions::crop` | `image: tensor`, `regions: dict` | `list` | | `regions::from_boxes` | `width: int`, `height: int`, `boxes: any` | `dict`
`boxes: tensor`
`height: int`
`width: int` | | `regions::paste` | `background: tensor`, `foregrounds: list`, `regions: dict` | `tensor` | @@ -213,3 +214,4 @@ Pass the ID as the component loader's `family` argument. The default is `"auto"` | `minimax_h3_image` | MiniMax-H3-Image | | `relayvsr` | RelayVSR | | `seedvr2` | SeedVR2 | +| `rd_flow_64` | RD Flow 64 | diff --git a/docs/dgl/README.md b/docs/dgl/README.md index 2f25476033..bf6cadb8db 100644 --- a/docs/dgl/README.md +++ b/docs/dgl/README.md @@ -73,6 +73,7 @@ and [NumPy tensor files](../dgl.md#tensor-files). | [Qwen Image](../models/qwen_image.md) | [Text to image](qwen_image/qwen-image-txt2img.dgl) | | [Qwen Image 2.1](../models/qwen_image_2.1.md) | [Text to image](qwen_image_2.1/qwen-image-2-1-txt2img.dgl) · [Image editing](qwen_image_2.1/qwen-image-2-1-edit.dgl) | | [Qwen Image Edit](../models/qwen_image_edit.md) | [Qwen Image Edit](qwen_image_edit/qwen-image-edit.dgl) · [Qwen Image Edit 2509](qwen_image_edit/qwen-image-edit-2509.dgl) · [Qwen Image Edit 2511](qwen_image_edit/qwen-image-edit-2511.dgl) | +| [RD Flow 64](../models/rd_flow_64.md) | [Text to image](rd_flow_64/rd-flow-64-txt2img.dgl) | | [Stable Diffusion – generation](../models/sd.md) | [SD 1.4](sd/sd1-4-txt2img.dgl) · [SD 1.5](sd/sd1-5-txt2img.dgl) · [SDXL](sd/sdxl-txt2img.dgl) · [NitroFusion](sd/nitrosd-realism-nitrofusion.dgl) | | [Stable Diffusion – image conditioning](../models/sd.md) | [SD 1.4 image to image](sd/sd1-4-img2img.dgl) · [SD 1.5 ControlNet](sd/sd1-5-controlnet.dgl) · [SD 1.5 inpainting](sd/sd1-5-inpainting.dgl) | | [Stable Diffusion 3](../models/sd3.md) | [SD 3.5 Large text to image](sd3/sd3-5-large-txt2img.dgl) | diff --git a/docs/dgl/rd_flow_64/rd-flow-64-txt2img.dgl b/docs/dgl/rd_flow_64/rd-flow-64-txt2img.dgl new file mode 100644 index 0000000000..3d71d2c210 --- /dev/null +++ b/docs/dgl/rd_flow_64/rd-flow-64-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/rd_flow_64.md — Text-to-image + +var { + model_path = "../models/rd-flow-64/rd-flow-64.safetensors" + text_path = "../models/rd-flow-64/text_encoder_model.safetensors" + tokenizer_path = "../models/rd-flow-64/text_encoder/tokenizer.json" + + output_path = "rd_flow_64.png" + palette_path = "rd_flow_64_palette.npy" + tokens_path = "rd_flow_64_tokens.npy" + + prompt = "a small red rocket with a round blue window, one tall pine, gradient dusk sky" + + seed = 1 + rng_type = "cpu" + width = 64 + height = 64 + + steps = 8 + cfg_scale = 4.0 +} + +fn main() { + model = load_dit(model_path, family = "rd_flow_64") + text = load_text_encoder(text_path, family = "rd_flow_64", tokenizer = tokenizer_path) + + condition = encode_prompt(text, prompt, width = width, height = height) + # The noise sprite is [4, width, height, 1]: ggml fills the fastest axis first, + # so a fixed seed hands the model the same noise as the reference's + # randn((64, 64, 4)), which is channel-last. + noise = tensor::randn_like(tensor::zeros([4, width, height, 1]), rng = make_rng(rng_type, seed = seed)) + # rd_flow::sample owns the whole drawing: its shifted schedule, guidance (it + # drops the prompt rows, because the model has no negative prompt), the palette + # it extracts partway through, and the per-pixel palette token it commits. + drawing = rd_flow::sample(noise, predict = predictor(model, condition), steps = steps, guidance = cfg_scale) + image::save(output_path, image::to_u8(drawing.image)) + # The palette and the pixel map are the lossless form of the sprite: re-decode + # them for another size, or save the swatches. + tensor::save(palette_path, drawing.palette) + tensor::save(tokens_path, drawing.tokens) + return {image = drawing.image, palette = drawing.palette, tokens = drawing.tokens} +} diff --git a/docs/models/README.md b/docs/models/README.md index 06820fac5b..03db42df4b 100644 --- a/docs/models/README.md +++ b/docs/models/README.md @@ -75,6 +75,7 @@ variant; a VAE or TAE selection must match that model. - [PixArt](pixart.md) - [Qwen Image](qwen_image.md) - [Qwen Image 2.1](qwen_image_2.1.md) +- [RD Flow 64](rd_flow_64.md) - [SeFi-Image](sefi_image.md) - [SenseNova U1.5](sensenova_u1.md) - [Stable Diffusion 1.x, 2.x, and SDXL, including Turbo variants](sd.md) diff --git a/docs/models/rd_flow_64.md b/docs/models/rd_flow_64.md new file mode 100644 index 0000000000..575d8e8ebd --- /dev/null +++ b/docs/models/rd_flow_64.md @@ -0,0 +1,313 @@ +# RD Flow 64 + +RD Flow 64 draws 64 x 64 pixel-art sprites in one pass: a 271M pixel-space flow +model plus the first 27 layers of Qwen3-VL-4B as the prompt reader. It returns a +palette and one palette index per pixel, so the output is an exact-colour RGBA +sprite rather than a decoded latent; the background stays transparent by default. + +## Model files + +| Component | Weights and downloads | CLI option | Requirement | +| --- | --- | --- | --- | +| RD Flow 64 drawing model | [Safetensors](https://huggingface.co/Retro-Diffusion/rd-flow-64) (`rd-flow-64.safetensors`) | `--model` | Required | +| Qwen3-VL prompt reader (layers 0-26) | [Safetensors](https://huggingface.co/Retro-Diffusion/rd-flow-64) (`text_encoder_model.safetensors`) | `--llm` | Required | +| Qwen3-VL tokenizer | [tokenizer.json](https://huggingface.co/Retro-Diffusion/rd-flow-64/tree/main/text_encoder) | `--tokenizer` | Required | + +The prompt reader ships trimmed: `text_encoder_model.safetensors` holds +`embed_tokens`, decoder layers 0-26 and the final norm, and the caption is +encoded as plain tokens with no chat template. + +By default the prompt reader loads at f16 (5.9 GiB) and the drawing model at +f16 (0.5 GiB); `--type f32` raises them to 11.6 GiB and 1.0 GiB. + +Any weight load type works, including the f16 default and quantized GGUF. The +port keeps activations in f32 regardless, so f16 weights do not overflow the way +`model.half()` does in the Python reference; only the stored weights lose +precision. **For the most accurate results, load the drawing model at bf16 or +f32** (`--type bf16` or `--type f32`). f16 and quantized weights still draw, but +the slightly different weights shift the extracted palette, so a handful of +pixels land on neighbouring colours (about 290 of the 4096 at f16, fewer at f32); +see the caveat under [Notes and limitations](#notes-and-limitations). + +## Usage + +### Web UI + +Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the +server, then select the recipe below. Fill the component slots and click +**Load models**. Use the files and compatibility requirements in +[Model files](#model-files). + +| Recipe | Component slots | +| --- | --- | +| RD Flow 64 (`rd-flow-64`) | `diffusion_model`, `llm`, `tokenizer` | + +Slot IDs correspond to CLI component options: `diffusion_model` uses `--model`, +`llm` uses `--llm`, and `tokenizer` uses `--tokenizer`. The canvas is fixed at +64 x 64, and img2img, masking and preview are disabled for this recipe. The +palette, background and other sampler settings in [Options](#options) are +available through the DGL editor. + +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/rd_flow_64/rd-flow-64-txt2img.dgl) | Draw a sprite and save its image, palette and per-pixel token map. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from the +build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\rd_flow_64\rd-flow-64-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/rd_flow_64/rd-flow-64-txt2img.dgl +``` + +Add `--check` to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths and +the server's file-access rules. + +Pixel-space generation runs through the `image_pixel` program, and the drawing +loop is the `rd_flow::sample` built-in (see [DGL +built-ins](../dgl-builtins.md)). It owns its shifted schedule, applies guidance +by dropping the prompt rows (the model has no negative prompt), extracts the +palette partway through the run, then commits pointer-head palette tokens per +pixel. It returns a dict: `image` (RGBA float pixels in 0..1), `palette` (the +colours it drew with, three values per slot) and `tokens` (the palette slot each +pixel uses, 0 for transparent). The [worked program](../dgl/rd_flow_64/rd-flow-64-txt2img.dgl) +saves all three. Beyond `steps` and `guidance` it +takes the reference defaults: `interval_lo` / `interval_hi` (guidance window), +`shift`, `palette_at`, `pointer_from`, `commit_from`, `commit_thresh`, +`max_colours`, `merge`, `background` (`transparent` or `opaque`) and `source`. +`palette` locks every pixel to a comma-separated list of `#rrggbb` colours +instead of letting the model choose one. + +Write the noise as `[4, width, height, 1]`, not as a pixel tensor: + +```dgl +noise = tensor::randn_like(tensor::zeros([4, width, height, 1]), rng = sampler_rng) +``` + +ggml fills the fastest axis first, so that order gives a fixed seed the same +noise the reference's `randn((64, 64, 4))` does. A `[width, height, 4, 1]` pixel +tensor holds the same draws with the channels apart, and `rd_flow::sample` +accepts either; only which pixel gets which draw changes. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). +The canvas is fixed at 64 x 64; `--width` / `--height` are ignored. `--steps` +and `--cfg-scale` map to the sampler's steps and guidance, and the model-specific +settings are in [Options](#options). The prompt is a caption, not a keyword list: +subjects, counts, layout, outline weight and palette intent all read through. + +Every image below is the 64 x 64 result scaled x4 with nearest neighbour, from a +CPU build with `--rng cpu` and `--cfg-scale 4`; the seed and steps are in each +command. + +#### A caption, not a keyword list + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe ` + --model ..\models\rd-flow-64\rd-flow-64.safetensors ` + --llm ..\models\rd-flow-64\text_encoder_model.safetensors ` + --tokenizer ..\models\rd-flow-64\text_encoder\tokenizer.json ` + --prompt "A small glass flask of red health potion stands upright, centred in the frame. The flask has a rounded, bulbous body that tapers upward into a narrow neck, topped with a short cork stopper in warm tan-brown. [...] The background is transparent. A dark outline surrounds the flask, with soft shading and a light source from the upper left, giving a saturated palette of red, pale blue-white, tan and dark brown." ` + --seed 5 --steps 16 --cfg-scale 4 --rng cpu -o flask.png +``` + +**Linux/macOS** + +```sh +./bin/sd-cli \ + --model ../models/rd-flow-64/rd-flow-64.safetensors \ + --llm ../models/rd-flow-64/text_encoder_model.safetensors \ + --tokenizer ../models/rd-flow-64/text_encoder/tokenizer.json \ + --prompt "A small glass flask of red health potion stands upright, centred in the frame. The flask has a rounded, bulbous body that tapers upward into a narrow neck, topped with a short cork stopper in warm tan-brown. [...] The background is transparent. A dark outline surrounds the flask, with soft shading and a light source from the upper left, giving a saturated palette of red, pale blue-white, tan and dark brown." \ + --seed 5 --steps 16 --cfg-scale 4 --rng cpu -o flask.png +``` + +RD Flow 64 sprite: a red health potion flask with a cork stopper + +The caption is the worked example from the reference's `PROMPTING.md` (about 190 +words, elided above): what the object is, its parts, the liquid level and +highlight, how much of the frame it fills, "The background is transparent", and +the palette intent last. Each of those reads through. Long captions with explicit +counts ("three gulls, one tall pine") are followed literally. + +A drawing is a palette plus one palette slot per pixel, and both are recoverable. +[The DGL example](../dgl/rd_flow_64/rd-flow-64-txt2img.dgl) saves them as tensors +for the same prompt and seed, and its sprite is byte-identical to the one above: + +| token map (grey = slot index) | the 37 colours it picked | +| --- | --- | +| per-pixel palette slot map of the flask sprite | the 37-colour palette the model extracted | + +#### Palette size + +The model picks its own palette, and `--rd-flow-max-colours` caps it. Same seed +as above, 8 slots instead of 64 (append these to the command): + +```sh + --seed 5 --steps 16 --rng cpu --rd-flow-max-colours 8 +``` + +the same flask drawn with at most 8 colours + +#### A palette you supply + +`--rd-flow-palette` locks every pixel to a fixed set of colours, from a list or +from a `.hex`/`.txt`/`.gpl`/`.pal` file (the reference's `--palette`). Describe +colours that exist in the palette you pass: + +```sh + --seed 5 --steps 16 --rng cpu \ + --rd-flow-palette "#e8d8c3,#c0392b,#7e1d14,#f0f4f8,#3f6f9c,#b07a3b,#4a3421,#1a1a1a" +``` + +| result | the palette it was given | +| --- | --- | +| flask sprite drawn from a locked eight-colour palette | the eight locked colours | + +The green it was offered went unused: the caption asked for red, tan and +blue-white. + +A locked palette can also come from a file: + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe ` + --model ..\models\rd-flow-64\rd-flow-64.safetensors ` + --llm ..\models\rd-flow-64\text_encoder_model.safetensors ` + --tokenizer ..\models\rd-flow-64\text_encoder\tokenizer.json ` + --prompt "a mossy stone bridge over a stream" ` + --rd-flow-palette ..\models\rd-flow-64\palette.gpl ` + --rd-flow-background opaque ` + --seed 1 --rng cpu -o bridge.png +``` + +**Linux/macOS** + +```sh +./bin/sd-cli \ + --model ../models/rd-flow-64/rd-flow-64.safetensors \ + --llm ../models/rd-flow-64/text_encoder_model.safetensors \ + --tokenizer ../models/rd-flow-64/text_encoder/tokenizer.json \ + --prompt "a mossy stone bridge over a stream" \ + --rd-flow-palette ../models/rd-flow-64/palette.gpl \ + --rd-flow-background opaque \ + --seed 1 --rng cpu -o bridge.png +``` + +#### A full-frame scene instead of a sprite + +`--rd-flow-background opaque` is the reference's `--opaque`: the caption describes +a scene edge to edge rather than an object with a margin. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe ` + --model ..\models\rd-flow-64\rd-flow-64.safetensors ` + --llm ..\models\rd-flow-64\text_encoder_model.safetensors ` + --tokenizer ..\models\rd-flow-64\text_encoder\tokenizer.json ` + --prompt "A landscape scene centers on a winding dirt path running through an autumn forest. [...] The view is a wide scene with the path centered and the trees framing both edges. The rendering uses black outlines, flat color fills with simple two-tone shading, and a warm autumn palette of orange, red, yellow, brown, and pale blue." ` + --seed 2 --steps 16 --rng cpu --rd-flow-background opaque -o path.png +``` + +**Linux/macOS** + +```sh +./bin/sd-cli \ + --model ../models/rd-flow-64/rd-flow-64.safetensors \ + --llm ../models/rd-flow-64/text_encoder_model.safetensors \ + --tokenizer ../models/rd-flow-64/text_encoder/tokenizer.json \ + --prompt "A landscape scene centers on a winding dirt path running through an autumn forest. [...] The view is a wide scene with the path centered and the trees framing both edges. The rendering uses black outlines, flat color fills with simple two-tone shading, and a warm autumn palette of orange, red, yellow, brown, and pale blue." \ + --seed 2 --steps 16 --rng cpu --rd-flow-background opaque -o path.png +``` + +RD Flow 64 opaque output: an autumn forest path + +#### Counts in a short caption + +A twelve-word caption is far below the 120-200 words the model likes, but +explicit counts still read: a lighthouse, a cliff, a gradient sky, one pine and +three gulls. + +```sh + --prompt "a lighthouse on a cliff at dusk; three gulls, one tall pine, gradient sky" \ + --seed 7 --steps 16 --rng cpu +``` + +RD Flow 64 output from a short caption with explicit counts + +## Options + +`--steps` and `--cfg-scale` are the reference's steps and guidance. The remaining +sampler knobs the reference draws with are model-specific CLI options: + +| Option | Default | Meaning | +| --- | --- | --- | +| `--rd-flow-palette` | empty | Lock every pixel to these colours: a comma-separated list of `#rrggbb`, or a palette file (`.hex`, `.txt`, `.gpl`, `.pal`). Empty lets the model choose its own. | +| `--rd-flow-background` | `transparent` | `opaque` asks for a full-frame picture instead of a sprite. It is a conditioning token, not a guarantee: the model can still leave pixels on the transparent slot. | +| `--rd-flow-shift` | `3` | Schedule shift; higher spends more steps at the noisy end. | +| `--rd-flow-palette-at` | `0.6` | The `t` at which the drawing's palette is extracted. | +| `--rd-flow-max-colours` | `64` | Palette size. | +| `--rd-flow-merge` | `0.05` | OKLab distance under which two extracted colours become one slot. | + +The pointer head windows (`interval_lo` / `interval_hi`, `pointer_from`, +`commit_from`, `commit_thresh`) and the `source` token keep their reference +values; set them in a [DGL](#dgl) program if you need them. + +## Notes and limitations + +- The canvas is fixed at 64 x 64; `--width` / `--height` are ignored. img2img, + masking and preview are not supported. +- Any weight load type works. The graph runs in f32 whatever the weights are, so + f16 (the default) and quantized GGUF draw without the fp16 activation overflow + that breaks the Python reference's `model.half()`. bf16 and f32 are the most + accurate; lower-precision weights shift the extracted palette, so some pixels + land on a neighbouring colour (about 290 of 4096 at f16, fewer at f32). The + tokens the model draws are unchanged; only the colours they point at move. + Load bf16/f32 (`--type bf16` / `--type f32`) when exact colours matter, f16 or + quantized when memory does. +- Sprites come back with a transparent background (`background = "transparent"`); + parts of a scene such as skies still get filled with palette colours. +- Sampling is chaotic at this size: two different RNG streams give different + drawings for the same prompt and seed, while the same stream reproduces + exactly. +- Through the API, `--rng cpu` plus a `[4, width, height, 1]` noise tensor gives + a seed the same noise the reference gives it, and the drawing then matches the + reference sprite for sprite: the same pixels fill in the same places, and the + palette differs only where rounding moved a colour across a merge threshold + (weights at f16 shift about 290 of the 4096 pixels by a few RGB steps, f32 by + fewer and by less). +- The prompt reader takes the caption as raw tokens, capped at 512 of them: a + longer caption is cut from the end, with no chat template and no re-ordering. +- One seed reproduces exactly, on CPU and on Vulkan alike: repeated runs at one + seed give pixel-identical sprites. What can differ between two otherwise + identical runs is which kernels were chosen, not what they compute. On CPU the + attention and convolution paths follow fixed rules, so CPU reproduces by + construction. On Vulkan, `--flash-attn auto` and `--conv-direct auto` time + both paths and take the faster one by a 5% margin, and fall back to off when + the probe cannot run at all (under 128 MiB free VRAM at model load). A run + that lands on the other path draws a different picture rather than a slightly + altered one: on a GPU, `--flash-attn on` against `off` moves every + pixel at 16 steps, and a few hundred to a few thousand at 1 to 8 steps. Pin + `--flash-attn` and `--conv-direct` when a run has to match a saved sample. + The samples above are all CPU runs, so the commands reproduce them. +- `--prompt-file` passes the file through as written, trailing newline included, + and that one extra token changes the drawing (199 of 4096 pixels on the flask + caption above). An inline `--prompt` and the same text without the newline are + not the same caption. \ No newline at end of file diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 9d9ad70882..503420e19e 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -1125,6 +1125,16 @@ ArgOptions SDGenerationParams::get_options() { "Also accepted: hed, softedge, pidi, ted (scribble); lineart, anime_lineart, mlsd (canny); seg (segment); inpaint, outpaint (repaint)", 0, &control_type}, + {"", + "--rd-flow-palette", + "RD Flow 64: draw with every pixel locked to a palette; comma-separated #rrggbb colours, or a palette file (.hex, .txt, .gpl, .pal)", + 0, + &rd_flow_palette}, + {"", + "--rd-flow-background", + "RD Flow 64: \"transparent\" sprite (default) or \"opaque\" full-frame picture", + 0, + &rd_flow_background}, {"", "--extra-sample-args", "extra sampler/scheduler/guidance args, key=value list. CFG supports guidance_schedule; APG supports apg_eta, apg_momentum, apg_norm_threshold, apg_norm_threshold_smoothing; lcm supports noise_clip_std, noise_scale_start, noise_scale_end; flux supports base_shift, max_shift; ltx2 supports max_shift, base_shift, stretch, terminal; euler_ge supports gamma; beta scheduler supports alpha, beta; logit_normal supports mu, std, logsnr_min, logsnr_max, resolution_aware; llada_image supports uniform; lms supports lms_max_order, lms_shift, lms_divisions; noise-injecting samplers support noise_sampler with value iid (default except for dpm++2m_sde_bt) or brownian_tree; brownian_tree_rng supports cpu (default), cuda, std_default or sampler_rng", @@ -1167,6 +1177,10 @@ ArgOptions SDGenerationParams::get_options() { "--qwen-image-layers", "number of Qwen Image Layered layers; latent/output count is layers + 1 (default: 3)", &qwen_image_layers}, + {"", + "--rd-flow-max-colours", + "RD Flow 64: maximum palette size (default: 64)", + &rd_flow_max_colours}, {"", "--video-frames", "video frames; unset uses the library default", @@ -1250,6 +1264,18 @@ ArgOptions SDGenerationParams::get_options() { "--hires-denoising-strength", "highres fix second pass denoising strength (default: 0.7)", &hires_denoising_strength}, + {"", + "--rd-flow-shift", + "RD Flow 64: schedule shift; higher spends more steps on the noisy end (default: 3)", + &rd_flow_shift}, + {"", + "--rd-flow-merge", + "RD Flow 64: OKLab distance below which extracted colours merge (default: 0.05)", + &rd_flow_merge}, + {"", + "--rd-flow-palette-at", + "RD Flow 64: t where the drawing's palette is extracted (default: 0.6)", + &rd_flow_palette_at}, }; options.bool_options = { @@ -2040,6 +2066,12 @@ bool SDGenerationParams::from_json_str( load_if_exists("height", height); load_if_exists("batch_count", batch_count); load_if_exists("qwen_image_layers", qwen_image_layers); + load_if_exists("rd_flow_palette", rd_flow_palette); + load_if_exists("rd_flow_background", rd_flow_background); + load_if_exists("rd_flow_shift", rd_flow_shift); + load_if_exists("rd_flow_merge", rd_flow_merge); + load_if_exists("rd_flow_palette_at", rd_flow_palette_at); + load_if_exists("rd_flow_max_colours", rd_flow_max_colours); load_if_exists("video_frames", video_frames); load_if_exists("fps", fps); load_if_exists("upscale_repeats", upscale_repeats); @@ -2535,6 +2567,12 @@ SDOptPtr SDGenerationParams::to_image_opt() { opt.set_int("seed", seed); opt.set_int("batch_count", batch_count); opt.set_int("qwen_image_layers", qwen_image_layers); + opt.set_string("rd_flow_palette", rd_flow_palette); + opt.set_string("rd_flow_background", rd_flow_background); + opt.set_float("rd_flow_shift", rd_flow_shift); + opt.set_float("rd_flow_merge", rd_flow_merge); + opt.set_float("rd_flow_palette_at", rd_flow_palette_at); + opt.set_int("rd_flow_max_colours", rd_flow_max_colours); opt.set_image("control_image", control_image.get()); opt.set_float("control_strength", control_strength); opt.set_string("control_type", control_type); @@ -2710,6 +2748,12 @@ std::string SDGenerationParams::to_string() const { << " height: " << height << ",\n" << " batch_count: " << batch_count << ",\n" << " qwen_image_layers: " << qwen_image_layers << ",\n" + << " rd_flow_palette: \"" << rd_flow_palette << "\",\n" + << " rd_flow_background: \"" << rd_flow_background << "\",\n" + << " rd_flow_shift: " << rd_flow_shift << ",\n" + << " rd_flow_merge: " << rd_flow_merge << ",\n" + << " rd_flow_palette_at: " << rd_flow_palette_at << ",\n" + << " rd_flow_max_colours: " << rd_flow_max_colours << ",\n" << " init_image_path: \"" << init_image_path << "\",\n" << " end_image_path: \"" << end_image_path << "\",\n" << " mask_image_path: \"" << mask_image_path << "\",\n" diff --git a/examples/common/common.h b/examples/common/common.h index 509f6734ba..57b540893a 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -219,6 +219,12 @@ struct SDGenerationParams { std::optional height; std::optional batch_count; std::optional qwen_image_layers; + std::optional rd_flow_palette; + std::optional rd_flow_background; + std::optional rd_flow_shift; + std::optional rd_flow_merge; + std::optional rd_flow_palette_at; + std::optional rd_flow_max_colours; std::optional seed; std::optional strength; std::optional control_strength; diff --git a/examples/server/recipes/rd-flow-64.json b/examples/server/recipes/rd-flow-64.json new file mode 100644 index 0000000000..4052621e52 --- /dev/null +++ b/examples/server/recipes/rd-flow-64.json @@ -0,0 +1,41 @@ +{ + "schema_version": 1, + "id": "rd-flow-64", + "name": "RD Flow 64", + "size_multiple": 1, + "description": "Pixel-space sprite model: 64 x 64 RGBA output drawn from a palette, no VAE required. Non-commercial weights.", + "model_url": "https://huggingface.co/Retro-Diffusion/rd-flow-64", + "slots": [ + { + "id": "diffusion_model", + "required": true, + "label": "rd-flow-64.safetensors" + }, + { + "id": "llm", + "required": true, + "label": "Qwen3-VL Prompt Reader (layers 0-26)" + }, + { + "id": "tokenizer", + "required": true, + "label": "Qwen3-VL tokenizer.json" + } + ], + "defaults": { + "cfg_scale": 4, + "steps": 16, + "width": 64, + "height": 64, + "sampling_method": "euler" + }, + "disabled_features": [ + "img2img", + "init_image", + "mask_image", + "preview", + "vae_tiling", + "cache", + "cache_dit" + ] +} diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index 6dbb1e2e09..bb6073d9bd 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -99,6 +99,12 @@ static json make_img_gen_defaults_json(const SDGenerationParams& defaults, const {"seed", defaults.seed}, {"batch_count", defaults.batch_count}, {"qwen_image_layers", defaults.qwen_image_layers}, + {"rd_flow_palette", defaults.rd_flow_palette}, + {"rd_flow_background", defaults.rd_flow_background}, + {"rd_flow_shift", defaults.rd_flow_shift}, + {"rd_flow_merge", defaults.rd_flow_merge}, + {"rd_flow_palette_at", defaults.rd_flow_palette_at}, + {"rd_flow_max_colours", defaults.rd_flow_max_colours}, {"control_strength", defaults.control_strength}, {"control_type", defaults.control_type}, {"ip_adapter_strength", defaults.ip_adapter_strength}, diff --git a/src/api/generation_image.cpp b/src/api/generation_image.cpp index 8d2fa414a8..a6902ed8bd 100644 --- a/src/api/generation_image.cpp +++ b/src/api/generation_image.cpp @@ -171,6 +171,29 @@ namespace sd::api { request.fields["negative_condition"] = "controlled_negative"; } + // RD Flow 64 draws a fixed 64 x 64 sprite from noise; unsupported inputs are + // refused and the sampler knobs are passed through to rd_flow::sample. + static void rd_flow_program(GenerationTemplate& request) { + const auto& image = request.image; + if (image.init_image.data) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "RD Flow 64 draws from noise; init_image is not supported"); + if (bound_tensor(request.options, "mask_image")) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "RD Flow 64 does not support mask_image"); + if (image.control_image.data) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "RD Flow 64 does not support control_image"); + if (image.hires.enabled && text(image.hires.upscaler) != "none") + throw dgl::Error(SD_STATUS_UNSUPPORTED, "RD Flow 64 does not support hires fix; draw at 64 x 64 and scale separately"); + const auto background = text(image.rd_flow_background); + if (background != "transparent" && background != "opaque") + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "rd_flow_background must be \"transparent\" or \"opaque\""); + request.values["rd_flow_palette"] = text(image.rd_flow_palette); + request.values["rd_flow_background"] = background; + request.values["rd_flow_shift"] = image.rd_flow_shift; + request.values["rd_flow_merge"] = image.rd_flow_merge; + request.values["rd_flow_palette_at"] = image.rd_flow_palette_at; + request.values["rd_flow_max_colours"] = image.rd_flow_max_colours; + } + void prepare_image_program(GenerationTemplate& request) { const auto version = request.definition.version; const auto& settings = request.context.model.config.context; @@ -187,9 +210,16 @@ namespace sd::api { throw dgl::Error(SD_STATUS_UNSUPPORTED, "sample.guidance.img_cfg is not supported by this model with these inputs"); if (version != VERSION_QWEN_IMAGE_LAYERED && request.options && scalar_values(request.options).contains("qwen_image_layers")) throw dgl::Error(SD_STATUS_UNSUPPORTED, "qwen_image_layers requires Qwen Image Layered"); + if (!sd_version_is_rd_flow(version) && request.options) { + const auto provided = scalar_values(request.options); + for (const char* key : {"rd_flow_palette", "rd_flow_background", "rd_flow_shift", "rd_flow_merge", "rd_flow_palette_at", "rd_flow_max_colours"}) { + if (provided.contains(key)) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "RD Flow sampler options require RD Flow 64"); + } + } const bool image_guidance = (inpaint || sd_version_is_control(version) || (sd_version_is_unet_edit(version) && refs) || reference_guidance) && std::isfinite(image_scale) && image_scale != 1.f; request.flags = { - {"has_init", bool(request.image.init_image.data)}, {"has_mask", mask}, {"mask_stage", mask || inpaint}, {"references", refs}, {"unet_edit", sd_version_is_unet_edit(version)}, {"inpaint_model", inpaint}, {"flux_fill", version == VERSION_FLUX_FILL}, {"flex", version == VERSION_FLEX_2}, {"control_image", control}, {"native_control", native_control}, {"controlnet", control && !native_control}, {"z_control", control && sd_version_is_z_image(version)}, {"image_guidance", image_guidance}, {"minit2i", sd_version_is_minit2i(version)}, {"ming", version == VERSION_MING_IMAGE}, {"ideogram", sd_version_is_ideogram4(version)}, {"separate_negative_model", false}, {"sdxl_zero", sd_version_is_sdxl(version) && text(request.image.negative_prompt).empty() && prediction != EDM_V_PRED}, {"layered", version == VERSION_QWEN_IMAGE_LAYERED}, {"ph3", version == VERSION_P_H3_IMAGE}, {"h3_reference_noise", version == VERSION_MINIMAX_H3_IMAGE && refs}, {"custom_sigmas", request.image.sample_params.custom_sigmas_count > 0}}; + {"has_init", bool(request.image.init_image.data)}, {"has_mask", mask}, {"mask_stage", mask || inpaint}, {"references", refs}, {"unet_edit", sd_version_is_unet_edit(version)}, {"inpaint_model", inpaint}, {"flux_fill", version == VERSION_FLUX_FILL}, {"flex", version == VERSION_FLEX_2}, {"control_image", control}, {"native_control", native_control}, {"controlnet", control && !native_control}, {"z_control", control && sd_version_is_z_image(version)}, {"image_guidance", image_guidance}, {"minit2i", sd_version_is_minit2i(version)}, {"rd_flow", sd_version_is_rd_flow(version)}, {"ming", version == VERSION_MING_IMAGE}, {"ideogram", sd_version_is_ideogram4(version)}, {"separate_negative_model", false}, {"sdxl_zero", sd_version_is_sdxl(version) && text(request.image.negative_prompt).empty() && prediction != EDM_V_PRED}, {"layered", version == VERSION_QWEN_IMAGE_LAYERED}, {"ph3", version == VERSION_P_H3_IMAGE}, {"h3_reference_noise", version == VERSION_MINIMAX_H3_IMAGE && refs}, {"custom_sigmas", request.image.sample_params.custom_sigmas_count > 0}}; request.fields["predictor_core"] = request.fields["predictor_options"]; request.flags["raw_reference"] = version == VERSION_SD1_PIX2PIX; request.flags["reference_image_guidance"] = reference_guidance && image_guidance; @@ -221,10 +251,13 @@ namespace sd::api { request.fields["negative_model"] = "negative_model"; request.fields["schedule_predictor"] = "pos"; } - if (sd_version_is_pid(version) || sd_version_is_minit2i(version) || version == VERSION_IRIS) { + if (sd_version_is_pid(version) || sd_version_is_minit2i(version) || version == VERSION_IRIS || + sd_version_is_rd_flow(version)) { request.fields["entry"] = "image_pixel"; if (sd_version_is_pid(version) && !refs) throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "PiD requires a reference image"); + if (sd_version_is_rd_flow(version)) + rd_flow_program(request); } request.fields["unconditional_prompt_options"] = request.fields["negative_prompt_options"]; image_references(request); diff --git a/src/api/generation_program.cpp b/src/api/generation_program.cpp index 30cb658fc7..c493220d21 100644 --- a/src/api/generation_program.cpp +++ b/src/api/generation_program.cpp @@ -226,8 +226,12 @@ namespace sd::api { const auto vae_version = definition.traits.vae_format_override && !components.tae ? sd::vae::version_for_format(settings.vae_format, definition.version) : definition.version; const int scale = sd_version_is_pid(definition.version) ? 1 : sd::vae::spatial_scale(vae_version); const int multiple = scale * definition.geometry.diffusion_down_factor; - values["width"] = sd_version_is_minit2i(definition.version) ? 512 : sd::align_image_dimension(image.width, multiple); - values["height"] = sd_version_is_minit2i(definition.version) ? 512 : sd::align_image_dimension(image.height, multiple); + // Both draw in pixel space at one fixed size rather than adapting to the + // requested canvas. + values["width"] = sd_version_is_minit2i(definition.version) ? 512 + : sd_version_is_rd_flow(definition.version) ? 64 : sd::align_image_dimension(image.width, multiple); + values["height"] = sd_version_is_minit2i(definition.version) ? 512 + : sd_version_is_rd_flow(definition.version) ? 64 : sd::align_image_dimension(image.height, multiple); const auto axes = tiling_options(image.vae_tiling_params, image.circular_x, image.circular_y); auto schedule_options = nlohmann::json::object(); if (std::isfinite(image.sample_params.flow_shift)) diff --git a/src/api/options.cpp b/src/api/options.cpp index f056647adf..fb5edbf9f8 100644 --- a/src/api/options.cpp +++ b/src/api/options.cpp @@ -364,6 +364,13 @@ static void add_generation_specs(std::vector& specs) { img.choice("control_type", &sd::ImageConfig::control_type, str_to_sd_control_type, SD_CONTROL_TYPE_COUNT); img.image("mask_image", &sd::ImageConfig::mask_image); img.integer("qwen_image_layers", &sd::ImageConfig::qwen_image_layers, 0, INT32_MAX); + // RD Flow 64 only. + img.string("rd_flow_palette", &sd::ImageConfig::rd_flow_palette); + img.string("rd_flow_background", &sd::ImageConfig::rd_flow_background); + img.number("rd_flow_shift", &sd::ImageConfig::rd_flow_shift, 0.01, 100); + img.number("rd_flow_merge", &sd::ImageConfig::rd_flow_merge, 0, 1); + img.number("rd_flow_palette_at", &sd::ImageConfig::rd_flow_palette_at, 0, 1); + img.integer("rd_flow_max_colours", &sd::ImageConfig::rd_flow_max_colours, 1, 256); vid.frames("control_frames", &sd::VideoConfig::control_frames, &sd::VideoConfig::control_frames_size); vid.image("end_image", &sd::VideoConfig::end_image); diff --git a/src/api/templates/image_pixel.dgl b/src/api/templates/image_pixel.dgl index 681470601b..466e719ef5 100644 --- a/src/api/templates/image_pixel.dgl +++ b/src/api/templates/image_pixel.dgl @@ -26,7 +26,9 @@ fn main({{inputs}}) { mask_latent = mask_pixels {% endif %} positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) -{% if flags.minit2i %} +{% if flags.rd_flow %} + negative_text = zero_out(positive_text, fields = ["vector"]) +{% elif flags.minit2i %} negative_text = zero_out(positive_text, fields = ["vector"]) {% else %} {% if flags.encode_negative %} @@ -54,6 +56,19 @@ fn main({{inputs}}) { {% else %} sampler_rng = make_rng(sampler_rng_type, seed = seed) {% endif %} +{% if flags.rd_flow %} + # RD Flow 64 draws pixels and a palette in one pass: rd_flow::sample owns its + # shifted schedule, applies guidance by dropping the text rows (the reference + # has no negative prompt), extracts the colours partway through, then commits + # pointer-head tokens. It returns RGBA in 0..1 plus the palette and the per- + # pixel palette index it drew with; the stock API keeps the pixels. + # The noise sprite is [4, width, height, 1] because ggml fills the fastest axis + # first: a fixed seed then hands the model the same noise as the reference's + # randn((64, 64, 4)), which is channel-last. + noise = tensor::randn_like(tensor::zeros([4, width, height, 1]), rng = sampler_rng) + drawing = rd_flow::sample(noise, predict = pos, steps = steps, guidance = cfg_scale, background = rd_flow_background, palette = rd_flow_palette, shift = rd_flow_shift, merge = rd_flow_merge, palette_at = rd_flow_palette_at, max_colours = rd_flow_max_colours) + return {image = image::to_u8(drawing.image), latent = drawing.image} +{% else %} start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) {% if flags.hires %} @@ -61,4 +76,5 @@ fn main({{inputs}}) { {% endif %} pixels = tensor::clamp(tensor::affine({{result_latent}}, scale = 0.5, offset = 0.5), 0, 1) return {image = image::to_u8(pixels), latent = {{result_latent}}} +{% endif %} } diff --git a/src/conditioning/llm_conditioner.cpp b/src/conditioning/llm_conditioner.cpp index a822d355b6..65a6b26d32 100644 --- a/src/conditioning/llm_conditioner.cpp +++ b/src/conditioning/llm_conditioner.cpp @@ -94,6 +94,7 @@ struct LLMEmbedder : public Conditioner { sd_version_is_krea2(version) || sd_version_is_minimax_h3(version) || sd_version_is_mage_flow(version) || + sd_version_is_rd_flow(version) || version == VERSION_IRIS) { arch = LLM::LLMArch::QWEN3_VL; } else if (sd_version_is_z_image(version) || sd_version_is_z_image_l2p(version) || version == VERSION_OVIS_IMAGE || version == VERSION_FLUX2_KLEIN) { @@ -1334,6 +1335,58 @@ struct LLMEmbedder : public Conditioner { prompt_attn_range.second = static_cast(prompt.size()); prompt += "<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"; + } else if (sd_version_is_rd_flow(version)) { + // Raw caption tokens, no chat template, Qwen3-VL cut at 27 layers through + // the final norm. Ref: rdflow/text.py. + constexpr int rd_flow_max_length = 512; // TEXT_LEN + prompt = conditioner_params.text; + prompt_attn_range = {0, 0}; + prompt_template_encode_start_idx = 0; + out_layers = {static_cast(llm->config.num_layers + 1)}; // final-norm tap + + sd::Tensor mask; + auto hidden_states = encode_prompt(n_threads, + prompt, + prompt_attn_range, + 0, + 0, + image_embeds, + out_layers, + 0, + false, + rd_flow_max_length, + {}, + {}, + "", + &mask); + if (hidden_states.empty()) { + return {}; + } + // Second RMS norm (no weight) over the hidden dim, then zero padded tokens. + const int64_t hidden = hidden_states.shape()[0]; + const int64_t len = hidden_states.shape()[1]; + for (int64_t t = 0; t < len; ++t) { + float* row = &hidden_states[t * hidden]; + const bool on = mask.empty() ? true : mask[t] != 0.f; + if (!on) { + std::fill(row, row + hidden, 0.f); + continue; + } + double sq = 0.0; + for (int64_t i = 0; i < hidden; ++i) + sq += double(row[i]) * double(row[i]); + const float inv = 1.0f / std::sqrt(float(sq / double(hidden)) + 1e-6f); + for (int64_t i = 0; i < hidden; ++i) + row[i] *= inv; + } + + int64_t t1 = ggml_time_ms(); + LOG_INFO("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); + + SDCondition result; + result.c_crossattn = std::move(hidden_states); // [2560, L] + result.c_vector = mask.empty() ? sd::Tensor::full({len}, 1.f) : std::move(mask); // token key-padding mask + return result; } else if (sd_version_is_pid(version)) { prompt = system_prefix(""); constexpr int pixeldit_max_length = 300; diff --git a/src/config.cpp b/src/config.cpp index a7f3add2c9..c8bf7904d5 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -84,6 +84,12 @@ namespace sd { batch_count = 1; control_strength = 0.9f; qwen_image_layers = 3; + rd_flow_palette = ""; + rd_flow_background = "transparent"; + rd_flow_shift = 3.0f; + rd_flow_merge = 0.05f; + rd_flow_palette_at = 0.6f; + rd_flow_max_colours = 64; circular_x = false; circular_y = false; vae_tiling_params = {false, false, 0, 0, 0.5f, 0.0f, 0.0f, nullptr}; diff --git a/src/config.h b/src/config.h index d0acd9375b..b8deef01b7 100644 --- a/src/config.h +++ b/src/config.h @@ -164,6 +164,13 @@ namespace sd { sd::CacheConfig cache{}; HiresConfig hires{}; int qwen_image_layers{}; + // RD Flow 64 only. + const char* rd_flow_palette{}; + const char* rd_flow_background{}; + float rd_flow_shift{}; + float rd_flow_merge{}; + float rd_flow_palette_at{}; + int rd_flow_max_colours{}; bool circular_x{}; bool circular_y{}; enum sd_control_type_t control_type {}; diff --git a/src/dgl/bindings/rd_flow.cpp b/src/dgl/bindings/rd_flow.cpp new file mode 100644 index 0000000000..d743a08776 --- /dev/null +++ b/src/dgl/bindings/rd_flow.cpp @@ -0,0 +1,93 @@ +#include "dgl/bindings/rd_flow.h" + +#include "dgl/bindings/arguments.h" +#include "dgl/bindings/values.h" + +#include "core/file_access.h" +#include "core/util.h" +#include "dgl/diagnostic.h" +#include "dgl/ops/predictor.h" +#include "dgl/ops/rd_flow_sampling.h" +#include "model/diffusion/rd_flow_sampler.hpp" + +#include +#include +#include + +namespace sd::dgl { + // The "palette" argument is either a comma-separated list of "#rrggbb" colours + // or the path of a palette file (Lospec/paint.net/GIMP/JASC). A path is only + // assumed for a single token that is not a colour, so "#abc,#def" never reads a + // file. + static std::vector palette_colours(const std::string& text) { + if (text.empty()) { + return {}; + } + const auto is_colour = [](std::string token) { + while (!token.empty() && (token.front() == ' ' || token.front() == '#')) + token.erase(token.begin()); + return token.size() == 3 || token.size() == 6 || token.size() == 8; + }; + if (text.find(',') == std::string::npos && !is_colour(text)) { + const auto path = std::filesystem::u8path(text); + std::error_code error; + if (std::filesystem::is_regular_file(path, error)) { + require_file_access(text, SD_DGL_FILE_READ); + std::ifstream file(path); + if (!file) { + throw Error(SD_STATUS_INVALID_ARGUMENT, "rd_flow::sample cannot read palette file '" + text + "'"); + } + std::stringstream contents; + contents << file.rdbuf(); + return RDFlow::parse_palette_text(contents.str()); + } + throw Error(SD_STATUS_INVALID_ARGUMENT, + "rd_flow::sample palette '" + text + "' is neither a colour list nor a palette file"); + } + std::vector colours; + std::stringstream stream(text); + std::string colour; + while (std::getline(stream, colour, ',')) { + if (!colour.empty()) { + colours.push_back(colour); + } + } + return colours; + } + + Value sample_rd_flow_tensor(Values& args, RunState& state) { + const auto predictor = object(args, "predict"); + + ops::RDFlowSampleArgs params; + params.steps = (int)get_int(args, "steps"); + params.guidance = (float)get_number(args, "guidance"); + params.interval_lo = (float)get_number(args, "interval_lo"); + params.interval_hi = (float)get_number(args, "interval_hi"); + params.shift = (float)get_number(args, "shift"); + params.palette_at = (float)get_number(args, "palette_at"); + params.pointer_from = (float)get_number(args, "pointer_from"); + params.commit_from = (float)get_number(args, "commit_from"); + params.commit_thresh = (float)get_number(args, "commit_thresh"); + params.max_colours = (int)get_int(args, "max_colours"); + params.merge = (float)get_number(args, "merge"); + params.bg_mode = get_string(args, "background") == "opaque" ? 1 : 2; + params.source = (int)get_int(args, "source"); + // Optional locked palette: every pixel is drawn from these colours instead + // of a palette the model extracts. A bad colour is an error rather than a + // silently smaller palette. + const auto colours = palette_colours(get_string(args, "palette")); + if (!colours.empty()) { + try { + RDFlow::parse_hex(colours, true); + } catch (const std::invalid_argument& error) { + throw Error(SD_STATUS_INVALID_ARGUMENT, std::string("rd_flow::sample palette: ") + error.what()); + } + params.locked.push_back(colours); + } + + const auto result = ops::rd_flow_sample(float_tensor(args, "start"), *predictor, params, state.events); + return Value::dict({{"image", Value::object(result.image)}, + {"palette", Value::object(result.palette)}, + {"tokens", Value::object(result.tokens)}}); + } +} // namespace sd::dgl diff --git a/src/dgl/bindings/rd_flow.h b/src/dgl/bindings/rd_flow.h new file mode 100644 index 0000000000..cf060f3aa6 --- /dev/null +++ b/src/dgl/bindings/rd_flow.h @@ -0,0 +1,12 @@ +#ifndef __SD_DGL_BINDINGS_RD_FLOW_H__ +#define __SD_DGL_BINDINGS_RD_FLOW_H__ + +#include "dgl/value.h" + +namespace sd::dgl { + struct RunState; + + Value sample_rd_flow_tensor(Values& args, RunState& state); +} // namespace sd::dgl + +#endif // __SD_DGL_BINDINGS_RD_FLOW_H__ diff --git a/src/dgl/bindings/registration.cpp b/src/dgl/bindings/registration.cpp index 52e2430595..f4004ae3f6 100644 --- a/src/dgl/bindings/registration.cpp +++ b/src/dgl/bindings/registration.cpp @@ -19,6 +19,7 @@ #include "dgl/bindings/postprocess.h" #include "dgl/bindings/predictor.h" #include "dgl/bindings/preview.h" +#include "dgl/bindings/rd_flow.h" #include "dgl/bindings/regions.h" #include "dgl/bindings/relay_vsr.h" #include "dgl/bindings/rng.h" @@ -638,6 +639,20 @@ namespace sd::dgl { sampling_arguments.insert(sampling_arguments.begin() + 2, required("semantic_sigmas", Kind::Tensor)); registry["sefi::sample"] = make_operation(std::move(sampling_arguments), {Kind::Tensor}, sample_sefi_tensor); registry["sefi::sample"].sampling = true; + + // RD Flow 64 owns its schedule and its palette, so the shared solver and + // make_sigmas do not apply; the loop lives in ops::rd_flow_sample. + registry["rd_flow::sample"] = make_operation( + {required("start", Kind::Tensor), required("predict", Kind::Predictor), integer("steps", 1, 200, 16), + number("guidance", 0, 100, 4.0), number("interval_lo", 0, 1, 0.0), number("interval_hi", 0, 1, 0.9), + number("shift", 0.01, 100, 3.0), number("palette_at", 0, 1, 0.6), number("pointer_from", 0, 1, 0.35), + number("commit_from", 0, 1, 0.55), number("commit_thresh", 0, 1, 0.9), integer("max_colours", 1, 256, 64), + number("merge", 0, 1, 0.05), choice("background", {"transparent", "opaque"}, "transparent"), + integer("source", 0, 15, 6), optional("palette", Kind::String, "")}, + {{Kind::Dict}, + {{"image", {Kind::Tensor}}, {"palette", {Kind::Tensor}}, {"tokens", {Kind::Tensor}}}}, + sample_rd_flow_tensor); + registry["rd_flow::sample"].sampling = true; } static void register_latent_operations(Registry& registry) { diff --git a/src/dgl/models/diffusion_prediction.h b/src/dgl/models/diffusion_prediction.h index 8b3330e947..9adf26482a 100644 --- a/src/dgl/models/diffusion_prediction.h +++ b/src/dgl/models/diffusion_prediction.h @@ -12,6 +12,7 @@ struct AttentionProcessor; struct FluxImageBlockProcessor; struct UNetBlockProcessor; struct SDCondition; +struct RDFlowDiffusionExtra; namespace sd_sample { struct SampleStepCacheDispatcher; @@ -44,6 +45,8 @@ namespace sd::dgl::models { Rope::RefIndexMode ref_index_mode = Rope::RefIndexMode::FIXED; Rope::RefRoPEAnchor ref_rope_anchor = Rope::RefRoPEAnchor::MODEL_DEFAULT; bool force_ref_timestep_zero = false; + // RD Flow 64 only. + const RDFlowDiffusionExtra* rd_flow = nullptr; std::function transform; }; diff --git a/src/dgl/models/dit.cpp b/src/dgl/models/dit.cpp index 7624674db3..a6b730f449 100644 --- a/src/dgl/models/dit.cpp +++ b/src/dgl/models/dit.cpp @@ -305,9 +305,12 @@ namespace sd::dgl::models { const auto down_factor = get_diffusion_model_down_factor(); const bool packed = sd_version_is_ltxav(version()) || sd_version_is_minimax_h3(version()); const bool unet_batch = shape.size() == 4 && sd_version_is_unet(version()); - if ((shape.size() != 4 && shape.size() != 5) || - (packed ? shape[channel_axis] < get_latent_channel() : shape[channel_axis] != get_latent_channel()) || - (!unet_batch && shape.back() != 1) || shape[0] % down_factor || shape[1] % down_factor) { + // RD Flow draws pixels and batches them itself, so the latent contract below does not apply. + const bool rd_flow = sd_version_is_rd_flow(version()); + if (!rd_flow && ((shape.size() != 4 && shape.size() != 5) || + (packed ? shape[channel_axis] < get_latent_channel() + : shape[channel_axis] != get_latent_channel()) || + (!unet_batch && shape.back() != 1) || shape[0] % down_factor || shape[1] % down_factor)) { throw std::runtime_error("latent shape does not match the diffusion model"); } if (!condition.c_concat.empty()) { @@ -400,6 +403,17 @@ namespace sd::dgl::models { present(options.video_positions), first(condition.extra_c_crossattns), present(step.mask)}; } else if (sd_version_is_minit2i(version())) { params.extra = MiniT2IDiffusionExtra{params.y}; + } else if (sd_version_is_rd_flow(version())) { + // rd_flow::sample passes per-step state through options; without it this + // is a plain text-to-image forward with the mask in c_vector. + RDFlowDiffusionExtra extra; + if (options.rd_flow != nullptr) { + extra = *options.rd_flow; + } + if (extra.text_mask == nullptr) { + extra.text_mask = params.y; + } + params.extra = extra; } else if (sd_version_is_sensenova_u1(version())) { params.extra = SenseNovaU1DiffusionExtra{present(condition.c_input_ids)}; } else if (sd_version_is_z_image(version()) && !step.controls.empty()) { @@ -417,7 +431,9 @@ namespace sd::dgl::models { } throw std::runtime_error("diffusion compute failed"); } - if (result.shape() != shape) { + // The RD Flow pointer head outputs palette-slot scores, not an image shape. + const bool rd_flow_pointer = options.rd_flow != nullptr && options.rd_flow->pointer_head; + if (!rd_flow_pointer && result.shape() != shape) { throw std::runtime_error("diffusion output shape " + sd::tensor_shape_to_string(result.shape()) + " does not match input " + sd::tensor_shape_to_string(shape)); } diff --git a/src/dgl/ops/rd_flow_sampling.cpp b/src/dgl/ops/rd_flow_sampling.cpp new file mode 100644 index 0000000000..645fcd14e8 --- /dev/null +++ b/src/dgl/ops/rd_flow_sampling.cpp @@ -0,0 +1,150 @@ +#include "dgl/ops/rd_flow_sampling.h" + +#include +#include +#include +#include +#include + +#include "dgl/models/dit.h" +#include "dgl/ops/predictor.h" +#include "dgl/run_events.h" +#include "model/diffusion/rd_flow.hpp" +#include "model/diffusion/rd_flow_sampler.hpp" + +namespace sd::dgl::ops { + using RDFlow::RDFlowPalette; + using RDFlow::RDFlowRGB; + using RDFlow::RDFlowSampler; + using RDFlow::RDFlowSamplerParams; + + RDFlowSampleResult rd_flow_sample(const sd::Tensor& noise, + const Predictor& predictor, + const RDFlowSampleArgs& args, + RunEvents& events) { + const auto& leaf = primary_predictor(predictor); + auto& dit = leaf.dit(); + auto* runner = dynamic_cast(dit.diffusion_model.get()); + if (!runner) + throw std::runtime_error("rd_flow::sample requires an RD Flow diffusion model"); + // The rd_flow conditioner keeps the prompt embeddings in c_crossattn + // ([hidden, tokens]) and the token key-padding mask in c_vector ([tokens]). + const auto& text = leaf.condition.c_crossattn; + const auto& mask = leaf.condition.c_vector; + if (text.empty() || mask.empty()) + throw std::runtime_error("rd_flow::sample needs prompt conditioning"); + + // Noise is an image tensor: [n, n, 4, batch] with the colour axis second to + // last. A [4, n, n, 1] tensor is the same sprite with the colour axis first, + // which is also the order a fixed seed fills a tensor in when the reference + // draws it channel-last, so both orders are accepted. + const auto& shape = noise.shape(); + bool colour_first = shape.size() == 4 && shape[0] == 4 && shape[3] == 1; + if (shape.size() != 4 || shape[3] < 1 || (!colour_first && (shape[2] != 4 || shape[3] != 1))) + throw std::runtime_error("rd_flow::sample expects noise shaped [n, n, 4, batch] or [4, n, n, 1]"); + const int64_t width = colour_first ? shape[1] : shape[0]; + const int64_t height = colour_first ? shape[2] : shape[1]; + if (width != height) + throw std::runtime_error("rd_flow::sample draws square sprites; width and height must match"); + const int64_t n = width; + const int64_t batch = colour_first ? 1 : shape[3]; + if (batch != 1) + throw std::runtime_error("rd_flow::sample draws one sprite per call"); + + sd::Tensor start(std::vector{n, n, 4, batch}); + if (colour_first) { + for (int64_t y = 0; y < n; ++y) + for (int64_t x = 0; x < n; ++x) + for (int64_t c = 0; c < 4; ++c) + start[x + n * (y + n * c)] = noise[c + 4 * (x + n * y)]; + } else { + std::memcpy(start.data(), noise.data(), sizeof(float) * (size_t)start.numel()); + } + + RDFlowSampler sampler; + RDFlowSamplerParams& params = sampler.params; + params.steps = args.steps; + params.guidance = args.guidance; + params.interval_lo = args.interval_lo; + params.interval_hi = args.interval_hi; + params.shift = args.shift; + params.palette_at = args.palette_at; + params.pointer_from = args.pointer_from; + params.commit_from = args.commit_from; + params.commit_thresh = args.commit_thresh; + params.max_colours = args.max_colours; + params.merge = args.merge; + params.bg_mode = args.bg_mode; + params.source = args.source; + for (const auto& colours : args.locked) + sampler.locked.push_back(RDFlow::parse_hex(colours, true)); + + // The drawing model is called directly: the sampler works in model space + // (the network predicts the clean sprite), which is what the shared solver + // would have to be told to believe. + models::Model::ExecutionScope scope(dit); + const int n_threads = dit.n_threads; + sampler.predict = [runner, n_threads](const RDFlow::RDFlowRunner::Request& request, sd::Tensor& x_hat, + sd::Tensor& feats) { + auto prediction = runner->predict(request, n_threads); + if (prediction.x_hat.empty()) + throw std::runtime_error("rd-flow-64 prediction failed"); + x_hat = std::move(prediction.x_hat); + feats = std::move(prediction.feats); + }; + sampler.pointer = [runner, n_threads](const sd::Tensor& feats, const RDFlowPalette& palette) { + const auto tensors = RDFlow::rd_flow_palette_tensors(palette); + RDFlow::RDFlowRunner::Palette pal; + pal.rgb = &tensors.rgb; + pal.valid = &tensors.valid; + pal.ramp = &tensors.ramp; + pal.level = &tensors.level; + pal.P = palette.P; + auto logits = runner->pointer_logits(feats, pal, palette.B, n_threads); + if (logits.empty()) + throw std::runtime_error("rd-flow-64 pointer head failed"); + return logits; + }; + // Report finished steps so progress and cancel work for a model that does + // not run through the shared solver; check_cancelled aborts the loop. + events.begin_sample(args.steps); + sampler.on_step = [&events](int completed, int total) { + events.sample_step(completed, total); + events.check_cancelled(); + }; + + const auto output = sampler.run(start, text, mask, n, n_threads); + + // The palette array always has RD_FLOW_SLOTS rows; only the leading valid + // ones were drawn with. + const int64_t colours = output.palette.empty() ? 0 : output.palette.count_valid(0); + const int64_t pixels = n * n; + std::vector used(output.palette.rgb.begin(), output.palette.rgb.begin() + colours); + const auto rgba = RDFlow::palette_decode(used, output.tokens.data(), size_t(pixels)); + + // Pixels leave as image tensors: [width, height, 4, batch], colour axis + // second to last, values in 0..1 for image::to_u8. + std::vector image(size_t(pixels) * 4, 0.f); + for (int64_t p = 0; p < pixels; ++p) + for (int64_t c = 0; c < 4; ++c) + image[size_t(c) * pixels + size_t(p)] = float(rgba[size_t(p) * 4 + size_t(c)]) / 255.f; + std::vector rgb(size_t(colours) * 3, 0), tokens(size_t(pixels), 0); + for (int64_t q = 0; q < colours; ++q) { + // [3, colours] with the colour axis first, so one slot is three + // consecutive values: red, green, blue. + rgb[3 * q + 0] = used[size_t(q)].r; + rgb[3 * q + 1] = used[size_t(q)].g; + rgb[3 * q + 2] = used[size_t(q)].b; + } + std::copy(output.tokens.begin(), output.tokens.begin() + pixels, tokens.begin()); + + // A zero-length tensor cannot be built from a null pointer, and a drawing + // with no colours at all (too few steps) is legal. + static const int32_t unused_colour[3] = {0, 0, 0}; + RDFlowSampleResult result; + result.image = make_tensor(SD_TENSOR_F32, std::vector{width, height, 4, batch}, image.data(), image.size() * sizeof(float)); + result.palette = make_tensor(SD_TENSOR_I32, std::vector{3, colours}, colours ? rgb.data() : unused_colour, size_t(colours) * 3 * sizeof(int32_t)); + result.tokens = make_tensor(SD_TENSOR_I32, std::vector{width, height, 1, 1}, tokens.data(), tokens.size() * sizeof(int32_t)); + return result; + } +} // namespace sd::dgl::ops diff --git a/src/dgl/ops/rd_flow_sampling.h b/src/dgl/ops/rd_flow_sampling.h new file mode 100644 index 0000000000..3b6852853c --- /dev/null +++ b/src/dgl/ops/rd_flow_sampling.h @@ -0,0 +1,56 @@ +#ifndef __SD_DGL_OPS_RD_FLOW_SAMPLING_H__ +#define __SD_DGL_OPS_RD_FLOW_SAMPLING_H__ + +#include "dgl/models/fwd.h" +#include "dgl/tensor.h" + +#include +#include +#include + +namespace sd::dgl { + class RunEvents; + + namespace ops { + struct Predictor; + + // rdflow.flow.sample defaults (the CLI/API can move all but the head windows). + struct RDFlowSampleArgs { + int steps = 16; + float guidance = 4.f; + float interval_lo = 0.f, interval_hi = .9f; + float shift = 3.f; + float palette_at = .6f; + float pointer_from = .35f; + float commit_from = .55f; + float commit_thresh = .9f; + int max_colours = 64; + float merge = .05f; + int bg_mode = 2; // 1 opaque, 2 transparent + int source = 6; + // One locked palette per image ("#rrggbb" tokens); empty means extract + // the palette from the drawing. + std::vector> locked; + }; + + // RD Flow draws pixels *and* the palette they came from, and the palette plus + // the per-pixel slot is the lossless form of a drawing. The op returns all + // three so a program can save swatches or re-decode the result. + struct RDFlowSampleResult { + std::shared_ptr image; // [width, height, 4, batch] float RGBA in 0..1 + std::shared_ptr palette; // [3, colours] sRGB bytes in draw order + std::shared_ptr tokens; // [width, height, 1, 1]: 0 transparent, else slot + 1 + }; + + // RD Flow draws pixels instead of denoising a latent, so it does not use the + // shared solver: this runs the reference loop against the drawing model held + // by the predictor. `noise` is an image tensor, [n, n, 4, batch], or the same + // sprite with the colour axis first (see the implementation). + RDFlowSampleResult rd_flow_sample(const sd::Tensor& noise, + const Predictor& predictor, + const RDFlowSampleArgs& args, + RunEvents& events); + } // namespace ops +} // namespace sd::dgl + +#endif // __SD_DGL_OPS_RD_FLOW_SAMPLING_H__ diff --git a/src/model.h b/src/model.h index 85dfb68d49..c1e7b06f1d 100644 --- a/src/model.h +++ b/src/model.h @@ -74,6 +74,7 @@ enum SDVersion { VERSION_MINIMAX_H3_IMAGE, VERSION_RELAY_VSR, VERSION_SEEDVR2, + VERSION_RD_FLOW_64, VERSION_COUNT, }; @@ -258,6 +259,10 @@ static inline bool sd_version_is_lens(SDVersion version) { return false; } +static inline bool sd_version_is_rd_flow(SDVersion version) { + return version == VERSION_RD_FLOW_64; +} + static inline bool sd_version_is_minit2i(SDVersion version) { if (version == VERSION_MINIT2I) { return true; diff --git a/src/model/diffusion/model.hpp b/src/model/diffusion/model.hpp index 0297e73baf..14e23b6bca 100644 --- a/src/model/diffusion/model.hpp +++ b/src/model/diffusion/model.hpp @@ -105,6 +105,20 @@ struct MiniT2IDiffusionExtra { const sd::Tensor* mask = nullptr; }; +struct RDFlowDiffusionExtra { + const sd::Tensor* text_mask = nullptr; // [L], 0 = padding, all-zero row = unconditional + const sd::Tensor* self_cond = nullptr; // [64, 64, 4, B], null on the first step + int bg_mode = 2; // 1 = opaque, 2 = transparent + const sd::Tensor* pal_rgb = nullptr; // [P, 3, B] sRGB 0..255 + const sd::Tensor* pal_valid = nullptr; // [P, B] + const sd::Tensor* pal_ramp = nullptr; // [P, B] + const sd::Tensor* pal_level = nullptr; // [P, B] + int style = 0; + int source = 6; + sd::Tensor* out_features = nullptr; // u0 features of the forward, when requested + bool pointer_head = false; // x holds features; result is [1 + P, size*size, B] slot scores +}; + struct SenseNovaU1DiffusionExtra { const sd::Tensor* input_ids = nullptr; }; @@ -153,6 +167,7 @@ using DiffusionExtraParams = std::variant +#include +#include +#include +#include +#include +#include + +#include "core/ggml_extend.h" +#include "core/ggml_runner.h" +#include "core/pe_cache.h" +#include "core/util.h" +#include "model/common/ggml_block.hpp" +#include "model/diffusion/model.hpp" +#include "model_loader.h" + +namespace RDFlow { + constexpr int RD_FLOW_GRAPH_SIZE = 32768; + + constexpr int CHANNELS = 4; // OKLab L, a, b + alpha + constexpr int N_RAMPS = 16; + constexpr float AB_SCALE = 3.0f; + // Optional attribute conditions (colour count, outline, dither, transparency). + constexpr int ATTR_VOCAB[4] = {8, 5, 5, 4}; + + struct RDFlowConfig { + int64_t size = 64; + int64_t d0 = 128; + int64_t d1 = 256; + int64_t d2 = 512; // unused at core_level 2, kept for parity + int64_t dc = 1024; + int64_t head_dim = 64; + int64_t depth0 = 2; + int64_t depth1 = 2; + int64_t depth_core = 16; + int64_t window = 8; + float mlp_ratio = 3.0f; + int64_t text_dim = 2560; + int64_t n_registers = 4; + int64_t n_styles = 512; + int64_t n_sources = 16; + int64_t dk = 128; + int64_t colour_freqs = 8; + int64_t colour_hidden = 256; + float rope_theta = 100.0f; + int64_t text_adapter = 2; + bool palette_tokens = true; + bool attrs = true; + bool self_cond = true; + bool bg_mode = true; + + static RDFlowConfig detect_from_weights(const String2TensorStorage& tensor_storage_map, + const std::string& prefix) { + RDFlowConfig config; + // The public checkpoint stores bare names; converted files may carry a + // component prefix. + auto qualified = [&](const std::string& suffix) { + return prefix.empty() ? suffix : prefix + "." + suffix; + }; + auto find = [&](const std::string& suffix) -> const TensorStorage* { + auto it = tensor_storage_map.find(qualified(suffix)); + return it == tensor_storage_map.end() ? nullptr : &it->second; + }; + if (const auto* inp = find("inp.weight")) { + // inp: Linear(CHANNELS * (2 if self_cond else 1) -> d0) + config.d0 = inp->ne[1]; + config.self_cond = inp->logical_ne0() == CHANNELS * 2; + } + if (const auto* merge0 = find("merge0.weight")) { + config.d1 = merge0->ne[1]; + } + if (const auto* core_ada = find("core_ada.weight")) { + config.dc = core_ada->logical_ne0(); + } + if (const auto* tp = find("text_proj.weight")) { + config.text_dim = tp->logical_ne0(); + } + if (const auto* reg = find("registers")) { + config.n_registers = reg->ne[1]; + } + if (const auto* dk = find("q.weight")) { + config.dk = dk->ne[1]; + } + if (const auto* ch = find("colour.mlp.0.weight")) { + config.colour_hidden = ch->ne[1]; + // in = 3 + 6 * colour_freqs + config.colour_freqs = (ch->logical_ne0() - 3) / 6; + } + // Count core blocks and adapter blocks. + int64_t core = 0, adapter = 0; + for (const auto& [name, ts] : tensor_storage_map) { + if (!starts_with(name, qualified(""))) + continue; + const auto rest = name.substr(qualified("").size()); + if (starts_with(rest, "core.")) { + auto items = split_string(rest, '.'); + if (items.size() > 1) + core = std::max(core, atoi(items[1].c_str()) + 1); + } else if (starts_with(rest, "adapter.")) { + auto items = split_string(rest, '.'); + if (items.size() > 1) + adapter = std::max(adapter, atoi(items[1].c_str()) + 1); + } + } + if (core > 0) + config.depth_core = core; + config.text_adapter = adapter; + config.palette_tokens = find("pal_tok.weight") != nullptr; + config.attrs = find("attr_emb.0.weight") != nullptr; + config.bg_mode = find("bg_emb.weight") != nullptr; + LOG_VERBOSE("rd-flow-64: d0=%" PRId64 " d1=%" PRId64 " dc=%" PRId64 " core=%" PRId64 " adapter=%" PRId64 + " dk=%" PRId64 " self_cond=%d palette=%d", + config.d0, config.d1, config.dc, config.depth_core, config.text_adapter, + config.dk, (int)config.self_cond, (int)config.palette_tokens); + return config; + } + + int64_t n0() const { return size; } + int64_t n1() const { return size / 2; } + int64_t nc() const { return size / 4; } + }; + + // RMSNorm with the "w" weight name. + struct RDRMSNorm : public GGMLBlock { + int64_t dim; + float eps; + RDRMSNorm(int64_t dim, float eps = 1e-6f) + : dim(dim), eps(eps) {} + void init_params(ggml_context* ctx, const String2TensorStorage&, const std::string = "") override { + params["w"] = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, dim); + } + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) { + x = ggml_rms_norm(ctx->ggml_ctx, x, eps); + return ggml_mul(ctx->ggml_ctx, x, params["w"]); + } + }; + + // ---- host helpers (positions, rope tables, window/merge permutations) ---- + + inline std::vector rope_freqs(int head_dim, float theta) { + int quarter = head_dim / 4; + std::vector f(quarter); + for (int i = 0; i < quarter; ++i) + f[i] = std::pow(theta, -float(i) / float(quarter)); + return f; + } + + // angle for frequency index j (0..head_dim/2-1) given a 2-D position. + inline float rope_angle(int j, int head_dim, const std::vector& freqs, float x, float y) { + int quarter = head_dim / 4; + return j < quarter ? x * freqs[j] : y * freqs[j - quarter]; + } + + // Rotate-half rope cos/sin for a flat token list: [head_dim/2, 1, tokens, 1], + // broadcast over heads and batch. Positions with use_pos == 0 get angle 0 + // (identity), which is how registers / text / palette tokens are handled. + inline std::pair, sd::Tensor> + make_rope_cos_sin(int head_dim, float theta, const std::vector>& positions, const std::vector& use_pos) { + const int half = head_dim / 2; + auto freqs = rope_freqs(head_dim, theta); + sd::Tensor cos({(int64_t)half, 1, (int64_t)positions.size(), 1}); + sd::Tensor sin({(int64_t)half, 1, (int64_t)positions.size(), 1}); + for (size_t t = 0; t < positions.size(); ++t) { + for (int j = 0; j < half; ++j) { + float ang = use_pos[t] ? rope_angle(j, head_dim, freqs, positions[t].first, positions[t].second) : 0.f; + cos[((int64_t)t * half) + j] = std::cos(ang); + sin[((int64_t)t * half) + j] = std::sin(ang); + } + } + return {std::move(cos), std::move(sin)}; + } + + // Core rope: S leading tokens with no position (registers, text, palette), + // then the nc x nc image grid in row-major (y * nc + x) order. + inline std::pair, sd::Tensor> make_core_rope(int head_dim, float theta, int64_t n_leading, int64_t nc) { + std::vector> positions; + std::vector use_pos; + positions.reserve((size_t)n_leading + (size_t)nc * nc); + use_pos.reserve((size_t)n_leading + (size_t)nc * nc); + for (int64_t i = 0; i < n_leading; ++i) { + positions.emplace_back(0.f, 0.f); + use_pos.push_back(0); + } + for (int64_t y = 0; y < nc; ++y) + for (int64_t x = 0; x < nc; ++x) { + positions.emplace_back((float)x, (float)y); + use_pos.push_back(1); + } + return make_rope_cos_sin(head_dim, theta, positions, use_pos); + } + + // Shifted-window gather order: output slot = win*(w*w) + tok, win = yo*nw+xo, + // tok = yi*w+xi; source token = ((Y+shift)%n)*n + ((X+shift)%n). + inline std::vector window_perm(int n, int w, int shift) { + const int nw = n / w; + std::vector perm((size_t)n * n); + for (int yo = 0; yo < nw; ++yo) + for (int xo = 0; xo < nw; ++xo) + for (int yi = 0; yi < w; ++yi) + for (int xi = 0; xi < w; ++xi) { + int Y = yo * w + yi, X = xo * w + xi; + int sy = ((Y + shift) % n + n) % n; + int sx = ((X + shift) % n + n) % n; + int slot = (yo * nw + xo) * (w * w) + (yi * w + xi); + perm[(size_t)slot] = sy * n + sx; + } + return perm; + } + + inline std::vector invert_perm(const std::vector& perm) { + std::vector inv(perm.size()); + for (size_t i = 0; i < perm.size(); ++i) + inv[(size_t)perm[i]] = (int32_t)i; + return inv; + } + + // window cos/sin for manual rope: [head_dim/2, 1, w*w, nwin], position per + // (tok,win). The ne3 dim broadcasts over batch while ne2 (= window) stays + // aligned with the graph's window-fastest group index. + inline std::pair, sd::Tensor> make_window_rope(int n, int w, int shift, int head_dim, float theta) { + const int nw = n / w; + const int half = head_dim / 2; + const int nwin = nw * nw; + auto freqs = rope_freqs(head_dim, theta); + sd::Tensor cos_out({(int64_t)half, 1, (int64_t)(w * w), (int64_t)nwin}); + sd::Tensor sin_out({(int64_t)half, 1, (int64_t)(w * w), (int64_t)nwin}); + for (int yo = 0; yo < nw; ++yo) + for (int xo = 0; xo < nw; ++xo) { + int win = yo * nw + xo; + for (int yi = 0; yi < w; ++yi) + for (int xi = 0; xi < w; ++xi) { + int tok = yi * w + xi; + float sx = float(((xo * w + xi + shift) % n + n) % n); + float sy = float(((yo * w + yi + shift) % n + n) % n); + for (int j = 0; j < half; ++j) { + float ang = rope_angle(j, head_dim, freqs, sx, sy); + size_t idx = ((size_t)win * (w * w) + tok) * half + j; + cos_out[idx] = std::cos(ang); + sin_out[idx] = std::sin(ang); + } + } + } + return {std::move(cos_out), std::move(sin_out)}; + } + + // Gather indices for ggml_get_rows: [tokens, batch], same permutation per + // batch (ggml indexes the source batch dim with the index tensor's ne1). + inline sd::Tensor make_index_tensor(const std::vector& perm, int64_t batch) { + sd::Tensor out({(int64_t)perm.size(), batch}); + for (int64_t b = 0; b < batch; ++b) + std::copy(perm.begin(), perm.end(), out.data() + b * (int64_t)perm.size()); + return out; + } + + // cat([sin(a), cos(a)]) with a = t * 1000 * exp(-log(10000) * j / half), + // timestep embedding -> [dim, 1, batch] + inline sd::Tensor make_timestep_embedding(const std::vector& t, int64_t dim) { + const int64_t half = dim / 2; + const int64_t batch = (int64_t)t.size(); + sd::Tensor out({dim, 1, batch}); + for (int64_t b = 0; b < batch; ++b) { + for (int64_t j = 0; j < half; ++j) { + const float a = t[(size_t)b] * 1000.f * std::exp(-std::log(10000.0f) * (float)j / (float)half); + out[(b * dim) + j] = std::sin(a); + out[(b * dim) + half + j] = std::cos(a); + } + } + return out; + } + + // Additive key-padding mask for ggml_ext_attention_ext's manual path: the + // mask is added to [L_k, L_q, n_head * batch], so it is [L_k, 1, n_head * batch, 1]. + inline sd::Tensor make_key_mask(const std::vector& valid, int64_t n_head, int64_t batch) { + const int64_t L_k = (int64_t)valid.size(); + sd::Tensor mask({L_k, 1, n_head * batch, 1}); + for (int64_t g = 0; g < n_head * batch; ++g) { + const int64_t b = g % batch; + const float* row = valid.data(); + for (int64_t k = 0; k < L_k; ++k) + mask[(g * L_k) + k] = row[b * L_k + k] > 0.f ? 0.f : -INFINITY; + } + return mask; + } + + // 2x2 merge gather: out token = block*4 + (yi*2+xi), block = yo*(n/2)+xo, + // source token = (2*yo+yi)*n + (2*xo+xi). + inline std::vector merge_perm(int n) { + const int h = n / 2; + std::vector perm((size_t)n * n); + for (int yo = 0; yo < h; ++yo) + for (int xo = 0; xo < h; ++xo) + for (int yi = 0; yi < 2; ++yi) + for (int xi = 0; xi < 2; ++xi) { + int slot = ((yo * h + xo) * 4) + (yi * 2 + xi); + perm[(size_t)slot] = (2 * yo + yi) * n + (2 * xo + xi); + } + return perm; + } + + // ---- building blocks ---- + + // Rotate-half rope on q/k [head_dim, n_head, L, groups] with cos/sin + // [head_dim/2, 1, L, 1] (broadcast over heads and groups). + inline ggml_tensor* rope_half(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* cos, ggml_tensor* sin) { + auto g = ctx->ggml_ctx; + const int64_t hd = x->ne[0], H = x->ne[1], L = x->ne[2], NB = x->ne[3]; + auto x0 = ggml_view_4d(g, x, hd / 2, H, L, NB, x->nb[1], x->nb[2], x->nb[3], 0); + auto x1 = ggml_view_4d(g, x, hd / 2, H, L, NB, x->nb[1], x->nb[2], x->nb[3], (size_t)(hd / 2) * x->nb[0]); + x0 = ggml_cont(g, x0); + x1 = ggml_cont(g, x1); + auto o0 = ggml_sub(g, ggml_mul(g, x0, cos), ggml_mul(g, x1, sin)); + auto o1 = ggml_add(g, ggml_mul(g, x0, sin), ggml_mul(g, x1, cos)); + return ggml_concat(g, o0, o1, 0); // [head_dim, n_head, L, groups] + } + + // Window permutations and rope tables for one level, bound as graph inputs. + struct RDWindowCache { + ggml_tensor* perm_even = nullptr; + ggml_tensor* inv_even = nullptr; + ggml_tensor* cos_even = nullptr; + ggml_tensor* sin_even = nullptr; + ggml_tensor* perm_odd = nullptr; + ggml_tensor* inv_odd = nullptr; + ggml_tensor* cos_odd = nullptr; + ggml_tensor* sin_odd = nullptr; + }; + + struct RDAttention : public GGMLBlock { + int64_t d, head_dim, n_head; + RDAttention(int64_t d, int64_t head_dim) + : d(d), head_dim(head_dim), n_head(d / head_dim) { + blocks["qkv"] = std::make_shared(d, 3 * d, false); + blocks["out"] = std::make_shared(d, d, false); + blocks["qn"] = std::make_shared(head_dim); + blocks["kn"] = std::make_shared(head_dim); + } + + // Returns q,k,v each [head_dim, n_head, L, B] with qn/kn applied to q,k. + std::array qkv_heads(GGMLRunnerContext* ctx, ggml_tensor* x) { + auto qkv_p = std::dynamic_pointer_cast(blocks["qkv"]); + auto qn = std::dynamic_pointer_cast(blocks["qn"]); + auto kn = std::dynamic_pointer_cast(blocks["kn"]); + auto g = ctx->ggml_ctx; + auto qkv = qkv_p->forward(ctx, x); // [3d, L, B] + int64_t L = qkv->ne[1], B = qkv->ne[2]; + auto slice = [&](int i) { + auto t = ggml_view_3d(g, qkv, d, L, B, qkv->nb[1], qkv->nb[2], (size_t)i * d * qkv->nb[0]); + t = ggml_cont(g, t); + return ggml_reshape_4d(g, t, head_dim, n_head, L, B); + }; + auto q = qn->forward(ctx, slice(0)); + auto k = kn->forward(ctx, slice(1)); + auto v = slice(2); + return {q, k, v}; + } + + ggml_tensor* project(GGMLRunnerContext* ctx, ggml_tensor* o) { + return std::dynamic_pointer_cast(blocks["out"])->forward(ctx, o); + } + }; + + struct RDSwiGLU : public GGMLBlock { + int64_t d, h; + bool conv; + RDSwiGLU(int64_t d, float ratio, bool conv) + : d(d), h((int64_t)(d * ratio)), conv(conv) { + blocks["w1"] = std::make_shared(d, 2 * h, false); + blocks["w2"] = std::make_shared(h, d, false); + if (conv) + blocks["conv"] = std::make_shared(h, h, (int)h, std::pair{3, 3}, + std::pair{1, 1}, std::pair{1, 1}); + } + // x: [d, n*n, B]; hw = n (square grid) when conv is used. + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, int n) { + auto g = ctx->ggml_ctx; + auto w1 = std::dynamic_pointer_cast(blocks["w1"]); + auto w2 = std::dynamic_pointer_cast(blocks["w2"]); + auto ag = w1->forward(ctx, x); // [2h, N, B] + int64_t N = ag->ne[1], B = ag->ne[2]; + auto a = ggml_cont(g, ggml_view_3d(g, ag, h, N, B, ag->nb[1], ag->nb[2], 0)); + auto gate = ggml_cont(g, ggml_view_3d(g, ag, h, N, B, ag->nb[1], ag->nb[2], (size_t)h * ag->nb[0])); + if (conv) { + auto conv_b = std::dynamic_pointer_cast(blocks["conv"]); + // a: [h, n*n, B] -> grid [n(x), n(y), h, B] + auto grid = ggml_reshape_4d(g, a, h, n, n, B); // [h, x, y, B] + grid = ggml_cont(g, ggml_permute(g, grid, 2, 0, 1, 3)); // [x, y, h, B] + grid = conv_b->forward(ctx, grid); // [x, y, h, B] + grid = ggml_cont(g, ggml_permute(g, grid, 1, 2, 0, 3)); // [h, x, y, B] + a = ggml_reshape_3d(g, grid, h, N, B); + } + auto act = ggml_mul(g, ggml_silu(g, gate), a); + return w2->forward(ctx, act); + } + }; + + // Pre-norm adaLN-single block. mod: [d, 6, B]; table param [d, 6]. + struct RDBlock : public GGMLBlock { + int64_t d; + bool conv; + RDBlock(int64_t d, const RDFlowConfig& cfg, bool conv) + : d(d), conv(conv) { + blocks["n1"] = std::make_shared(d); + blocks["n2"] = std::make_shared(d); + blocks["attn"] = std::make_shared(d, cfg.head_dim); + blocks["mlp"] = std::make_shared(d, cfg.mlp_ratio, conv); + } + void init_params(ggml_context* ctx, const String2TensorStorage&, const std::string = "") override { + params["table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, d, 6); + } + + std::shared_ptr attention() { + return std::dynamic_pointer_cast(blocks["attn"]); + } + + // slice modulation component i from [d,6,B] + table -> [d,1,B] + ggml_tensor* comp(GGMLRunnerContext* ctx, ggml_tensor* mod, int i) { + auto g = ctx->ggml_ctx; + auto table = ggml_reshape_3d(g, params["table"], d, 6, 1); + auto full = ggml_add(g, mod, table); // broadcast over B + return ggml_view_3d(g, full, d, 1, full->ne[2], full->nb[1], full->nb[2], (size_t)i * full->nb[1]); + } + + template + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* mod, AttnFn attn_fn, int n = 0) { + auto g = ctx->ggml_ctx; + auto n1 = std::dynamic_pointer_cast(blocks["n1"]); + auto n2 = std::dynamic_pointer_cast(blocks["n2"]); + auto mlp = std::dynamic_pointer_cast(blocks["mlp"]); + auto sh1 = comp(ctx, mod, 0), sc1 = comp(ctx, mod, 1), g1 = comp(ctx, mod, 2); + auto sh2 = comp(ctx, mod, 3), sc2 = comp(ctx, mod, 4), g2 = comp(ctx, mod, 5); + auto h1 = ggml_ext_modulate(ctx, n1->forward(ctx, x), sh1, sc1); + auto ao = attn_fn(h1); + x = ggml_add(g, x, ggml_mul(g, ao, g1)); + auto h2 = ggml_ext_modulate(ctx, n2->forward(ctx, x), sh2, sc2); + auto mo = mlp->forward(ctx, h2, n); + x = ggml_add(g, x, ggml_mul(g, mo, g2)); + return x; + } + }; + + // A stack of window-attention blocks on an n x n grid (shifted on odd blocks). + struct RDWindowLevel : public GGMLBlock { + int64_t d, n, w, head_dim, n_head; + float theta; + int depth; + RDWindowLevel(int64_t d, int64_t n, int depth, const RDFlowConfig& cfg) + : d(d), n(n), w(cfg.window), head_dim(cfg.head_dim), n_head(d / cfg.head_dim), theta(cfg.rope_theta), depth(depth) { + for (int i = 0; i < depth; ++i) + blocks["blocks." + std::to_string(i)] = std::make_shared(d, cfg, true); + blocks["ada"] = std::make_shared(cfg.dc, 6 * d); + } + + // Manual rotate-half rope on q [head_dim, n_head, w*w, nwin*B] with + // cos/sin [head_dim/2, 1, w*w, nwin]. + ggml_tensor* rope(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* cos, ggml_tensor* sin) { + return rope_half(ctx, x, cos, sin); + } + + // x: [d, n*n, B]; c: [dc, 1, B]; window tables precomputed by the runner. + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* c, const RDWindowCache& cache) { + auto g = ctx->ggml_ctx; + auto ada = std::dynamic_pointer_cast(blocks["ada"]); + int64_t B = x->ne[2]; + auto mod = ggml_reshape_3d(g, ada->forward(ctx, ggml_silu(g, c)), d, 6, B); + int nw = (int)(n / w); + int nwin = nw * nw; + for (int i = 0; i < depth; ++i) { + auto blk = std::dynamic_pointer_cast(blocks["blocks." + std::to_string(i)]); + bool odd = (i % 2) != 0; + auto perm = odd ? cache.perm_odd : cache.perm_even; + auto inv = odd ? cache.inv_odd : cache.inv_even; + auto cos = odd ? cache.cos_odd : cache.cos_even; + auto sin = odd ? cache.sin_odd : cache.sin_even; + auto attn_fn = [&](ggml_tensor* h) { + auto attn = blk->attention(); + // window partition: gather tokens (ne1) by perm -> [d, nwin*w*w, B] + auto win = ggml_get_rows(g, h, perm); + win = ggml_reshape_4d(g, win, d, w * w, nwin, B); + win = ggml_reshape_3d(g, win, d, w * w, nwin * B); // window fast in ne2 + auto qkv = attn->qkv_heads(ctx, win); // each [head_dim, n_head, w*w, nwin*B] + auto q = rope(ctx, qkv[0], cos, sin); + auto k = rope(ctx, qkv[1], cos, sin); + auto v = qkv[2]; + // attention_ext splits the head axis itself: feed [d, w*w, nwin*B] + // in the (head_dim, head, seq, batch) memory order. + auto flat = [&](ggml_tensor* t) { + if (!ggml_is_contiguous(t)) { + t = ggml_cont(g, t); + } + return ggml_reshape_3d(g, t, d, w * w, nwin * B); + }; + auto o = ggml_ext_attention_ext(ctx, flat(q), flat(k), flat(v), n_head, nullptr, false, false); + o = attn->project(ctx, o); // [d, w*w, nwin*B] + o = ggml_reshape_4d(g, o, d, w * w, nwin, B); + o = ggml_reshape_3d(g, o, d, (int64_t)w * w * nwin, B); + return ggml_get_rows(g, o, inv); // scatter back -> [d, n*n, B] + }; + x = blk->forward(ctx, x, mod, attn_fn, (int)n); + } + return x; + } + }; + + struct RDColourEmbed : public GGMLBlock { + int64_t freqs_n, hidden; + RDColourEmbed(const RDFlowConfig& cfg) + : freqs_n(cfg.colour_freqs), hidden(cfg.colour_hidden) { + blocks["mlp.0"] = std::make_shared(3 + 6 * cfg.colour_freqs, cfg.colour_hidden, true); + blocks["mlp.2"] = std::make_shared(cfg.colour_hidden, cfg.colour_hidden, true); + } + // Colour features are cheap and position-free; compute OKLab + Fourier on + // the host and feed the [3 + 6F, P, B] tensor as `feat`. + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* feat) { + auto m0 = std::dynamic_pointer_cast(blocks["mlp.0"]); + auto m2 = std::dynamic_pointer_cast(blocks["mlp.2"]); + return m2->forward(ctx, ggml_silu(ctx->ggml_ctx, m0->forward(ctx, feat))); + } + }; + + // sRGB [0,255] -> OKLab. + inline std::array srgb_to_oklab(float r, float g, float b) { + auto lin = [](float c) { + c /= 255.0f; + return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); + }; + float rl = lin(r), gl = lin(g), bl = lin(b); + float l = std::cbrt(0.4122214708f * rl + 0.5363325363f * gl + 0.0514459929f * bl); + float m = std::cbrt(0.2119034982f * rl + 0.6806995451f * gl + 0.1073969566f * bl); + float s = std::cbrt(0.0883024619f * rl + 0.2817188376f * gl + 0.6299787005f * bl); + return {0.2104542553f * l + 0.7936177850f * m - 0.0040720468f * s, + 1.9779984951f * l - 2.4285922050f * m + 0.4505937099f * s, + 0.0259040371f * l + 0.7827717662f * m - 0.8086757660f * s}; + } + + // Host-side colour feature: cat([lab, sin(lab*freqs), cos(lab*freqs)]) with + // freqs = 2^arange(F) * pi. pal_rgb is [P, 3, B] (slot, channel, image). + // -> [3+6F, P, B]. + inline sd::Tensor colour_features(const sd::Tensor& pal_rgb, int freqs_n, int64_t batch) { + const int64_t P = pal_rgb.shape()[0]; + const int64_t dim = 3 + 6 * freqs_n; + std::vector freqs(freqs_n); + constexpr float kPi = 3.14159265358979323846f; + for (int i = 0; i < freqs_n; ++i) + freqs[i] = std::pow(2.0f, (float)i) * kPi; + sd::Tensor out({dim, P, batch}); + for (int64_t b = 0; b < batch; ++b) + for (int64_t p = 0; p < P; ++p) { + float r = pal_rgb[p + P * (0 + 3 * b)]; + float gg = pal_rgb[p + P * (1 + 3 * b)]; + float bb = pal_rgb[p + P * (2 + 3 * b)]; + auto lab = srgb_to_oklab(r, gg, bb); + float* o = &out[(b * P + p) * dim]; + o[0] = lab[0]; + o[1] = lab[1]; + o[2] = lab[2]; + for (int c = 0; c < 3; ++c) + for (int j = 0; j < freqs_n; ++j) { + float a = lab[c] * freqs[j]; + o[3 + c * freqs_n + j] = std::sin(a); + o[3 + 3 * freqs_n + c * freqs_n + j] = std::cos(a); + } + } + return out; + } + + // Graph inputs for one drawing-model forward. + struct RDFlowModelInputs { + ggml_tensor* x_img = nullptr; // [size, size, 4, B] noisy pixels + ggml_tensor* sc_img = nullptr; // [size, size, 4, B] self-conditioning guess + ggml_tensor* temb = nullptr; // [256, 1, B] timestep embedding (host) + ggml_tensor* style_ids = nullptr; // [B, 1] i32 + ggml_tensor* source_ids = nullptr; // [B, 1] i32 + ggml_tensor* bg_ids = nullptr; // [B, 1] i32 + ggml_tensor* attr_ids[4] = {}; + ggml_tensor* text = nullptr; // [text_dim, L, B] raw prompt features + ggml_tensor* text_mask = nullptr; // [1 + L, B] row 0 is the null-text row + ggml_tensor* text_count = nullptr; // [1, 1, B] number of valid text rows + ggml_tensor* pal_feat = nullptr; // [3 + 6*colour_freqs, P, B] host OKLab + Fourier + ggml_tensor* pal_ramp = nullptr; // [P, B] i32 + ggml_tensor* pal_level = nullptr; // [P, B] + ggml_tensor* pal_valid = nullptr; // [P, B] 0/1 (pointer head: -inf on invalid slots) + ggml_tensor* txt_key_mask = nullptr; // [1 + L, 1, n_head * B, 1] additive + ggml_tensor* text_kept = nullptr; // [1, 1, B] 0 when the whole text row is dropped + ggml_tensor* core_key_mask = nullptr; // [S + nc*nc, 1, n_head * B, 1] additive + ggml_tensor* core_cos = nullptr; // [head_dim/2, 1, S + nc*nc, 1] + ggml_tensor* core_sin = nullptr; + ggml_tensor* merge64 = nullptr; // [size*size, B] i32 gather order + ggml_tensor* merge32 = nullptr; + ggml_tensor* split64 = nullptr; // inverse of merge64 + ggml_tensor* split32 = nullptr; + int64_t B = 1; + int64_t n_text = 0; // L, excluding the null-text row + int64_t n_pal = 0; // P (0 = no palette tokens in the core) + }; + + struct RDFlowModelOutputs { + ggml_tensor* x_hat = nullptr; // [size, size, 4, B] predicted clean image + ggml_tensor* feats = nullptr; // [d0, size*size, B] pointer-head pixel features + }; + + // The full hourglass network. + struct PixelFlowModel : public GGMLBlock { + RDFlowConfig cfg; + PixelFlowModel(const RDFlowConfig& cfg) + : cfg(cfg) { + blocks["inp"] = std::make_shared(CHANNELS * (cfg.self_cond ? 2 : 1), cfg.d0); + blocks["t_mlp.0"] = std::make_shared(256, cfg.dc); + blocks["t_mlp.2"] = std::make_shared(cfg.dc, cfg.dc); + blocks["style"] = std::make_shared(cfg.n_styles, cfg.dc); + blocks["source"] = std::make_shared(cfg.n_sources, cfg.dc); + blocks["text_pool"] = std::make_shared(cfg.text_dim, cfg.dc); + blocks["text_proj"] = std::make_shared(cfg.text_dim, cfg.dc); + if (cfg.attrs) + for (int j = 0; j < 4; ++j) + blocks["attr_emb." + std::to_string(j)] = std::make_shared(ATTR_VOCAB[j], cfg.dc); + if (cfg.bg_mode) + blocks["bg_emb"] = std::make_shared(3, cfg.dc); + for (int i = 0; i < cfg.text_adapter; ++i) + blocks["adapter." + std::to_string(i)] = std::make_shared(cfg.dc, cfg, false); + blocks["down0"] = std::make_shared(cfg.d0, cfg.n0(), (int)cfg.depth0, cfg); + blocks["merge0"] = std::make_shared(4 * cfg.d0, cfg.d1); + blocks["down1"] = std::make_shared(cfg.d1, cfg.n1(), (int)cfg.depth1, cfg); + blocks["merge1"] = std::make_shared(4 * cfg.d1, cfg.dc); + for (int i = 0; i < cfg.depth_core; ++i) + blocks["core." + std::to_string(i)] = std::make_shared(cfg.dc, cfg, false); + blocks["core_ada"] = std::make_shared(cfg.dc, 6 * cfg.dc); + blocks["split1"] = std::make_shared(cfg.dc, 4 * cfg.d1); + blocks["skip1"] = std::make_shared(2 * cfg.d1, cfg.d1); + blocks["up1"] = std::make_shared(cfg.d1, cfg.n1(), (int)cfg.depth1, cfg); + blocks["split0"] = std::make_shared(cfg.d1, 4 * cfg.d0); + blocks["skip0"] = std::make_shared(2 * cfg.d0, cfg.d0); + blocks["up0"] = std::make_shared(cfg.d0, cfg.n0(), (int)cfg.depth0, cfg); + blocks["out_norm"] = std::make_shared(cfg.d0); + blocks["x_head"] = std::make_shared(cfg.d0, CHANNELS); + blocks["colour"] = std::make_shared(cfg); + if (cfg.palette_tokens) { + blocks["ramp_emb"] = std::make_shared(N_RAMPS, cfg.colour_hidden); + blocks["level_proj"] = std::make_shared(1, cfg.colour_hidden); + blocks["pal_tok"] = std::make_shared(cfg.colour_hidden, cfg.dc); + } + blocks["q"] = std::make_shared(cfg.d0, cfg.dk); + blocks["k.0"] = std::make_shared(cfg.colour_hidden, cfg.dk); + blocks["k.2"] = std::make_shared(cfg.dk, cfg.dk); + blocks["transparent"] = std::make_shared(cfg.d0, 1); + } + + void init_params(ggml_context* ctx, const String2TensorStorage&, const std::string = "") override { + params["null_text"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, cfg.text_dim, 1); + params["registers"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, cfg.dc, cfg.n_registers); + params["modality"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, cfg.dc, cfg.palette_tokens ? 4 : 3); + } + + Linear* lin(const std::string& name) { return std::dynamic_pointer_cast(blocks[name]).get(); } + + // modality[i]: [dc] view. + ggml_tensor* modality(GGMLRunnerContext* ctx, int i) { + auto g = ctx->ggml_ctx; + return ggml_view_1d(g, params["modality"], cfg.dc, (size_t)i * params["modality"]->nb[1]); + } + + // [D, n*n, B] -> [4D, (n/2)^2, B]; patch pair (yi,xi) is the channel + // block order (yi * 2 + xi). + ggml_tensor* merge_tokens(GGMLRunnerContext* ctx, ggml_tensor* h, int64_t n, int64_t d, ggml_tensor* perm) { + auto g = ctx->ggml_ctx; + auto gathered = ggml_get_rows(g, h, perm); // [d, n*n, B] in slot order + return ggml_reshape_3d(g, gathered, 4 * d, (n / 2) * (n / 2), h->ne[2]); + } + + // Inverse of merge_tokens: [4D, (n/2)^2, B] -> [D, n*n, B]. + ggml_tensor* split_tokens(GGMLRunnerContext* ctx, ggml_tensor* x, int64_t n, int64_t d, ggml_tensor* inv) { + auto g = ctx->ggml_ctx; + const int64_t B = x->ne[2]; + // The merged channel axis is (pair * d + channel) and the token axis is + // (block * 4 + pair), so a plain reshape already gives token = block*4+pair. + auto t = ggml_reshape_3d(g, x, d, 4 * ((n / 2) * (n / 2)), B); // token = block*4 + pair + return ggml_get_rows(g, t, inv); // [d, n*n, B] + } + + ggml_tensor* image_from_tokens(GGMLRunnerContext* ctx, ggml_tensor* tok) { + auto g = ctx->ggml_ctx; + const int64_t B = tok->ne[2]; + auto grid = ggml_reshape_4d(g, tok, CHANNELS, cfg.size, cfg.size, B); // [4, x, y, B] + return ggml_cont(g, ggml_permute(g, grid, 2, 0, 1, 3)); // [x, y, 4, B] + } + + // Joint (unwindowed) attention over [dc, L, B] tokens, with 2-D rope when + // cos/sin are given and an additive key-padding mask. + ggml_tensor* attn_joint(GGMLRunnerContext* ctx, RDBlock* blk, ggml_tensor* h, ggml_tensor* cos, ggml_tensor* sin, ggml_tensor* key_mask) { + auto g = ctx->ggml_ctx; + auto attn = blk->attention(); + const int64_t B = h->ne[2]; + const int64_t L = h->ne[1]; + const int64_t nh = cfg.dc / cfg.head_dim; + auto qkv = attn->qkv_heads(ctx, h); // [head_dim, nh, L, B] + auto q = cos ? rope_half(ctx, qkv[0], cos, sin) : qkv[0]; + auto k = cos ? rope_half(ctx, qkv[1], cos, sin) : qkv[1]; + // attention_ext wants [d_model, seq, batch]; the (head_dim, head, seq, + // batch) order qkv_heads returns is already what it reshapes to. + auto flat = [&](ggml_tensor* t) { + if (!ggml_is_contiguous(t)) { + t = ggml_cont(g, t); + } + return ggml_reshape_3d(g, t, cfg.dc, L, B); + }; + auto o = ggml_ext_attention_ext(ctx, flat(q), flat(k), flat(qkv[2]), nh, key_mask, false, false); + return attn->project(ctx, o); // [dc, L, B] + } + + RDFlowModelOutputs forward(GGMLRunnerContext* ctx, + const RDFlowModelInputs& in, + const RDWindowCache& cache64, + const RDWindowCache& cache32, + bool want_features) { + auto g = ctx->ggml_ctx; + const int64_t B = in.B; + const int64_t N = cfg.size * cfg.size; + const int64_t nc = cfg.nc(); + RDFlowModelOutputs out; + + // 1. conditioning vector c = t_mlp(temb) + style + source + text_pool + // + attrs + bg [dc, 1, B] + auto c = lin("t_mlp.2")->forward(ctx, ggml_silu(g, lin("t_mlp.0")->forward(ctx, in.temb))); + auto add_embedding = [&](ggml_tensor* ids, const std::string& name) { + auto emb = std::dynamic_pointer_cast(blocks[name])->forward(ctx, ids); // [dc, B, 1] + c = ggml_add(g, c, ggml_reshape_3d(g, emb, cfg.dc, 1, B)); + }; + add_embedding(in.style_ids, "style"); + add_embedding(in.source_ids, "source"); + + auto null_row = ggml_reshape_3d(g, params["null_text"], cfg.text_dim, 1, 1); + null_row = ggml_repeat(g, null_row, ggml_new_tensor_3d(g, GGML_TYPE_F32, cfg.text_dim, 1, B)); + // A sample whose text is entirely dropped feeds all-zero text features + // (only the null-text row survives), which also zeroes text_proj. + auto text_raw = in.text; + if (in.text_kept != nullptr) { + text_raw = ggml_mul(g, in.text, ggml_repeat(g, in.text_kept, in.text)); + } + auto text_all = ggml_concat(g, null_row, text_raw, 1); // [text_dim, 1 + L, B] + { + auto mask = ggml_reshape_3d(g, in.text_mask, 1, 1 + in.n_text, B); + auto weighted = ggml_mul(g, text_all, mask); + auto summed = ggml_sum_rows(g, ggml_cont(g, ggml_permute(g, weighted, 1, 0, 2, 3))); // [1, text_dim, B] + auto pooled = ggml_cont(g, ggml_permute(g, ggml_div(g, summed, in.text_count), 1, 0, 2, 3)); // [text_dim, 1, B] + c = ggml_add(g, c, lin("text_pool")->forward(ctx, pooled)); + } + for (int j = 0; j < 4; ++j) + if (in.attr_ids[j] != nullptr) + add_embedding(in.attr_ids[j], "attr_emb." + std::to_string(j)); + if (in.bg_ids != nullptr) + add_embedding(in.bg_ids, "bg_emb"); + + // 2. input tokens: cat([x_t, self_cond]) -> [8, N, B] + auto to_tokens = [&](ggml_tensor* img) { + // ggml_permute here maps source axis k to destination axis p[k]. + auto t = ggml_cont(g, ggml_permute(g, img, 1, 2, 0, 3)); // [4, x, y, B] + return ggml_reshape_3d(g, t, CHANNELS, N, B); + }; + auto xin = to_tokens(in.x_img); + if (cfg.self_cond) { + ggml_tensor* sc = nullptr; + if (in.sc_img != nullptr) { + sc = to_tokens(in.sc_img); + } else { + sc = ggml_ext_zeros(ctx, CHANNELS, N, B, 1); + } + xin = ggml_concat(g, xin, sc, 0); + } + + // 3. down levels + auto in0 = lin("inp")->forward(ctx, xin); + auto h0 = std::dynamic_pointer_cast(blocks["down0"])->forward(ctx, in0, c, cache64); // [d0, N, B] + auto m0 = lin("merge0")->forward(ctx, merge_tokens(ctx, h0, cfg.size, cfg.d0, in.merge64)); + auto h1 = std::dynamic_pointer_cast(blocks["down1"])->forward(ctx, m0, c, cache32); // [d1, nc*4, B] + + // 4. text adapter: ctx includes the null-text row; zero modulation, per-block table only + auto ctx_tok = lin("text_proj")->forward(ctx, text_all); // [dc, 1 + L, B] + for (int i = 0; i < cfg.text_adapter; ++i) { + auto blk = std::dynamic_pointer_cast(blocks["adapter." + std::to_string(i)]); + auto zmod = ggml_ext_zeros(ctx, cfg.dc, 6, B, 1); + ctx_tok = blk->forward(ctx, ctx_tok, zmod, [&](ggml_tensor* h) { return attn_joint(ctx, blk.get(), h, nullptr, nullptr, in.txt_key_mask); }, 0); + } + + // 5. core: [registers; text; palette; image] with rope on the image only + auto mc = lin("merge1")->forward(ctx, merge_tokens(ctx, h1, cfg.n1(), cfg.d1, in.merge32)); // [dc, nc*nc, B] + auto tok = ggml_add(g, ggml_repeat(g, ggml_reshape_3d(g, params["registers"], cfg.dc, cfg.n_registers, 1), ggml_new_tensor_3d(g, GGML_TYPE_F32, cfg.dc, cfg.n_registers, B)), + modality(ctx, 0)); + tok = ggml_concat(g, tok, ggml_add(g, ctx_tok, modality(ctx, 1)), 1); + if (in.n_pal > 0) { + auto e = std::dynamic_pointer_cast(blocks["colour"])->forward(ctx, in.pal_feat); // [hidden, P, B] + e = ggml_add(g, e, std::dynamic_pointer_cast(blocks["ramp_emb"])->forward(ctx, in.pal_ramp)); + e = ggml_add(g, e, lin("level_proj")->forward(ctx, ggml_reshape_3d(g, in.pal_level, 1, in.n_pal, B))); + auto pt = lin("pal_tok")->forward(ctx, e); + tok = ggml_concat(g, tok, ggml_add(g, pt, modality(ctx, 3)), 1); + } + tok = ggml_concat(g, tok, ggml_add(g, mc, modality(ctx, 2)), 1); + for (int i = 0; i < cfg.depth_core; ++i) { + auto blk = std::dynamic_pointer_cast(blocks["core." + std::to_string(i)]); + tok = blk->forward(ctx, tok, ggml_reshape_3d(g, lin("core_ada")->forward(ctx, ggml_silu(g, c)), cfg.dc, 6, B), [&](ggml_tensor* h) { return attn_joint(ctx, blk.get(), h, in.core_cos, in.core_sin, in.core_key_mask); }, 0); + } + const int64_t S = cfg.n_registers + 1 + in.n_text + in.n_pal; + GGML_ASSERT(tok->ne[1] == S + nc * nc); + auto hc = ggml_ext_slice(ctx, tok, 1, S, S + nc * nc); + + // 6. up levels with skips + auto sp1 = lin("split1")->forward(ctx, hc); + auto s1 = split_tokens(ctx, sp1, cfg.n1(), cfg.d1, in.split32); + auto sk1 = lin("skip1")->forward(ctx, ggml_concat(g, s1, h1, 0)); + auto u1 = std::dynamic_pointer_cast(blocks["up1"])->forward(ctx, sk1, c, cache32); + auto sp0 = lin("split0")->forward(ctx, u1); + auto s0 = split_tokens(ctx, sp0, cfg.size, cfg.d0, in.split64); + auto sk0 = lin("skip0")->forward(ctx, ggml_concat(g, s0, h0, 0)); + auto up0 = std::dynamic_pointer_cast(blocks["up0"])->forward(ctx, sk0, c, cache64); + auto u0 = std::dynamic_pointer_cast(blocks["out_norm"])->forward(ctx, up0); + + // 7. heads + auto xh = lin("x_head")->forward(ctx, u0); + out.x_hat = image_from_tokens(ctx, xh); + if (want_features) + out.feats = u0; + return out; + } + + // Pointer logits [1 + P, size*size, B]; channel 0 is transparent, + // 1 + s is palette slot s (invalid slots are -inf). + ggml_tensor* pointer_logits(GGMLRunnerContext* ctx, + ggml_tensor* feats, + const RDFlowModelInputs& in) { + auto g = ctx->ggml_ctx; + auto e = std::dynamic_pointer_cast(blocks["colour"])->forward(ctx, in.pal_feat); + e = ggml_add(g, e, std::dynamic_pointer_cast(blocks["ramp_emb"])->forward(ctx, in.pal_ramp)); + e = ggml_add(g, e, lin("level_proj")->forward(ctx, ggml_reshape_3d(g, in.pal_level, 1, in.n_pal, in.B))); + auto keys = lin("k.2")->forward(ctx, ggml_silu(g, lin("k.0")->forward(ctx, e))); // [dk, P, B] + auto q = lin("q")->forward(ctx, feats); // [dk, N, B] + auto logits = ggml_mul_mat(g, keys, q); // [P, N, B] + logits = ggml_scale_inplace(g, logits, 1.0f / std::sqrt((float)cfg.dk)); + // per-slot bias: logits is [P, N, B], so the -inf mask broadcasts as [P, 1, B] + logits = ggml_add(g, logits, ggml_reshape_3d(g, in.pal_valid, in.n_pal, 1, in.B)); + auto transparent = lin("transparent")->forward(ctx, feats); // [1, N, B] + return ggml_concat(g, transparent, logits, 0); + } + }; + + struct RDFlowRunner : public DiffusionModelRunner { + // One drawing-model request. Tensor shapes are sd::Tensor (host) shapes. + struct Palette { + const sd::Tensor* rgb = nullptr; // [P, 3, B] sRGB 0..255 + const sd::Tensor* ramp = nullptr; // [P, B] + const sd::Tensor* level = nullptr; // [P, B] + const sd::Tensor* valid = nullptr; // [P, B] 0/1 + int64_t P = 0; + }; + + struct Request { + const sd::Tensor* x = nullptr; // [size, size, 4, B] + std::vector t; // per image, 0 = noise, 1 = data + const sd::Tensor* text = nullptr; // [text_dim, L] + const sd::Tensor* text_mask = nullptr; // [L, B] 0/1 (an all-zero row = no text) + const sd::Tensor* self_cond = nullptr; // [size, size, 4, B] or null + Palette pal; + int bg_mode = 2; // 1 opaque, 2 transparent + int style = 0; + int source = 6; + int attrs[4] = {0, 0, 0, 0}; + bool want_features = false; + }; + + struct Prediction { + sd::Tensor x_hat; // [size, size, 4, B] + sd::Tensor feats; // [d0, size*size, B] + }; + + sd::PECache pe_cache_; + RDFlowConfig config; + PixelFlowModel model; + + private: + std::map> index_cache_; + + const sd::Tensor& cached_index(const std::string& key, + const std::vector& perm, + int64_t batch) { + auto it = index_cache_.find(key); + if (it == index_cache_.end()) { + it = index_cache_.emplace(key, make_index_tensor(perm, batch)).first; + } + return it->second; + } + + const sd::Tensor& cached_table(const std::string& name, + const std::function()>& build, + int64_t a = 0, + int64_t b = 0) { + sd::PECacheKey key(name); + key.add(a).add(b); + return pe_cache_.get_or_create(key, build); + } + + // Window partitions and rope tables for one level (n = grid side). + RDWindowCache window_tables(int64_t n, int64_t batch) { + const int w = (int)config.window; + const int shift = w / 2; + RDWindowCache cache; + cache.perm_even = make_input(cached_index("perm." + std::to_string(n) + ".0." + std::to_string(batch), + window_perm((int)n, w, 0), batch)); + cache.inv_even = make_input(cached_index("inv." + std::to_string(n) + ".0." + std::to_string(batch), + invert_perm(window_perm((int)n, w, 0)), batch)); + cache.perm_odd = make_input(cached_index("perm." + std::to_string(n) + "." + std::to_string(shift) + "." + + std::to_string(batch), + window_perm((int)n, w, shift), batch)); + cache.inv_odd = make_input(cached_index("inv." + std::to_string(n) + "." + std::to_string(shift) + "." + + std::to_string(batch), + invert_perm(window_perm((int)n, w, shift)), batch)); + cache.cos_even = make_input(cached_table("win_cos." + std::to_string(n) + ".0", [&]() { return make_window_rope((int)n, w, 0, (int)config.head_dim, config.rope_theta).first; }, n, config.head_dim)); + cache.sin_even = make_input(cached_table("win_sin." + std::to_string(n) + ".0", [&]() { return make_window_rope((int)n, w, 0, (int)config.head_dim, config.rope_theta).second; }, n, config.head_dim)); + cache.cos_odd = make_input(cached_table("win_cos." + std::to_string(n) + "." + std::to_string(shift), [&]() { return make_window_rope((int)n, w, shift, (int)config.head_dim, config.rope_theta).first; }, n, config.head_dim)); + cache.sin_odd = make_input(cached_table("win_sin." + std::to_string(n) + "." + std::to_string(shift), [&]() { return make_window_rope((int)n, w, shift, (int)config.head_dim, config.rope_theta).second; }, n, config.head_dim)); + return cache; + } + + std::pair*, const sd::Tensor*> core_rope(int64_t leading) { + const auto& cos = cached_table("core_cos", [this, leading]() { return make_core_rope((int)config.head_dim, config.rope_theta, leading, config.nc()).first; }, leading, config.head_dim); + const auto& sin = cached_table("core_sin", [this, leading]() { return make_core_rope((int)config.head_dim, config.rope_theta, leading, config.nc()).second; }, leading, config.head_dim); + return {&cos, &sin}; + } + + // Host-side gather/scatter orders for the 2x2 merge and split. + struct HourglassTables { + ggml_tensor* merge64 = nullptr; + ggml_tensor* merge32 = nullptr; + ggml_tensor* split64 = nullptr; + ggml_tensor* split32 = nullptr; + }; + + HourglassTables hourglass_tables(int64_t batch) { + HourglassTables tables; + tables.merge64 = make_input(cached_index("merge." + std::to_string(config.size) + "." + std::to_string(batch), + merge_perm((int)config.size), batch)); + tables.merge32 = make_input(cached_index("merge." + std::to_string(config.n1()) + "." + std::to_string(batch), + merge_perm((int)config.n1()), batch)); + tables.split64 = make_input(cached_index("split." + std::to_string(config.size) + "." + std::to_string(batch), + invert_perm(merge_perm((int)config.size)), batch)); + tables.split32 = make_input(cached_index("split." + std::to_string(config.n1()) + "." + std::to_string(batch), + invert_perm(merge_perm((int)config.n1())), batch)); + return tables; + } + + // One int per image, as ggml_get_rows expects [n_token, 1]. + sd::Tensor id_tensor(int64_t batch, int32_t value) { + sd::Tensor ids({batch, 1}); + std::fill(ids.data(), ids.data() + ids.numel(), value); + return ids; + } + + // [text_dim, L] -> [text_dim, L, B] (the same prompt for every image). + // A per-image text tensor ([text_dim, L, B], what the conditioner emits + // for a CFG batch) is passed through unchanged. + sd::Tensor repeat_text(const sd::Tensor& text, int64_t batch) { + if (batch == 1 || (text.dim() >= 3 && text.shape()[2] == batch)) + return text; + const int64_t per = text.numel(); + sd::Tensor out({text.shape()[0], text.shape()[1], batch}); + for (int64_t b = 0; b < batch; ++b) + std::copy(text.data(), text.data() + per, out.data() + b * per); + return out; + } + + // Build [1 + L, B] (row 0 marks the null-text row, on only when the + // image has no text at all) and the [1, 1, B] counts. + void text_pooling_tables(const Request& req, int64_t batch, std::vector& mask_all, std::vector& counts) { + const int64_t L = req.text_mask->shape()[0]; + const int64_t rows = L + 1; + mask_all.assign((size_t)rows * (size_t)batch, 0.f); + counts.assign((size_t)batch, 0.f); + for (int64_t b = 0; b < batch; ++b) { + int64_t valid = 0; + for (int64_t l = 0; l < L; ++l) { + const float on = (*req.text_mask)[b * L + l] > 0.f ? 1.f : 0.f; + mask_all[(size_t)(l + 1) + (size_t)rows * (size_t)b] = on; + valid += on > 0.f ? 1 : 0; + } + mask_all[(size_t)b * rows] = valid == 0 ? 1.f : 0.f; + counts[(size_t)b] = std::max(valid, 1); + } + } + + public: + sd::Tensor palette_key_mask(const Palette& pal, int64_t batch) { + sd::Tensor mask({1, pal.P, batch}); + for (int64_t b = 0; b < batch; ++b) + for (int64_t p = 0; p < pal.P; ++p) + mask[(b * pal.P) + p] = (*pal.valid)[b * pal.P + p] > 0.f ? 0.f : -INFINITY; + return mask; + } + + private: + // Joint key-padding mask for the core: [leading, batch] valid flags over + // registers, text, palette and image tokens, expanded over heads. + sd::Tensor core_key_mask(const Request& req, + int64_t batch, + int64_t leading, + const std::vector& mask_all) { + const int64_t nc = config.nc(); + const int64_t keys = leading + nc * nc; + const int64_t rows = 1 + req.text_mask->shape()[0]; + std::vector valid((size_t)keys * (size_t)batch, 1.f); + for (int64_t b = 0; b < batch; ++b) { + float* row = valid.data() + (size_t)b * (size_t)keys; + // registers are always valid; the null_text token is only attended when + // the whole row was dropped + for (int64_t l = 0; l < rows; ++l) + row[config.n_registers + l] = mask_all[(size_t)b * (size_t)rows + (size_t)l] > 0.f ? 1.f : 0.f; + for (int64_t p = 0; p < req.pal.P; ++p) + row[config.n_registers + rows + p] = (*req.pal.valid)[b * req.pal.P + p] > 0.f ? 1.f : 0.f; + } + return make_key_mask(valid, config.dc / config.head_dim, batch); + } + + public: + RDFlowRunner(ggml_backend_t backend, + const String2TensorStorage& tensor_storage_map = {}, + const std::string prefix = "", + std::shared_ptr weight_manager = nullptr) + : DiffusionModelRunner(backend, prefix, weight_manager), + config(RDFlowConfig::detect_from_weights(tensor_storage_map, prefix)), + model(config) { + model.init(params_ctx, tensor_storage_map, prefix); + } + + std::string get_desc() override { return "RD Flow 64"; } + + void get_param_tensors(std::map& tensors, const std::string& prefix) override { + model.get_param_tensors(tensors, prefix); + } + + int64_t batch_of(const sd::Tensor& x) { + return x.dim() >= 4 ? x.shape()[3] : 1; + } + + // Forward pass. Returns the predicted clean image and (optionally) the + // pointer-head pixel features. + // + // The joint key-padding mask varies per image (the unconditional half of a + // CFG pair masks its text rows away), and ggml can only broadcast an + // additive mask over the head/batch axis it shares, so a batched request + // runs one image at a time. + Prediction predict(const Request& request, int n_threads) { + const int64_t batch = batch_of(*request.x); + if (batch <= 1) { + return predict_one(request, n_threads); + } + Prediction out; + for (int64_t b = 0; b < batch; ++b) { + Sliced sliced; + build_slice(request, b, sliced); + auto part = predict_one(sliced.request, n_threads); + if (b == 0) { + out.x_hat = sd::Tensor(std::vector{sliced.x.shape()[0], sliced.x.shape()[1], + sliced.x.shape()[2], batch}); + if (!part.feats.empty()) { + out.feats = sd::Tensor(std::vector{part.feats.shape()[0], part.feats.shape()[1], batch}); + } + } + const int64_t per_x = out.x_hat.numel() / batch; + std::copy(part.x_hat.data(), part.x_hat.data() + per_x, out.x_hat.data() + b * per_x); + if (!out.feats.empty() && !part.feats.empty()) { + const int64_t per_f = out.feats.numel() / batch; + std::copy(part.feats.data(), part.feats.data() + per_f, out.feats.data() + b * per_f); + } + } + return out; + } + + private: + // Holds the per-image copies a sub-request points at. + struct Sliced { + sd::Tensor x, text, text_mask, self_cond, pal_rgb, pal_valid, pal_level; + sd::Tensor pal_ramp; + Request request; + }; + + template + static sd::Tensor slice_batch(const sd::Tensor& t, int64_t b) { + std::vector shape = t.shape(); + int64_t per = 1; + for (size_t i = 0; i + 1 < shape.size(); ++i) { + per *= shape[i]; + } + shape.back() = 1; + sd::Tensor out(shape); + std::copy(t.data() + b * per, t.data() + (b + 1) * per, out.data()); + return out; + } + + void build_slice(const Request& src, int64_t b, Sliced& s) { + s.x = slice_batch(*src.x, b); + s.text = src.text->dim() >= 3 ? slice_batch(*src.text, b) : *src.text; + s.text_mask = slice_batch(*src.text_mask, b); + s.request.x = &s.x; + s.request.text = &s.text; + s.request.text_mask = &s.text_mask; + s.request.t = {src.t[(size_t)b]}; + s.request.style = src.style; + s.request.source = src.source; + s.request.bg_mode = src.bg_mode; + for (int j = 0; j < 4; ++j) { + s.request.attrs[j] = src.attrs[j]; + } + s.request.want_features = src.want_features; + if (src.self_cond != nullptr) { + s.self_cond = slice_batch(*src.self_cond, b); + s.request.self_cond = &s.self_cond; + } + if (src.pal.P > 0 && src.pal.rgb != nullptr) { + s.pal_rgb = slice_batch(*src.pal.rgb, b); + s.pal_valid = slice_batch(*src.pal.valid, b); + s.pal_level = slice_batch(*src.pal.level, b); + s.pal_ramp = slice_batch(*src.pal.ramp, b); + s.request.pal.rgb = &s.pal_rgb; + s.request.pal.valid = &s.pal_valid; + s.request.pal.level = &s.pal_level; + s.request.pal.ramp = &s.pal_ramp; + s.request.pal.P = src.pal.P; + } + } + + public: + Prediction predict_one(const Request& request, int n_threads) { + GGML_ASSERT(request.x != nullptr); + GGML_ASSERT(request.text != nullptr); + GGML_ASSERT(request.text_mask != nullptr); + const int64_t batch = batch_of(*request.x); + GGML_ASSERT((int64_t)request.t.size() == batch); + + auto temb = make_timestep_embedding(request.t, 256); + auto text = repeat_text(*request.text, batch); + std::vector mask_all, counts; + text_pooling_tables(request, batch, mask_all, counts); + sd::Tensor mask_all_t(std::vector{1 + request.text_mask->shape()[0], batch}, mask_all); + std::vector kept((size_t)batch); + const int64_t rows = request.text_mask->shape()[0] + 1; + for (int64_t b = 0; b < batch; ++b) { + kept[(size_t)b] = mask_all[(size_t)b * rows] > 0.f ? 0.f : 1.f; // dropped -> zero text + } + sd::Tensor kept_t(std::vector{1, 1, batch}, kept); + sd::Tensor counts_t(std::vector{1, 1, batch}, counts); + const bool has_pal = request.pal.P > 0 && request.pal.rgb != nullptr; + sd::Tensor pal_feat; + if (has_pal) + pal_feat = colour_features(*request.pal.rgb, (int)config.colour_freqs, batch); + sd::Tensor pal_valid; + if (has_pal) + pal_valid = *request.pal.valid; + + const int64_t leading = config.n_registers + 1 + request.text_mask->shape()[0] + (has_pal ? request.pal.P : 0); + auto rope = core_rope(leading); + auto key_mask = core_key_mask(request, batch, leading, mask_all); + // make_input only records a host pointer; every input tensor has to stay + // alive until the graph has been computed. + std::vector> ids; + ids.push_back(id_tensor(batch, request.style)); + ids.push_back(id_tensor(batch, request.source)); + if (config.bg_mode) { + ids.push_back(id_tensor(batch, request.bg_mode)); + } + if (config.attrs) { + for (int j = 0; j < 4; ++j) { + ids.push_back(id_tensor(batch, request.attrs[j])); + } + } + sd::Tensor txt_key_mask = make_key_mask(mask_all, config.dc / config.head_dim, batch); + + Prediction prediction; + ggml_tensor* graph_x_hat = nullptr; + ggml_tensor* graph_feats = nullptr; + auto get_graph = [&]() -> ggml_cgraph* { + ggml_cgraph* gf = new_graph_custom(RD_FLOW_GRAPH_SIZE); + auto runner_ctx = get_context(gf); + + RDFlowModelInputs in; + in.B = batch; + in.n_text = request.text_mask->shape()[0]; + in.n_pal = has_pal ? request.pal.P : 0; + in.x_img = make_input(*request.x); + in.sc_img = request.self_cond != nullptr ? make_input(*request.self_cond) : nullptr; + in.temb = make_input(temb); + in.style_ids = make_input(ids[0]); + in.source_ids = make_input(ids[1]); + in.bg_ids = config.bg_mode ? make_input(ids[2]) : nullptr; + if (config.attrs) + for (int j = 0; j < 4; ++j) + in.attr_ids[j] = make_input(ids[config.bg_mode ? 3 + j : j]); + in.text = make_input(text); + in.text_mask = make_input(mask_all_t); + in.text_kept = make_input(kept_t); + in.text_count = make_input(counts_t); + if (has_pal) { + in.pal_feat = make_input(pal_feat); + in.pal_ramp = make_input(*request.pal.ramp); + in.pal_level = make_input(*request.pal.level); + in.pal_valid = make_input(pal_valid); + } + in.txt_key_mask = make_input(txt_key_mask); + in.core_key_mask = make_input(key_mask); + in.core_cos = make_input(*rope.first); + in.core_sin = make_input(*rope.second); + auto tables = hourglass_tables(batch); + in.merge64 = tables.merge64; + in.merge32 = tables.merge32; + in.split64 = tables.split64; + in.split32 = tables.split32; + auto cache64 = window_tables(config.size, batch); + auto cache32 = window_tables(config.n1(), batch); + + auto outputs = model.forward(&runner_ctx, in, cache64, cache32, request.want_features); + graph_x_hat = outputs.x_hat; + graph_feats = outputs.feats; + ggml_set_output(graph_x_hat); + ggml_build_forward_expand(gf, graph_x_hat); + if (graph_feats != nullptr) { + ggml_set_output(graph_feats); + ggml_build_forward_expand(gf, graph_feats); + } + return gf; + }; + auto read_outputs = [&]() { + prediction.x_hat = sd::make_sd_tensor_from_ggml(graph_x_hat); + if (graph_feats != nullptr) + prediction.feats = sd::make_sd_tensor_from_ggml(graph_feats); + return !prediction.x_hat.empty() && (graph_feats == nullptr || !prediction.feats.empty()); + }; + if (!GGMLRunner::compute(get_graph, n_threads, true, true, read_outputs).has_value()) { + throw std::runtime_error("rd-flow-64 forward pass failed"); + } + return prediction; + } + + // Pointer logits over the features of a previous forward. + sd::Tensor pointer_logits(const sd::Tensor& feats, + const Palette& palette, + int64_t batch, + int n_threads) { + GGML_ASSERT(palette.P > 0 && palette.rgb != nullptr); + auto pal_feat = colour_features(*palette.rgb, (int)config.colour_freqs, batch); + auto key_mask = palette_key_mask(palette, batch); + sd::Tensor logits; + ggml_tensor* graph_out = nullptr; + auto get_graph = [&]() -> ggml_cgraph* { + ggml_cgraph* gf = new_graph_custom(4096); + auto runner_ctx = get_context(gf); + RDFlowModelInputs in; + in.B = batch; + in.n_pal = palette.P; + in.pal_feat = make_input(pal_feat); + in.pal_ramp = make_input(*palette.ramp); + in.pal_level = make_input(*palette.level); + in.pal_valid = make_input(key_mask); + auto out = model.pointer_logits(&runner_ctx, make_input(feats), in); + graph_out = out; + ggml_set_output(out); + ggml_build_forward_expand(gf, out); + return gf; + }; + auto read_outputs = [&]() { + logits = sd::make_sd_tensor_from_ggml(graph_out); + return !logits.empty(); + }; + if (!GGMLRunner::compute(get_graph, n_threads, true, true, read_outputs).has_value()) { + throw std::runtime_error("rd-flow-64 pointer head failed"); + } + return logits; + } + + // Standard sample path: t in model space is 1 - sigma, and the runtime + // hands us timesteps as sigma * 1000 (runtime/denoiser.hpp TIMESTEPS). + sd::Tensor compute(int n_threads, const DiffusionParams& diffusion_params) override { + GGML_ASSERT(diffusion_params.x != nullptr); + GGML_ASSERT(diffusion_params.timesteps != nullptr); + const auto* extra = diffusion_extra_as(diffusion_params); + + Palette pal; + if (extra->pal_rgb != nullptr && extra->pal_valid != nullptr && extra->pal_ramp != nullptr && + extra->pal_level != nullptr && !extra->pal_rgb->empty()) { + pal.rgb = extra->pal_rgb; + pal.ramp = extra->pal_ramp; + pal.level = extra->pal_level; + pal.valid = extra->pal_valid; + pal.P = extra->pal_rgb->shape()[0]; + } + + // The pointer head runs on the features of a previous forward, so it + // takes those features as x and returns slot scores. + if (extra->pointer_head) { + GGML_ASSERT(pal.P > 0); + // features are [d_model, size * size, batch], so the batch axis is + // the last one rather than the fourth of an image tensor + const int64_t batch = diffusion_params.x->dim() >= 3 ? diffusion_params.x->shape().back() : 1; + return pointer_logits(*diffusion_params.x, pal, batch, n_threads); + } + + GGML_ASSERT(diffusion_params.context != nullptr); + Request request; + request.x = diffusion_params.x; + request.text = diffusion_params.context; + request.text_mask = extra->text_mask; + request.self_cond = extra->self_cond; + request.bg_mode = extra->bg_mode; + request.style = extra->style; + request.source = extra->source; + request.pal = pal; + request.want_features = extra->out_features != nullptr; + for (int64_t i = 0; i < diffusion_params.timesteps->numel(); ++i) + request.t.push_back(1.f - (*diffusion_params.timesteps)[i] / 1000.f); + GGML_ASSERT(request.text_mask != nullptr && !request.text_mask->empty()); + auto prediction = predict(request, n_threads); + if (extra->out_features != nullptr) { + *extra->out_features = std::move(prediction.feats); + } + return prediction.x_hat; + } + }; +} // namespace RDFlow + +#endif // __SD_MODEL_DIFFUSION_RD_FLOW_HPP__ diff --git a/src/model/diffusion/rd_flow_sampler.hpp b/src/model/diffusion/rd_flow_sampler.hpp new file mode 100644 index 0000000000..a56fbcebd5 --- /dev/null +++ b/src/model/diffusion/rd_flow_sampler.hpp @@ -0,0 +1,925 @@ +// RD Flow 64 sampler: host-side colour helpers and the Euler/pointer sampling +// loop. The model itself lives in rd_flow.hpp; this file only drives it. +#ifndef __SD_MODEL_DIFFUSION_RD_FLOW_SAMPLER_HPP__ +#define __SD_MODEL_DIFFUSION_RD_FLOW_SAMPLER_HPP__ + +#include "model/diffusion/rd_flow.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace RDFlow { + + constexpr int64_t RD_FLOW_SLOTS = 256; // palette slots (P) + // OKLab a, b are scaled by this in model space + constexpr float RD_FLOW_AB_SCALE = 3.0f; + + struct RDFlowRGB { + uint8_t r = 0, g = 0, b = 0; + bool operator<(const RDFlowRGB& o) const { + return std::tie(r, g, b) < std::tie(o.r, o.g, o.b); + } + bool operator==(const RDFlowRGB& o) const { return r == o.r && g == o.g && b == o.b; } + }; + + using OKLab = std::array; + + // round-half-to-even, matching numpy/torch rounding in the reference + static inline double round_half_even(double v) { + return std::nearbyint(v); + } + static inline float round_half_even_f(float v) { + return std::nearbyintf(v); + } + + // uint8 -> OKLab (float64 maths, float32 result) + inline OKLab srgb_to_oklab(const RDFlowRGB& c) { + double k[3] = {c.r / 255.0, c.g / 255.0, c.b / 255.0}; + for (double& v : k) + v = v <= 0.04045 ? v / 12.92 : std::pow((v + 0.055) / 1.055, 2.4); + const double r = k[0], g = k[1], b = k[2]; + const double l = std::cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const double m = std::cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const double s = std::cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + return {float(0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s), + float(1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s), + float(0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s)}; + } + + // layers.ColourEmbed.oklab: the model's own sRGB -> OKLab, computed in f32 + inline OKLab oklab_model(const RDFlowRGB& c) { + float k[3] = {c.r / 255.0f, c.g / 255.0f, c.b / 255.0f}; + for (float& v : k) + v = v <= 0.04045f ? v / 12.92f : std::pow((v + 0.055f) / 1.055f, 2.4f); + const float r = k[0], g = k[1], b = k[2]; + auto cube = [](float v) { return std::pow(v > 0.f ? v : 0.f, 1.0f / 3.0f); }; + const float l = cube(0.4122214708f * r + 0.5363325363f * g + 0.0514459929f * b); + const float m = cube(0.2119034982f * r + 0.6806995451f * g + 0.1073969566f * b); + const float s = cube(0.0883024619f * r + 0.2817188376f * g + 0.6299787005f * b); + return {0.2104542553f * l + 0.7936177850f * m - 0.0040720468f * s, + 1.9779984951f * l - 2.4285922050f * m + 0.4505937099f * s, + 0.0259040371f * l + 0.7827717662f * m - 0.8086757660f * s}; + } + + // OKLab -> sRGB 0..255 (f32 maths, round-half-to-even) + inline RDFlowRGB oklab_to_srgb(const OKLab& lab) { + const double L = lab[0], a = lab[1], b = lab[2]; + const double l = std::pow(L + 0.3963377774 * a + 0.2158037573 * b, 3.0); + const double m = std::pow(L - 0.1055613458 * a - 0.0638541728 * b, 3.0); + const double s = std::pow(L - 0.0894841775 * a - 1.2914855480 * b, 3.0); + double rgb[3] = {4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, + -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, + -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s}; + RDFlowRGB out; + uint8_t* dst[3] = {&out.r, &out.g, &out.b}; + for (int i = 0; i < 3; ++i) { + double v = std::clamp(rgb[i], 0.0, 1.0); + v = v <= 0.0031308 ? v * 12.92 : 1.055 * std::pow(std::max(v, 1e-12), 1.0 / 2.4) - 0.055; + *dst[i] = (uint8_t)std::clamp(round_half_even(v * 255.0), 0.0, 255.0); + } + return out; + } + + // The same conversion in float32. extract_palette uses this one, so the + // rounding of near-.5 channels matches the f32 golden palettes. + inline RDFlowRGB oklab_to_srgb_f32(const OKLab& lab) { + const float L = lab[0], a = lab[1], b = lab[2]; + const float l = std::pow(L + 0.3963377774f * a + 0.2158037573f * b, 3.0f); + const float m = std::pow(L - 0.1055613458f * a - 0.0638541728f * b, 3.0f); + const float s = std::pow(L - 0.0894841775f * a - 1.2914855480f * b, 3.0f); + float rgb[3] = {4.0767416621f * l - 3.3077115913f * m + 0.2309699292f * s, + -1.2684380046f * l + 2.6097574011f * m - 0.3413193965f * s, + -0.0041960863f * l - 0.7034186147f * m + 1.7076147010f * s}; + RDFlowRGB out; + uint8_t* dst[3] = {&out.r, &out.g, &out.b}; + for (int i = 0; i < 3; ++i) { + float v = std::clamp(rgb[i], 0.0f, 1.0f); + v = v <= 0.0031308f ? v * 12.92f : 1.055f * std::pow(std::max(v, 1e-12f), 1.0f / 2.4f) - 0.055f; + *dst[i] = (uint8_t)std::clamp(std::nearbyintf(v * 255.0f), 0.0f, 255.0f); + } + return out; + } + + // model-space pixel -> (OKLab, opaque) + inline void pixel_from_model(const float* x, OKLab& lab, bool& opaque) { + lab = {(x[0] + 1.0f) * 0.5f, x[1] / RD_FLOW_AB_SCALE, x[2] / RD_FLOW_AB_SCALE}; + opaque = x[3] > 0.0f; + } + + // numpy's np.unwrap for hue sequences (consecutive values differ by less than 2*pi) + inline std::vector hue_unwrap(const std::vector& v) { + std::vector out = v; + for (size_t i = 1; i < out.size(); ++i) { + double d = out[i] - out[i - 1]; + if (d > M_PI) + out[i] -= 2.0 * M_PI * std::ceil((d - M_PI) / (2.0 * M_PI)); + else if (d < -M_PI) + out[i] += 2.0 * M_PI * std::ceil((-d - M_PI) / (2.0 * M_PI)); + } + return out; + } + + // ramp_order: hue family, then lightness, then rgb (lexsort order) + inline std::vector ramp_order(const std::vector& colours) { + const float ACHROMATIC_C = 0.04f; + const size_t n = colours.size(); + std::vector L(n); + std::vector family(n); + for (size_t i = 0; i < n; ++i) { + const OKLab lab = srgb_to_oklab(colours[i]); + L[i] = lab[0]; + const float chroma = std::sqrt(lab[1] * lab[1] + lab[2] * lab[2]); + float hue = std::atan2(lab[2], lab[1]) * 180.0f / (float)M_PI; + hue = std::fmod(hue + 360.0f, 360.0f); + family[i] = chroma < ACHROMATIC_C ? 0 : 1 + std::min((int)std::floor(hue / 30.0f), 11); + } + std::vector idx(n); + for (size_t i = 0; i < n; ++i) + idx[i] = i; + // np.lexsort((b, g, r, L, family)): family is the primary key + std::stable_sort(idx.begin(), idx.end(), [&](size_t a, size_t b) { + if (family[a] != family[b]) + return family[a] < family[b]; + if (L[a] != L[b]) + return L[a] < L[b]; + if (colours[a].r != colours[b].r) + return colours[a].r < colours[b].r; + if (colours[a].g != colours[b].g) + return colours[a].g < colours[b].g; + return colours[a].b < colours[b].b; + }); + return idx; + } + + // OKLab palette -> (ramp id, dark->light level) + inline void palette_ramps(const std::vector& lab, std::vector& ramp, std::vector& level) { + const float NEUTRAL_C = 0.035f; + const double HUE_GAP = 28.0 * M_PI / 180.0; + const double HUE_SPAN = 75.0 * M_PI / 180.0; + const int MAX_RAMPS = 15; + const int n = (int)lab.size(); + ramp.assign(n, 0); + level.assign(n, 0.5f); + if (!n) + return; + std::vector L(n), hue(n); + std::vector chromatic, neutral; + for (int i = 0; i < n; ++i) { + L[i] = lab[i][0]; + // numpy keeps the float32 dtype here: chroma and hue are float32 values + const float chroma = std::sqrt(lab[i][1] * lab[i][1] + lab[i][2] * lab[i][2]); + double h = std::atan2(lab[i][2], lab[i][1]); + hue[i] = std::fmod(h + 2.0 * M_PI, 2.0 * M_PI); + if (chroma >= NEUTRAL_C) + chromatic.push_back(i); + else + neutral.push_back(i); + } + std::vector> groups; + if (!chromatic.empty()) { + std::vector order = chromatic; + std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return hue[a] < hue[b]; }); + std::vector gaps(order.size()); + for (size_t i = 0; i + 1 < order.size(); ++i) + gaps[i] = hue[order[i + 1]] - hue[order[i]]; + gaps.back() = hue[order[0]] + 2.0 * M_PI - hue[order.back()]; + size_t best = 0; + for (size_t i = 1; i < gaps.size(); ++i) + if (gaps[i] > gaps[best]) + best = i; + std::rotate(order.begin(), order.begin() + (long)(best + 1), order.end()); + std::vector seq; + seq.reserve(order.size()); + for (int i : order) + seq.push_back(hue[i]); + seq = hue_unwrap(seq); + std::vector cur{order[0]}; + for (size_t i = 1; i < order.size(); ++i) { + if (seq[i] - seq[i - 1] > HUE_GAP) { + groups.push_back(cur); + cur.clear(); + } + cur.push_back(order[i]); + } + groups.push_back(cur); + std::vector> split; + for (auto g : groups) { + while (g.size() > 2) { + std::vector hg; + hg.reserve(g.size()); + for (int i : g) + hg.push_back(hue[i]); + hg = hue_unwrap(hg); + if (hg.back() - hg.front() <= HUE_SPAN) + break; + size_t k = 0; + double worst = -1e300; + for (size_t i = 0; i + 1 < hg.size(); ++i) { + double d = hg[i + 1] - hg[i]; + if (d > worst) { + worst = d; + k = i + 1; + } + } + split.emplace_back(g.begin(), g.begin() + (long)k); + g.erase(g.begin(), g.begin() + (long)k); + } + split.push_back(g); + } + groups = split; + } + std::vector>> sets; + sets.emplace_back(0, neutral); + for (size_t i = 0; i < groups.size(); ++i) + sets.emplace_back(std::min((int)i + 1, MAX_RAMPS), groups[i]); + for (auto& [rid, g] : sets) { + if (g.empty()) + continue; + for (int i : g) + ramp[i] = rid; + if (g.size() > 1) { + // np.argsort(np.argsort(L[g])): rank of each element, ties keep their position + std::vector ord = g; + std::stable_sort(ord.begin(), ord.end(), [&](int a, int b) { return L[a] < L[b]; }); + for (size_t r = 0; r < ord.size(); ++r) + level[ord[r]] = (float)r / (float)(ord.size() - 1); + } + } + } + + // extract_palette: one image's continuous guess -> sRGB colours + inline std::vector extract_palette(const float* x, int64_t n, int max_colours = 64, double merge = 0.05, double bin_size = 0.015, int iters = 4) { + // OKLab of the opaque pixels, in float64 (the reference forces the CPU dtype) + std::vector> pts; + pts.reserve((size_t)n * n); + for (int64_t p = 0; p < n * n; ++p) { + const float* px = x + p * 4; + OKLab lab; + bool opaque = false; + pixel_from_model(px, lab, opaque); + if (!opaque) + continue; + pts.push_back({lab[0], lab[1], lab[2]}); + } + if (pts.empty()) + return {}; + // np.unique(round(pts / bin_size), axis=0) -> keys in lex order, inverse, counts + std::map, int> key_index; + std::vector inv(pts.size()); + std::vector counts; + std::vector> sums; + for (size_t i = 0; i < pts.size(); ++i) { + auto key = std::make_tuple((int64_t)round_half_even(pts[i][0] / bin_size), (int64_t)round_half_even(pts[i][1] / bin_size), + (int64_t)round_half_even(pts[i][2] / bin_size)); + auto it = key_index.find(key); + int ki; + if (it == key_index.end()) { + ki = (int)counts.size(); + key_index.emplace(key, ki); + counts.push_back(0.0); + sums.push_back({0.0, 0.0, 0.0}); + } else { + ki = it->second; + } + inv[i] = ki; + counts[ki] += 1.0; + for (int c = 0; c < 3; ++c) + sums[ki][c] += pts[i][c]; + } + // np.unique hands back its keys in lexicographic order and counts aligned to + // that order, and the stable argsort below breaks ties by key index. A std::map + // iterates in key order, so replay it to put the bin arrays in the same order. + { + const int nb = (int)counts.size(); + std::vector remap((size_t)nb); + std::vector counts_sorted((size_t)nb); + std::vector> sums_sorted((size_t)nb); + int ni = 0; + for (auto& [key, ki] : key_index) { + remap[(size_t)ki] = ni; + counts_sorted[(size_t)ni] = counts[(size_t)ki]; + sums_sorted[(size_t)ni] = sums[(size_t)ki]; + ++ni; + } + for (auto& v : inv) + v = remap[(size_t)v]; + counts = std::move(counts_sorted); + sums = std::move(sums_sorted); + } + const int nk = (int)counts.size(); + std::vector> means(nk); + for (int k = 0; k < nk; ++k) + for (int c = 0; c < 3; ++c) + means[k][c] = sums[k][c] / counts[k]; + // np.argsort(-counts, kind="stable"): descending count, ties in key order + std::vector order(nk); + for (int k = 0; k < nk; ++k) + order[k] = k; + std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return counts[a] > counts[b]; }); + std::vector> C; + for (int k : order) { + if (C.empty()) { + C.push_back(means[k]); + } else { + double best = 1e300; + for (auto& c : C) { + double d = std::sqrt(std::pow(c[0] - means[k][0], 2) + std::pow(c[1] - means[k][1], 2) + + std::pow(c[2] - means[k][2], 2)); + best = std::min(best, d); + } + if (best > merge) + C.push_back(means[k]); + } + if ((int)C.size() >= max_colours) + break; + } + for (int it = 0; it < iters && !C.empty(); ++it) { + std::vector assign(pts.size(), 0); + std::vector cnt(C.size(), 0.0); + for (size_t i = 0; i < pts.size(); ++i) { + double best = 1e300; + int bk = 0; + for (size_t k = 0; k < C.size(); ++k) { + double d = std::pow(pts[i][0] - C[k][0], 2) + std::pow(pts[i][1] - C[k][1], 2) + + std::pow(pts[i][2] - C[k][2], 2); + if (d < best) { + best = d; + bk = (int)k; + } + } + assign[i] = bk; + cnt[bk] += 1.0; + } + std::vector> nc; + for (size_t k = 0; k < C.size(); ++k) { + if (cnt[k] <= 0.0) + continue; + std::array s{0.0, 0.0, 0.0}; + for (size_t i = 0; i < pts.size(); ++i) + if (assign[i] == (int)k) + for (int c = 0; c < 3; ++c) + s[c] += pts[i][c]; + for (int c = 0; c < 3; ++c) + s[c] /= cnt[k]; + nc.push_back(s); + } + C = nc; + } + // torch.unique(oklab_to_srgb(C), dim=0): sorted unique rows + std::set out; + for (auto& c : C) + out.insert(oklab_to_srgb_f32({(float)c[0], (float)c[1], (float)c[2]})); + return {out.begin(), out.end()}; + } + + // A palette in the shape the sampler and the model need. rgb/valid/ramp/level are + // per image over P slots; space is [B][1 + P][4] model space (slot 0 = transparent). + struct RDFlowPalette { + int64_t B = 0; + int64_t P = 0; + std::vector rgb; + std::vector valid; + std::vector ramp; + std::vector level; + std::vector space; + bool empty() const { return P == 0; } + int64_t count_valid(int64_t b) const { + int64_t k = 0; + for (int64_t p = 0; p < P; ++p) + k += valid[(size_t)b * P + p] != 0; + return k; + } + }; + + inline RDFlowPalette palette_dict(const std::vector>& colour_lists) { + RDFlowPalette pal; + pal.B = (int64_t)colour_lists.size(); + pal.P = RD_FLOW_SLOTS; + pal.rgb.assign((size_t)pal.B * pal.P, RDFlowRGB{}); + pal.valid.assign((size_t)pal.B * pal.P, 0); + pal.ramp.assign((size_t)pal.B * pal.P, 0); + pal.level.assign((size_t)pal.B * pal.P, 0.5f); + for (size_t b = 0; b < colour_lists.size(); ++b) { + std::vector cols = colour_lists[b]; + if (cols.size() > (size_t)pal.P) + cols.resize((size_t)pal.P); + std::vector lab; + lab.reserve(cols.size()); + for (auto& c : cols) + lab.push_back(srgb_to_oklab(c)); + std::vector ramp; + std::vector level; + palette_ramps(lab, ramp, level); + for (size_t k = 0; k < cols.size(); ++k) { + pal.rgb[(size_t)b * pal.P + k] = cols[k]; + pal.valid[(size_t)b * pal.P + k] = 1; + pal.ramp[(size_t)b * pal.P + k] = ramp[k]; + pal.level[(size_t)b * pal.P + k] = level[k]; + } + } + // palette_model_space: slot 0 is transparent, then each colour in model space + pal.space.assign((size_t)pal.B * (pal.P + 1) * 4, 0.0f); + for (int64_t b = 0; b < pal.B; ++b) { + float* t = &pal.space[(size_t)b * (pal.P + 1) * 4]; + t[0] = t[1] = t[2] = 0.0f; + t[3] = -1.0f; + for (int64_t p = 0; p < pal.P; ++p) { + const OKLab lab = oklab_model(pal.rgb[(size_t)b * pal.P + p]); + float* dst = t + (p + 1) * 4; + dst[0] = 2.0f * lab[0] - 1.0f; + dst[1] = lab[1] * RD_FLOW_AB_SCALE; + dst[2] = lab[2] * RD_FLOW_AB_SCALE; + dst[3] = 1.0f; + } + } + return pal; + } + + // bucket_palette: the shortest fixed-length palette that still holds every image's colours + inline RDFlowPalette bucket_palette(const RDFlowPalette& pal) { + if (pal.empty()) + return {}; + int64_t need = 0; + for (int64_t b = 0; b < pal.B; ++b) + need = std::max(need, pal.count_valid(b)); + if (need == 0) + return {}; + static const int64_t buckets[] = {32, 64, 128, 256}; + int64_t keep = pal.P; + for (int64_t bucket : buckets) { + if (bucket >= need) { + keep = std::min(pal.P, bucket); + break; + } + } + keep = std::min(keep, pal.P); + // v[:, :keep] for every per-image field: the arrays are re-strided to `keep` + // slots per image, not merely truncated in place + RDFlowPalette out; + out.B = pal.B; + out.P = keep; + out.rgb.assign((size_t)pal.B * keep, RDFlowRGB{}); + out.valid.assign((size_t)pal.B * keep, 0); + out.ramp.assign((size_t)pal.B * keep, 0); + out.level.assign((size_t)pal.B * keep, 0.5f); + for (int64_t b = 0; b < pal.B; ++b) + for (int64_t q = 0; q < keep; ++q) { + out.rgb[(size_t)b * keep + q] = pal.rgb[(size_t)b * pal.P + q]; + out.valid[(size_t)b * keep + q] = pal.valid[(size_t)b * pal.P + q]; + out.ramp[(size_t)b * keep + q] = pal.ramp[(size_t)b * pal.P + q]; + out.level[(size_t)b * keep + q] = pal.level[(size_t)b * pal.P + q]; + } + // the pointer head always gets the full palette, so this one carries no model space + return out; + } + + // decode: (palette, tokens) -> RGBA + inline std::vector palette_decode(const std::vector& pal, const int32_t* tokens, size_t count) { + std::vector out(count * 4, 0); + for (size_t i = 0; i < count; ++i) { + const int64_t t = tokens[i]; + if (t <= 0) + continue; + const RDFlowRGB& c = pal[(size_t)(t - 1)]; + out[i * 4 + 0] = c.r; + out[i * 4 + 1] = c.g; + out[i * 4 + 2] = c.b; + out[i * 4 + 3] = 255; + } + return out; + } + + // RDFlowPalette -> the tensors rd_flow.hpp wants: rgb [P, 3, B] (sRGB 0..255), + // ramp/level/valid [P, B]. Kept next to the palette struct so the parity tests + // and the pipeline build the same thing. + struct RDFlowPaletteTensors { + sd::Tensor rgb, valid, level; + sd::Tensor ramp; + }; + + inline RDFlowPaletteTensors rd_flow_palette_tensors(const RDFlowPalette& pal) { + RDFlowPaletteTensors t; + const int64_t P = pal.P, B = pal.B; + t.rgb = sd::Tensor(std::vector{P, 3, B}); + t.valid = sd::Tensor(std::vector{P, B}); + t.level = sd::Tensor(std::vector{P, B}); + t.ramp = sd::Tensor(std::vector{P, B}); + for (int64_t b = 0; b < B; ++b) { + for (int64_t q = 0; q < P; ++q) { + const RDFlowRGB& c = pal.rgb[(size_t)b * P + q]; + t.rgb[q + P * (0 + 3 * b)] = (float)c.r; + t.rgb[q + P * (1 + 3 * b)] = (float)c.g; + t.rgb[q + P * (2 + 3 * b)] = (float)c.b; + t.valid[q + P * b] = pal.valid[(size_t)b * P + q] ? 1.f : 0.f; + t.ramp[q + P * b] = pal.ramp[(size_t)b * P + q]; + t.level[q + P * b] = pal.level[(size_t)b * P + q]; + } + } + return t; + } + + // parse_hex: "#aabbcc" | "aabbcc" | "abc" -> colours, deduped, in ramp order. + // strict reports a token that is not a colour instead of dropping it, so a typo in + // a user-supplied palette cannot silently draw with fewer colours. + inline std::vector parse_hex(const std::vector& colours, bool strict = false) { + std::set seen; + for (auto raw : colours) { + std::string h = raw; + while (!h.empty() && (h.front() == ' ' || h.front() == '#')) + h.erase(h.begin()); + while (!h.empty() && (h.back() == ' ' || h.back() == '\r' || h.back() == '\n')) + h.pop_back(); + if (h.size() == 3) { + std::string e; + for (char ch : h) + e += ch, e += ch; + h = e; + } else if (h.size() == 8) { + bool ff = raw.size() >= 2 && (raw[0] == 'F' || raw[0] == 'f') && (raw[1] == 'F' || raw[1] == 'f'); + h = ff ? h.substr(2) : h.substr(0, 6); + } + if (h.size() != 6) { + if (strict) { + throw std::invalid_argument("not a colour: '" + raw + "'"); + } + continue; + } + auto hex = [](const std::string& s, size_t at) { + auto v = [](char c) { return c <= '9' ? c - '0' : (char)(std::tolower(c) - 'a' + 10); }; + return (uint8_t)(v(s[at]) * 16 + v(s[at + 1])); + }; + seen.insert(RDFlowRGB{hex(h, 0), hex(h, 2), hex(h, 4)}); + } + std::vector out(seen.begin(), seen.end()); + if (out.size() > (size_t)RD_FLOW_SLOTS) + out.resize((size_t)RD_FLOW_SLOTS); + std::vector order = ramp_order(out); + std::vector sorted; + for (size_t i = 0; i < order.size(); ++i) + sorted.push_back(out[order[i]]); + return sorted; + } + + // The text of a Lospec/paint.net/GIMP/JASC palette file -> colour tokens for + // parse_hex. Text in, tokens out, so file access and parsing stay separable. + inline std::vector parse_palette_text(const std::string& text) { + std::vector lines; + std::string line; + for (char ch : text) { + if (ch == '\n') { + lines.push_back(line); + line.clear(); + } else if (ch != '\r') { + line += ch; + } + } + lines.push_back(line); + + auto trim = [](std::string s) { + while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) + s.erase(s.begin()); + while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) + s.pop_back(); + return s; + }; + std::vector colours; + // The reference turns "r g b" triplets into hex before calling parse_hex, so do + // the same and keep parse_hex the only colour parser. + auto to_hex = [](const std::string& r, const std::string& g, const std::string& b) { + char hex[8]; + std::snprintf(hex, sizeof(hex), "%02x%02x%02x", + std::atoi(r.c_str()) & 0xff, std::atoi(g.c_str()) & 0xff, std::atoi(b.c_str()) & 0xff); + return std::string(hex); + }; + auto triplets = [&](const std::vector& rows, size_t from, bool digits_only) { + for (size_t i = from; i < rows.size(); ++i) { + std::stringstream fields(rows[i]); + std::string values[3]; + size_t count = 0; + while (count < 3 && fields >> values[count]) + ++count; + if (count < 3) + continue; + if (digits_only) { + for (const std::string& v : values) { + if (v.empty() || std::any_of(v.begin(), v.end(), [](char c) { return c < '0' || c > '9'; })) { + count = 0; + break; + } + } + } + if (count == 3) + colours.push_back(to_hex(values[0], values[1], values[2])); + } + }; + if (!lines.empty() && trim(lines[0]) == "JASC-PAL") { + triplets(lines, 3, false); + } else if (!lines.empty() && trim(lines[0]) == "GIMP Palette") { + triplets(lines, 1, true); + } else { + for (const std::string& l : lines) { + const std::string s = trim(l); + if (!s.empty() && s[0] != ';') + colours.push_back(s); + } + } + return colours; + } + + // The drawing-model branch call: fills x_hat [n, n, 4, B] and the decoder features. + using RDFlowPredictFn = + std::function& x_hat, sd::Tensor& feats)>; + // Pointer head over a palette: logits [1 + P, n * n, B] (invalid slots -inf) + using RDFlowPointerFn = std::function(const sd::Tensor& feats, const RDFlowPalette& pal)>; + + struct RDFlowSamplerParams { + int steps = 16; + float guidance = 4.0f; + float interval_lo = 0.0f, interval_hi = 0.9f; + float shift = 3.0f; + float palette_at = 0.6f; + float pointer_from = 0.35f; + float commit_from = 0.55f; + float commit_thresh = 0.9f; + int max_colours = 64; + float merge = 0.05f; + int bg_mode = 2; // 1 opaque, 2 transparent + int source = 6; + }; + + struct RDFlowSamplerOutput { + RDFlowPalette palette; // full palette the image was decoded against + std::vector tokens; // [B][n * n]: 0 transparent, 1 + s = slot s + std::vector probs; // [B][n * n][1 + P] pointer probabilities of the last guided step + }; + + struct RDFlowSampler { + RDFlowSamplerParams params; + RDFlowPredictFn predict; + RDFlowPointerFn pointer; + // Reports finished steps so the caller can show progress and cancel a long + // draw; throwing here aborts the loop. Optional. + std::function on_step; + + // Per-image locked palettes (empty outer vector = nothing locked). + std::vector> locked; + + RDFlowSamplerOutput run(const sd::Tensor& noise, + const sd::Tensor& text, + const sd::Tensor& text_mask, + int64_t n, + int n_threads = 0) const; + }; + + // The drawing loop. `predict` runs one branch (B images) and `pointer` scores + // a palette; both are supplied by the caller. + inline RDFlowSamplerOutput RDFlowSampler::run(const sd::Tensor& noise, + const sd::Tensor& text, + const sd::Tensor& text_mask, + int64_t n, + int n_threads) const { + const RDFlowSamplerParams& p = params; + const int64_t B = noise.shape().back(); + const int64_t per_image = n * n * 4; + // image tensors are [x, y, channel, batch]: the channel stride is n * n, so a + // pixel is not four contiguous floats + auto sd_idx = [n](int64_t x, int64_t y, int64_t c, int64_t b) { + return x + n * (y + n * (c + 4 * b)); + }; + // sd [n, n, 4, B] image -> torch-order [n, n, 4] slice for one image + auto image_torch_order = [&](const sd::Tensor& img, int64_t b) { + std::vector out((size_t)n * n * 4); + for (int64_t y = 0; y < n; ++y) + for (int64_t x = 0; x < n; ++x) + for (int64_t c = 0; c < 4; ++c) + out[((size_t)y * n + x) * 4 + c] = img[sd_idx(x, y, c, b)]; + return out; + }; + RDFlowSamplerOutput out; + + sd::Tensor x(std::vector{n, n, 4, B}); + std::memcpy(x.data(), noise.data(), sizeof(float) * (size_t)noise.numel()); + + // ts = linspace(0, 1, steps + 1) shifted towards the noisy end + std::vector ts((size_t)p.steps + 1); + for (int i = 0; i <= p.steps; ++i) { + const float u = (float)i / (float)p.steps; + ts[i] = u / (u + p.shift * (1.0f - u)); + } + + sd::Tensor null_mask(text_mask.shape()); + std::fill(null_mask.data(), null_mask.data() + null_mask.numel(), 0.0f); + + bool all_locked = !locked.empty(); + for (auto& cols : locked) + if (cols.empty()) + all_locked = false; + RDFlowPalette pal = all_locked ? palette_dict(locked) : RDFlowPalette{}; + + sd::Tensor sc, x_hat, feats; // self-cond, current guess, guided features + bool have_sc = false, have_x_hat = false, have_feats = false; + std::vector probs; // [B][n * n][1 + P] of the most recent pointer step + int64_t prob_slots = 0; + bool have_probs = false; + + // one drawing-model branch: x + optional self-cond + bucketed palette tokens + auto branch = [&](const sd::Tensor& mask, const RDFlowPalette* pb, sd::Tensor& xh, + sd::Tensor& ft, float t) { + RDFlowRunner::Request req; + req.x = &x; + req.t = std::vector((size_t)B, t); + req.text = &text; + req.text_mask = &mask; + req.self_cond = have_sc ? &sc : nullptr; + req.bg_mode = p.bg_mode; + req.style = 0; + req.source = p.source; + req.want_features = true; + sd::Tensor rgb, valid, level; + sd::Tensor ramp; + if (pb != nullptr) { + const int64_t Pk = pb->P; + rgb.resize(std::vector{Pk, 3, B}); + valid.resize(std::vector{Pk, B}); + level.resize(std::vector{Pk, B}); + ramp.resize(std::vector{Pk, B}); + for (int64_t b = 0; b < B; ++b) + for (int64_t q = 0; q < Pk; ++q) { + const RDFlowRGB& c = pb->rgb[(size_t)b * pb->P + q]; + rgb[q + Pk * (0 + 3 * b)] = (float)c.r; + rgb[q + Pk * (1 + 3 * b)] = (float)c.g; + rgb[q + Pk * (2 + 3 * b)] = (float)c.b; + valid[q + Pk * b] = pb->valid[(size_t)b * pb->P + q] ? 1.0f : 0.0f; + ramp[q + Pk * b] = pb->ramp[(size_t)b * pb->P + q]; + level[q + Pk * b] = pb->level[(size_t)b * pb->P + q]; + } + req.pal.rgb = &rgb; + req.pal.valid = &valid; + req.pal.ramp = &ramp; + req.pal.level = &level; + req.pal.P = Pk; + } + predict(req, xh, ft); + }; + + // pointer head -> probabilities and the expected model-space colour + auto expected = [&](const sd::Tensor& ft, const RDFlowPalette& full, std::vector& xp, + std::vector* probabilities) { + sd::Tensor logits = pointer(ft, full); // [1 + P, n * n, B] + const int64_t S = full.P + 1; + const int64_t npix = n * n; + std::vector pr((size_t)B * npix * S); + for (int64_t b = 0; b < B; ++b) + for (int64_t q = 0; q < npix; ++q) { + const float* row = logits.data() + q * S + b * npix * S; + float mx = -INFINITY; + for (int64_t s = 0; s < S; ++s) + mx = std::max(mx, row[s]); + double sum = 0.0; + for (int64_t s = 0; s < S; ++s) { + const double e = std::exp((double)row[s] - mx); + pr[(size_t)(b * npix + q) * S + s] = (float)e; + sum += e; + } + for (int64_t s = 0; s < S; ++s) + pr[(size_t)(b * npix + q) * S + s] /= (float)sum; + } + xp.assign((size_t)B * npix * 4, 0.0f); + for (int64_t b = 0; b < B; ++b) + for (int64_t q = 0; q < npix; ++q) { + const float* prw = &pr[(size_t)(b * npix + q) * S]; + const float* spc = &full.space[(size_t)b * S * 4]; + float* dst = &xp[(size_t)(b * npix + q) * 4]; + for (int c = 0; c < 4; ++c) { + double acc = 0.0; + for (int64_t s = 0; s < S; ++s) + acc += (double)prw[s] * spc[s * 4 + c]; + dst[c] = (float)acc; + } + } + if (probabilities != nullptr) { + *probabilities = std::move(pr); + prob_slots = S; + } + }; + + for (int i = 0; i < p.steps; ++i) { + const float t = ts[i], t2 = ts[i + 1]; + if (pal.empty() && t >= p.palette_at && have_x_hat) { + std::vector> lists((size_t)B); + for (int64_t b = 0; b < B; ++b) { + auto img = image_torch_order(x_hat, b); + lists[(size_t)b] = extract_palette(img.data(), n, p.max_colours, (double)p.merge); + } + pal = palette_dict(lists); + } + const bool guide = p.guidance != 1.0f && t >= p.interval_lo && t <= p.interval_hi; + RDFlowPalette pb = pal.empty() ? RDFlowPalette{} : bucket_palette(pal); + + sd::Tensor xc, fc, xu, fu; + branch(text_mask, pb.empty() ? nullptr : &pb, xc, fc, t); + if (guide) + branch(null_mask, pb.empty() ? nullptr : &pb, xu, fu, t); + + sd::Tensor guess(std::vector{n, n, 4, B}); + if (guide) { + for (int64_t j = 0; j < guess.numel(); ++j) + guess[j] = xu[j] + p.guidance * (xc[j] - xu[j]); + } else { + std::memcpy(guess.data(), xc.data(), sizeof(float) * (size_t)guess.numel()); + } + feats = fc; + have_feats = true; + + if (!pal.empty() && t >= p.pointer_from) { + std::vector xp, xpu; + expected(fc, pal, xp, &probs); + have_probs = true; + if (guide) { + expected(fu, pal, xpu, nullptr); + for (size_t j = 0; j < xp.size(); ++j) + xp[j] = xpu[j] + p.guidance * (xp[j] - xpu[j]); + } + if (t >= p.commit_from) { + const int64_t S = pal.P + 1; + const int64_t npix = n * n; + for (int64_t b = 0; b < B; ++b) + for (int64_t q = 0; q < npix; ++q) { + const float* prw = &probs[(size_t)(b * npix + q) * S]; + int64_t best = 0; + for (int64_t s = 1; s < S; ++s) + if (prw[s] > prw[best]) + best = s; + if (prw[best] < p.commit_thresh) + continue; + const float* exact = &pal.space[((size_t)b * S + best) * 4]; + for (int c = 0; c < 4; ++c) + xp[(size_t)(b * npix + q) * 4 + c] = exact[c]; + } + } + // [B][n * n][4] (torch order) -> [x, y, 4, B] (sd order) + for (int64_t b = 0; b < B; ++b) + for (int64_t q = 0; q < n * n; ++q) + for (int c = 0; c < 4; ++c) + guess[sd_idx(q % n, q / n, c, b)] = xp[(size_t)(b * n * n + q) * 4 + c]; + } + x_hat = guess; + have_x_hat = true; + sc = x_hat; + have_sc = true; + + const float denom = std::max(1.0f - t, 1e-4f); + for (int64_t j = 0; j < x.numel(); ++j) + x[j] = x[j] + ((t2 - t) * (x_hat[j] - x[j])) / denom; + if (on_step) + on_step(i + 1, p.steps); + } + + if (pal.empty()) { + std::vector> lists((size_t)B); + for (int64_t b = 0; b < B; ++b) { + if (all_locked) { + lists[(size_t)b] = locked[(size_t)b]; + continue; + } + auto img = image_torch_order(x_hat, b); + lists[(size_t)b] = extract_palette(img.data(), n, p.max_colours, (double)p.merge); + } + pal = palette_dict(lists); + } + + if (!have_probs) { + std::vector xp; + expected(feats, pal, xp, &probs); + } + out.palette = pal; + out.probs = probs; + out.tokens.assign((size_t)B * n * n, 0); + for (int64_t b = 0; b < B; ++b) + for (int64_t q = 0; q < n * n; ++q) { + const float* prw = &probs[(size_t)(b * n * n + q) * prob_slots]; + int64_t best = 0; + for (int64_t s = 1; s < prob_slots; ++s) + if (prw[s] > prw[best]) + best = s; + out.tokens[(size_t)b * n * n + q] = (int32_t)best; + } + (void)n_threads; + return out; + } + +} // namespace RDFlow + +#endif // __SD_MODEL_DIFFUSION_RD_FLOW_SAMPLER_HPP__ diff --git a/src/model/integrations/rd_flow.cpp b/src/model/integrations/rd_flow.cpp new file mode 100644 index 0000000000..6519f4a1e6 --- /dev/null +++ b/src/model/integrations/rd_flow.cpp @@ -0,0 +1,48 @@ +#include "model/diffusion/rd_flow.hpp" +#include "conditioning/llm_conditioner.h" +#include "model_build_context.h" +#include "model_definition.h" + +static bool build_rd_flow(const sd::model_builders::Context& ctx, const TokenizerConfig& tokenizers, sd::model_builders::CoreRunners& result) { + const auto& tensor_storage_map = ctx.tensor_storage_map; + const auto version = ctx.version; + const auto& weight_manager = ctx.weight_manager; + if (ctx.build_conditioner) { + // Qwen3-VL-4B prompt reader (first 27 layers); raw caption tokens. + result.conditioner = sd::make_llm_conditioner(ctx.backends.runtime_backend(SDBackendModule::TE), + tensor_storage_map, version, false, weight_manager, tokenizers); + } + if (ctx.build_diffusion) { + // The checkpoint ships unprefixed names; GGUF/converted files may carry + // the stable-diffusion.cpp diffusion prefix. + const bool prefixed = tensor_storage_map.count("model.diffusion_model.pal_tok.weight") > 0; + result.diffusion = std::make_shared(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION), + tensor_storage_map, + prefixed ? "model.diffusion_model" : "", + weight_manager); + } + return true; +} + +const std::vector& rd_flow_definitions() { + static const std::vector definitions = [] { + std::vector result; + { + ModelDefinition definition; + definition.version = VERSION_RD_FLOW_64; + // down_factor 1 (pixel space), 4 "latent"/image channels = RGBA. + definition.geometry = {1, 4, 4}; + definition.name = "RD Flow 64"; + definition.id = "rd_flow_64"; + definition.traits.is_dit = true; + definition.traits.fake_vae = true; + definition.sampling = {FLOW_PRED, INFINITY}; + definition.sampling.default_sample_method = EULER_SAMPLE_METHOD; + definition.sampling.default_scheduler = DISCRETE_SCHEDULER; + definition.build = build_rd_flow; + result.push_back(std::move(definition)); + } + return result; + }(); + return definitions; +} diff --git a/src/model/vae/geometry.hpp b/src/model/vae/geometry.hpp index 19581497a5..0a2b357611 100644 --- a/src/model/vae/geometry.hpp +++ b/src/model/vae/geometry.hpp @@ -30,7 +30,7 @@ namespace sd::vae { return 16; if (version == VERSION_CHROMA_RADIANCE || version == VERSION_HIDREAM_O1 || sd_version_is_minit2i(version) || sd_version_is_sensenova_u1(version) || - sd_version_is_z_image_l2p(version) || version == VERSION_IRIS) + sd_version_is_z_image_l2p(version) || version == VERSION_IRIS || sd_version_is_rd_flow(version)) return 1; return 8; } diff --git a/src/model_loader.cpp b/src/model_loader.cpp index 65869cef83..00ee5a5329 100644 --- a/src/model_loader.cpp +++ b/src/model_loader.cpp @@ -458,6 +458,13 @@ SDVersion ModelLoader::get_sd_version() const { return VERSION_SEEDVR2; } + for (const std::string prefix : {"", "model.diffusion_model."}) { + if (tensor_storage_map.count(prefix + "pal_tok.weight") && + tensor_storage_map.count(prefix + "down0.ada.weight") && + tensor_storage_map.count(prefix + "transparent.weight")) + return VERSION_RD_FLOW_64; + } + if (tensor_storage_map.count("model.diffusion_model.perceiver.latent_queries")) { return VERSION_FIBO2; } diff --git a/src/model_registry.cpp b/src/model_registry.cpp index 231b699c09..3766e655e6 100644 --- a/src/model_registry.cpp +++ b/src/model_registry.cpp @@ -35,6 +35,7 @@ const std::vector& iris_definitions(); const std::vector& sd_definitions(); const std::vector& moss_image_definitions(); const std::vector& seedvr2_definitions(); +const std::vector& rd_flow_definitions(); static bool valid_model_id(std::string_view id) { if (id.empty() || id == "auto" || id.front() < 'a' || id.front() > 'z') @@ -99,6 +100,7 @@ static const std::array& model_definition append(sd_definitions()); append(moss_image_definitions()); append(seedvr2_definitions()); + append(rd_flow_definitions()); for (const auto* definition : result) { if (!definition) throw std::logic_error("missing model registration"); diff --git a/src/name_conversion.cpp b/src/name_conversion.cpp index 1dc095d40c..ac52ac1a12 100644 --- a/src/name_conversion.cpp +++ b/src/name_conversion.cpp @@ -1923,6 +1923,29 @@ std::string convert_tensor_name(std::string name, SDVersion version) { } } + if (sd_version_is_rd_flow(version)) { + // The checkpoint strips the "model."/language_model wrapper from the trimmed + // prompt reader; restore the prefix the LLM runner expects. + static const std::vector rd_flow_te_prefixes = { + "text_encoders.llm.", + "text_encoders.llm.model.", + "text_encoders.llm.model.language_model.", + "text_encoders.llm.language_model.model.", + "text_encoders.llm.model.text_model.", + }; + for (const auto& from : rd_flow_te_prefixes) { + if (!starts_with(name, from)) { + continue; + } + const std::string rest = name.substr(from.size()); + if (starts_with(rest, "layers.") || starts_with(rest, "embed_tokens.") || + starts_with(rest, "norm.")) { + name = "text_encoders.llm.model." + rest; + break; + } + } + } + if (version == VERSION_FIBO2 || version == VERSION_QWEN_IMAGE_2_1 || version == VERSION_MOSS_IMAGE || version == VERSION_IRIS || sd_version_is_flux3(version) || sd_version_is_lingbot_video(version) || sd_version_is_ideogram4(version) || sd_version_is_sefi_image(version) || sd_version_is_boogu_image(version) ||