Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
387 lines (325 loc) · 16.7 KB
/
Copy path__init__.py
File metadata and controls
387 lines (325 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
"""ComfyUI-Krea2Edit — in-context edit forward for the Krea2 model.
ComfyUI's native Krea2 `_forward` is text-to-image only: it builds the sequence
`[text | target]`. The krea2_edit LoRA (trained in ai-toolkit) needs the *appearance
path*: the VAE-encoded SOURCE latent prepended as a block of clean tokens, distinguished
from the (noisy) target purely by the 3-axis RoPE frame index (source=1, target=0, h/w
aligned). This node adds that by wrapping the model's DIFFUSION_MODEL forward and rebuilding
the sequence as `[text | source(frame=1) | target(frame=0)]`, keeping only the target tokens
out — mirroring ai-toolkit's `predict_velocity_edit` exactly, using the model's own submodules.
Wiring: LoadImage -> VAEEncode(source) --\
Krea2EditModelPatch(model, source_latent) -> KSampler
UNETLoader -> LoraLoaderModelOnly -/
KSampler.latent_image <- EmptySD3LatentImage (noise). Text: NATIVE krea2 CLIP + CLIPTextEncode.
"""
import math
import torch
import torch.nn.functional as F
from einops import rearrange
import comfy.patcher_extension
import comfy.utils
import comfy.ldm.common_dit
from comfy.ldm.flux.layers import timestep_embedding
from comfy.ldm.flux.math import apply_rope
from comfy.ldm.modules.attention import optimized_attention_masked
def _imgids(bs, frame, h_, w_, device):
ids = torch.zeros(h_, w_, 3, device=device, dtype=torch.float32)
ids[..., 0] = frame
ids[..., 1] = torch.arange(h_, device=device, dtype=torch.float32)[:, None]
ids[..., 2] = torch.arange(w_, device=device, dtype=torch.float32)[None, :]
return ids.reshape(1, h_ * w_, 3).repeat(bs, 1, 1)
def _imgids_offset(bs, frame, gh, gw, th, tw, device):
off_h, off_w = max(0, (th - gh) // 2), max(0, (tw - gw) // 2)
ids = torch.zeros(gh, gw, 3, device=device, dtype=torch.float32)
ids[..., 0] = frame
ids[..., 1] = (torch.arange(gh, device=device, dtype=torch.float32) + off_h)[:, None]
ids[..., 2] = (torch.arange(gw, device=device, dtype=torch.float32) + off_w)[None, :]
return ids.reshape(1, gh * gw, 3).repeat(bs, 1, 1)
def _to_4d(v):
if v.ndim == 5:
b, c, t, h, w = v.shape
return v.reshape(b * t, c, h, w)
return v
def _fit_src(src, H, W):
sh, sw = src.shape[-2:]
if (sh, sw) == (H, W):
return src
s = max(H / sh, W / sw)
ch, cw = min(sh, int(round(H / s))), min(sw, int(round(W / s)))
y0, x0 = (sh - ch) // 2, (sw - cw) // 2
src = src[..., y0:y0 + ch, x0:x0 + cw]
return F.interpolate(src.float(), size=(H, W), mode="bilinear")
def _fit_encode_image(image, vae, H, W, cache, key, fit_mode="crop"):
key = key + (fit_mode,)
if key in cache:
return cache[key]
print(f"[krea2edit] _fit_encode_image: mode={fit_mode} in={tuple(image.shape)} target_latent={H}x{W}", flush=True)
px_h, px_w = H * 8, W * 8
img = image.movedim(-1, 1) # B,H,W,C -> B,C,H,W
ih, iw = img.shape[-2:]
if fit_mode == "fit":
sc = min(px_h / ih, px_w / iw)
CROP_TOL = 0.08
if ih * sc >= px_h * (1 - CROP_TOL) and iw * sc >= px_w * (1 - CROP_TOL):
s = max(px_h / ih, px_w / iw)
ch, cw = min(ih, int(round(px_h / s))), min(iw, int(round(px_w / s)))
y0, x0 = (ih - ch) // 2, (iw - cw) // 2
img = img[..., y0:y0 + ch, x0:x0 + cw]
nh, nw = px_h, px_w
else:
nh = min(max(16, int(ih * sc) // 16 * 16), max(16, px_h // 16 * 16))
nw = min(max(16, int(iw * sc) // 16 * 16), max(16, px_w // 16 * 16))
img = F.interpolate(img.float(), size=(nh, nw), mode="bicubic", antialias=True)
lat = vae.encode(img.movedim(1, -1)[..., :3].clamp(0, 1))
cache[key] = lat
return lat
s = max(px_h / ih, px_w / iw)
ch, cw = min(ih, int(round(px_h / s))), min(iw, int(round(px_w / s)))
y0, x0 = (ih - ch) // 2, (iw - cw) // 2
img = img[..., y0:y0 + ch, x0:x0 + cw]
img = F.interpolate(img.float(), size=(px_h, px_w), mode="bicubic", antialias=True)
lat = vae.encode(img.movedim(1, -1)[..., :3].clamp(0, 1))
cache[key] = lat
return lat
def _ref_attn_bias(boosts, boost_mask, txtlen, slens, tgtlen, mask_hw, device, dtype):
nsrc = len(slens)
offs = [txtlen]
for sl in slens:
offs.append(offs[-1] + sl)
rows0 = offs[-1]
L = rows0 + tgtlen
bias = torch.zeros(1, 1, L, L, device=device, dtype=dtype)
for i, b in enumerate(boosts):
if i >= nsrc:
break
# Защита от NaN или кривых значений
if b is None or math.isnan(b) or b == 1.0:
continue
off, sl = offs[i], slens[i]
if boost_mask is not None and i == nsrc - 1 and mask_hw is not None:
mask = boost_mask[:1]
if mask.ndim == 2:
mask = mask[None]
mask = F.interpolate(mask[None].float(), size=mask_hw[i], mode="area")[0, 0]
cols = off + torch.nonzero(mask.reshape(-1) > 0.5, as_tuple=True)[0].to(device)
else:
cols = torch.arange(off, off + sl, device=device)
bias[:, :, rows0:, cols] = math.log(max(b, 1e-4))
return bias
def krea2_edit_forward(m, x, timesteps, context, src_latent, transformer_options,
ref_boosts=[1.0], ref_boost_mask=None,
ref_native=False, pos_mode="anchor"):
patch = m.patch
temporal = x.ndim == 5
if temporal:
b5, c5, t5, h5, w5 = x.shape
x = _to_4d(x)
bs, c, H_orig, W_orig = x.shape
x = comfy.ldm.common_dit.pad_to_patch_size(x, (patch, patch), padding_mode="replicate")
H, W = x.shape[-2], x.shape[-1]
h_, w_ = H // patch, W // patch
src_list = src_latent if isinstance(src_latent, (list, tuple)) else [src_latent]
srcs = []
for sl in src_list:
src = _to_4d(sl).to(x.device, x.dtype)
if src.shape[0] != bs:
src = src[:1].expand(bs, *src.shape[1:])
if not ref_native and src.shape[-2:] != (H, W):
print(f"[krea2edit] LATENT-PATH fit_src (crop): src={tuple(src.shape[-2:])} -> {H}x{W}", flush=True)
src = _fit_src(src, H, W).to(x.dtype)
srcs.append(comfy.ldm.common_dit.pad_to_patch_size(src, (patch, patch), padding_mode="replicate"))
src_grids = [(s_.shape[-2] // patch, s_.shape[-1] // patch) for s_ in srcs]
context = m._unpack_context(context)
tgt_img = m.first(rearrange(x, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=patch, pw=patch))
src_imgs = [m.first(rearrange(s_, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=patch, pw=patch))
for s_ in srcs]
t = m.tmlp(timestep_embedding(timesteps, m.tdim).unsqueeze(1).to(tgt_img.dtype))
tvec = m.tproj(t)
context = m.txtfusion(context, mask=None, transformer_options=transformer_options)
context = m.txtmlp(context)
txtlen, tgtlen = context.shape[1], tgt_img.shape[1]
srclen = sum(si.shape[1] for si in src_imgs)
combined = torch.cat([context] + src_imgs + [tgt_img], dim=1)
device = combined.device
if pos_mode == "stride1" and ref_native:
print(f"[krea2edit] STRIDE1-POS fit: ref grids {src_grids} centered in ({h_},{w_})", flush=True)
ref_ids = [_imgids_offset(bs, i + 1, gh, gw, h_, w_, device)
for i, (gh, gw) in enumerate(src_grids)]
else:
ref_ids = [_imgids(bs, i + 1, gh, gw, device) for i, (gh, gw) in enumerate(src_grids)]
pos = torch.cat([
torch.zeros(bs, txtlen, 3, device=device, dtype=torch.float32)]
+ ref_ids
+ [_imgids(bs, 0, h_, w_, device)],
dim=1)
freqs = m.pe_embedder(pos)
attn_bias = None
# Проверяем валидность каждого значения в ref_boosts
clean_boosts = [1.0 if (b is None or math.isnan(b)) else b for b in ref_boosts]
if any(b != 1.0 for b in clean_boosts):
attn_bias = _ref_attn_bias(clean_boosts, ref_boost_mask, txtlen,
[si.shape[1] for si in src_imgs], tgtlen,
src_grids, combined.device, combined.dtype)
for block in m.blocks:
combined = block(combined, tvec, freqs, attn_bias, transformer_options=transformer_options)
final = m.last(combined, t)
out = final[:, txtlen + srclen: txtlen + srclen + tgtlen, :]
out = rearrange(out, "b (h w) (c ph pw) -> b c (h ph) (w pw)",
h=h_, w=w_, ph=patch, pw=patch, c=m.channels)
out = out[:, :, :H_orig, :W_orig]
if temporal:
out = out.reshape(b5, t5, m.channels, H_orig, W_orig).movedim(1, 2)
return out
class Krea2EditModelPatch:
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"model": ("MODEL",),
}, "optional": {
"source_latent": ("LATENT", {"tooltip": "1st reference (scene)"}),
"source_latent_b": ("LATENT", {"tooltip": "2nd reference (subject photo)"}),
"source_latent_c": ("LATENT", {"tooltip": "3rd reference"}),
"source_latent_d": ("LATENT", {"tooltip": "4th reference"}),
"source_latent_e": ("LATENT", {"tooltip": "5th reference"}),
"ref_boost": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1000.0, "step": 0.01, "round": 0.001, "tooltip": "Boost for 1st reference"}),
"ref_boost_b": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1000.0, "step": 0.01, "round": 0.001, "tooltip": "Boost for 2nd reference"}),
"ref_boost_c": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1000.0, "step": 0.01, "round": 0.001, "tooltip": "Boost for 3rd reference"}),
"ref_boost_d": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1000.0, "step": 0.01, "round": 0.001, "tooltip": "Boost for 4th reference"}),
"ref_boost_e": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1000.0, "step": 0.01, "round": 0.001, "tooltip": "Boost for 5th reference"}),
"fit_mode": (["fit", "crop (legacy)"], {"default": "fit"}),
"ref_boost_mask": ("MASK",),
"vae": ("VAE",),
"source_image": ("IMAGE", {"tooltip": "1st reference as IMAGE"}),
"source_image_b": ("IMAGE", {"tooltip": "2nd reference as IMAGE"}),
"source_image_c": ("IMAGE", {"tooltip": "3rd reference as IMAGE"}),
"source_image_d": ("IMAGE", {"tooltip": "4th reference as IMAGE"}),
"source_image_e": ("IMAGE", {"tooltip": "5th reference as IMAGE"}),
}}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "krea2edit"
DESCRIPTION = "Adds the krea2_edit in-context source-preservation path to a Krea2 model (supports up to 5 references)."
def patch(self, model, source_latent=None, source_latent_b=None, source_latent_c=None,
source_latent_d=None, source_latent_e=None, ref_boost=1.0, ref_boost_b=1.0,
ref_boost_c=1.0, ref_boost_d=1.0, ref_boost_e=1.0,
ref_boost_mask=None, vae=None, source_image=None, source_image_b=None,
source_image_c=None, source_image_d=None, source_image_e=None,
fit_mode="fit", **_future):
m = model.clone()
mm = model.model
lats_raw = [source_latent, source_latent_b, source_latent_c, source_latent_d, source_latent_e]
lats_raw = [l for l in lats_raw if l is not None]
src_samples = []
for l in lats_raw:
src_samples.append(mm.process_latent_in(l["samples"]))
if len(src_samples) == 1:
src_samples = src_samples[0]
imgs_raw = [source_image, source_image_b, source_image_c, source_image_d, source_image_e]
imgs_raw = [i for i in imgs_raw if i is not None]
# Безопасная фильтрация и присвоение бустов
def _clean_val(v):
return 1.0 if (v is None or math.isnan(v)) else v
ref_boosts = [
_clean_val(ref_boost),
_clean_val(ref_boost_b),
_clean_val(ref_boost_c),
_clean_val(ref_boost_d),
_clean_val(ref_boost_e),
]
px_cache = {}
def wrapper(executor, x, timesteps, context, *wargs, **kwargs):
transformer_options = kwargs.pop("transformer_options", None)
if transformer_options is None:
transformer_options = {}
for a in reversed(wargs):
if isinstance(a, dict):
transformer_options = a
break
dm = executor.class_obj
src = src_samples
if vae is not None and len(imgs_raw) > 0:
xx = _to_4d(x)
Hh, Ww = xx.shape[-2], xx.shape[-1]
encoded_list = []
for idx, img in enumerate(imgs_raw):
encoded = _fit_encode_image(img, vae, Hh, Ww, px_cache, (f"ref_{idx}", Hh, Ww), fit_mode)
encoded_list.append(mm.process_latent_in(encoded))
src = encoded_list if len(encoded_list) > 1 else encoded_list[0]
v = krea2_edit_forward(dm, x, timesteps, context, src, transformer_options,
ref_boosts=ref_boosts,
ref_boost_mask=ref_boost_mask,
ref_native=(fit_mode == "fit" and vae is not None and len(imgs_raw) > 0),
pos_mode=("stride1" if fit_mode == "fit" else "anchor"))
return v
to = m.model_options.setdefault("transformer_options", {})
comfy.patcher_extension.add_wrapper_with_key(
comfy.patcher_extension.WrappersMP.DIFFUSION_MODEL, "krea2_edit", wrapper, to
)
return (m,)
class Krea2EditGroundedEncode:
DEFAULT_SYSTEM = (
"Describe the image by detailing the color, shape, size, "
"texture, quantity, text, spatial relationships of the objects and background:"
)
@classmethod
def _template(cls, nimg, system_prompt=""):
sp = system_prompt.strip() or cls.DEFAULT_SYSTEM
vis = "<|vision_start|><|image_pad|><|vision_end|>" * nimg
return ("<|im_start|>system\n" + sp + "<|im_end|>\n<|im_start|>user\n"
+ vis + "{}<|im_end|>\n<|im_start|>assistant\n")
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"clip": ("CLIP",),
"prompt": ("STRING", {"multiline": True, "default": ""}),
},
"optional": {
"image": ("IMAGE", {"tooltip": "1st reference image"}),
"image_b": ("IMAGE", {"tooltip": "2nd reference image"}),
"image_c": ("IMAGE", {"tooltip": "3rd reference image"}),
"image_d": ("IMAGE", {"tooltip": "4th reference image"}),
"image_e": ("IMAGE", {"tooltip": "5th reference image"}),
"grounding_px": ("INT", {"default": 768, "min": 0, "max": 4096, "step": 64}),
"system_prompt": ("STRING", {"multiline": True, "default": ""}),
},
}
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "encode"
CATEGORY = "krea2edit"
DESCRIPTION = "Encodes the edit instruction grounded on up to 5 source images."
def _prep(self, image, grounding_px):
samples = image.movedim(-1, 1)
h, w = samples.shape[2], samples.shape[3]
if grounding_px and max(h, w) > grounding_px:
s = grounding_px / max(h, w)
samples = comfy.utils.common_upscale(samples, round(w * s), round(h * s), "area", "disabled")
return samples.movedim(1, -1)[:, :, :, :3]
def encode(self, clip, prompt, image=None, image_b=None, image_c=None,
image_d=None, image_e=None, grounding_px=768, system_prompt="", **_future):
raw_imgs = [image, image_b, image_c, image_d, image_e]
raw_imgs = [i for i in raw_imgs if i is not None]
if not raw_imgs:
tokens = clip.tokenize(prompt)
return (clip.encode_from_tokens_scheduled(tokens),)
imgs = [self._prep(img, grounding_px) for img in raw_imgs]
template = self._template(len(imgs), system_prompt)
tokens = clip.tokenize(prompt, images=imgs, llama_template=template)
return (clip.encode_from_tokens_scheduled(tokens),)
NODE_CLASS_MAPPINGS = {
"Krea2EditModelPatch": Krea2EditModelPatch,
"Krea2EditGroundedEncode": Krea2EditGroundedEncode,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"Krea2EditModelPatch": "Krea2 Edit (source patch)",
"Krea2EditGroundedEncode": "Krea2 Edit (grounded encode)",
}
def _pack_version():
try:
import os, re
p = os.path.join(os.path.dirname(__file__), "pyproject.toml")
with open(p) as f:
m = re.search(r'^version\s*=\s*"([^"]+)"', f.read(), re.M)
return m.group(1) if m else "unknown"
except Exception:
return "unknown"
print(f"[krea2edit] nodes v{_pack_version()} loaded (5-ref edit fixed)", flush=True)