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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Save this file as:
|
| 2 |
+
# ComfyUI/custom_nodes/SDXL_LongPromptWeightedEncode.py
|
| 3 |
+
# then restart ComfyUI
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
import re
|
| 7 |
+
from typing import Dict, List, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
# Comfy core helpers (MAX_RESOLUTION is used by built-in SDXL nodes)
|
| 13 |
+
from nodes import MAX_RESOLUTION
|
| 14 |
+
except Exception:
|
| 15 |
+
MAX_RESOLUTION = 16384
|
| 16 |
+
|
| 17 |
+
# ---------- minimal copy of prompt attention parser (A1111-style) ----------
|
| 18 |
+
# Based on AUTOMATIC1111 prompt parser behaviour. Supports ( ... :w ) and [ ... ]
|
| 19 |
+
_re_attention = re.compile(r"""
|
| 20 |
+
\\\(|\\\)|\\\[|\\]|\\\\|\\|\(|\[|:([+-]?[.\d]+)\)|\)|]|[^\\()\[\]:]+|:
|
| 21 |
+
""", re.X)
|
| 22 |
+
_re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
|
| 23 |
+
|
| 24 |
+
def parse_prompt_attention(text: str) -> List[Tuple[str, float]]:
|
| 25 |
+
if not isinstance(text, str) or not text:
|
| 26 |
+
return [["", 1.0]]
|
| 27 |
+
res: List[List[object]] = []
|
| 28 |
+
round_brackets: List[int] = []
|
| 29 |
+
square_brackets: List[int] = []
|
| 30 |
+
rb_mul = 1.1
|
| 31 |
+
sb_mul = 1.0 / 1.1
|
| 32 |
+
|
| 33 |
+
def mul_range(start: int, m: float):
|
| 34 |
+
for i in range(start, len(res)):
|
| 35 |
+
res[i][1] *= m
|
| 36 |
+
|
| 37 |
+
for m in _re_attention.finditer(text):
|
| 38 |
+
t = m.group(0)
|
| 39 |
+
w = m.group(1)
|
| 40 |
+
if t.startswith('\\'):
|
| 41 |
+
res.append([t[1:], 1.0])
|
| 42 |
+
elif t == '(':
|
| 43 |
+
round_brackets.append(len(res))
|
| 44 |
+
elif t == '[':
|
| 45 |
+
square_brackets.append(len(res))
|
| 46 |
+
elif w is not None and len(round_brackets) > 0:
|
| 47 |
+
mul_range(round_brackets.pop(), float(w))
|
| 48 |
+
elif t == ')' and len(round_brackets) > 0:
|
| 49 |
+
mul_range(round_brackets.pop(), rb_mul)
|
| 50 |
+
elif t == ']' and len(square_brackets) > 0:
|
| 51 |
+
mul_range(square_brackets.pop(), sb_mul)
|
| 52 |
+
else:
|
| 53 |
+
parts = _re_break.split(t)
|
| 54 |
+
for i, p in enumerate(parts):
|
| 55 |
+
if i > 0:
|
| 56 |
+
res.append(["BREAK", -1])
|
| 57 |
+
res.append([p, 1.0])
|
| 58 |
+
|
| 59 |
+
for pos in round_brackets:
|
| 60 |
+
mul_range(pos, rb_mul)
|
| 61 |
+
for pos in square_brackets:
|
| 62 |
+
mul_range(pos, sb_mul)
|
| 63 |
+
|
| 64 |
+
if not res:
|
| 65 |
+
res = [["", 1.0]]
|
| 66 |
+
|
| 67 |
+
# merge adjacent same-weight chunks
|
| 68 |
+
i = 0
|
| 69 |
+
while i + 1 < len(res):
|
| 70 |
+
if res[i][1] == res[i + 1][1]:
|
| 71 |
+
res[i][0] += res[i + 1][0]
|
| 72 |
+
res.pop(i + 1)
|
| 73 |
+
else:
|
| 74 |
+
i += 1
|
| 75 |
+
return [(str(t), float(w)) for t, w in res]
|
| 76 |
+
|
| 77 |
+
# ---------- helpers to build long token streams using Comfy's clip.tokenize ----------
|
| 78 |
+
|
| 79 |
+
def _strip_bos_eos_and_pad(ids: List[int]) -> Tuple[List[int], int, int]:
|
| 80 |
+
"""Given a 77-length token list like [BOS, ..., EOS, EOS, EOS],
|
| 81 |
+
return (core_without_specials, BOS, EOS).
|
| 82 |
+
"""
|
| 83 |
+
if not ids:
|
| 84 |
+
return [], 49406, 49407 # sensible defaults for CLIP
|
| 85 |
+
bos, eos = ids[0], ids[-1]
|
| 86 |
+
core = ids[1:]
|
| 87 |
+
while core and core[-1] == eos:
|
| 88 |
+
core.pop()
|
| 89 |
+
return core, bos, eos
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def tokenize_with_weights_via_comfy_clip(clip, text: str) -> Tuple[List[int], List[int], List[float]]:
|
| 93 |
+
"""Tokenize a text chunk using Comfy's clip.tokenize so we stay 100% compatible
|
| 94 |
+
with whatever CLIP pair is loaded (SDXL: g + l). Returns (ids_g, ids_l, weights)
|
| 95 |
+
where weights has one value per token (same for g and l at this stage).
|
| 96 |
+
"""
|
| 97 |
+
tokens = clip.tokenize(text)
|
| 98 |
+
# tokens is a dict like {"g": [list77, list77, ...], "l": [list77, ...]}
|
| 99 |
+
# For a small chunk, we only need the first 77-block and strip BOS/EOS/pad
|
| 100 |
+
g77 = tokens.get("g", [[]])
|
| 101 |
+
l77 = tokens.get("l", [[]])
|
| 102 |
+
g77 = g77[0] if isinstance(g77, list) and len(g77) > 0 else []
|
| 103 |
+
l77 = l77[0] if isinstance(l77, list) and len(l77) > 0 else []
|
| 104 |
+
|
| 105 |
+
g_core, g_bos, g_eos = _strip_bos_eos_and_pad([int(x) for x in g77])
|
| 106 |
+
l_core, l_bos, l_eos = _strip_bos_eos_and_pad([int(x) for x in l77])
|
| 107 |
+
|
| 108 |
+
# If one side is empty (rare), keep lengths aligned by mirroring the other
|
| 109 |
+
if len(l_core) == 0 and len(g_core) > 0:
|
| 110 |
+
l_core = g_core[:]
|
| 111 |
+
if len(g_core) == 0 and len(l_core) > 0:
|
| 112 |
+
g_core = l_core[:]
|
| 113 |
+
|
| 114 |
+
# Weights are applied per-token (shared to both encoders). The calling site will
|
| 115 |
+
# generate the weight list based on parse_prompt_attention.
|
| 116 |
+
return g_core, l_core, [] # weights are aggregated outside
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def build_long_ids_and_weights(clip, text: str) -> Tuple[List[int], List[int], List[float], int, int]:
|
| 120 |
+
"""Parse attention, tokenize each fragment, and concatenate into *unlimited* token streams
|
| 121 |
+
for both encoders. Returns ids_g, ids_l, weights_per_token, bos_id, eos_id (we take from 'l').
|
| 122 |
+
"""
|
| 123 |
+
parts = parse_prompt_attention(text)
|
| 124 |
+
ids_g: List[int] = []
|
| 125 |
+
ids_l: List[int] = []
|
| 126 |
+
w_all: List[float] = []
|
| 127 |
+
|
| 128 |
+
example_eos = 49407
|
| 129 |
+
example_bos = 49406
|
| 130 |
+
|
| 131 |
+
for frag, w in parts:
|
| 132 |
+
if frag == "BREAK":
|
| 133 |
+
continue # (optional) treat BREAK as neutral separator
|
| 134 |
+
g_ids, l_ids, _ = tokenize_with_weights_via_comfy_clip(clip, frag)
|
| 135 |
+
ids_g.extend(g_ids)
|
| 136 |
+
ids_l.extend(l_ids)
|
| 137 |
+
w_all.extend([w] * max(len(g_ids), len(l_ids)))
|
| 138 |
+
|
| 139 |
+
# try to update BOS/EOS from observed short tokenizations
|
| 140 |
+
# (by encoding a single word we likely saw real BOS/EOS)
|
| 141 |
+
# We can't recover them from core ids, so keep defaults.
|
| 142 |
+
|
| 143 |
+
# Keep streams same length by padding with EOS later anyway.
|
| 144 |
+
return ids_g, ids_l, w_all, example_bos, example_eos
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def group_into_77(ids: List[int], weights: List[float], bos: int, eos: int, pad_last_block: bool) -> Tuple[List[List[int]], List[List[float]]]:
|
| 148 |
+
"""Split a (potentially long) token id stream into 77-long blocks as [BOS, 75 body, EOS].
|
| 149 |
+
We also split weights accordingly, inserting 1.0 for BOS/EOS and any extra EOS padding.
|
| 150 |
+
"""
|
| 151 |
+
ids = list(ids)
|
| 152 |
+
weights = list(weights)
|
| 153 |
+
blocks_ids: List[List[int]] = []
|
| 154 |
+
blocks_w: List[List[float]] = []
|
| 155 |
+
while len(ids) >= 75:
|
| 156 |
+
body = [ids.pop(0) for _ in range(75)]
|
| 157 |
+
body_w = [weights.pop(0) for _ in range(75)]
|
| 158 |
+
blocks_ids.append([bos] + body + [eos])
|
| 159 |
+
blocks_w.append([1.0] + body_w + [1.0])
|
| 160 |
+
if ids:
|
| 161 |
+
pad_len = 75 - len(ids) if pad_last_block else 0
|
| 162 |
+
body = ids + [eos] * pad_len
|
| 163 |
+
body_w = weights + [1.0] * pad_len
|
| 164 |
+
blocks_ids.append([bos] + body + [eos])
|
| 165 |
+
blocks_w.append([1.0] + body_w + [1.0])
|
| 166 |
+
return blocks_ids, blocks_w
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# ---------- the ComfyUI node ----------
|
| 170 |
+
class SDXL_LongPromptWeightedEncode:
|
| 171 |
+
"""
|
| 172 |
+
Encode *arbitrarily long* SDXL prompts with A1111-style token weights, using the
|
| 173 |
+
already-loaded ComfyUI CLIP pair (no diffusers import) and output a CONDITIONING
|
| 174 |
+
compatible with SDXL samplers.
|
| 175 |
+
|
| 176 |
+
Implementation notes:
|
| 177 |
+
- Uses clip.tokenize() to stay vocab-compatible with your loaded CLIP L/G.
|
| 178 |
+
- Splits to 77-token blocks under the hood, applies per-token weights to the
|
| 179 |
+
concatenated "cond" tensor returned by clip.encode_from_tokens().
|
| 180 |
+
- Outputs *two* conditionings: positive and negative.
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
@classmethod
|
| 184 |
+
def INPUT_TYPES(s):
|
| 185 |
+
return {
|
| 186 |
+
"required": {
|
| 187 |
+
"clip": ("CLIP",),
|
| 188 |
+
"width": ("INT", {"default": 1024, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
|
| 189 |
+
"height": ("INT", {"default": 1024, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
|
| 190 |
+
"crop_w": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
| 191 |
+
"crop_h": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
| 192 |
+
"target_width": ("INT", {"default": 1024, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
|
| 193 |
+
"target_height": ("INT", {"default": 1024, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
|
| 194 |
+
"prompt": ("STRING", {"multiline": True, "dynamicPrompts": True}),
|
| 195 |
+
"negative": ("STRING", {"multiline": True, "dynamicPrompts": True}),
|
| 196 |
+
"pad_last_block": ("BOOLEAN", {"default": True}),
|
| 197 |
+
},
|
| 198 |
+
"optional": {
|
| 199 |
+
# If you want to reduce influence of extreme weights, you can later add alternative modes
|
| 200 |
+
# (e.g., tanh mapping). For now we simply multiply.
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
RETURN_TYPES = ("CONDITIONING", "CONDITIONING")
|
| 205 |
+
RETURN_NAMES = ("positive", "negative")
|
| 206 |
+
FUNCTION = "encode"
|
| 207 |
+
CATEGORY = "advanced/conditioning"
|
| 208 |
+
|
| 209 |
+
def _encode_one(self, clip, text: str, width: int, height: int, crop_w: int, crop_h: int, target_width: int, target_height: int, pad_last_block: bool):
|
| 210 |
+
# 1) build unlimited token streams + weights for both CLIPs
|
| 211 |
+
ids_g, ids_l, weights, bos, eos = build_long_ids_and_weights(clip, text)
|
| 212 |
+
|
| 213 |
+
# keep both streams same length by padding the shorter with EOS/1.0
|
| 214 |
+
max_len = max(len(ids_g), len(ids_l), len(weights))
|
| 215 |
+
if len(ids_g) < max_len:
|
| 216 |
+
ids_g += [eos] * (max_len - len(ids_g))
|
| 217 |
+
if len(ids_l) < max_len:
|
| 218 |
+
ids_l += [eos] * (max_len - len(ids_l))
|
| 219 |
+
if len(weights) < max_len:
|
| 220 |
+
weights += [1.0] * (max_len - len(weights))
|
| 221 |
+
|
| 222 |
+
# 2) split to 77-token blocks per encoder
|
| 223 |
+
g_blocks, g_w_blocks = group_into_77(ids_g, weights, bos, eos, pad_last_block)
|
| 224 |
+
l_blocks, l_w_blocks = group_into_77(ids_l, weights, bos, eos, pad_last_block)
|
| 225 |
+
|
| 226 |
+
# ensure same number of blocks for g/l by padding empty blocks
|
| 227 |
+
if len(l_blocks) != len(g_blocks):
|
| 228 |
+
# create an "empty" block via clip.tokenize("") to match what SDXL node does
|
| 229 |
+
empty = clip.tokenize("")
|
| 230 |
+
empty_g = empty.get("g", [[]])[0]
|
| 231 |
+
empty_l = empty.get("l", [[]])[0]
|
| 232 |
+
# weights of an empty block are just ones
|
| 233 |
+
empty_w = [1.0] * len(empty_g)
|
| 234 |
+
while len(l_blocks) < len(g_blocks):
|
| 235 |
+
l_blocks.append(list(empty_l))
|
| 236 |
+
l_w_blocks.append(list(empty_w))
|
| 237 |
+
while len(g_blocks) < len(l_blocks):
|
| 238 |
+
g_blocks.append(list(empty_g))
|
| 239 |
+
g_w_blocks.append(list(empty_w))
|
| 240 |
+
|
| 241 |
+
# 3) run CLIP through Comfy for the whole packed token dict
|
| 242 |
+
tokens: Dict[str, List[List[int]]] = {"g": g_blocks, "l": l_blocks}
|
| 243 |
+
cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
|
| 244 |
+
# cond shape: [1, total_seq, 2048] for SDXL; pooled is CLIP-G pooled
|
| 245 |
+
|
| 246 |
+
# 4) apply per-token weights (broadcast multiply)
|
| 247 |
+
# Flatten weights blocks to match the concatenated sequence length
|
| 248 |
+
seq_weights: List[float] = []
|
| 249 |
+
for wb_g, wb_l in zip(g_w_blocks, l_w_blocks):
|
| 250 |
+
# both wb_g and wb_l share the same pattern; take one
|
| 251 |
+
seq_weights.extend(wb_g)
|
| 252 |
+
w = torch.tensor(seq_weights, dtype=cond.dtype, device=cond.device).unsqueeze(0).unsqueeze(-1) # [1, T, 1]
|
| 253 |
+
cond = cond * w
|
| 254 |
+
|
| 255 |
+
# 5) package into Comfy conditioning structure
|
| 256 |
+
c = [[cond, {
|
| 257 |
+
"pooled_output": pooled,
|
| 258 |
+
"width": width,
|
| 259 |
+
"height": height,
|
| 260 |
+
"crop_w": crop_w,
|
| 261 |
+
"crop_h": crop_h,
|
| 262 |
+
"target_width": target_width,
|
| 263 |
+
"target_height": target_height,
|
| 264 |
+
}]]
|
| 265 |
+
return c
|
| 266 |
+
|
| 267 |
+
def encode(self, clip, width, height, crop_w, crop_h, target_width, target_height, prompt, negative, pad_last_block=True):
|
| 268 |
+
pos_c = self._encode_one(clip, prompt if (prompt and len(prompt) > 0) else "", width, height, crop_w, crop_h, target_width, target_height, pad_last_block)
|
| 269 |
+
neg_c = self._encode_one(clip, negative if (negative and len(negative) > 0) else "", width, height, crop_w, crop_h, target_width, target_height, pad_last_block)
|
| 270 |
+
return (pos_c, neg_c)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
NODE_CLASS_MAPPINGS = {
|
| 274 |
+
"SDXL_LongPromptWeightedEncode": SDXL_LongPromptWeightedEncode,
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 278 |
+
"SDXL_LongPromptWeightedEncode": "SDXL Long Prompt Weighted Encode",
|
| 279 |
+
}
|