diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 6fde1f91..c567a630 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -378,8 +378,16 @@ typedef struct RadGenBatch { /* COND: the pass's token ids on the host ([n_tok]), for a plugin whose issue depends on * where a window's end-of-text marker sits. */ const int32_t* tokens_h; + /* ---- appended in ABI 26 (Krea 2's rebalance) */ + /* COND: the request's RAD_GEN_COND_* options, 0 for none. */ + int32_t cond_opts; } RadGenBatch; +/* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */ +enum { + RAD_GEN_COND_REBALANCE = 1 /* Krea 2: the text taps at the plugin's fixed rebalance gains */ +}; + /* An entry's flags on a DENOISE pass. */ enum { RAD_GEN_F_FIRST = 1, /* the image's first step: its latent is the noise its seed draws */ diff --git a/arch/krea2/krea2.cpp b/arch/krea2/krea2.cpp index 99300df0..e143ca61 100644 --- a/arch/krea2/krea2.cpp +++ b/arch/krea2/krea2.cpp @@ -73,6 +73,11 @@ 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 }; + static const char* kSysPrompt = "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial " "relationships of the objects and background:"; @@ -85,6 +90,8 @@ 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_tap_g = 0; /* the scatter from te.h2, when rebalanced */ int tap = -1; /* this layer's output is tap `tap`, or none */ }; @@ -131,6 +138,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 */ /* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks * over the mixed rows `b_ft` */ @@ -371,6 +379,24 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { else std::snprintf(sections, sizeof sections, "24 20 20"); + /* The rebalance gains, as chan_affine lists: the tap's row seen as rows of 64 channels. The + * scaled copy goes through te.h2, free between a layer's add and the next layer's projections, + * so the residual stream itself is never scaled. */ + enum { kGainCh = 64 }; + if (g.n_embd % kGainCh) return RAD_E_INVAL; + 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; + } + } + static std::string zeros64; + if (zeros64.empty()) + for (int k = 0; k < kGainCh; ++k) zeros64 += k ? " 0" : "0"; + /* Layers up to the last tap only. */ const int n_run = kTaps[kNTaps - 1]; if (g.n_layer < n_run) { @@ -449,6 +475,22 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { T)); L.op_ar2 = all_reduce(b, g, m.b_th2, T); 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", zeros64.c_str()), + RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"), + RAD_INT("round", 0)), + RAD_NOWEIGHTS), + { m.b_tx }, { m.b_th2 }); + 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")), + RAD_NOWEIGHTS), + { m.b_th2, m.b_tidx, m.b_taps }, { m.b_taps }); + } if (L.tap >= 0) L.op_tap = rw(b, RAD_OP(b, "scatter_rows", RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", g.n_embd), @@ -456,7 +498,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.tap >= 0 && (!L.op_tap || !L.op_gain || !L.op_tap_g))) return RAD_E_INVAL; } return m.op_embed && m.op_iota ? RAD_OK : RAD_E_INVAL; @@ -1157,6 +1199,7 @@ 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); 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)); @@ -1180,8 +1223,11 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { L.down.step(c, m.a_tffn, m.b_th2, T); 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)); if (L.tap >= 0) - RAD_ISSUE_N(c, L.op_tap, T, brows(m.b_tx, T), brows(m.b_tidx, T), + 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), brow_slice(m.b_taps, L.tap, (int64_t)kTeRows * kNTaps - L.tap, g.n_embd)); } diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index 001883cf..20b5d6e6 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -816,6 +816,7 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { G.aux_cu = n_aux ? dptr(ri, R_AUX) : nullptr; G.aux_ids = n_aux ? dptr(ri, R_AUX) + 2 : nullptr; G.tokens_h = hptr(R_TOK); + G.cond_opts = j.req->cond_opts; if (joint()) { B.n_kv_groups = 0; B.kv = nullptr; diff --git a/core/gen/gen.h b/core/gen/gen.h index 597f9361..cd23d240 100644 --- a/core/gen/gen.h +++ b/core/gen/gen.h @@ -118,6 +118,8 @@ struct Request { * for none, and the hold that keeps the slot's adapters in it until the request is done. */ int32_t lora_slot = -1; std::shared_ptr lora_hold; + /* RAD_GEN_COND_* for the plugin's COND passes (`rebalance`: Krea 2's tap gains). */ + int32_t cond_opts = 0; std::shared_ptr ticket; }; diff --git a/core/server/images.cpp b/core/server/images.cpp index 15b44357..95725f77 100644 --- a/core/server/images.cpp +++ b/core/server/images.cpp @@ -65,6 +65,7 @@ struct ImgReq { std::string background = "auto", format = "png", quality = "auto"; int32_t compression = -1; bool stream = false; + bool rebalance = false; std::vector images; bool has_mask = false; mm::FrameRGBA mask; @@ -87,7 +88,7 @@ json form_value(const std::string& key, const std::string& v) { if (e && *e == 0 && !v.empty()) return json(x); return json(v); } - if (key == "stream") { + if (key == "stream" || key == "rebalance") { if (v == "true" || v == "1") return json(true); if (v == "false" || v == "0") return json(false); } @@ -243,6 +244,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { "style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale", "guidance_scale", "num_inference_steps", "width", "height", "loras", "lora", "sampler", "scheduler", + "rebalance", }; for (auto it = body.begin(); it != body.end(); ++it) { bool known = false; @@ -395,6 +397,13 @@ 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; } + /* Krea 2's fixed tap gains (ConditioningKrea2Rebalance's defaults, arch/krea2); other models + * ignore it. */ + 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(); + } if (str("negative_prompt", &r.negative) < 0) return error_response(err_bad("negative_prompt", "expected a string"), req.peer); /* The scale in the model card's terms: off at 0 for a card that states it as @@ -527,6 +536,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; /* 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 ac38eeb1..00968f9a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2066,7 +2066,9 @@ under Qwen's research license, non-commercial. (`background: transparent` is a 400), 1024x1024 by default, sides rounded down to multiples of 16, up to 2048x2048 (16384 latent tokens). Krea 2 Raw runs 28 steps at guidance 4.5 against an empty negative prompt and Turbo 8 steps unguided; Krea 2 reads only text, so `/v1/images/edits` answers -501. FLUX.3 [klein] runs 16 steps unguided and its base 50 at guidance 3.5; both edit from up to ten +501. `rebalance: true` multiplies Krea 2's twelve text taps by +fixed gains before the text fusion, as ComfyUI's ConditioningKrea2Rebalance at its defaults +(4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4); other models ignore the field. FLUX.3 [klein] runs 16 steps unguided and its base 50 at guidance 3.5; both edit from up to ten pictures, each shrunk to 1024x1024 of area when larger. The guidance scale is `guidance_scale` or `true_cfg_scale` (one of them), in the model card's terms. FLUX.3's pipeline can rewrite a prompt with a separate language model first; radiance reads the prompt as given. diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index e95bb306..11b06316 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -379,6 +379,7 @@ ABI_FIELD(RadGenBatch, step) ABI_FIELD(RadGenBatch, size_px) ABI_FIELD(RadGenBatch, entry_h) ABI_FIELD(RadGenBatch, tokens_h) +ABI_FIELD(RadGenBatch, cond_opts) ABI_STRUCT(RadGeneratorDecl) ABI_FIELD(RadGeneratorDecl, name) ABI_FIELD(RadGeneratorDecl, layout) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index dc5940cc..fe5769e5 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -321,7 +321,7 @@ { "RadFuseStep", "n_p", 584, 4 }, { "RadFuseStep", "from", 588, 32 }, { "RadFuseStep", "n_from", 620, 4 }, -{ "RadGenBatch", "", 0, 400 }, +{ "RadGenBatch", "", 0, 408 }, { "RadGenBatch", "rows", 0, 8 }, { "RadGenBatch", "src", 8, 8 }, { "RadGenBatch", "rope", 16, 8 }, @@ -375,6 +375,7 @@ { "RadGenBatch", "size_px", 376, 8 }, { "RadGenBatch", "entry_h", 384, 8 }, { "RadGenBatch", "tokens_h", 392, 8 }, +{ "RadGenBatch", "cond_opts", 400, 4 }, { "RadGeneratorDecl", "", 0, 376 }, { "RadGeneratorDecl", "name", 0, 8 }, { "RadGeneratorDecl", "layout", 8, 4 },