From 71c194b2935ce1c05e3b97c71597697908a95b3d Mon Sep 17 00:00:00 2001 From: jahu00 Date: Sun, 29 Nov 2026 12:11:43 +0100 Subject: [PATCH 1/4] feat: add RD Flow 64 support (#2465) --- README.md | 1 + assets/rd_flow_64/dgl_output.png | Bin 0 -> 1547 bytes assets/rd_flow_64/dgl_palette.png | Bin 0 -> 558 bytes assets/rd_flow_64/dgl_tokens.png | Bin 0 -> 1382 bytes assets/rd_flow_64/lighthouse.png | Bin 0 -> 5330 bytes assets/rd_flow_64/locked_palette.png | Bin 0 -> 1141 bytes assets/rd_flow_64/locked_palette_strip.png | Bin 0 -> 225 bytes assets/rd_flow_64/max_colours_8.png | Bin 0 -> 1213 bytes assets/rd_flow_64/opaque.png | Bin 0 -> 7244 bytes assets/rd_flow_64/sprite.png | Bin 0 -> 1547 bytes docs/dgl-builtins.md | 2 + docs/dgl/README.md | 1 + docs/dgl/rd_flow_64/rd-flow-64-txt2img.dgl | 43 + docs/models/README.md | 1 + docs/models/rd_flow_64.md | 307 +++++ examples/common/common.cpp | 44 + examples/common/common.h | 6 + examples/server/recipes/rd-flow-64.json | 41 + examples/server/routes_sdcpp.cpp | 6 + src/api/generation_image.cpp | 39 +- src/api/generation_program.cpp | 8 +- src/api/options.cpp | 8 + src/api/templates/image_pixel.dgl | 18 +- src/conditioning/conditioner.hpp | 56 + src/config.cpp | 8 + src/config.h | 9 + src/dgl/bindings/rd_flow.cpp | 94 ++ src/dgl/bindings/rd_flow.h | 12 + src/dgl/bindings/registration.cpp | 15 + src/dgl/models/diffusion_prediction.h | 5 + src/dgl/models/dit.cpp | 29 +- src/dgl/ops/rd_flow_sampling.cpp | 150 +++ src/dgl/ops/rd_flow_sampling.h | 56 + src/model.h | 5 + src/model/diffusion/model.hpp | 28 + src/model/diffusion/rd_flow.hpp | 1338 ++++++++++++++++++++ src/model/diffusion/rd_flow_sampler.hpp | 933 ++++++++++++++ src/model/integrations/rd_flow.cpp | 48 + src/model/vae/geometry.hpp | 2 +- src/model_loader.cpp | 7 + src/model_registry.cpp | 2 + src/name_conversion.cpp | 25 + 42 files changed, 3337 insertions(+), 10 deletions(-) create mode 100644 assets/rd_flow_64/dgl_output.png create mode 100644 assets/rd_flow_64/dgl_palette.png create mode 100644 assets/rd_flow_64/dgl_tokens.png create mode 100644 assets/rd_flow_64/lighthouse.png create mode 100644 assets/rd_flow_64/locked_palette.png create mode 100644 assets/rd_flow_64/locked_palette_strip.png create mode 100644 assets/rd_flow_64/max_colours_8.png create mode 100644 assets/rd_flow_64/opaque.png create mode 100644 assets/rd_flow_64/sprite.png create mode 100644 docs/dgl/rd_flow_64/rd-flow-64-txt2img.dgl create mode 100644 docs/models/rd_flow_64.md create mode 100644 examples/server/recipes/rd-flow-64.json create mode 100644 src/dgl/bindings/rd_flow.cpp create mode 100644 src/dgl/bindings/rd_flow.h create mode 100644 src/dgl/ops/rd_flow_sampling.cpp create mode 100644 src/dgl/ops/rd_flow_sampling.h create mode 100644 src/model/diffusion/rd_flow.hpp create mode 100644 src/model/diffusion/rd_flow_sampler.hpp create mode 100644 src/model/integrations/rd_flow.cpp diff --git a/README.md b/README.md index b5ddd2a03f..6f79b7ee75 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 0000000000000000000000000000000000000000..16caa49b61ccf79b88b10a1c326e13091a652310 GIT binary patch literal 1547 zcmb_cZB&wH7=Fo*3}v|5Jc$)?=B6%_C87&V2u#yFT4|Z4L3zZQX+~+NAbqKsH9uMt z&9aYU$NYe^&`d>NJ7rP`)SOy5r6$IP3MNB*g=Bg>XW0LqKhN{yzOVbbuj{^_f}P>P z2sjE3001Ind*E&WfXzQ)fSv99700Y$0D#T!A%R(BO{5yt&&ejh(?(`k)3%%#ThOSwVAK|na=5>vLkw%7jZhL zjU?Pv70KIMiNl?%98}u_vB5C%AvmxSS2dP4T4`<@Kp#;Pc>qr#AJiNt7y-_)XQ&OqfC<1As z%MMr>xtK9Ns7X`F4>(TS__yaIP*pB2E`lufm;{?UPJ|J!Svo2Q(;qSsbOT*fq`(nV z_3j3QiD@b-=4#BI$_>#CUqCO78oSphauRNl$bu5`Wv;!#ziN4fBYyfJ$0-$!y|(}UZEO$J+^*l-H$dY^?-!3<*OjR`PMsCxq)iq=I-zf*3{se9uG9*! zT3s0`-pV~@6))z}qHXi8^swu@Dz>Pw_-w>mk_!E2w4MdESw;Atw_Lsr1!im(5f%G?c?m|)6s@GyZS~Nf3>LDvYaSY ze+&n$uqklpX_DW0cGl2{R3xg%aY6I5L~&GJy5UW&fIB(dMtOjxXDw-#1Ejp~)g$vo zvro!}qA7GRSfhnZLGk;PB_#_qiENtsxjjxnXsxb1`zxgR| z;QjLB#yZTJctxHFWIjAoSEmr=4&?f`j$SRsW=m0I;u6`CffT+-P8&X@*!+T2t>un2 z)lm*K9u5}|W=z!28t!yQoM*>G@-H$z$=T>@ev8BuHT_MH-5uU+KC78&B)8a-vp)&4 zmVB?H^6@IHVXk+n4JdNqT1|Y6p4DOiMOg6Ydf96?Cocy`d<#wWQjL#(h*h9>&T%po zVAR-;4NF!kC%>WVxdP5UF@$@^g05%nkQJKm-#YVgkDSI|;iE34=2JT8(ARrtB*PgZ zHRpKubTMgMYj8e_S+a7-n^K3WfVE5rIjfH{HFS;+c-3XGZ?o2c{TwJ(t}RQ3H_1r- zLLcSaxsg3``M=(l88gra!&)w338BnPGVgL43{R~H{wiqxSFnGH9 KxvX*Zf35d>)L6xRU3+PX?&S=qQZr> zHD-3vbst0oH7Pz=L%gLEVz*#32$S>KEsonGz-5k&!yozc6c&OVBWS*YCBZ~&JG+)3XY zj^$c>3O2%nJY?q90o#kZ!#1h(Lxmug9uBl&futfJx3X(N4y-_Sd$JaSAc1^jq~FTa z>-Dfa@#%OZ5cMWN?EyH?UIHD@N#7;Ik#eTzkWC~Km9;lU@?wiqPVVG`Bky7!UD{Yc zva8tMm)0_5k(PmVS*_K=nCR#gFI=2@Y-e5=5H+)}7~j;?Bmj{BOITY|<7f;_e}%KH zGvaMdqrwRJuHHPjgMb3sN+cso8|Qr%4c`bcniWZ{P(U@#kmm>_a6E32zX z+Ru2|*v5;5ANjCm17170_2@7vw=y{H6+%KTzO=OT3}iQ(X}7p}$?H{MjrhdAI5q1ufilw=aDxeDmz*A^?28&$Kx+>nh@LU z11f|acx#vUeKOROZ9%*)NUO1Yz|M3gj1Fw?GixAhC}?k&=*nV4;L0=v$XVN&E(Yiv zl{Pskq~0Q5L@8}|V>~pYB8TP0*~sibk>BTbe=8gs9HjV7sxGS2ZlAbHl1in5NfNMd zdAGbN`(63QK?%~hxzb|BuSR4S>h+zQDamB;@y)e9wJF~z^NZlV$lu!eL)*3F*Q z>2#ES_}JXsT=B~C)M%)&h^a<`1~ya~?y=7`ze91HmNjqEZE#vzTHZs<)E;Pa80dNQweI%<^ua%h>xtOKL)D#ewmwW1w*~ADsrl>r zS`VmrSBI7bHy>}DpT{m_Q3+iw}quFBb=Vta~J%e>L@&UWw8(j|fZ zu|)E=O~%h1RC}cAU417s2|Z&K>7uH-a?|=;?F#BYtzOqZwCZXZSwzZuvND$xMc!9k N3ky!=4^k?w{R8g~Q|tf$ literal 0 HcmV?d00001 diff --git a/assets/rd_flow_64/lighthouse.png b/assets/rd_flow_64/lighthouse.png new file mode 100644 index 0000000000000000000000000000000000000000..9d7baa03181cba61c1c2b4826c7bf32ec89d9148 GIT binary patch literal 5330 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 SG~QK${0^V|sowYO)&B*YzNqE^ literal 0 HcmV?d00001 diff --git a/assets/rd_flow_64/locked_palette.png b/assets/rd_flow_64/locked_palette.png new file mode 100644 index 0000000000000000000000000000000000000000..56e62788efd1cf09dc591632a88192a5b905d93d GIT binary patch literal 1141 zcmeAS@N?(olHy`uVBq!ia0y~yU<5K5893O0R7}x|GzJD18&4O-$$R1SMS~%_kQ_q-$L7BrpwEi z8WNZonm8Fa()be6e!ctI|IT*(zoK>5@25v-F>t6s41lPBa=tP8`0V}u|77?6?(^k( zwO3z%?Ylqi^}nx?&1>JbZe|olHS(Q()vcGm|Ihn#@$y^)R)mq)a@5z|6aR4ZyLnjE z-s$YuyEm5p&kSaCFkoaj$il#~nLi;-?#`cu64zh<>c0Of{m(=nRfLM`rp3! zpZCAXX-H@D>qeOJFDGT%*FU*yf5p~6V_D`4*K;Paq4De8&+BiWpMOX5nE3iXQ9a_m zU)LRKetnLwrvstivSDWA*Io5%-~E(-|5ohr-|VN)quI6ht40MNJjk{?E%*B0{{6p~ zN!0)S9e;GkyPxx8|86|}_UpT|Pd^{sG0*tMtvHe7-%QuM5%$|POa#W`uJ(1kYoD)| zy{kQ6yx`+02lGS!gWv`mvl|pWm*1!P|AY7L_ww`hyej$omRox7zk93hhk95eBH$T= z+Om7<7q+VBuYPaI*tQfYAvA1_`fkkq(?FDg1sL2u3=Rgx49wEi{&&je*59;aOlLfX z2*xwUH?FU#(|36LqF}#-e)Y5aH@-i*Ud&|uf6u=M`@hFEd_}nIaz5{xdBQvX|4g4- zm!DJ2RG(K9)zk0)U;9|qzr>aBlxE3ouwfVbz06s0&snamjr+bocJ1%iKaV4<^szT9 z`fAs>EuA$h_Wbwj`}P#CmdMZ5@7g%8{!R$Qy}(5DC0+RPw@Rkk)zyDy&8v?>lE^mR roYS{J+xFj{6);PwlocD6WzKqL+ZB2Dw!M&zE67k!S3j3^P6xG^3JXz~%QKXztc_<^+DHTTYSdv2e9|Kh*@e@$=QkA1)R z@7aGQx9+d&U;Ov*{p2n6m3!QOufAwiW63-rjo}iH!z@M*V}?vNg|iGxBpXb~7JSRR X>YPBI?(&DvK|b(w^>bP0l+XkKAUss| literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..75f5f33bab5effe987b031077ed8c656993bfd57 GIT binary patch literal 1213 zcmeAS@N?(olHy`uVBq!ia0y~yU<5K5893O0R7}x|GzJEi7Ec$)kcv5P@9yu836)@b z5U65it@Fa{-+^PNIKl)YbG8X^{^rjScJxS9Ps~+b5-MiR&B?K>U?YFhR5cdGt6fo@ z0#{5XJKS(JaNY8C&Ve|->hyPeKim127rj5nv-|Mu_rIUrvED2Rw2)dLbDrcc)(h*4 zrKA7PE32`)uXFAA@%~wT_I8mK=hsY3Z?9uKP{6{#BFrG*V{cwqdcOYiv+qYgwwKqx z`1(^X)>h+M8q?)vObrQ43{9L29N+F-&~KN6(dA{<%h66r!EM!N9n| zAl9~ib(MTmE#u`ya9wF^28N~QYrp*7`{>8@_xmot{#;x7r+nkO^`;cz z^BRz)>>5lzUt^b_U$y6+`Gt22ev7C%BlPhooLQYeC*SJ-8)N2UK1kvXYM+0mZLBNU zB=KVE1$Jbwbgo?gfBpN*`*Y&!igrfC@2YyRn^7I1)n~t1k^a6fRTq=*+x=Q;5%>OT z{@vI2mwt_E__dqqEXy%pxFtUIW=65L|1X?jxz^1E4n~k)>v9s3-~Ze_gVSd=Lhv`^ znwg99_hneszrHp%Y444jdB1*&>+QK;V)qykoX?DJh-Ux2^MC#6>Z8A&zHUFd>)p@S z^Xjg?l61P>b6{UX;z~$R0;B9EyMa;Z`TMCa=KVjv`}?W-71#K`pFaGJw+G1~k_WnE zGNLoqrc8he)>=T!};e=_qE>Kp2m=ja7Y^4 zh9qFUZXhtKauEgw?+1ws`%%d2=A6g8?Hr6@0eMVP3so z`@`<-=f#iz-Y4&HooB&&x&J@^ev)gGuPxgfVZY=5?C%d6LVzh6=nkN!H_Q?de=UC` zrSG;mXv-L>^qvit*zB5RX99D^(R~fl*VoOd`WJkE@Aj0hTRHr{+1q~obN6od(O(}= z9;(iBK^XQWSvfpj`@+)?1v`x!_wL>MZt}n5asLa0;qJRUf9=d`Gaa>U|5m{rO|8tl d`DTvUZ+?zNZ~yMuF~0<4s;8@;%Q~loCIAPz+mZkP literal 0 HcmV?d00001 diff --git a/assets/rd_flow_64/opaque.png b/assets/rd_flow_64/opaque.png new file mode 100644 index 0000000000000000000000000000000000000000..bbd9856e2ce934e0c18a66d3f04b4558efb05c32 GIT binary patch literal 7244 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 D;?Fj- literal 0 HcmV?d00001 diff --git a/assets/rd_flow_64/sprite.png b/assets/rd_flow_64/sprite.png new file mode 100644 index 0000000000000000000000000000000000000000..16caa49b61ccf79b88b10a1c326e13091a652310 GIT binary patch literal 1547 zcmb_cZB&wH7=Fo*3}v|5Jc$)?=B6%_C87&V2u#yFT4|Z4L3zZQX+~+NAbqKsH9uMt z&9aYU$NYe^&`d>NJ7rP`)SOy5r6$IP3MNB*g=Bg>XW0LqKhN{yzOVbbuj{^_f}P>P z2sjE3001Ind*E&WfXzQ)fSv99700Y$0D#T!A%R(BO{5yt&&ejh(?(`k)3%%#ThOSwVAK|na=5>vLkw%7jZhL zjU?Pv70KIMiNl?%98}u_vB5C%AvmxSS2dP4T4`<@Kp#;Pc>qr#AJiNt7y-_)XQ&OqfC<1As z%MMr>xtK9Ns7X`F4>(TS__yaIP*pB2E`lufm;{?UPJ|J!Svo2Q(;qSsbOT*fq`(nV z_3j3QiD@b-=4#BI$_>#CUqCO78oSphauRNl$bu5`Wv;!#ziN4fBYyfJ$0-$!y|(}UZEO$J+^*l-H$dY^?-!3<*OjR`PMsCxq)iq=I-zf*3{se9uG9*! zT3s0`-pV~@6))z}qHXi8^swu@Dz>Pw_-w>mk_!E2w4MdESw;Atw_Lsr1!im(5f%G?c?m|)6s@GyZS~Nf3>LDvYaSY ze+&n$uqklpX_DW0cGl2{R3xg%aY6I5L~&GJy5UW&fIB(dMtOjxXDw-#1Ejp~)g$vo zvro!}qA7GRSfhnZLGk;PB_#_qiENtsxjjxnXsxb1`zxgR| z;QjLB#yZTJctxHFWIjAoSEmr=4&?f`j$SRsW=m0I;u6`CffT+-P8&X@*!+T2t>un2 z)lm*K9u5}|W=z!28t!yQoM*>G@-H$z$=T>@ev8BuHT_MH-5uU+KC78&B)8a-vp)&4 zmVB?H^6@IHVXk+n4JdNqT1|Y6p4DOiMOg6Ydf96?Cocy`d<#wWQjL#(h*h9>&T%po zVAR-;4NF!kC%>WVxdP5UF@$@^g05%nkQJKm-#YVgkDSI|;iE34=2JT8(ARrtB*PgZ zHRpKubTMgMYj8e_S+a7-n^K3WfVE5rIjfH{HFS;+c-3XGZ?o2c{TwJ(t}RQ3H_1r- zLLcSaxsg3``M=(l88gra!&`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` | `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 df8958cc69..516f29b9f4 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..c6bb90e3d3 --- /dev/null +++ b/docs/models/rd_flow_64.md @@ -0,0 +1,307 @@ +# 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. Both parts run +on the CPU by default. Build with `-DSD_VULKAN=ON` and add `--backend vulkan0` +to run them on a GPU, where f32 fits in 24 GiB of VRAM. + +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. +- On CPU, one seed reproduces exactly. On the Vulkan backend it does not: two + identical runs at the same seed differ in about 410 of the 4096 pixels (the + palette assignments move), and the drawings are equally good. 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. diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 9beaaa525b..767d5cd9ba 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -1105,6 +1105,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", @@ -1147,6 +1157,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", @@ -1230,6 +1244,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 = { @@ -2020,6 +2046,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); @@ -2515,6 +2547,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); @@ -2689,6 +2727,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 f4418adf4d..edd78ab985 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -217,6 +217,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 5e92df0ff5..79770c6997 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..eb02720c26 100644 --- a/src/api/generation_image.cpp +++ b/src/api/generation_image.cpp @@ -171,6 +171,31 @@ namespace sd::api { request.fields["negative_condition"] = "controlled_negative"; } + // RD Flow 64 draws one fixed 64 x 64 sprite from noise in a single pass. The + // pixel template has no branch for the modes it cannot serve, so those inputs + // are refused rather than quietly ignored, and its sampler knobs are passed to + // rd_flow::sample, which otherwise runs on its reference defaults. + 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 +212,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 +253,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 f3b87be6f0..72d773a6bf 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 5ec536a757..80436cabca 100644 --- a/src/api/options.cpp +++ b/src/api/options.cpp @@ -354,6 +354,14 @@ 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; generation_image.cpp rejects them on other models. Ranges + // match the rd_flow::sample built-in arguments. + 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/conditioner.hpp b/src/conditioning/conditioner.hpp index 980e74560d..5075282a4b 100644 --- a/src/conditioning/conditioner.hpp +++ b/src/conditioning/conditioner.hpp @@ -2045,6 +2045,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) { @@ -3285,6 +3286,61 @@ 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)) { + // RD Flow 64: raw caption tokens, no chat template, Qwen3-VL cut at + // 27 layers through the final norm, then a second weightless RMS norm + // per token, masked. Mirrors rd-flow-64/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 mask padded + // tokens to zero. hidden_states is [hidden, L] (+ optional batch). + 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] + // Carry the token key-padding mask to the drawing model. + result.c_vector = mask.empty() ? sd::Tensor::full({len}, 1.f) : std::move(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..c9669a9335 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -84,6 +84,14 @@ namespace sd { batch_count = 1; control_strength = 0.9f; qwen_image_layers = 3; + // Same defaults as the rd_flow::sample built-in, so the passthrough is a + // no-op until the user changes one of them. + 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 5319863f0b..66fe523a07 100644 --- a/src/config.h +++ b/src/config.h @@ -162,6 +162,15 @@ namespace sd { sd::CacheConfig cache{}; HiresConfig hires{}; int qwen_image_layers{}; + // RD Flow 64: a locked palette ("#rrggbb,..." or a palette file path), the + // background mode, and the sampler knobs the reference flow exposes but its + // Pipeline does not. Unused on other models. + 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..4fc9d9382a --- /dev/null +++ b/src/dgl/bindings/rd_flow.cpp @@ -0,0 +1,94 @@ +#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 { + // pipeline.parse_hex / read_palette_file: the "palette" argument is either a + // comma-separated list of "#rrggbb" colours or the path of a palette file + // (Lospec/paint.net/GIMP/JASC), like `generate.py --palette`. 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 6a066ef1c2..67e14be204 100644 --- a/src/dgl/bindings/registration.cpp +++ b/src/dgl/bindings/registration.cpp @@ -18,6 +18,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" @@ -624,6 +625,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..a8b5bb9f3e 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,10 @@ 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: per-step self-conditioning, palette and background + // state, plus the features/pointer-head outputs rd_flow::sample reads + // back. Owned by that op for the duration of the call. + const RDFlowDiffusionExtra* rd_flow = nullptr; std::function transform; }; diff --git a/src/dgl/models/dit.cpp b/src/dgl/models/dit.cpp index 206d40cb31..ececc4f466 100644 --- a/src/dgl/models/dit.cpp +++ b/src/dgl/models/dit.cpp @@ -305,9 +305,14 @@ 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 (rd_flow::sample runs the + // doubled CFG batch, and its pointer head is fed features, not an image), + // so the latent contract below does not apply to it. + 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()) { @@ -399,6 +404,19 @@ namespace sd::dgl::models { params.extra = LTXAVDiffusionExtra{nullptr, present(audio_time), options.audio_length, options.fps, present(options.video_positions), first(condition.extra_c_crossattns)}; } else if (sd_version_is_minit2i(version())) { params.extra = MiniT2IDiffusionExtra{params.y}; + } else if (sd_version_is_rd_flow(version())) { + // rd_flow::sample owns the loop, so it hands the per-step state + // (self-conditioning, palette, background) through the options and + // reads the u0 features / pointer scores back out of them. Without + // that state this is a plain text-to-image forward, 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()) { @@ -416,7 +434,10 @@ namespace sd::dgl::models { } throw std::runtime_error("diffusion compute failed"); } - if (result.shape() != shape) { + // The RD Flow pointer head scores palette slots over the features of an + // earlier forward, so its output shape is not the 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 993624b526..914fe18589 100644 --- a/src/model/diffusion/model.hpp +++ b/src/model/diffusion/model.hpp @@ -116,6 +116,33 @@ struct MiniT2IDiffusionExtra { const sd::Tensor* mask = nullptr; }; +struct RDFlowDiffusionExtra { + // Token key-padding mask [L] (1 = real token, 0 = padding). An all-zero row + // means no text (the unconditional pass). + const sd::Tensor* text_mask = nullptr; + // Previous step's clean guess [64, 64, 4, B], the self-conditioning input + // (null on the first step). + const sd::Tensor* self_cond = nullptr; + // Background mode: 1 = opaque, 2 = transparent. + int bg_mode = 2; + // Palette tokens for the core: rgb [P, 3, B] sRGB 0..255, ramp [P, B], + // level [P, B], valid [P, B]. Empty until the sampler locks or extracts a + // palette. rdflow::sample drives these directly on the runner. + const sd::Tensor* pal_rgb = nullptr; + const sd::Tensor* pal_valid = nullptr; + const sd::Tensor* pal_ramp = nullptr; + const sd::Tensor* pal_level = nullptr; + int style = 0; + int source = 6; + // rd_flow::sample drives the loop itself, so it also needs things the plain + // sample path never asks for: the u0 features of a forward (written to + // out_features when set), and the pointer head as its own request - with + // pointer_head the input x holds those features and the result is the + // [1 + P, size*size, B] slot scores instead of an image. + sd::Tensor* out_features = nullptr; + bool pointer_head = false; +}; + struct SenseNovaU1DiffusionExtra { const sd::Tensor* input_ids = nullptr; }; @@ -164,6 +191,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 Python "w" weight name (layers.py RMSNorm uses self.w). + 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), + // exactly layers.py timestep_embed. -> [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). Mirrors + // layers.py apply_rope. + 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 (matches layers.py ColourEmbed.oklab / palette.py). + 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 (see model.py 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. See model.py PixelFlowModel. + 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]; layers.py merge, 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; + } + + // model.py 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 (model.py: tmask = cat([dropped, mask], 1)) + 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: model.py PixelFlowModel.forward. 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; + } + + // model.py 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..7ac7cf82f0 --- /dev/null +++ b/src/model/diffusion/rd_flow_sampler.hpp @@ -0,0 +1,933 @@ +// RD Flow 64 sampler: host-side colour helpers and the Euler/pointer sampling +// loop. Ports rd-flow-64/rdflow/{flow,palette,ramps}.py. The model itself lives +// in rd_flow.hpp; this file only drives it, so the numerical behaviour of the +// reference sampler (palette extraction, pointer expectations, commit) can be +// checked step by step against the Python pipeline. +#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 { + + // rdflow/consts.py + constexpr int64_t RD_FLOW_SLOTS = 256; // palette slots (P) + // rdflow/flow.py: 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); + } + + // palette.srgb_to_oklab: 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}; + } + + // flow.oklab_to_srgb: 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; + } + + // flow.oklab_to_srgb: the same conversion but done in float32, which is what the + // reference does (torch float32 maths). extract_palette uses this one, so the + // rounding of near-.5 channels matches the 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; + } + + // flow.from_model: 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; + } + + // palette.ramp_order: hue family, then lightness, then rgb (numpy 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; + } + + // ramps.ramps: 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); + } + } + } + + // flow.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; + } + }; + + // flow.palette_dict + 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; + } + + // flow.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; + } + + // palette.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; + } + + // pipeline.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; + } + + // pipeline.read_palette_file body: the text of a Lospec/paint.net/GIMP/JASC palette + // file -> colour tokens for parse_hex. Text in, tokens out, so the file access and + // the parsing stay separately testable. + 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; + }; + + // rdflow.flow.sample - the drawing loop. `predict` runs one branch (B images) + // and `pointer` scores a palette; both are supplied by the caller so the loop can + // be driven either by RDFlowRunner directly (parity tests) or by the pipeline. + 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..cd9ac5a2c5 --- /dev/null +++ b/src/model/integrations/rd_flow.cpp @@ -0,0 +1,48 @@ +#include "model/diffusion/rd_flow.hpp" +#include "conditioning/conditioner.hpp" +#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 = std::make_shared(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 86f49d8ae2..7a2b7359ef 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 c543dbe403..cd44e3323f 100644 --- a/src/name_conversion.cpp +++ b/src/name_conversion.cpp @@ -1913,6 +1913,31 @@ std::string convert_tensor_name(std::string name, SDVersion version) { } } + if (sd_version_is_rd_flow(version)) { + // rdflow/text.py ships the prompt reader trimmed to embed_tokens, decoder + // layers 0-26 and the final norm, with the "model." level (and any + // language_model wrapper) stripped off. Put it back where the LLM runner + // expects it. + 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) || From a0ec8b889243dc2fee53aeebd79ae7abc656687b Mon Sep 17 00:00:00 2001 From: jahu00 Date: Sun, 29 Nov 2026 12:30:40 +0100 Subject: [PATCH 2/4] docs: Trimmed excess information in RD Flow 64 docs --- docs/models/rd_flow_64.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/models/rd_flow_64.md b/docs/models/rd_flow_64.md index c6bb90e3d3..39642618be 100644 --- a/docs/models/rd_flow_64.md +++ b/docs/models/rd_flow_64.md @@ -18,9 +18,7 @@ The prompt reader ships trimmed: `text_encoder_model.safetensors` holds 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. Both parts run -on the CPU by default. Build with `-DSD_VULKAN=ON` and add `--backend vulkan0` -to run them on a GPU, where f32 fits in 24 GiB of VRAM. +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 From e5eb8c7115c7b70f7bc2c393dfaa3e05fd11fc51 Mon Sep 17 00:00:00 2001 From: jahu00 Date: Sun, 29 Nov 2026 14:48:30 +0100 Subject: [PATCH 3/4] docs: trim excessive RD Flow 64 comments --- src/api/generation_image.cpp | 6 ++-- src/api/options.cpp | 3 +- src/conditioning/conditioner.hpp | 11 +++---- src/config.cpp | 2 -- src/config.h | 4 +-- src/dgl/bindings/rd_flow.cpp | 5 ++- src/dgl/models/diffusion_prediction.h | 4 +-- src/dgl/models/dit.cpp | 13 +++----- src/model/diffusion/model.hpp | 35 +++++++-------------- src/model/diffusion/rd_flow.hpp | 39 +++++++++++------------ src/model/diffusion/rd_flow_sampler.hpp | 42 ++++++++++--------------- src/name_conversion.cpp | 6 ++-- 12 files changed, 63 insertions(+), 107 deletions(-) diff --git a/src/api/generation_image.cpp b/src/api/generation_image.cpp index eb02720c26..a6902ed8bd 100644 --- a/src/api/generation_image.cpp +++ b/src/api/generation_image.cpp @@ -171,10 +171,8 @@ namespace sd::api { request.fields["negative_condition"] = "controlled_negative"; } - // RD Flow 64 draws one fixed 64 x 64 sprite from noise in a single pass. The - // pixel template has no branch for the modes it cannot serve, so those inputs - // are refused rather than quietly ignored, and its sampler knobs are passed to - // rd_flow::sample, which otherwise runs on its reference defaults. + // 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) diff --git a/src/api/options.cpp b/src/api/options.cpp index 80436cabca..1f888053c7 100644 --- a/src/api/options.cpp +++ b/src/api/options.cpp @@ -354,8 +354,7 @@ 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; generation_image.cpp rejects them on other models. Ranges - // match the rd_flow::sample built-in arguments. + // 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); diff --git a/src/conditioning/conditioner.hpp b/src/conditioning/conditioner.hpp index 5075282a4b..ec9c93630a 100644 --- a/src/conditioning/conditioner.hpp +++ b/src/conditioning/conditioner.hpp @@ -3287,9 +3287,8 @@ struct LLMEmbedder : public Conditioner { prompt += "<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"; } else if (sd_version_is_rd_flow(version)) { - // RD Flow 64: raw caption tokens, no chat template, Qwen3-VL cut at - // 27 layers through the final norm, then a second weightless RMS norm - // per token, masked. Mirrors rd-flow-64/rdflow/text.py. + // 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}; @@ -3314,8 +3313,7 @@ struct LLMEmbedder : public Conditioner { if (hidden_states.empty()) { return {}; } - // Second RMS norm (no weight) over the hidden dim, then mask padded - // tokens to zero. hidden_states is [hidden, L] (+ optional batch). + // 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) { @@ -3338,8 +3336,7 @@ struct LLMEmbedder : public Conditioner { SDCondition result; result.c_crossattn = std::move(hidden_states); // [2560, L] - // Carry the token key-padding mask to the drawing model. - result.c_vector = mask.empty() ? sd::Tensor::full({len}, 1.f) : std::move(mask); + 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(""); diff --git a/src/config.cpp b/src/config.cpp index c9669a9335..c8bf7904d5 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -84,8 +84,6 @@ namespace sd { batch_count = 1; control_strength = 0.9f; qwen_image_layers = 3; - // Same defaults as the rd_flow::sample built-in, so the passthrough is a - // no-op until the user changes one of them. rd_flow_palette = ""; rd_flow_background = "transparent"; rd_flow_shift = 3.0f; diff --git a/src/config.h b/src/config.h index 66fe523a07..fb683d1fc5 100644 --- a/src/config.h +++ b/src/config.h @@ -162,9 +162,7 @@ namespace sd { sd::CacheConfig cache{}; HiresConfig hires{}; int qwen_image_layers{}; - // RD Flow 64: a locked palette ("#rrggbb,..." or a palette file path), the - // background mode, and the sampler knobs the reference flow exposes but its - // Pipeline does not. Unused on other models. + // RD Flow 64 only. const char* rd_flow_palette{}; const char* rd_flow_background{}; float rd_flow_shift{}; diff --git a/src/dgl/bindings/rd_flow.cpp b/src/dgl/bindings/rd_flow.cpp index 4fc9d9382a..d743a08776 100644 --- a/src/dgl/bindings/rd_flow.cpp +++ b/src/dgl/bindings/rd_flow.cpp @@ -15,9 +15,8 @@ #include namespace sd::dgl { - // pipeline.parse_hex / read_palette_file: the "palette" argument is either a - // comma-separated list of "#rrggbb" colours or the path of a palette file - // (Lospec/paint.net/GIMP/JASC), like `generate.py --palette`. A path is only + // 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) { diff --git a/src/dgl/models/diffusion_prediction.h b/src/dgl/models/diffusion_prediction.h index a8b5bb9f3e..9adf26482a 100644 --- a/src/dgl/models/diffusion_prediction.h +++ b/src/dgl/models/diffusion_prediction.h @@ -45,9 +45,7 @@ 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: per-step self-conditioning, palette and background - // state, plus the features/pointer-head outputs rd_flow::sample reads - // back. Owned by that op for the duration of the call. + // 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 ececc4f466..ed6d24a962 100644 --- a/src/dgl/models/dit.cpp +++ b/src/dgl/models/dit.cpp @@ -305,9 +305,7 @@ 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()); - // RD Flow draws pixels and batches them itself (rd_flow::sample runs the - // doubled CFG batch, and its pointer head is fed features, not an image), - // so the latent contract below does not apply to it. + // 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() @@ -405,10 +403,8 @@ namespace sd::dgl::models { } else if (sd_version_is_minit2i(version())) { params.extra = MiniT2IDiffusionExtra{params.y}; } else if (sd_version_is_rd_flow(version())) { - // rd_flow::sample owns the loop, so it hands the per-step state - // (self-conditioning, palette, background) through the options and - // reads the u0 features / pointer scores back out of them. Without - // that state this is a plain text-to-image forward, mask in c_vector. + // 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; @@ -434,8 +430,7 @@ namespace sd::dgl::models { } throw std::runtime_error("diffusion compute failed"); } - // The RD Flow pointer head scores palette slots over the features of an - // earlier forward, so its output shape is not the image 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()) + diff --git a/src/model/diffusion/model.hpp b/src/model/diffusion/model.hpp index 914fe18589..878b58d5d9 100644 --- a/src/model/diffusion/model.hpp +++ b/src/model/diffusion/model.hpp @@ -117,30 +117,17 @@ struct MiniT2IDiffusionExtra { }; struct RDFlowDiffusionExtra { - // Token key-padding mask [L] (1 = real token, 0 = padding). An all-zero row - // means no text (the unconditional pass). - const sd::Tensor* text_mask = nullptr; - // Previous step's clean guess [64, 64, 4, B], the self-conditioning input - // (null on the first step). - const sd::Tensor* self_cond = nullptr; - // Background mode: 1 = opaque, 2 = transparent. - int bg_mode = 2; - // Palette tokens for the core: rgb [P, 3, B] sRGB 0..255, ramp [P, B], - // level [P, B], valid [P, B]. Empty until the sampler locks or extracts a - // palette. rdflow::sample drives these directly on the runner. - const sd::Tensor* pal_rgb = nullptr; - const sd::Tensor* pal_valid = nullptr; - const sd::Tensor* pal_ramp = nullptr; - const sd::Tensor* pal_level = nullptr; - int style = 0; - int source = 6; - // rd_flow::sample drives the loop itself, so it also needs things the plain - // sample path never asks for: the u0 features of a forward (written to - // out_features when set), and the pointer head as its own request - with - // pointer_head the input x holds those features and the result is the - // [1 + P, size*size, B] slot scores instead of an image. - sd::Tensor* out_features = nullptr; - bool pointer_head = false; + 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 { diff --git a/src/model/diffusion/rd_flow.hpp b/src/model/diffusion/rd_flow.hpp index e4c9340e4d..9f2443b9f2 100644 --- a/src/model/diffusion/rd_flow.hpp +++ b/src/model/diffusion/rd_flow.hpp @@ -2,15 +2,13 @@ #define __SD_MODEL_DIFFUSION_RD_FLOW_HPP__ // RD Flow 64 drawing model: an hourglass flow transformer over the 64x64 pixel -// grid with a palette-pointer head. Port of rd-flow-64/rdflow/model.py and -// layers.py. See docs/development/rd-flow-64-port.md. +// grid with a palette-pointer head. // -// Precision: the Python model runs in bf16 or fp32 only (fp16 activations -// overflow). Keep this graph in f32; weights load as bf16/f32. +// Precision: the model runs in bf16 or fp32 only (fp16 activations overflow). +// Keep this graph in f32; weights load as bf16/f32. // -// Tensor layout note: sd.cpp ggml tensors are [ne0 = feature, ne1 = token, -// ne2 = batch]. The Python reference is [B, token, feature]; indices below are -// given in ggml order unless marked "(torch)". +// Tensor layout: ggml tensors are [ne0 = feature, ne1 = token, ne2 = batch]; +// indices below are in ggml order unless marked "(torch)". #include #include @@ -134,7 +132,7 @@ namespace RDFlow { int64_t nc() const { return size / 4; } }; - // RMSNorm with the Python "w" weight name (layers.py RMSNorm uses self.w). + // RMSNorm with the "w" weight name. struct RDRMSNorm : public GGMLBlock { int64_t dim; float eps; @@ -267,7 +265,7 @@ namespace RDFlow { } // cat([sin(a), cos(a)]) with a = t * 1000 * exp(-log(10000) * j / half), - // exactly layers.py timestep_embed. -> [dim, 1, batch] + // 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(); @@ -314,8 +312,7 @@ namespace RDFlow { // ---- 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). Mirrors - // layers.py apply_rope. + // [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]; @@ -532,7 +529,7 @@ namespace RDFlow { } }; - // sRGB [0,255] -> OKLab (matches layers.py ColourEmbed.oklab / palette.py). + // sRGB [0,255] -> OKLab. inline std::array srgb_to_oklab(float r, float g, float b) { auto lin = [](float c) { c /= 255.0f; @@ -578,7 +575,7 @@ namespace RDFlow { return out; } - // Graph inputs for one drawing-model forward (see model.py forward()). + // 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 @@ -613,7 +610,7 @@ namespace RDFlow { ggml_tensor* feats = nullptr; // [d0, size*size, B] pointer-head pixel features }; - // The full hourglass network. See model.py PixelFlowModel. + // The full hourglass network. struct PixelFlowModel : public GGMLBlock { RDFlowConfig cfg; PixelFlowModel(const RDFlowConfig& cfg) @@ -673,8 +670,8 @@ namespace RDFlow { 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]; layers.py merge, patch pair (yi,xi) is - // the channel block order (yi * 2 + xi). + // [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 @@ -835,7 +832,7 @@ namespace RDFlow { return out; } - // model.py pointer_logits: [1 + P, size*size, B]; channel 0 is transparent, + // 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, @@ -1021,7 +1018,7 @@ namespace RDFlow { 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 (model.py: tmask = cat([dropped, mask], 1)) + // 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) @@ -1051,8 +1048,8 @@ namespace RDFlow { return x.dim() >= 4 ? x.shape()[3] : 1; } - // Forward pass: model.py PixelFlowModel.forward. Returns the predicted - // clean image and (optionally) the pointer-head pixel features. + // 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 @@ -1249,7 +1246,7 @@ namespace RDFlow { return prediction; } - // model.py pointer_logits over the features of a previous forward. + // Pointer logits over the features of a previous forward. sd::Tensor pointer_logits(const sd::Tensor& feats, const Palette& palette, int64_t batch, diff --git a/src/model/diffusion/rd_flow_sampler.hpp b/src/model/diffusion/rd_flow_sampler.hpp index 7ac7cf82f0..a56fbcebd5 100644 --- a/src/model/diffusion/rd_flow_sampler.hpp +++ b/src/model/diffusion/rd_flow_sampler.hpp @@ -1,8 +1,5 @@ // RD Flow 64 sampler: host-side colour helpers and the Euler/pointer sampling -// loop. Ports rd-flow-64/rdflow/{flow,palette,ramps}.py. The model itself lives -// in rd_flow.hpp; this file only drives it, so the numerical behaviour of the -// reference sampler (palette extraction, pointer expectations, commit) can be -// checked step by step against the Python pipeline. +// 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__ @@ -25,9 +22,8 @@ namespace RDFlow { - // rdflow/consts.py constexpr int64_t RD_FLOW_SLOTS = 256; // palette slots (P) - // rdflow/flow.py: OKLab a, b are scaled by this in model space + // OKLab a, b are scaled by this in model space constexpr float RD_FLOW_AB_SCALE = 3.0f; struct RDFlowRGB { @@ -48,7 +44,7 @@ namespace RDFlow { return std::nearbyintf(v); } - // palette.srgb_to_oklab: uint8 -> OKLab (float64 maths, float32 result) + // 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) @@ -77,7 +73,7 @@ namespace RDFlow { 0.0259040371f * l + 0.7827717662f * m - 0.8086757660f * s}; } - // flow.oklab_to_srgb: OKLab -> sRGB 0..255 (f32 maths, round-half-to-even) + // 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); @@ -96,9 +92,8 @@ namespace RDFlow { return out; } - // flow.oklab_to_srgb: the same conversion but done in float32, which is what the - // reference does (torch float32 maths). extract_palette uses this one, so the - // rounding of near-.5 channels matches the golden palettes. + // 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); @@ -117,7 +112,7 @@ namespace RDFlow { return out; } - // flow.from_model: model-space pixel -> (OKLab, opaque) + // 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; @@ -136,7 +131,7 @@ namespace RDFlow { return out; } - // palette.ramp_order: hue family, then lightness, then rgb (numpy lexsort order) + // 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(); @@ -168,7 +163,7 @@ namespace RDFlow { return idx; } - // ramps.ramps: OKLab palette -> (ramp id, dark->light level) + // 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; @@ -264,7 +259,7 @@ namespace RDFlow { } } - // flow.extract_palette: one image's continuous guess -> sRGB colours + // 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; @@ -408,7 +403,6 @@ namespace RDFlow { } }; - // flow.palette_dict inline RDFlowPalette palette_dict(const std::vector>& colour_lists) { RDFlowPalette pal; pal.B = (int64_t)colour_lists.size(); @@ -453,7 +447,7 @@ namespace RDFlow { return pal; } - // flow.bucket_palette: the shortest fixed-length palette that still holds every image's colours + // 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 {}; @@ -491,7 +485,7 @@ namespace RDFlow { return out; } - // palette.decode: (palette, tokens) -> RGBA + // 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) { @@ -536,7 +530,7 @@ namespace RDFlow { return t; } - // pipeline.parse_hex: "#aabbcc" | "aabbcc" | "abc" -> colours, deduped, in ramp order. + // 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) { @@ -578,9 +572,8 @@ namespace RDFlow { return sorted; } - // pipeline.read_palette_file body: the text of a Lospec/paint.net/GIMP/JASC palette - // file -> colour tokens for parse_hex. Text in, tokens out, so the file access and - // the parsing stay separately testable. + // 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; @@ -690,9 +683,8 @@ namespace RDFlow { int n_threads = 0) const; }; - // rdflow.flow.sample - the drawing loop. `predict` runs one branch (B images) - // and `pointer` scores a palette; both are supplied by the caller so the loop can - // be driven either by RDFlowRunner directly (parity tests) or by the pipeline. + // 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, diff --git a/src/name_conversion.cpp b/src/name_conversion.cpp index cd44e3323f..f35c1b99ff 100644 --- a/src/name_conversion.cpp +++ b/src/name_conversion.cpp @@ -1914,10 +1914,8 @@ std::string convert_tensor_name(std::string name, SDVersion version) { } if (sd_version_is_rd_flow(version)) { - // rdflow/text.py ships the prompt reader trimmed to embed_tokens, decoder - // layers 0-26 and the final norm, with the "model." level (and any - // language_model wrapper) stripped off. Put it back where the LLM runner - // expects it. + // 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.", From 83090dcfb7be66be3a414754faa010d25b6058e2 Mon Sep 17 00:00:00 2001 From: jahu00 Date: Mon, 30 Nov 2026 21:13:21 +0100 Subject: [PATCH 4/4] docs: update RD Flow 64 docs --- docs/models/rd_flow_64.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/models/rd_flow_64.md b/docs/models/rd_flow_64.md index 39642618be..575d8e8ebd 100644 --- a/docs/models/rd_flow_64.md +++ b/docs/models/rd_flow_64.md @@ -295,11 +295,19 @@ values; set them in a [DGL](#dgl) program if you need them. 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. -- On CPU, one seed reproduces exactly. On the Vulkan backend it does not: two - identical runs at the same seed differ in about 410 of the 4096 pixels (the - palette assignments move), and the drawings are equally good. The samples above - are all CPU runs, so the commands reproduce them. +- 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. + not the same caption. \ No newline at end of file