Models / sdembed_sdxl_no_diffusers.py
Dervlex's picture
Upload sdembed_sdxl_no_diffusers.py
525c385 verified
Raw History Blame Contribute Delete
11.7 kB
# SDXL_LongPromptWeightedEncode (no-diffusers)
#
# Drop this file into: ComfyUI/custom_nodes/sdembed_sdxl_no_diffusers.py
# Then restart ComfyUI. The node will show up under
# "conditioning/advanced" as: SDXL Long Prompt Weighted Encode (no-diffusers)
#
# What it does:
# - Reproduces the core idea of xhinker/sd_embed for SDXL *without* importing
# diffusers (saves VRAM and reuses the CLIP already loaded by ComfyUI).
# - Accepts extra-long prompts with (…:weight) attention syntax and applies
# token-level weights over unlimited-length prompts by chunking into 75-token
# blocks (with BOS/EOS added by CLIP).
# - Works directly with the CLIP object output by CheckpointLoaderSimple.
# - Returns standard ComfyUI CONDITIONING objects for positive and negative
# conditioning, compatible with KSampler.
#
# Notes:
# - We use the token groups produced by clip.tokenize() (keys 'g' and 'l').
# - We compute weights from the 'g' tokenizer and apply them to the concatenated
# SDXL embedding (like sd_embed's default method 3).
# - We mirror padding logic by adding groups of empty tokens when 'g' and 'l'
# have differing counts.
# - We avoid clip_skip or LoRA scaling here to keep things simple/VRAM-friendly.
# (You can pair this with Comfy's existing CLIP Set Last Layer and LoRA nodes.)
#
# Tested with recent ComfyUI builds. If ComfyUI internals change, minor tweaks
# may be required.
from __future__ import annotations
import re
import math
from typing import List, Tuple, Dict, Any
import torch
# ---- Minimal prompt attention parser --------------------------------------
# Supports explicit "(text:1.25)" weights and falls back to weight 1.0
# for everything else. Nested parentheses without explicit weights are
# not altered here (use explicit :weight if you need emphasis).
# This keeps the implementation light and dependency-free.
_WEIGHTED_RE = re.compile(r"\\(([^()]+?):([0-9]+(?:\\.[0-9]+)?)\\)")
def parse_prompt_attention(text: str) -> List[Tuple[str, float]]:
"""
Parse a prompt into [(substring, weight)] parts.
Recognizes explicit (…:w) patterns. Anything not matched keeps weight 1.0.
Example: "a (red cat:1.5) walking" -> [("a ",1.0),("red cat",1.5),(" walking",1.0)]
"""
if not text:
return [("empty", 1.0)]
parts: List[Tuple[str, float]] = []
idx = 0
for m in _WEIGHTED_RE.finditer(text):
if m.start() > idx:
parts.append((text[idx:m.start()], 1.0))
chunk = m.group(1)
w = float(m.group(2))
parts.append((chunk, w))
idx = m.end()
if idx < len(text):
parts.append((text[idx:], 1.0))
# Merge contiguous literals to keep things tidy
merged: List[Tuple[str, float]] = []
for t, w in parts:
if merged and w == 1.0 and merged[-1][1] == 1.0:
merged[-1] = (merged[-1][0] + t, 1.0)
else:
merged.append((t, w))
return merged
# ---- Token utilities -------------------------------------------------------
def _count_non_special_in_group(group: List[int]) -> int:
"""Count tokens in a 77-length group excluding BOS and trailing EOS padding.
We derive EOS as the last id in the group and stop at its first occurrence.
"""
if not group:
return 0
eos_id = group[-1]
count = 0
for tok in group[1:]: # skip BOS at index 0
if tok == eos_id:
break
count += 1
return count
def _token_count_for_text(clip, text: str) -> Tuple[int, int]:
"""Return (g_count, l_count) of non-special tokens for a text chunk."""
toks = clip.tokenize(text)
g = sum(_count_non_special_in_group(grp) for grp in toks.get("g", []))
l = sum(_count_non_special_in_group(grp) for grp in toks.get("l", []))
return g, l
def _weights_per_group_from_text(clip, text: str, num_groups: int) -> List[List[float]]:
"""Build a list of length `num_groups`, each with 75 weights for the 'g' encoder.
We expand explicit weights over the number of non-special tokens of each
parsed chunk, then slice into 75-token groups and pad the last group.
"""
parsed = parse_prompt_attention(text)
expanded: List[float] = []
for chunk, w in parsed:
g_count, _ = _token_count_for_text(clip, chunk)
if g_count > 0:
expanded.extend([float(w)] * g_count)
# Now partition into 75-token groups
groups: List[List[float]] = []
needed = max(1, num_groups)
for i in range(needed):
start = i * 75
end = start + 75
slice75 = expanded[start:end]
if len(slice75) < 75:
slice75 = slice75 + [1.0] * (75 - len(slice75))
groups.append(slice75)
return groups
def _pad_token_groups(tokens: Dict[str, List[List[int]]], clip) -> Dict[str, List[List[int]]]:
"""Ensure tokens['g'] and tokens['l'] have same number of 77-length groups
by padding with empty prompt groups from clip.tokenize("").
"""
g_groups = tokens.get("g", [])
l_groups = tokens.get("l", [])
if len(g_groups) == len(l_groups):
return tokens
empty = clip.tokenize("")
eg = empty.get("g", [])
el = empty.get("l", [])
while len(g_groups) < len(l_groups):
g_groups += eg
while len(l_groups) < len(g_groups):
l_groups += el
tokens["g"], tokens["l"] = g_groups, l_groups
return tokens
def _encode_groups_with_weights(clip, tokens: Dict[str, List[List[int]]], weight_groups_g: List[List[float]],
width: int, height: int, crop_w: int, crop_h: int, target_width: int, target_height: int) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, Any]]:
"""Encode each 77-token group, apply per-token weights (from 'g' only),
then concat along the sequence dimension. Return (cond, pooled, meta_dict).
"""
tokens = _pad_token_groups(tokens, clip)
num_groups = len(tokens["g"]) if tokens.get("g") else 0
# Make sure weight groups match number of token groups
if len(weight_groups_g) < num_groups:
# pad missing weight groups with 1.0s
for _ in range(num_groups - len(weight_groups_g)):
weight_groups_g.append([1.0] * 75)
cond_chunks: List[torch.Tensor] = []
pooled_last: torch.Tensor | None = None
for i in range(num_groups):
grp_tokens = {"g": [tokens["g"][i]], "l": [tokens["l"][i]]}
cond, pooled = clip.encode_from_tokens(grp_tokens, return_pooled=True)
# cond shape: [1, 77, embed_dim]; apply weights across the 75 non-special tokens.
weights_75 = weight_groups_g[i]
# 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.
w_vec = torch.tensor([1.0] + list(weights_75) + [1.0], dtype=cond.dtype, device=cond.device)
# 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.
# Derive EOS id from tokens to compute real token count and zero-out weights beyond first EOS.
grp_g = tokens["g"][i]
real_len = _count_non_special_in_group(grp_g) # in [0..75]
# After BOS, positions [1..real_len] are real tokens; [real_len+1..75] are EOS padding.
# So overwrite those padded positions with 1.0 to avoid amplifying padding.
for pos in range(real_len + 1, 75 + 1): # map 75 non-special into indices 1..75
w_vec[pos] = 1.0
w = w_vec.view(1, -1, 1)
cond = cond * w
cond_chunks.append(cond)
pooled_last = pooled
if not cond_chunks:
# Fallback: encode empty string
cond, pooled = clip.encode_from_tokens(clip.tokenize(""), return_pooled=True)
pooled_last = pooled
return cond, pooled_last, {"pooled_output": pooled_last, "width": width, "height": height,
"crop_w": crop_w, "crop_h": crop_h,
"target_width": target_width, "target_height": target_height}
cond_all = torch.cat(cond_chunks, dim=1)
meta = {"pooled_output": pooled_last, "width": width, "height": height,
"crop_w": crop_w, "crop_h": crop_h,
"target_width": target_width, "target_height": target_height}
return cond_all, pooled_last, meta
# ---- ComfyUI node ----------------------------------------------------------
class SDXL_LongPromptWeightedEncode_NoDiffusers:
"""Encode extra-long prompts for SDXL with token-level weights and no diffusers.
Inputs mirror CLIPTextEncodeSDXL so you can drop this into existing graphs.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"clip": ("CLIP",),
"width": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
"height": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
"crop_w": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 8}),
"crop_h": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 8}),
"target_width": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
"target_height": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
"text_g": ("STRING", {"multiline": True, "default": ""}),
"text_l": ("STRING", {"multiline": True, "default": None}),
"neg_g": ("STRING", {"multiline": True, "default": ""}),
"neg_l": ("STRING", {"multiline": True, "default": None}),
},
}
RETURN_TYPES = ("CONDITIONING", "CONDITIONING")
RETURN_NAMES = ("positive", "negative")
FUNCTION = "encode"
CATEGORY = "conditioning/advanced"
def encode(self, clip, width: int, height: int, crop_w: int, crop_h: int,
target_width: int, target_height: int,
text_g: str, text_l: str | None,
neg_g: str, neg_l: str | None):
# Use the same text for l if not provided (typical SDXL usage)
text_l = text_g if (text_l is None or text_l == "") else text_l
neg_l = neg_g if (neg_l is None or neg_l == "") else neg_l
# --- Positive ---
pos_tokens = clip.tokenize(text_g)
# Replace 'l' part with separate tokenize(text_l)
pos_tokens["l"] = clip.tokenize(text_l).get("l", [])
pos_tokens = _pad_token_groups(pos_tokens, clip)
num_groups_pos = len(pos_tokens.get("g", []))
pos_weight_groups_g = _weights_per_group_from_text(clip, text_g, num_groups_pos)
pos_cond, pos_pooled, pos_meta = _encode_groups_with_weights(
clip, pos_tokens, pos_weight_groups_g,
width, height, crop_w, crop_h, target_width, target_height
)
positive = [[pos_cond, pos_meta]]
# --- Negative ---
neg_tokens = clip.tokenize(neg_g)
neg_tokens["l"] = clip.tokenize(neg_l).get("l", [])
neg_tokens = _pad_token_groups(neg_tokens, clip)
num_groups_neg = len(neg_tokens.get("g", []))
neg_weight_groups_g = _weights_per_group_from_text(clip, neg_g, num_groups_neg)
neg_cond, neg_pooled, neg_meta = _encode_groups_with_weights(
clip, neg_tokens, neg_weight_groups_g,
width, height, crop_w, crop_h, target_width, target_height
)
negative = [[neg_cond, neg_meta]]
return (positive, negative)
NODE_CLASS_MAPPINGS = {
"SDXL_LongPromptWeightedEncode_NoDiffusers": SDXL_LongPromptWeightedEncode_NoDiffusers,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"SDXL_LongPromptWeightedEncode_NoDiffusers": "SDXL Long Prompt Weighted Encode (no-diffusers)",
}