From aa5dfaec19d77250c9110e8bf9ab0e9feb33d377 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 22 Oct 2026 14:55:31 +0200 Subject: [PATCH] krea2: rebalance presets balanced, detail and subtle at the taps' measured RMS `rebalance` takes a preset's name beside true/false: "balanced", "detail" and "subtle" are comfyui-krea2-conditioning's presets with renormalize on at multiplier 1, "legacy" is true (ConditioningKrea2Rebalance's defaults, about 9x the taps' RMS). The node renormalises by s = sqrt(sum m_t / sum w_t^2 m_t) per prompt, m_t tap t's mean square; the plugin holds s as a constant per preset, m_t averaged over twenty prompts through krea/Krea-2-Turbo's text encoder (scripts/krea2_rebalance_calib.py: balanced 0.44109, detail 0.35702, subtle 0.84759; per prompt s stayed within 1.7 % of it). The gains are fixed per tap, so the presets reuse #187's chan_affine into te.h2 with their own `mul`, one declared op per preset and tap. The preset rides in RAD_GEN_COND_REBALANCE_PRESET, bits 8 to 15 of cond_opts beside RAD_GEN_COND_REBALANCE, which a plugin declares when it has presets; the driver accepts both bits, and the server refuses a preset's name on a model whose rebalance declares none. A row the plugin does not know scales nothing. Enum values only, so no ABI bump. Co-Authored-By: Claude Opus 5.5 --- abi/rad_runtime.h | 7 ++- arch/krea2/krea2.cpp | 80 +++++++++++++++++--------- core/gen/driver.cpp | 7 ++- core/server/images.cpp | 32 ++++++++--- docs/GUIDE.md | 2 +- scripts/README.md | 1 + scripts/krea2_rebalance_calib.py | 98 ++++++++++++++++++++++++++++++++ tests/arch_test.cpp | 34 ++++++++--- tests/images_test.cpp | 38 +++++++++++++ 9 files changed, 252 insertions(+), 47 deletions(-) create mode 100755 scripts/krea2_rebalance_calib.py diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 07488d31..a0e46936 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -453,8 +453,13 @@ typedef struct RadGenBatch { /* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */ enum { - RAD_GEN_COND_REBALANCE = 1 /* the conditioning at the plugin's fixed rebalance gains (the + RAD_GEN_COND_REBALANCE = 1, /* the conditioning at the plugin's fixed rebalance gains (the * request field `rebalance`; Krea 2: its text taps) */ + /* which of the plugin's rebalance presets, beside RAD_GEN_COND_REBALANCE: 0 its default + * gains, Krea 2: 1 balanced, 2 detail, 3 subtle (arch/krea2). A plugin declares these bits in + * RadGeneratorDecl::cond_opts when it has presets. */ + RAD_GEN_COND_REBALANCE_PRESET = 0xff00, + RAD_GEN_COND_REBALANCE_PRESET_SHIFT = 8 }; /* An entry's flags on a DENOISE pass. */ diff --git a/arch/krea2/krea2.cpp b/arch/krea2/krea2.cpp index 42497eda..f5b884fa 100644 --- a/arch/krea2/krea2.cpp +++ b/arch/krea2/krea2.cpp @@ -73,10 +73,30 @@ enum { kMaxLanes = 8 }; static const int kTaps[] = { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 }; enum { kNTaps = 12 }; -/* The rebalance a request may ask for (`rebalance`, RAD_GEN_COND_REBALANCE): every tap times a fixed - * gain before the text fusion, ComfyUI's ConditioningKrea2Rebalance (nova452) at its defaults -- - * multiplier 4 times the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1. */ -static const double kRebalance[] = { 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 }; +/* The rebalance presets a request may ask for (`rebalance`, RAD_GEN_COND_REBALANCE with the row in + * RAD_GEN_COND_REBALANCE_PRESET): every tap times a fixed gain before the text fusion. + * legacy ComfyUI's ConditioningKrea2Rebalance (nova452) at its defaults -- multiplier 4 times + * the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1, about 9x the taps' RMS. + * balanced, detail, subtle + * comfyui-krea2-conditioning's presets (huwhitememes) with renormalize on, multiplier 1: + * the weights times s = sqrt(sum m_t / sum w_t^2 m_t), m_t the mean square of tap t over + * the prompt's rows. The node measures s per prompt; here it is a constant, m_t averaged + * over twenty prompts through krea/Krea-2-Turbo's text encoder + * (scripts/krea2_rebalance_calib.py), and per prompt s stayed within 1.7 % of it. + * A preset row the plugin does not know scales nothing: the plain model. */ +enum { kNPresets = 4 }; +static const double kRebalance[kNPresets][kNTaps] = { + { 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 }, + /* balanced: 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1 at s 0.44109 */ + { 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 1.1027, 2.2055, 0.4852, + 1.7644, 0.44109 }, + /* detail: 0.8, 0.8, 0.9, 0.9, 1, 1, 1.2, 3, 6, 1.5, 5, 1.2 at s 0.35702 */ + { 0.28562, 0.28562, 0.32132, 0.32132, 0.35702, 0.35702, 0.42842, 1.0711, 2.1421, 0.53553, + 1.7851, 0.42842 }, + /* subtle: 1, 1, 1, 1, 1, 1, 1, 1.5, 2, 1, 1.5, 1 at s 0.84759 */ + { 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 1.2714, 1.6952, 0.84759, + 1.2714, 0.84759 }, +}; static const char* kSysPrompt = "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial " @@ -90,7 +110,7 @@ struct TeLayer { GateQuantFP8 gq{}; rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0; - rad_op op_gain = 0; /* the tap's rebalance gain into te.h2 */ + rad_op op_gain[kNPresets] = {}; /* the tap's rebalance gain into te.h2, a preset each */ rad_op op_tap_g = 0; /* the scatter from te.h2, when rebalanced */ int tap = -1; /* this layer's output is tap `tap`, or none */ }; @@ -138,7 +158,7 @@ struct Model { ActFP8 a_th{}, a_tattn{}, a_tffn{}; std::vector te; rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */ - std::string tap_mul[kNTaps]; /* chan_affine's `mul` for each tap's rebalance gain */ + std::string tap_mul[kNPresets][kNTaps]; /* chan_affine's `mul` for each preset's tap gain */ std::string tap_add; /* chan_affine's `add`: zeros */ /* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks @@ -390,15 +410,17 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { (int)kGainCh); return RAD_E_UNSUPPORTED; } - for (int t = 0; t < kNTaps; ++t) { - char v[32]; - std::snprintf(v, sizeof v, "%.9g", kRebalance[t]); - m.tap_mul[t].clear(); - for (int k = 0; k < kGainCh; ++k) { - if (k) m.tap_mul[t] += ' '; - m.tap_mul[t] += v; + for (int p = 0; p < kNPresets; ++p) + for (int t = 0; t < kNTaps; ++t) { + char v[32]; + std::snprintf(v, sizeof v, "%.9g", kRebalance[p][t]); + std::string& s = m.tap_mul[p][t]; + s.clear(); + for (int k = 0; k < kGainCh; ++k) { + if (k) s += ' '; + s += v; + } } - } m.tap_add.clear(); for (int k = 0; k < kGainCh; ++k) m.tap_add += k ? " 0" : "0"; @@ -482,14 +504,18 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { L.op_add2 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); if (L.tap >= 0) { /* f32 arithmetic, rounded once into bf16 (`round` 0) */ - L.op_gain = rw(b, RAD_OP(b, "chan_affine", - RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", kGainCh), - RAD_STR("mul", m.tap_mul[L.tap].c_str()), - RAD_STR("add", m.tap_add.c_str()), - RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"), - RAD_INT("round", 0)), - RAD_NOWEIGHTS), - { m.b_tx }, { m.b_th2 }); + for (int p = 0; p < kNPresets; ++p) { + L.op_gain[p] = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), + RAD_INT("n", kGainCh), + RAD_STR("mul", m.tap_mul[p][L.tap].c_str()), + RAD_STR("add", m.tap_add.c_str()), + RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"), + RAD_INT("round", 0)), + RAD_NOWEIGHTS), + { m.b_tx }, { m.b_th2 }); + if (!L.op_gain[p]) return RAD_E_INVAL; + } L.op_tap_g = rw(b, RAD_OP(b, "scatter_rows", RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", g.n_embd), RAD_STR("dtype", "bf16")), @@ -503,7 +529,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_NOWEIGHTS), { m.b_tx, m.b_tidx, m.b_taps }, { m.b_taps }); if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2 || - (L.tap >= 0 && (!L.op_tap || !L.op_gain || !L.op_tap_g))) + (L.tap >= 0 && (!L.op_tap || !L.op_tap_g))) return RAD_E_INVAL; } return m.op_embed && m.op_iota ? RAD_OK : RAD_E_INVAL; @@ -1186,7 +1212,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.cond_rows = kCondRows; d.rope_hw_scale = 1.0; d.rope_text_l = 0; - d.cond_opts = RAD_GEN_COND_REBALANCE; + d.cond_opts = RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET; RAD_ARCH_TRY(rad_declare_generator(b, &d)); } rad_note(b, "rank %d/%d: Krea 2%s -- text encoder %d of %lld layers, text fusion %zu + %zu " @@ -1205,7 +1231,9 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { const Geom& g = m.gt; const int64_t T = batch->n_tok; const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); - const bool rebalance = batch->gen_b && (batch->gen_b->cond_opts & RAD_GEN_COND_REBALANCE); + const int32_t opts = batch->gen_b ? batch->gen_b->cond_opts : 0; + const int preset = (opts & RAD_GEN_COND_REBALANCE_PRESET) >> RAD_GEN_COND_REBALANCE_PRESET_SHIFT; + const bool rebalance = (opts & RAD_GEN_COND_REBALANCE) && preset < kNPresets; RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_tx, T)); RAD_ISSUE_N(c, m.op_iota, T, brows(m.b_tidx, T)); @@ -1230,7 +1258,7 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); if (L.tap >= 0 && rebalance) - RAD_ISSUE_N(c, L.op_gain, T, brows(m.b_tx, T), brows(m.b_th2, T)); + RAD_ISSUE_N(c, L.op_gain[preset], T, brows(m.b_tx, T), brows(m.b_th2, T)); if (L.tap >= 0) RAD_ISSUE_N(c, rebalance ? L.op_tap_g : L.op_tap, T, brows(rebalance ? m.b_th2 : m.b_tx, T), brows(m.b_tidx, T), diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index 5206421c..fd86ce5c 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -119,10 +119,11 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector& kv_ = kv; ranks_ = ranks; table_ = DiscreteTable{}; - if (decl_.cond_opts & ~(uint32_t)RAD_GEN_COND_REBALANCE) { + if (decl_.cond_opts & ~(uint32_t)(RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET)) { RAD_ERR("image generator: '%s' declares conditioning options 0x%x, and this engine knows " - "only RAD_GEN_COND_REBALANCE (0x%x)", decl_.name ? decl_.name : "", - (unsigned)decl_.cond_opts, (unsigned)RAD_GEN_COND_REBALANCE); + "only RAD_GEN_COND_REBALANCE (0x%x) and its preset (0x%x)", + decl_.name ? decl_.name : "", (unsigned)decl_.cond_opts, (unsigned)RAD_GEN_COND_REBALANCE, + (unsigned)RAD_GEN_COND_REBALANCE_PRESET); return RAD_E_UNSUPPORTED; } if (discrete()) { diff --git a/core/server/images.cpp b/core/server/images.cpp index d830f70e..30071a8c 100644 --- a/core/server/images.cpp +++ b/core/server/images.cpp @@ -65,7 +65,7 @@ struct ImgReq { std::string background = "auto", format = "png", quality = "auto"; int32_t compression = -1; bool stream = false; - bool rebalance = false; + int32_t rebalance = 0; /* RadGenBatch::cond_opts: RAD_GEN_COND_REBALANCE and its preset */ std::vector images; bool has_mask = false; mm::FrameRGBA mask; @@ -397,15 +397,33 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { r.seed = (uint64_t)body["seed"].get(); r.seed_given = body["seed"].is_number_unsigned() || body["seed"].get() != -1; } - /* The conditioning at the plugin's fixed rebalance gains (Krea 2: its text taps at - * ConditioningKrea2Rebalance's defaults). `false` is accepted everywhere. */ + /* The conditioning at the plugin's fixed rebalance gains (Krea 2: its text taps). true or + * "legacy" ConditioningKrea2Rebalance's defaults; "balanced", "detail", "subtle" the + * comfyui-krea2-conditioning presets at the taps' RMS, on a model that declares presets + * (RAD_GEN_COND_REBALANCE_PRESET). `false` is accepted everywhere. */ if (body.contains("rebalance") && !body["rebalance"].is_null()) { - if (!body["rebalance"].is_boolean()) - return error_response(err_bad("rebalance", "expected true or false"), req.peer); - r.rebalance = body["rebalance"].get(); + const json& rb = body["rebalance"]; + static const char* const kPresets[] = { "legacy", "balanced", "detail", "subtle" }; + bool ok = rb.is_boolean(); + if (ok) r.rebalance = rb.get() ? RAD_GEN_COND_REBALANCE : 0; + else if (rb.is_string()) + for (int i = 0; i < 4; ++i) + if (rb.get() == kPresets[i]) { + r.rebalance = RAD_GEN_COND_REBALANCE | (i << RAD_GEN_COND_REBALANCE_PRESET_SHIFT); + ok = true; + } + if (!ok) + return error_response(err_bad("rebalance", "expected true, false, \"legacy\", " + "\"balanced\", \"detail\" or \"subtle\""), + req.peer); if (r.rebalance && !(info.cond_opts & RAD_GEN_COND_REBALANCE)) return error_response(err_unsupported("rebalance", "this model has no rebalance"), req.peer); + if ((r.rebalance & RAD_GEN_COND_REBALANCE_PRESET) && + !(info.cond_opts & RAD_GEN_COND_REBALANCE_PRESET)) + return error_response(err_unsupported("rebalance", "this model's rebalance has no " + "presets; use true"), + req.peer); } if (str("negative_prompt", &r.negative) < 0) return error_response(err_bad("negative_prompt", "expected a string"), req.peer); @@ -539,7 +557,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { g->scheduler = r.scheduler; g->seed = r.seed; g->previews = r.previews; - g->cond_opts = r.rebalance ? RAD_GEN_COND_REBALANCE : 0; + g->cond_opts = r.rebalance; /* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is * that at s + 1. */ g->cfg = (float)(info.cfg_original ? r.cfg + 1.0 : r.cfg); diff --git a/docs/GUIDE.md b/docs/GUIDE.md index b536efbc..c60e384e 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2255,7 +2255,7 @@ more field: | field | | |---|---| -| `rebalance` | `true` multiplies the twelve text taps by fixed gains before the text fusion, as ComfyUI's ConditioningKrea2Rebalance at its defaults (multiplier 4 times 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1); it applies to the negative prompt's conditioning too. `false` (the default) is the plain model. A boolean, or `true`/`false`/`1`/`0` in a form; a model without it refuses `true` with a 400 | +| `rebalance` | `true` (or `"legacy"`) multiplies the twelve text taps by fixed gains before the text fusion, as ComfyUI's ConditioningKrea2Rebalance at its defaults (multiplier 4 times 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1), about nine times the taps' RMS; it applies to the negative prompt's conditioning too. `"balanced"`, `"detail"` and `"subtle"` are comfyui-krea2-conditioning's presets (renormalize on, multiplier 1): their per-layer weights times a constant that keeps the taps' RMS, measured over twenty prompts through Krea 2 Turbo's text encoder (`scripts/krea2_rebalance_calib.py`; the node's per-prompt factor stayed within 1.7 % of it), so they shift the balance between layers without the default's overall gain. `false` (the default) is the plain model. A boolean or a preset's name, also in a form (`true`/`false`/`1`/`0` or the name); a model without it refuses anything but `false` with a 400 | **Anima** makes RGB pictures, 1024x1024 by default, sides rounded down to multiples of 16, up to 1536x1536 (9216 latent tokens; the card's range is 512x512 to 1536x1536). Base and Aesthetic run 30 diff --git a/scripts/README.md b/scripts/README.md index 1c098ec4..9b8c6105 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -24,6 +24,7 @@ and `agentreplay.py` need `python3`. Scripts find each other through `$(dirname | `convfn.sh` | Rebuilds the container `fnserve.sh` serves, as `w4nl64-i8lm.new.rad` beside it, from `data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`. Needs `CALIB=`: the recipe's expert rule runs GPTQ against the calibration Grams there (`docs/MOE-W4.md`). | | `hfget.sh` | Fetches a Hugging Face repo with `curl` and `jq`. Resumable, and skips the duplicate weight formats a repo often carries beside its safetensors. `radiance --model ` runs it. | | `krea2_native.py` | Rewrites a Krea 2 DiT single file in Krea's own key names (`turbo.safetensors`, civitai and ComfyUI finetunes) as diffusers' transformer file, bytes unchanged, so it converts as the `transformer/` of a Krea 2 pipeline directory (`docs/GUIDE.md`). | +| `krea2_rebalance_calib.py` | Measures the constant of each Krea 2 rebalance preset (`rebalance`: balanced, detail, subtle): the taps' mean squares over twenty prompts through a pipeline's text encoder, and the renormalising factor arch/krea2 holds for them (`docs/GUIDE.md`). Needs torch and transformers. | ## Measuring diff --git a/scripts/krea2_rebalance_calib.py b/scripts/krea2_rebalance_calib.py new file mode 100755 index 00000000..27b9455b --- /dev/null +++ b/scripts/krea2_rebalance_calib.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +# krea2_rebalance_calib.py -- the constants of arch/krea2's rebalance presets (`rebalance`: +# "balanced", "detail", "subtle"): each preset's per-layer weights times s, the factor +# comfyui-krea2-conditioning's renormalize applies at multiplier 1. +# +# krea2_rebalance_calib.py [out.json] +# +# The node scales tap t by w_t and renormalises so the taps keep their total energy: +# s = sqrt(sum_t m_t / sum_t w_t^2 m_t), m_t the mean square of tap t over the prompt's rows. The +# plugin cannot measure m_t per request without a reduction across the encoder's rows, so it takes +# s as a constant: m_t averaged over the twenty prompts below, each run through the release's text +# encoder in arch/krea2's template with its system prefix dropped, as the plugin keeps the rows. +# The script prints, per preset, that s, the per-prompt range of s, and the twelve gains, and for +# the default gains (`rebalance: true`) their factor on the taps' RMS. +# +# Measured on krea/Krea-2-Turbo's text_encoder (bf16, CPU, about a minute): balanced 0.44109 +# (per prompt 0.43449 to 0.44879), detail 0.35702, subtle 0.84759; the default gains are 9.07x the +# taps' RMS. Needs torch and transformers. +import json +import sys + +import torch +from transformers import AutoModel, AutoTokenizer + +# Tap t is the hidden state after layer TAPS[t] - 1 (hidden_states[TAPS[t]]), arch/krea2's kTaps. +TAPS = [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35] +SYS = ("Describe the image by detailing the color, shape, size, texture, quantity, text, spatial " + "relationships of the objects and background:") +DROP = f"<|im_start|>system\n{SYS}<|im_end|>\n<|im_start|>user\n" +PRESETS = { + "balanced": [1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1], + "detail": [0.8, 0.8, 0.9, 0.9, 1, 1, 1.2, 3, 6, 1.5, 5, 1.2], + "subtle": [1, 1, 1, 1, 1, 1, 1, 1.5, 2, 1, 1.5, 1], +} +# ConditioningKrea2Rebalance's defaults: multiplier 4 times these, no renormalisation. +DEFAULT = [4 * w for w in PRESETS["balanced"]] +PROMPTS = [ + "a cat", + "portrait of an old fisherman with a weathered face, grey beard, wool cap, soft window light", + "a young woman with freckles and red hair laughing in a sunflower field, golden hour, 35mm photo", + "close-up of a man's face, sharp focus on the eyes, studio lighting, black background", + "a mountain lake at dawn with mist over the water and pine trees on the shore", + "a busy street market in Marrakech, colorful spices, people in motion, afternoon sun", + "a neon sign that reads \"OPEN 24 HOURS\" above the door of a small diner at night, rain on the street", + "a hand-written note on yellow paper saying 'Buy milk, call mom, feed the dog'", + "an astronaut riding a horse on the moon, earth in the sky, cinematic", + "three red apples and two green pears on a wooden table, top-down view", + "a cozy living room with a fireplace, a grey sofa, a knitted blanket and a sleeping dog", + "architectural photo of a brutalist concrete building against a blue sky, wide angle", + "a watercolor painting of a lighthouse on a cliff during a storm", + "anime style illustration of a girl with a sword standing on a rooftop at sunset", + "macro photo of a dewdrop on a spider web, bokeh background", + "a group of five friends sitting around a campfire at night, smiling, warm light on their faces", + "a vintage red car parked in front of a gas station in the desert, 1960s, film grain", + "a bowl of ramen with a soft-boiled egg, chopsticks resting on the side, steam rising", + "an elderly woman knitting in a rocking chair next to a window, her cat on her lap, overcast daylight, " + "muted colors, documentary photography, shallow depth of field, the room is full of old books and plants", + "a futuristic city skyline with flying cars, holographic billboards in Japanese and English, dusk", +] + + +def main(): + if len(sys.argv) not in (2, 3): + sys.exit(__doc__ or "usage: krea2_rebalance_calib.py [out.json]") + pipe = sys.argv[1] + tok = AutoTokenizer.from_pretrained(f"{pipe}/tokenizer") + model = AutoModel.from_pretrained(f"{pipe}/text_encoder", dtype=torch.bfloat16).eval() + lm = getattr(model, "language_model", model) + n_drop = len(tok(DROP, add_special_tokens=False).input_ids) + rows = [] + with torch.no_grad(): + for p in PROMPTS: + text = DROP + p + "<|im_end|>\n<|im_start|>assistant\n" + ids = tok(text, add_special_tokens=False, return_tensors="pt").input_ids + hs = lm(input_ids=ids, output_hidden_states=True).hidden_states + rows.append([hs[i][0, n_drop:].float().pow(2).mean().item() for i in TAPS]) + M = torch.tensor(rows, dtype=torch.float64) # (prompts, taps) + m = M.mean(0) + out = {"taps": TAPS, "m_mean": m.tolist(), "presets": {}} + for name, w in PRESETS.items(): + w2 = torch.tensor(w, dtype=torch.float64) ** 2 + per = (M.sum(1) / (M * w2).sum(1)).sqrt() + s = float((m.sum() / (m * w2).sum()).sqrt()) + out["presets"][name] = {"s": s, "s_min": float(per.min()), "s_max": float(per.max()), + "gains": [x * s for x in w]} + d2 = torch.tensor(DEFAULT, dtype=torch.float64) ** 2 + out["default_rms_gain"] = float(((m * d2).sum() / m.sum()).sqrt()) + for name, p in out["presets"].items(): + print(f"{name:9s} s {p['s']:.5f} ({p['s_min']:.5f} to {p['s_max']:.5f}) gains " + + ", ".join(f"{g:.5g}" for g in p["gains"])) + print(f"default gains: {out['default_rms_gain']:.2f}x the taps' RMS") + if len(sys.argv) == 3: + with open(sys.argv[2], "w") as f: + json.dump(out, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 1d87c15b..9985a922 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -9751,13 +9751,24 @@ MetaKV krea2_meta() { } /* namespace */ -/* `rebalance` (RAD_GEN_COND_REBALANCE, declared in the generator's cond_opts): each of the twelve - * taps is scaled into te.h2 by its gain (ComfyUI's ConditioningKrea2Rebalance at its defaults, - * multiplier 4 times 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1), f32 and rounded once, and the - * tap's scatter reads te.h2. Without it the pass issues no scale and scatters te.x. */ +/* `rebalance` (RAD_GEN_COND_REBALANCE, declared in the generator's cond_opts with its presets): + * each of the twelve taps is scaled into te.h2 by its preset's gain (row 0 ComfyUI's + * ConditioningKrea2Rebalance at its defaults, multiplier 4 times 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, + * 4, 1; rows 1 to 3 balanced, detail, subtle), f32 and rounded once, and the tap's scatter reads + * te.h2. Without it, or with a preset row the plugin does not know, the pass issues no scale and + * scatters te.x. */ TEST(krea2_rebalance_scales_each_tap_and_is_off_without_the_option) { MetaKV mk = krea2_meta(); - const double gains[12] = { 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 }; + /* RAD_GEN_COND_REBALANCE_PRESET rows 0 (the default), 1 balanced, 2 detail, 3 subtle */ + const double gains[4][12] = { + { 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 }, + { 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 1.1027, 2.2055, 0.4852, + 1.7644, 0.44109 }, + { 0.28562, 0.28562, 0.32132, 0.32132, 0.35702, 0.35702, 0.42842, 1.0711, 2.1421, 0.53553, + 1.7851, 0.42842 }, + { 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 1.2714, 1.6952, 0.84759, + 1.2714, 0.84759 }, + }; RadArchProbe probe{}; REQUIRE_EQ(krea2::probe(mk.meta(), &probe), RAD_OK); CHECK_EQ(probe.gen_rows, (int64_t)2 * (16384 + 512)); @@ -9766,7 +9777,8 @@ TEST(krea2_rebalance_scales_each_tap_and_is_off_without_the_option) { RadBuilder b; RadBuildCtx ctx = qimg_ctx(rank, world); REQUIRE_EQ(stderr_of_rc([&] { return krea2::declare(&b, mk.meta(), &ctx); }), RAD_OK); - CHECK_EQ(b.generator.cond_opts, (uint32_t)RAD_GEN_COND_REBALANCE); + CHECK_EQ(b.generator.cond_opts, + (uint32_t)(RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET)); const RecBuf* bx = find_b(b, "te.x"); const RecBuf* bh = find_b(b, "te.h2"); const RecBuf* bt = find_b(b, "te.taps"); @@ -9774,9 +9786,13 @@ TEST(krea2_rebalance_scales_each_tap_and_is_off_without_the_option) { const rad_buf x = (rad_buf)(bx - b.bufs.data() + 1); const rad_buf h2 = (rad_buf)(bh - b.bufs.data() + 1); const rad_buf taps = (rad_buf)(bt - b.bufs.data() + 1); - for (bool rebalance : { false, true }) { + /* -1: no option; 0 to 3 the presets; 4 a row the plugin does not know */ + for (int preset : { -1, 0, 1, 2, 3, 4 }) { + const bool rebalance = preset >= 0 && preset < 4; auto k = gen_pass(b, RAD_GEN_PASS_COND, 12); - k->g.cond_opts = rebalance ? RAD_GEN_COND_REBALANCE : 0; + k->g.cond_opts = preset >= 0 ? RAD_GEN_COND_REBALANCE | + (preset << RAD_GEN_COND_REBALANCE_PRESET_SHIFT) + : 0; RadCtx c{ .b = &b, .batch = &k->b, .rank = rank, .world = world }; krea2::step(&c, &k->b); CHECK(c.step_fail.empty()); @@ -9809,7 +9825,7 @@ TEST(krea2_rebalance_scales_each_tap_and_is_off_without_the_option) { const std::vector mul = list(pstr(g, "mul")), add = list(pstr(g, "add")); CHECK_EQ(mul.size(), (size_t)64); CHECK_EQ(add.size(), (size_t)64); - for (double v : mul) CHECK_EQ(v, gains[tap]); + for (double v : mul) CHECK_EQ(v, gains[preset][tap]); for (double v : add) CHECK_EQ(v, 0.0); } ++tap; diff --git a/tests/images_test.cpp b/tests/images_test.cpp index b0c86384..4210cadb 100644 --- a/tests/images_test.cpp +++ b/tests/images_test.cpp @@ -277,6 +277,44 @@ TEST(rebalance_reaches_a_model_that_declares_it_and_is_refused_by_one_that_does_ CHECK_EQ(s.f->srv->router().dispatch(q).status, 400); } +/* `rebalance` also names a preset: "legacy" is `true`, "balanced", "detail" and "subtle" set + * RAD_GEN_COND_REBALANCE with the preset's row in RAD_GEN_COND_REBALANCE_PRESET, in JSON and in a + * form. A model whose rebalance declares no presets takes `true` and "legacy" and refuses the + * others with a 400 naming the field; an unknown name is a 400 everywhere. */ +TEST(rebalance_presets_reach_a_model_that_declares_them) { + Images s; + const int32_t R = RAD_GEN_COND_REBALANCE, sh = RAD_GEN_COND_REBALANCE_PRESET_SHIFT; + s.img.inf.cond_opts = RAD_GEN_COND_REBALANCE; + s.gen({ { "prompt", "x" }, { "rebalance", "legacy" } }); + CHECK_EQ(s.last().cond_opts, R); + for (const char* p : { "balanced", "detail", "subtle" }) { + const json e = s.gen({ { "prompt", "x" }, { "rebalance", p } }, 400); + CHECK_EQ(str_at(e["error"], "param"), std::string("rebalance")); + } + s.img.inf.cond_opts = RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET; + const struct { const char* name; int32_t opts; } kWant[] = { + { "legacy", R }, { "balanced", R | 1 << sh }, { "detail", R | 2 << sh }, { "subtle", R | 3 << sh }, + }; + for (const auto& w : kWant) { + s.gen({ { "prompt", "x" }, { "rebalance", w.name } }); + CHECK_EQ(s.last().cond_opts, w.opts); + } + s.gen({ { "prompt", "x" }, { "rebalance", true } }); + CHECK_EQ(s.last().cond_opts, R); + for (const json& bad : { json("Balanced"), json("strong"), json("") }) { + const json e = s.gen({ { "prompt", "x" }, { "rebalance", bad } }, 400); + CHECK_EQ(str_at(e["error"], "param"), std::string("rebalance")); + } + HttpRequest q; + q.method = "POST"; + q.path = "/v1/images/generations"; + q.form = { FormPart{ "prompt", "", "", "a cat" }, FormPart{ "rebalance", "", "", "detail" } }; + CHECK_EQ(s.f->srv->router().dispatch(q).status, 200); + CHECK_EQ(s.last().cond_opts, R | 2 << sh); + q.form[1].data = "nope"; + CHECK_EQ(s.f->srv->router().dispatch(q).status, 400); +} + /* `background: auto` keeps an edited picture's transparency and is opaque otherwise; a mask must * be the first picture's size. */ /* A model whose card states guidance as cond + s (cond - uncond) and guides by default (Krea 2):