Dervlex commited on
Commit
525c385
·
verified ·
1 Parent(s): 2333059

Upload sdembed_sdxl_no_diffusers.py

Browse files
Files changed (1) hide show
  1. sdembed_sdxl_no_diffusers.py +268 -0
sdembed_sdxl_no_diffusers.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SDXL_LongPromptWeightedEncode (no-diffusers)
2
+ #
3
+ # Drop this file into: ComfyUI/custom_nodes/sdembed_sdxl_no_diffusers.py
4
+ # Then restart ComfyUI. The node will show up under
5
+ # "conditioning/advanced" as: SDXL Long Prompt Weighted Encode (no-diffusers)
6
+ #
7
+ # What it does:
8
+ # - Reproduces the core idea of xhinker/sd_embed for SDXL *without* importing
9
+ # diffusers (saves VRAM and reuses the CLIP already loaded by ComfyUI).
10
+ # - Accepts extra-long prompts with (…:weight) attention syntax and applies
11
+ # token-level weights over unlimited-length prompts by chunking into 75-token
12
+ # blocks (with BOS/EOS added by CLIP).
13
+ # - Works directly with the CLIP object output by CheckpointLoaderSimple.
14
+ # - Returns standard ComfyUI CONDITIONING objects for positive and negative
15
+ # conditioning, compatible with KSampler.
16
+ #
17
+ # Notes:
18
+ # - We use the token groups produced by clip.tokenize() (keys 'g' and 'l').
19
+ # - We compute weights from the 'g' tokenizer and apply them to the concatenated
20
+ # SDXL embedding (like sd_embed's default method 3).
21
+ # - We mirror padding logic by adding groups of empty tokens when 'g' and 'l'
22
+ # have differing counts.
23
+ # - We avoid clip_skip or LoRA scaling here to keep things simple/VRAM-friendly.
24
+ # (You can pair this with Comfy's existing CLIP Set Last Layer and LoRA nodes.)
25
+ #
26
+ # Tested with recent ComfyUI builds. If ComfyUI internals change, minor tweaks
27
+ # may be required.
28
+
29
+ from __future__ import annotations
30
+ import re
31
+ import math
32
+ from typing import List, Tuple, Dict, Any
33
+
34
+ import torch
35
+
36
+ # ---- Minimal prompt attention parser --------------------------------------
37
+ # Supports explicit "(text:1.25)" weights and falls back to weight 1.0
38
+ # for everything else. Nested parentheses without explicit weights are
39
+ # not altered here (use explicit :weight if you need emphasis).
40
+ # This keeps the implementation light and dependency-free.
41
+
42
+ _WEIGHTED_RE = re.compile(r"\\(([^()]+?):([0-9]+(?:\\.[0-9]+)?)\\)")
43
+
44
+
45
+ def parse_prompt_attention(text: str) -> List[Tuple[str, float]]:
46
+ """
47
+ Parse a prompt into [(substring, weight)] parts.
48
+ Recognizes explicit (…:w) patterns. Anything not matched keeps weight 1.0.
49
+ Example: "a (red cat:1.5) walking" -> [("a ",1.0),("red cat",1.5),(" walking",1.0)]
50
+ """
51
+ if not text:
52
+ return [("empty", 1.0)]
53
+
54
+ parts: List[Tuple[str, float]] = []
55
+ idx = 0
56
+ for m in _WEIGHTED_RE.finditer(text):
57
+ if m.start() > idx:
58
+ parts.append((text[idx:m.start()], 1.0))
59
+ chunk = m.group(1)
60
+ w = float(m.group(2))
61
+ parts.append((chunk, w))
62
+ idx = m.end()
63
+ if idx < len(text):
64
+ parts.append((text[idx:], 1.0))
65
+ # Merge contiguous literals to keep things tidy
66
+ merged: List[Tuple[str, float]] = []
67
+ for t, w in parts:
68
+ if merged and w == 1.0 and merged[-1][1] == 1.0:
69
+ merged[-1] = (merged[-1][0] + t, 1.0)
70
+ else:
71
+ merged.append((t, w))
72
+ return merged
73
+
74
+
75
+ # ---- Token utilities -------------------------------------------------------
76
+
77
+ def _count_non_special_in_group(group: List[int]) -> int:
78
+ """Count tokens in a 77-length group excluding BOS and trailing EOS padding.
79
+ We derive EOS as the last id in the group and stop at its first occurrence.
80
+ """
81
+ if not group:
82
+ return 0
83
+ eos_id = group[-1]
84
+ count = 0
85
+ for tok in group[1:]: # skip BOS at index 0
86
+ if tok == eos_id:
87
+ break
88
+ count += 1
89
+ return count
90
+
91
+
92
+ def _token_count_for_text(clip, text: str) -> Tuple[int, int]:
93
+ """Return (g_count, l_count) of non-special tokens for a text chunk."""
94
+ toks = clip.tokenize(text)
95
+ g = sum(_count_non_special_in_group(grp) for grp in toks.get("g", []))
96
+ l = sum(_count_non_special_in_group(grp) for grp in toks.get("l", []))
97
+ return g, l
98
+
99
+
100
+ def _weights_per_group_from_text(clip, text: str, num_groups: int) -> List[List[float]]:
101
+ """Build a list of length `num_groups`, each with 75 weights for the 'g' encoder.
102
+ We expand explicit weights over the number of non-special tokens of each
103
+ parsed chunk, then slice into 75-token groups and pad the last group.
104
+ """
105
+ parsed = parse_prompt_attention(text)
106
+ expanded: List[float] = []
107
+ for chunk, w in parsed:
108
+ g_count, _ = _token_count_for_text(clip, chunk)
109
+ if g_count > 0:
110
+ expanded.extend([float(w)] * g_count)
111
+ # Now partition into 75-token groups
112
+ groups: List[List[float]] = []
113
+ needed = max(1, num_groups)
114
+ for i in range(needed):
115
+ start = i * 75
116
+ end = start + 75
117
+ slice75 = expanded[start:end]
118
+ if len(slice75) < 75:
119
+ slice75 = slice75 + [1.0] * (75 - len(slice75))
120
+ groups.append(slice75)
121
+ return groups
122
+
123
+
124
+ def _pad_token_groups(tokens: Dict[str, List[List[int]]], clip) -> Dict[str, List[List[int]]]:
125
+ """Ensure tokens['g'] and tokens['l'] have same number of 77-length groups
126
+ by padding with empty prompt groups from clip.tokenize("").
127
+ """
128
+ g_groups = tokens.get("g", [])
129
+ l_groups = tokens.get("l", [])
130
+ if len(g_groups) == len(l_groups):
131
+ return tokens
132
+ empty = clip.tokenize("")
133
+ eg = empty.get("g", [])
134
+ el = empty.get("l", [])
135
+ while len(g_groups) < len(l_groups):
136
+ g_groups += eg
137
+ while len(l_groups) < len(g_groups):
138
+ l_groups += el
139
+ tokens["g"], tokens["l"] = g_groups, l_groups
140
+ return tokens
141
+
142
+
143
+ def _encode_groups_with_weights(clip, tokens: Dict[str, List[List[int]]], weight_groups_g: List[List[float]],
144
+ width: int, height: int, crop_w: int, crop_h: int, target_width: int, target_height: int) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, Any]]:
145
+ """Encode each 77-token group, apply per-token weights (from 'g' only),
146
+ then concat along the sequence dimension. Return (cond, pooled, meta_dict).
147
+ """
148
+ tokens = _pad_token_groups(tokens, clip)
149
+ num_groups = len(tokens["g"]) if tokens.get("g") else 0
150
+
151
+ # Make sure weight groups match number of token groups
152
+ if len(weight_groups_g) < num_groups:
153
+ # pad missing weight groups with 1.0s
154
+ for _ in range(num_groups - len(weight_groups_g)):
155
+ weight_groups_g.append([1.0] * 75)
156
+
157
+ cond_chunks: List[torch.Tensor] = []
158
+ pooled_last: torch.Tensor | None = None
159
+
160
+ for i in range(num_groups):
161
+ grp_tokens = {"g": [tokens["g"][i]], "l": [tokens["l"][i]]}
162
+ cond, pooled = clip.encode_from_tokens(grp_tokens, return_pooled=True)
163
+ # cond shape: [1, 77, embed_dim]; apply weights across the 75 non-special tokens.
164
+ weights_75 = weight_groups_g[i]
165
+ # Build a [1, 77, 1] weight tensor: BOS=1.0; then 75 weights; any padding EOS beyond actual tokens stays at 1.0 automatically via below mask.
166
+ w_vec = torch.tensor([1.0] + list(weights_75) + [1.0], dtype=cond.dtype, device=cond.device)
167
+ # However, some of the tail positions can already be EOS padding; they will still receive 1.0 effectively once we clip through an EOS mask.
168
+ # Derive EOS id from tokens to compute real token count and zero-out weights beyond first EOS.
169
+ grp_g = tokens["g"][i]
170
+ real_len = _count_non_special_in_group(grp_g) # in [0..75]
171
+ # After BOS, positions [1..real_len] are real tokens; [real_len+1..75] are EOS padding.
172
+ # So overwrite those padded positions with 1.0 to avoid amplifying padding.
173
+ for pos in range(real_len + 1, 75 + 1): # map 75 non-special into indices 1..75
174
+ w_vec[pos] = 1.0
175
+ w = w_vec.view(1, -1, 1)
176
+ cond = cond * w
177
+ cond_chunks.append(cond)
178
+ pooled_last = pooled
179
+
180
+ if not cond_chunks:
181
+ # Fallback: encode empty string
182
+ cond, pooled = clip.encode_from_tokens(clip.tokenize(""), return_pooled=True)
183
+ pooled_last = pooled
184
+ return cond, pooled_last, {"pooled_output": pooled_last, "width": width, "height": height,
185
+ "crop_w": crop_w, "crop_h": crop_h,
186
+ "target_width": target_width, "target_height": target_height}
187
+
188
+ cond_all = torch.cat(cond_chunks, dim=1)
189
+ meta = {"pooled_output": pooled_last, "width": width, "height": height,
190
+ "crop_w": crop_w, "crop_h": crop_h,
191
+ "target_width": target_width, "target_height": target_height}
192
+ return cond_all, pooled_last, meta
193
+
194
+
195
+ # ---- ComfyUI node ----------------------------------------------------------
196
+
197
+ class SDXL_LongPromptWeightedEncode_NoDiffusers:
198
+ """Encode extra-long prompts for SDXL with token-level weights and no diffusers.
199
+
200
+ Inputs mirror CLIPTextEncodeSDXL so you can drop this into existing graphs.
201
+ """
202
+
203
+ @classmethod
204
+ def INPUT_TYPES(cls):
205
+ return {
206
+ "required": {
207
+ "clip": ("CLIP",),
208
+ "width": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
209
+ "height": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
210
+ "crop_w": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 8}),
211
+ "crop_h": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 8}),
212
+ "target_width": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
213
+ "target_height": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
214
+ "text_g": ("STRING", {"multiline": True, "default": ""}),
215
+ "text_l": ("STRING", {"multiline": True, "default": None}),
216
+ "neg_g": ("STRING", {"multiline": True, "default": ""}),
217
+ "neg_l": ("STRING", {"multiline": True, "default": None}),
218
+ },
219
+ }
220
+
221
+ RETURN_TYPES = ("CONDITIONING", "CONDITIONING")
222
+ RETURN_NAMES = ("positive", "negative")
223
+ FUNCTION = "encode"
224
+ CATEGORY = "conditioning/advanced"
225
+
226
+ def encode(self, clip, width: int, height: int, crop_w: int, crop_h: int,
227
+ target_width: int, target_height: int,
228
+ text_g: str, text_l: str | None,
229
+ neg_g: str, neg_l: str | None):
230
+ # Use the same text for l if not provided (typical SDXL usage)
231
+ text_l = text_g if (text_l is None or text_l == "") else text_l
232
+ neg_l = neg_g if (neg_l is None or neg_l == "") else neg_l
233
+
234
+ # --- Positive ---
235
+ pos_tokens = clip.tokenize(text_g)
236
+ # Replace 'l' part with separate tokenize(text_l)
237
+ pos_tokens["l"] = clip.tokenize(text_l).get("l", [])
238
+ pos_tokens = _pad_token_groups(pos_tokens, clip)
239
+ num_groups_pos = len(pos_tokens.get("g", []))
240
+ pos_weight_groups_g = _weights_per_group_from_text(clip, text_g, num_groups_pos)
241
+ pos_cond, pos_pooled, pos_meta = _encode_groups_with_weights(
242
+ clip, pos_tokens, pos_weight_groups_g,
243
+ width, height, crop_w, crop_h, target_width, target_height
244
+ )
245
+ positive = [[pos_cond, pos_meta]]
246
+
247
+ # --- Negative ---
248
+ neg_tokens = clip.tokenize(neg_g)
249
+ neg_tokens["l"] = clip.tokenize(neg_l).get("l", [])
250
+ neg_tokens = _pad_token_groups(neg_tokens, clip)
251
+ num_groups_neg = len(neg_tokens.get("g", []))
252
+ neg_weight_groups_g = _weights_per_group_from_text(clip, neg_g, num_groups_neg)
253
+ neg_cond, neg_pooled, neg_meta = _encode_groups_with_weights(
254
+ clip, neg_tokens, neg_weight_groups_g,
255
+ width, height, crop_w, crop_h, target_width, target_height
256
+ )
257
+ negative = [[neg_cond, neg_meta]]
258
+
259
+ return (positive, negative)
260
+
261
+
262
+ NODE_CLASS_MAPPINGS = {
263
+ "SDXL_LongPromptWeightedEncode_NoDiffusers": SDXL_LongPromptWeightedEncode_NoDiffusers,
264
+ }
265
+
266
+ NODE_DISPLAY_NAME_MAPPINGS = {
267
+ "SDXL_LongPromptWeightedEncode_NoDiffusers": "SDXL Long Prompt Weighted Encode (no-diffusers)",
268
+ }