// RD Flow 64 sampler: host-side colour helpers and the Euler/pointer sampling // loop. The model itself lives in rd_flow.hpp; this file only drives it. #ifndef __SD_MODEL_DIFFUSION_RD_FLOW_SAMPLER_HPP__ #define __SD_MODEL_DIFFUSION_RD_FLOW_SAMPLER_HPP__ #include "model/diffusion/rd_flow.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace RDFlow { constexpr int64_t RD_FLOW_SLOTS = 256; // palette slots (P) // OKLab a, b are scaled by this in model space constexpr float RD_FLOW_AB_SCALE = 3.0f; struct RDFlowRGB { uint8_t r = 0, g = 0, b = 0; bool operator<(const RDFlowRGB& o) const { return std::tie(r, g, b) < std::tie(o.r, o.g, o.b); } bool operator==(const RDFlowRGB& o) const { return r == o.r && g == o.g && b == o.b; } }; using OKLab = std::array; // round-half-to-even, matching numpy/torch rounding in the reference static inline double round_half_even(double v) { return std::nearbyint(v); } static inline float round_half_even_f(float v) { return std::nearbyintf(v); } // uint8 -> OKLab (float64 maths, float32 result) inline OKLab srgb_to_oklab(const RDFlowRGB& c) { double k[3] = {c.r / 255.0, c.g / 255.0, c.b / 255.0}; for (double& v : k) v = v <= 0.04045 ? v / 12.92 : std::pow((v + 0.055) / 1.055, 2.4); const double r = k[0], g = k[1], b = k[2]; const double l = std::cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); const double m = std::cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); const double s = std::cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); return {float(0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s), float(1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s), float(0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s)}; } // layers.ColourEmbed.oklab: the model's own sRGB -> OKLab, computed in f32 inline OKLab oklab_model(const RDFlowRGB& c) { float k[3] = {c.r / 255.0f, c.g / 255.0f, c.b / 255.0f}; for (float& v : k) v = v <= 0.04045f ? v / 12.92f : std::pow((v + 0.055f) / 1.055f, 2.4f); const float r = k[0], g = k[1], b = k[2]; auto cube = [](float v) { return std::pow(v > 0.f ? v : 0.f, 1.0f / 3.0f); }; const float l = cube(0.4122214708f * r + 0.5363325363f * g + 0.0514459929f * b); const float m = cube(0.2119034982f * r + 0.6806995451f * g + 0.1073969566f * b); const float s = cube(0.0883024619f * r + 0.2817188376f * g + 0.6299787005f * b); return {0.2104542553f * l + 0.7936177850f * m - 0.0040720468f * s, 1.9779984951f * l - 2.4285922050f * m + 0.4505937099f * s, 0.0259040371f * l + 0.7827717662f * m - 0.8086757660f * s}; } // OKLab -> sRGB 0..255 (f32 maths, round-half-to-even) inline RDFlowRGB oklab_to_srgb(const OKLab& lab) { const double L = lab[0], a = lab[1], b = lab[2]; const double l = std::pow(L + 0.3963377774 * a + 0.2158037573 * b, 3.0); const double m = std::pow(L - 0.1055613458 * a - 0.0638541728 * b, 3.0); const double s = std::pow(L - 0.0894841775 * a - 1.2914855480 * b, 3.0); double rgb[3] = {4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s}; RDFlowRGB out; uint8_t* dst[3] = {&out.r, &out.g, &out.b}; for (int i = 0; i < 3; ++i) { double v = std::clamp(rgb[i], 0.0, 1.0); v = v <= 0.0031308 ? v * 12.92 : 1.055 * std::pow(std::max(v, 1e-12), 1.0 / 2.4) - 0.055; *dst[i] = (uint8_t)std::clamp(round_half_even(v * 255.0), 0.0, 255.0); } return out; } // The same conversion in float32. extract_palette uses this one, so the // rounding of near-.5 channels matches the f32 golden palettes. inline RDFlowRGB oklab_to_srgb_f32(const OKLab& lab) { const float L = lab[0], a = lab[1], b = lab[2]; const float l = std::pow(L + 0.3963377774f * a + 0.2158037573f * b, 3.0f); const float m = std::pow(L - 0.1055613458f * a - 0.0638541728f * b, 3.0f); const float s = std::pow(L - 0.0894841775f * a - 1.2914855480f * b, 3.0f); float rgb[3] = {4.0767416621f * l - 3.3077115913f * m + 0.2309699292f * s, -1.2684380046f * l + 2.6097574011f * m - 0.3413193965f * s, -0.0041960863f * l - 0.7034186147f * m + 1.7076147010f * s}; RDFlowRGB out; uint8_t* dst[3] = {&out.r, &out.g, &out.b}; for (int i = 0; i < 3; ++i) { float v = std::clamp(rgb[i], 0.0f, 1.0f); v = v <= 0.0031308f ? v * 12.92f : 1.055f * std::pow(std::max(v, 1e-12f), 1.0f / 2.4f) - 0.055f; *dst[i] = (uint8_t)std::clamp(std::nearbyintf(v * 255.0f), 0.0f, 255.0f); } return out; } // model-space pixel -> (OKLab, opaque) inline void pixel_from_model(const float* x, OKLab& lab, bool& opaque) { lab = {(x[0] + 1.0f) * 0.5f, x[1] / RD_FLOW_AB_SCALE, x[2] / RD_FLOW_AB_SCALE}; opaque = x[3] > 0.0f; } // numpy's np.unwrap for hue sequences (consecutive values differ by less than 2*pi) inline std::vector hue_unwrap(const std::vector& v) { std::vector out = v; for (size_t i = 1; i < out.size(); ++i) { double d = out[i] - out[i - 1]; if (d > M_PI) out[i] -= 2.0 * M_PI * std::ceil((d - M_PI) / (2.0 * M_PI)); else if (d < -M_PI) out[i] += 2.0 * M_PI * std::ceil((-d - M_PI) / (2.0 * M_PI)); } return out; } // ramp_order: hue family, then lightness, then rgb (lexsort order) inline std::vector ramp_order(const std::vector& colours) { const float ACHROMATIC_C = 0.04f; const size_t n = colours.size(); std::vector L(n); std::vector family(n); for (size_t i = 0; i < n; ++i) { const OKLab lab = srgb_to_oklab(colours[i]); L[i] = lab[0]; const float chroma = std::sqrt(lab[1] * lab[1] + lab[2] * lab[2]); float hue = std::atan2(lab[2], lab[1]) * 180.0f / (float)M_PI; hue = std::fmod(hue + 360.0f, 360.0f); family[i] = chroma < ACHROMATIC_C ? 0 : 1 + std::min((int)std::floor(hue / 30.0f), 11); } std::vector idx(n); for (size_t i = 0; i < n; ++i) idx[i] = i; // np.lexsort((b, g, r, L, family)): family is the primary key std::stable_sort(idx.begin(), idx.end(), [&](size_t a, size_t b) { if (family[a] != family[b]) return family[a] < family[b]; if (L[a] != L[b]) return L[a] < L[b]; if (colours[a].r != colours[b].r) return colours[a].r < colours[b].r; if (colours[a].g != colours[b].g) return colours[a].g < colours[b].g; return colours[a].b < colours[b].b; }); return idx; } // OKLab palette -> (ramp id, dark->light level) inline void palette_ramps(const std::vector& lab, std::vector& ramp, std::vector& level) { const float NEUTRAL_C = 0.035f; const double HUE_GAP = 28.0 * M_PI / 180.0; const double HUE_SPAN = 75.0 * M_PI / 180.0; const int MAX_RAMPS = 15; const int n = (int)lab.size(); ramp.assign(n, 0); level.assign(n, 0.5f); if (!n) return; std::vector L(n), hue(n); std::vector chromatic, neutral; for (int i = 0; i < n; ++i) { L[i] = lab[i][0]; // numpy keeps the float32 dtype here: chroma and hue are float32 values const float chroma = std::sqrt(lab[i][1] * lab[i][1] + lab[i][2] * lab[i][2]); double h = std::atan2(lab[i][2], lab[i][1]); hue[i] = std::fmod(h + 2.0 * M_PI, 2.0 * M_PI); if (chroma >= NEUTRAL_C) chromatic.push_back(i); else neutral.push_back(i); } std::vector> groups; if (!chromatic.empty()) { std::vector order = chromatic; std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return hue[a] < hue[b]; }); std::vector gaps(order.size()); for (size_t i = 0; i + 1 < order.size(); ++i) gaps[i] = hue[order[i + 1]] - hue[order[i]]; gaps.back() = hue[order[0]] + 2.0 * M_PI - hue[order.back()]; size_t best = 0; for (size_t i = 1; i < gaps.size(); ++i) if (gaps[i] > gaps[best]) best = i; std::rotate(order.begin(), order.begin() + (long)(best + 1), order.end()); std::vector seq; seq.reserve(order.size()); for (int i : order) seq.push_back(hue[i]); seq = hue_unwrap(seq); std::vector cur{order[0]}; for (size_t i = 1; i < order.size(); ++i) { if (seq[i] - seq[i - 1] > HUE_GAP) { groups.push_back(cur); cur.clear(); } cur.push_back(order[i]); } groups.push_back(cur); std::vector> split; for (auto g : groups) { while (g.size() > 2) { std::vector hg; hg.reserve(g.size()); for (int i : g) hg.push_back(hue[i]); hg = hue_unwrap(hg); if (hg.back() - hg.front() <= HUE_SPAN) break; size_t k = 0; double worst = -1e300; for (size_t i = 0; i + 1 < hg.size(); ++i) { double d = hg[i + 1] - hg[i]; if (d > worst) { worst = d; k = i + 1; } } split.emplace_back(g.begin(), g.begin() + (long)k); g.erase(g.begin(), g.begin() + (long)k); } split.push_back(g); } groups = split; } std::vector>> sets; sets.emplace_back(0, neutral); for (size_t i = 0; i < groups.size(); ++i) sets.emplace_back(std::min((int)i + 1, MAX_RAMPS), groups[i]); for (auto& [rid, g] : sets) { if (g.empty()) continue; for (int i : g) ramp[i] = rid; if (g.size() > 1) { // np.argsort(np.argsort(L[g])): rank of each element, ties keep their position std::vector ord = g; std::stable_sort(ord.begin(), ord.end(), [&](int a, int b) { return L[a] < L[b]; }); for (size_t r = 0; r < ord.size(); ++r) level[ord[r]] = (float)r / (float)(ord.size() - 1); } } } // extract_palette: one image's continuous guess -> sRGB colours inline std::vector extract_palette(const float* x, int64_t n, int max_colours = 64, double merge = 0.05, double bin_size = 0.015, int iters = 4) { // OKLab of the opaque pixels, in float64 (the reference forces the CPU dtype) std::vector> pts; pts.reserve((size_t)n * n); for (int64_t p = 0; p < n * n; ++p) { const float* px = x + p * 4; OKLab lab; bool opaque = false; pixel_from_model(px, lab, opaque); if (!opaque) continue; pts.push_back({lab[0], lab[1], lab[2]}); } if (pts.empty()) return {}; // np.unique(round(pts / bin_size), axis=0) -> keys in lex order, inverse, counts std::map, int> key_index; std::vector inv(pts.size()); std::vector counts; std::vector> sums; for (size_t i = 0; i < pts.size(); ++i) { auto key = std::make_tuple((int64_t)round_half_even(pts[i][0] / bin_size), (int64_t)round_half_even(pts[i][1] / bin_size), (int64_t)round_half_even(pts[i][2] / bin_size)); auto it = key_index.find(key); int ki; if (it == key_index.end()) { ki = (int)counts.size(); key_index.emplace(key, ki); counts.push_back(0.0); sums.push_back({0.0, 0.0, 0.0}); } else { ki = it->second; } inv[i] = ki; counts[ki] += 1.0; for (int c = 0; c < 3; ++c) sums[ki][c] += pts[i][c]; } // np.unique hands back its keys in lexicographic order and counts aligned to // that order, and the stable argsort below breaks ties by key index. A std::map // iterates in key order, so replay it to put the bin arrays in the same order. { const int nb = (int)counts.size(); std::vector remap((size_t)nb); std::vector counts_sorted((size_t)nb); std::vector> sums_sorted((size_t)nb); int ni = 0; for (auto& [key, ki] : key_index) { remap[(size_t)ki] = ni; counts_sorted[(size_t)ni] = counts[(size_t)ki]; sums_sorted[(size_t)ni] = sums[(size_t)ki]; ++ni; } for (auto& v : inv) v = remap[(size_t)v]; counts = std::move(counts_sorted); sums = std::move(sums_sorted); } const int nk = (int)counts.size(); std::vector> means(nk); for (int k = 0; k < nk; ++k) for (int c = 0; c < 3; ++c) means[k][c] = sums[k][c] / counts[k]; // np.argsort(-counts, kind="stable"): descending count, ties in key order std::vector order(nk); for (int k = 0; k < nk; ++k) order[k] = k; std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return counts[a] > counts[b]; }); std::vector> C; for (int k : order) { if (C.empty()) { C.push_back(means[k]); } else { double best = 1e300; for (auto& c : C) { double d = std::sqrt(std::pow(c[0] - means[k][0], 2) + std::pow(c[1] - means[k][1], 2) + std::pow(c[2] - means[k][2], 2)); best = std::min(best, d); } if (best > merge) C.push_back(means[k]); } if ((int)C.size() >= max_colours) break; } for (int it = 0; it < iters && !C.empty(); ++it) { std::vector assign(pts.size(), 0); std::vector cnt(C.size(), 0.0); for (size_t i = 0; i < pts.size(); ++i) { double best = 1e300; int bk = 0; for (size_t k = 0; k < C.size(); ++k) { double d = std::pow(pts[i][0] - C[k][0], 2) + std::pow(pts[i][1] - C[k][1], 2) + std::pow(pts[i][2] - C[k][2], 2); if (d < best) { best = d; bk = (int)k; } } assign[i] = bk; cnt[bk] += 1.0; } std::vector> nc; for (size_t k = 0; k < C.size(); ++k) { if (cnt[k] <= 0.0) continue; std::array s{0.0, 0.0, 0.0}; for (size_t i = 0; i < pts.size(); ++i) if (assign[i] == (int)k) for (int c = 0; c < 3; ++c) s[c] += pts[i][c]; for (int c = 0; c < 3; ++c) s[c] /= cnt[k]; nc.push_back(s); } C = nc; } // torch.unique(oklab_to_srgb(C), dim=0): sorted unique rows std::set out; for (auto& c : C) out.insert(oklab_to_srgb_f32({(float)c[0], (float)c[1], (float)c[2]})); return {out.begin(), out.end()}; } // A palette in the shape the sampler and the model need. rgb/valid/ramp/level are // per image over P slots; space is [B][1 + P][4] model space (slot 0 = transparent). struct RDFlowPalette { int64_t B = 0; int64_t P = 0; std::vector rgb; std::vector valid; std::vector ramp; std::vector level; std::vector space; bool empty() const { return P == 0; } int64_t count_valid(int64_t b) const { int64_t k = 0; for (int64_t p = 0; p < P; ++p) k += valid[(size_t)b * P + p] != 0; return k; } }; inline RDFlowPalette palette_dict(const std::vector>& colour_lists) { RDFlowPalette pal; pal.B = (int64_t)colour_lists.size(); pal.P = RD_FLOW_SLOTS; pal.rgb.assign((size_t)pal.B * pal.P, RDFlowRGB{}); pal.valid.assign((size_t)pal.B * pal.P, 0); pal.ramp.assign((size_t)pal.B * pal.P, 0); pal.level.assign((size_t)pal.B * pal.P, 0.5f); for (size_t b = 0; b < colour_lists.size(); ++b) { std::vector cols = colour_lists[b]; if (cols.size() > (size_t)pal.P) cols.resize((size_t)pal.P); std::vector lab; lab.reserve(cols.size()); for (auto& c : cols) lab.push_back(srgb_to_oklab(c)); std::vector ramp; std::vector level; palette_ramps(lab, ramp, level); for (size_t k = 0; k < cols.size(); ++k) { pal.rgb[(size_t)b * pal.P + k] = cols[k]; pal.valid[(size_t)b * pal.P + k] = 1; pal.ramp[(size_t)b * pal.P + k] = ramp[k]; pal.level[(size_t)b * pal.P + k] = level[k]; } } // palette_model_space: slot 0 is transparent, then each colour in model space pal.space.assign((size_t)pal.B * (pal.P + 1) * 4, 0.0f); for (int64_t b = 0; b < pal.B; ++b) { float* t = &pal.space[(size_t)b * (pal.P + 1) * 4]; t[0] = t[1] = t[2] = 0.0f; t[3] = -1.0f; for (int64_t p = 0; p < pal.P; ++p) { const OKLab lab = oklab_model(pal.rgb[(size_t)b * pal.P + p]); float* dst = t + (p + 1) * 4; dst[0] = 2.0f * lab[0] - 1.0f; dst[1] = lab[1] * RD_FLOW_AB_SCALE; dst[2] = lab[2] * RD_FLOW_AB_SCALE; dst[3] = 1.0f; } } return pal; } // bucket_palette: the shortest fixed-length palette that still holds every image's colours inline RDFlowPalette bucket_palette(const RDFlowPalette& pal) { if (pal.empty()) return {}; int64_t need = 0; for (int64_t b = 0; b < pal.B; ++b) need = std::max(need, pal.count_valid(b)); if (need == 0) return {}; static const int64_t buckets[] = {32, 64, 128, 256}; int64_t keep = pal.P; for (int64_t bucket : buckets) { if (bucket >= need) { keep = std::min(pal.P, bucket); break; } } keep = std::min(keep, pal.P); // v[:, :keep] for every per-image field: the arrays are re-strided to `keep` // slots per image, not merely truncated in place RDFlowPalette out; out.B = pal.B; out.P = keep; out.rgb.assign((size_t)pal.B * keep, RDFlowRGB{}); out.valid.assign((size_t)pal.B * keep, 0); out.ramp.assign((size_t)pal.B * keep, 0); out.level.assign((size_t)pal.B * keep, 0.5f); for (int64_t b = 0; b < pal.B; ++b) for (int64_t q = 0; q < keep; ++q) { out.rgb[(size_t)b * keep + q] = pal.rgb[(size_t)b * pal.P + q]; out.valid[(size_t)b * keep + q] = pal.valid[(size_t)b * pal.P + q]; out.ramp[(size_t)b * keep + q] = pal.ramp[(size_t)b * pal.P + q]; out.level[(size_t)b * keep + q] = pal.level[(size_t)b * pal.P + q]; } // the pointer head always gets the full palette, so this one carries no model space return out; } // decode: (palette, tokens) -> RGBA inline std::vector palette_decode(const std::vector& pal, const int32_t* tokens, size_t count) { std::vector out(count * 4, 0); for (size_t i = 0; i < count; ++i) { const int64_t t = tokens[i]; if (t <= 0) continue; const RDFlowRGB& c = pal[(size_t)(t - 1)]; out[i * 4 + 0] = c.r; out[i * 4 + 1] = c.g; out[i * 4 + 2] = c.b; out[i * 4 + 3] = 255; } return out; } // RDFlowPalette -> the tensors rd_flow.hpp wants: rgb [P, 3, B] (sRGB 0..255), // ramp/level/valid [P, B]. Kept next to the palette struct so the parity tests // and the pipeline build the same thing. struct RDFlowPaletteTensors { sd::Tensor rgb, valid, level; sd::Tensor ramp; }; inline RDFlowPaletteTensors rd_flow_palette_tensors(const RDFlowPalette& pal) { RDFlowPaletteTensors t; const int64_t P = pal.P, B = pal.B; t.rgb = sd::Tensor(std::vector{P, 3, B}); t.valid = sd::Tensor(std::vector{P, B}); t.level = sd::Tensor(std::vector{P, B}); t.ramp = sd::Tensor(std::vector{P, B}); for (int64_t b = 0; b < B; ++b) { for (int64_t q = 0; q < P; ++q) { const RDFlowRGB& c = pal.rgb[(size_t)b * P + q]; t.rgb[q + P * (0 + 3 * b)] = (float)c.r; t.rgb[q + P * (1 + 3 * b)] = (float)c.g; t.rgb[q + P * (2 + 3 * b)] = (float)c.b; t.valid[q + P * b] = pal.valid[(size_t)b * P + q] ? 1.f : 0.f; t.ramp[q + P * b] = pal.ramp[(size_t)b * P + q]; t.level[q + P * b] = pal.level[(size_t)b * P + q]; } } return t; } // parse_hex: "#aabbcc" | "aabbcc" | "abc" -> colours, deduped, in ramp order. // strict reports a token that is not a colour instead of dropping it, so a typo in // a user-supplied palette cannot silently draw with fewer colours. inline std::vector parse_hex(const std::vector& colours, bool strict = false) { std::set seen; for (auto raw : colours) { std::string h = raw; while (!h.empty() && (h.front() == ' ' || h.front() == '#')) h.erase(h.begin()); while (!h.empty() && (h.back() == ' ' || h.back() == '\r' || h.back() == '\n')) h.pop_back(); if (h.size() == 3) { std::string e; for (char ch : h) e += ch, e += ch; h = e; } else if (h.size() == 8) { bool ff = raw.size() >= 2 && (raw[0] == 'F' || raw[0] == 'f') && (raw[1] == 'F' || raw[1] == 'f'); h = ff ? h.substr(2) : h.substr(0, 6); } if (h.size() != 6) { if (strict) { throw std::invalid_argument("not a colour: '" + raw + "'"); } continue; } auto hex = [](const std::string& s, size_t at) { auto v = [](char c) { return c <= '9' ? c - '0' : (char)(std::tolower(c) - 'a' + 10); }; return (uint8_t)(v(s[at]) * 16 + v(s[at + 1])); }; seen.insert(RDFlowRGB{hex(h, 0), hex(h, 2), hex(h, 4)}); } std::vector out(seen.begin(), seen.end()); if (out.size() > (size_t)RD_FLOW_SLOTS) out.resize((size_t)RD_FLOW_SLOTS); std::vector order = ramp_order(out); std::vector sorted; for (size_t i = 0; i < order.size(); ++i) sorted.push_back(out[order[i]]); return sorted; } // The text of a Lospec/paint.net/GIMP/JASC palette file -> colour tokens for // parse_hex. Text in, tokens out, so file access and parsing stay separable. inline std::vector parse_palette_text(const std::string& text) { std::vector lines; std::string line; for (char ch : text) { if (ch == '\n') { lines.push_back(line); line.clear(); } else if (ch != '\r') { line += ch; } } lines.push_back(line); auto trim = [](std::string s) { while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.erase(s.begin()); while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) s.pop_back(); return s; }; std::vector colours; // The reference turns "r g b" triplets into hex before calling parse_hex, so do // the same and keep parse_hex the only colour parser. auto to_hex = [](const std::string& r, const std::string& g, const std::string& b) { char hex[8]; std::snprintf(hex, sizeof(hex), "%02x%02x%02x", std::atoi(r.c_str()) & 0xff, std::atoi(g.c_str()) & 0xff, std::atoi(b.c_str()) & 0xff); return std::string(hex); }; auto triplets = [&](const std::vector& rows, size_t from, bool digits_only) { for (size_t i = from; i < rows.size(); ++i) { std::stringstream fields(rows[i]); std::string values[3]; size_t count = 0; while (count < 3 && fields >> values[count]) ++count; if (count < 3) continue; if (digits_only) { for (const std::string& v : values) { if (v.empty() || std::any_of(v.begin(), v.end(), [](char c) { return c < '0' || c > '9'; })) { count = 0; break; } } } if (count == 3) colours.push_back(to_hex(values[0], values[1], values[2])); } }; if (!lines.empty() && trim(lines[0]) == "JASC-PAL") { triplets(lines, 3, false); } else if (!lines.empty() && trim(lines[0]) == "GIMP Palette") { triplets(lines, 1, true); } else { for (const std::string& l : lines) { const std::string s = trim(l); if (!s.empty() && s[0] != ';') colours.push_back(s); } } return colours; } // The drawing-model branch call: fills x_hat [n, n, 4, B] and the decoder features. using RDFlowPredictFn = std::function& x_hat, sd::Tensor& feats)>; // Pointer head over a palette: logits [1 + P, n * n, B] (invalid slots -inf) using RDFlowPointerFn = std::function(const sd::Tensor& feats, const RDFlowPalette& pal)>; struct RDFlowSamplerParams { int steps = 16; float guidance = 4.0f; float interval_lo = 0.0f, interval_hi = 0.9f; float shift = 3.0f; float palette_at = 0.6f; float pointer_from = 0.35f; float commit_from = 0.55f; float commit_thresh = 0.9f; int max_colours = 64; float merge = 0.05f; int bg_mode = 2; // 1 opaque, 2 transparent int source = 6; }; struct RDFlowSamplerOutput { RDFlowPalette palette; // full palette the image was decoded against std::vector tokens; // [B][n * n]: 0 transparent, 1 + s = slot s std::vector probs; // [B][n * n][1 + P] pointer probabilities of the last guided step }; struct RDFlowSampler { RDFlowSamplerParams params; RDFlowPredictFn predict; RDFlowPointerFn pointer; // Reports finished steps so the caller can show progress and cancel a long // draw; throwing here aborts the loop. Optional. std::function on_step; // Per-image locked palettes (empty outer vector = nothing locked). std::vector> locked; RDFlowSamplerOutput run(const sd::Tensor& noise, const sd::Tensor& text, const sd::Tensor& text_mask, int64_t n, int n_threads = 0) const; }; // The drawing loop. `predict` runs one branch (B images) and `pointer` scores // a palette; both are supplied by the caller. inline RDFlowSamplerOutput RDFlowSampler::run(const sd::Tensor& noise, const sd::Tensor& text, const sd::Tensor& text_mask, int64_t n, int n_threads) const { const RDFlowSamplerParams& p = params; const int64_t B = noise.shape().back(); const int64_t per_image = n * n * 4; // image tensors are [x, y, channel, batch]: the channel stride is n * n, so a // pixel is not four contiguous floats auto sd_idx = [n](int64_t x, int64_t y, int64_t c, int64_t b) { return x + n * (y + n * (c + 4 * b)); }; // sd [n, n, 4, B] image -> torch-order [n, n, 4] slice for one image auto image_torch_order = [&](const sd::Tensor& img, int64_t b) { std::vector out((size_t)n * n * 4); for (int64_t y = 0; y < n; ++y) for (int64_t x = 0; x < n; ++x) for (int64_t c = 0; c < 4; ++c) out[((size_t)y * n + x) * 4 + c] = img[sd_idx(x, y, c, b)]; return out; }; RDFlowSamplerOutput out; sd::Tensor x(std::vector{n, n, 4, B}); std::memcpy(x.data(), noise.data(), sizeof(float) * (size_t)noise.numel()); // ts = linspace(0, 1, steps + 1) shifted towards the noisy end std::vector ts((size_t)p.steps + 1); for (int i = 0; i <= p.steps; ++i) { const float u = (float)i / (float)p.steps; ts[i] = u / (u + p.shift * (1.0f - u)); } sd::Tensor null_mask(text_mask.shape()); std::fill(null_mask.data(), null_mask.data() + null_mask.numel(), 0.0f); bool all_locked = !locked.empty(); for (auto& cols : locked) if (cols.empty()) all_locked = false; RDFlowPalette pal = all_locked ? palette_dict(locked) : RDFlowPalette{}; sd::Tensor sc, x_hat, feats; // self-cond, current guess, guided features bool have_sc = false, have_x_hat = false, have_feats = false; std::vector probs; // [B][n * n][1 + P] of the most recent pointer step int64_t prob_slots = 0; bool have_probs = false; // one drawing-model branch: x + optional self-cond + bucketed palette tokens auto branch = [&](const sd::Tensor& mask, const RDFlowPalette* pb, sd::Tensor& xh, sd::Tensor& ft, float t) { RDFlowRunner::Request req; req.x = &x; req.t = std::vector((size_t)B, t); req.text = &text; req.text_mask = &mask; req.self_cond = have_sc ? &sc : nullptr; req.bg_mode = p.bg_mode; req.style = 0; req.source = p.source; req.want_features = true; sd::Tensor rgb, valid, level; sd::Tensor ramp; if (pb != nullptr) { const int64_t Pk = pb->P; rgb.resize(std::vector{Pk, 3, B}); valid.resize(std::vector{Pk, B}); level.resize(std::vector{Pk, B}); ramp.resize(std::vector{Pk, B}); for (int64_t b = 0; b < B; ++b) for (int64_t q = 0; q < Pk; ++q) { const RDFlowRGB& c = pb->rgb[(size_t)b * pb->P + q]; rgb[q + Pk * (0 + 3 * b)] = (float)c.r; rgb[q + Pk * (1 + 3 * b)] = (float)c.g; rgb[q + Pk * (2 + 3 * b)] = (float)c.b; valid[q + Pk * b] = pb->valid[(size_t)b * pb->P + q] ? 1.0f : 0.0f; ramp[q + Pk * b] = pb->ramp[(size_t)b * pb->P + q]; level[q + Pk * b] = pb->level[(size_t)b * pb->P + q]; } req.pal.rgb = &rgb; req.pal.valid = &valid; req.pal.ramp = &ramp; req.pal.level = &level; req.pal.P = Pk; } predict(req, xh, ft); }; // pointer head -> probabilities and the expected model-space colour auto expected = [&](const sd::Tensor& ft, const RDFlowPalette& full, std::vector& xp, std::vector* probabilities) { sd::Tensor logits = pointer(ft, full); // [1 + P, n * n, B] const int64_t S = full.P + 1; const int64_t npix = n * n; std::vector pr((size_t)B * npix * S); for (int64_t b = 0; b < B; ++b) for (int64_t q = 0; q < npix; ++q) { const float* row = logits.data() + q * S + b * npix * S; float mx = -INFINITY; for (int64_t s = 0; s < S; ++s) mx = std::max(mx, row[s]); double sum = 0.0; for (int64_t s = 0; s < S; ++s) { const double e = std::exp((double)row[s] - mx); pr[(size_t)(b * npix + q) * S + s] = (float)e; sum += e; } for (int64_t s = 0; s < S; ++s) pr[(size_t)(b * npix + q) * S + s] /= (float)sum; } xp.assign((size_t)B * npix * 4, 0.0f); for (int64_t b = 0; b < B; ++b) for (int64_t q = 0; q < npix; ++q) { const float* prw = &pr[(size_t)(b * npix + q) * S]; const float* spc = &full.space[(size_t)b * S * 4]; float* dst = &xp[(size_t)(b * npix + q) * 4]; for (int c = 0; c < 4; ++c) { double acc = 0.0; for (int64_t s = 0; s < S; ++s) acc += (double)prw[s] * spc[s * 4 + c]; dst[c] = (float)acc; } } if (probabilities != nullptr) { *probabilities = std::move(pr); prob_slots = S; } }; for (int i = 0; i < p.steps; ++i) { const float t = ts[i], t2 = ts[i + 1]; if (pal.empty() && t >= p.palette_at && have_x_hat) { std::vector> lists((size_t)B); for (int64_t b = 0; b < B; ++b) { auto img = image_torch_order(x_hat, b); lists[(size_t)b] = extract_palette(img.data(), n, p.max_colours, (double)p.merge); } pal = palette_dict(lists); } const bool guide = p.guidance != 1.0f && t >= p.interval_lo && t <= p.interval_hi; RDFlowPalette pb = pal.empty() ? RDFlowPalette{} : bucket_palette(pal); sd::Tensor xc, fc, xu, fu; branch(text_mask, pb.empty() ? nullptr : &pb, xc, fc, t); if (guide) branch(null_mask, pb.empty() ? nullptr : &pb, xu, fu, t); sd::Tensor guess(std::vector{n, n, 4, B}); if (guide) { for (int64_t j = 0; j < guess.numel(); ++j) guess[j] = xu[j] + p.guidance * (xc[j] - xu[j]); } else { std::memcpy(guess.data(), xc.data(), sizeof(float) * (size_t)guess.numel()); } feats = fc; have_feats = true; if (!pal.empty() && t >= p.pointer_from) { std::vector xp, xpu; expected(fc, pal, xp, &probs); have_probs = true; if (guide) { expected(fu, pal, xpu, nullptr); for (size_t j = 0; j < xp.size(); ++j) xp[j] = xpu[j] + p.guidance * (xp[j] - xpu[j]); } if (t >= p.commit_from) { const int64_t S = pal.P + 1; const int64_t npix = n * n; for (int64_t b = 0; b < B; ++b) for (int64_t q = 0; q < npix; ++q) { const float* prw = &probs[(size_t)(b * npix + q) * S]; int64_t best = 0; for (int64_t s = 1; s < S; ++s) if (prw[s] > prw[best]) best = s; if (prw[best] < p.commit_thresh) continue; const float* exact = &pal.space[((size_t)b * S + best) * 4]; for (int c = 0; c < 4; ++c) xp[(size_t)(b * npix + q) * 4 + c] = exact[c]; } } // [B][n * n][4] (torch order) -> [x, y, 4, B] (sd order) for (int64_t b = 0; b < B; ++b) for (int64_t q = 0; q < n * n; ++q) for (int c = 0; c < 4; ++c) guess[sd_idx(q % n, q / n, c, b)] = xp[(size_t)(b * n * n + q) * 4 + c]; } x_hat = guess; have_x_hat = true; sc = x_hat; have_sc = true; const float denom = std::max(1.0f - t, 1e-4f); for (int64_t j = 0; j < x.numel(); ++j) x[j] = x[j] + ((t2 - t) * (x_hat[j] - x[j])) / denom; if (on_step) on_step(i + 1, p.steps); } if (pal.empty()) { std::vector> lists((size_t)B); for (int64_t b = 0; b < B; ++b) { if (all_locked) { lists[(size_t)b] = locked[(size_t)b]; continue; } auto img = image_torch_order(x_hat, b); lists[(size_t)b] = extract_palette(img.data(), n, p.max_colours, (double)p.merge); } pal = palette_dict(lists); } if (!have_probs) { std::vector xp; expected(feats, pal, xp, &probs); } out.palette = pal; out.probs = probs; out.tokens.assign((size_t)B * n * n, 0); for (int64_t b = 0; b < B; ++b) for (int64_t q = 0; q < n * n; ++q) { const float* prw = &probs[(size_t)(b * n * n + q) * prob_slots]; int64_t best = 0; for (int64_t s = 1; s < prob_slots; ++s) if (prw[s] > prw[best]) best = s; out.tokens[(size_t)b * n * n + q] = (int32_t)best; } (void)n_threads; return out; } } // namespace RDFlow #endif // __SD_MODEL_DIFFUSION_RD_FLOW_SAMPLER_HPP__