Upload 2 files
Browse files- __init__.py.py +3 -0
- sd3-weighted-embeddings-comfyui.py +252 -0
__init__.py.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .sd3_embedding_nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
| 2 |
+
|
| 3 |
+
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
|
sd3-weighted-embeddings-comfyui.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SD3 Weighted Embeddings Node for ComfyUI
|
| 3 |
+
This provides functionality similar to the SD3 embedding functionality from the sd_embed library.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import re
|
| 8 |
+
from comfy.sd3 import SD3Model, SD3Tokenizer, TextEncoderSD3, MAX_TEXT_LEN
|
| 9 |
+
import comfy.model_management as model_management
|
| 10 |
+
import comfy.utils
|
| 11 |
+
|
| 12 |
+
class SD3WeightedEmbeddings:
|
| 13 |
+
@classmethod
|
| 14 |
+
def INPUT_TYPES(cls):
|
| 15 |
+
return {
|
| 16 |
+
"required": {
|
| 17 |
+
"model": ("MODEL",),
|
| 18 |
+
"positive_prompt": ("STRING", {"multiline": True}),
|
| 19 |
+
"negative_prompt": ("STRING", {"multiline": True, "default": ""}),
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "CONDITIONING", "CONDITIONING")
|
| 24 |
+
RETURN_NAMES = ("prompt_embeds", "negative_prompt_embeds", "pooled_prompt_embeds", "negative_pooled_prompt_embeds")
|
| 25 |
+
FUNCTION = "process"
|
| 26 |
+
CATEGORY = "conditioning"
|
| 27 |
+
|
| 28 |
+
def process(self, model, positive_prompt, negative_prompt):
|
| 29 |
+
# Get SD3 models from the ComfyUI model
|
| 30 |
+
try:
|
| 31 |
+
text_encoders = model.text_encoders
|
| 32 |
+
tokenizers = model.tokenizers
|
| 33 |
+
except AttributeError:
|
| 34 |
+
raise ValueError("This node only works with SD3 models.")
|
| 35 |
+
|
| 36 |
+
# Get weighted text embeddings for positive prompt
|
| 37 |
+
(prompt_embeds, pooled_prompt_embeds) = self.get_weighted_embeddings(
|
| 38 |
+
text_encoders=text_encoders,
|
| 39 |
+
tokenizers=tokenizers,
|
| 40 |
+
prompt=positive_prompt
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# Get weighted text embeddings for negative prompt
|
| 44 |
+
(negative_prompt_embeds, negative_pooled_prompt_embeds) = self.get_weighted_embeddings(
|
| 45 |
+
text_encoders=text_encoders,
|
| 46 |
+
tokenizers=tokenizers,
|
| 47 |
+
prompt=negative_prompt
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# Convert to ComfyUI conditioning format
|
| 51 |
+
prompt_cond = [[prompt_embeds, {"pooled_output": pooled_prompt_embeds}]]
|
| 52 |
+
negative_cond = [[negative_prompt_embeds, {"pooled_output": negative_pooled_prompt_embeds}]]
|
| 53 |
+
|
| 54 |
+
return (
|
| 55 |
+
prompt_cond,
|
| 56 |
+
negative_cond,
|
| 57 |
+
[[pooled_prompt_embeds, {}]],
|
| 58 |
+
[[negative_pooled_prompt_embeds, {}]]
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def get_weighted_embeddings(self, text_encoders, tokenizers, prompt):
|
| 62 |
+
# Parse weights from the prompt
|
| 63 |
+
parsed_prompts = self.parse_prompt_attention(prompt)
|
| 64 |
+
|
| 65 |
+
# Convert to ComfyUI format
|
| 66 |
+
parsed_prompts = [(text, float(weight)) for text, weight in parsed_prompts]
|
| 67 |
+
|
| 68 |
+
# Tokenize and encode the text
|
| 69 |
+
device = model_management.get_torch_device()
|
| 70 |
+
chunk_count = len(text_encoders)
|
| 71 |
+
|
| 72 |
+
# Process each text part
|
| 73 |
+
text_embeddings = []
|
| 74 |
+
pooled_embeddings = []
|
| 75 |
+
|
| 76 |
+
for text, weight in parsed_prompts:
|
| 77 |
+
tokens = []
|
| 78 |
+
for i, tokenizer in enumerate(tokenizers):
|
| 79 |
+
token = tokenizer(
|
| 80 |
+
text,
|
| 81 |
+
padding="max_length",
|
| 82 |
+
max_length=MAX_TEXT_LEN,
|
| 83 |
+
truncation=True,
|
| 84 |
+
return_tensors="pt",
|
| 85 |
+
).input_ids.to(device)
|
| 86 |
+
tokens.append(token)
|
| 87 |
+
|
| 88 |
+
# Process with each encoder
|
| 89 |
+
for i, text_encoder in enumerate(text_encoders):
|
| 90 |
+
with torch.no_grad():
|
| 91 |
+
encoder_hidden_states, pooled_output = text_encoder(tokens[i % len(tokens)])
|
| 92 |
+
encoder_hidden_states = encoder_hidden_states * weight # Apply weight
|
| 93 |
+
|
| 94 |
+
if i == 0:
|
| 95 |
+
# For the first encoder, initialize the embeddings
|
| 96 |
+
text_embedding = encoder_hidden_states
|
| 97 |
+
pooled_embedding = pooled_output
|
| 98 |
+
else:
|
| 99 |
+
# For other encoders, concatenate
|
| 100 |
+
text_embedding = torch.cat([text_embedding, encoder_hidden_states], dim=-1)
|
| 101 |
+
pooled_embedding = torch.cat([pooled_embedding, pooled_output], dim=-1)
|
| 102 |
+
|
| 103 |
+
text_embeddings.append(text_embedding)
|
| 104 |
+
pooled_embeddings.append(pooled_embedding)
|
| 105 |
+
|
| 106 |
+
# Combine all text parts
|
| 107 |
+
if len(text_embeddings) > 1:
|
| 108 |
+
final_embedding = torch.cat(text_embeddings, dim=1)
|
| 109 |
+
final_pooled = torch.mean(torch.stack(pooled_embeddings), dim=0)
|
| 110 |
+
else:
|
| 111 |
+
final_embedding = text_embeddings[0]
|
| 112 |
+
final_pooled = pooled_embeddings[0]
|
| 113 |
+
|
| 114 |
+
return final_embedding, final_pooled
|
| 115 |
+
|
| 116 |
+
def parse_prompt_attention(self, text):
|
| 117 |
+
"""
|
| 118 |
+
Parses a string with attention tokens and returns a list of (text, weight) pairs.
|
| 119 |
+
Attention tokens are in the form of (text:weight) or (text) where text is a string
|
| 120 |
+
and weight is a float.
|
| 121 |
+
"""
|
| 122 |
+
re_attention = r"\([^:]+:[^:]+\)"
|
| 123 |
+
re_weight = r":[^:]+\)"
|
| 124 |
+
|
| 125 |
+
res = []
|
| 126 |
+
|
| 127 |
+
for match_weights in re.finditer(re_attention, text):
|
| 128 |
+
start_pos = match_weights.start()
|
| 129 |
+
end_pos = match_weights.end()
|
| 130 |
+
|
| 131 |
+
# Extract weight value
|
| 132 |
+
weight_match = re.search(re_weight, match_weights.group(0))
|
| 133 |
+
if weight_match is not None:
|
| 134 |
+
weight_str = weight_match.group(0)[1:-1]
|
| 135 |
+
try:
|
| 136 |
+
weight = float(weight_str)
|
| 137 |
+
except ValueError:
|
| 138 |
+
print(f"Warning: invalid weight '{weight_str}', using weight of 1.0")
|
| 139 |
+
weight = 1.0
|
| 140 |
+
else:
|
| 141 |
+
weight = 1.0
|
| 142 |
+
|
| 143 |
+
# Extract content
|
| 144 |
+
content = match_weights.group(0)
|
| 145 |
+
content = re.sub(r":[^:]+\)", ")", content)
|
| 146 |
+
content = content[1:-1]
|
| 147 |
+
|
| 148 |
+
res.append((content, weight))
|
| 149 |
+
|
| 150 |
+
# Add any remaining text with default weight
|
| 151 |
+
parsed_text = text
|
| 152 |
+
for match_weights in re.finditer(re_attention, text):
|
| 153 |
+
parsed_text = parsed_text.replace(match_weights.group(0), "", 1)
|
| 154 |
+
|
| 155 |
+
if parsed_text.strip():
|
| 156 |
+
res.append((parsed_text, 1.0))
|
| 157 |
+
|
| 158 |
+
return res
|
| 159 |
+
|
| 160 |
+
# SD3 Embedding Visualizer Node
|
| 161 |
+
class SD3EmbeddingVisualizer:
|
| 162 |
+
@classmethod
|
| 163 |
+
def INPUT_TYPES(cls):
|
| 164 |
+
return {
|
| 165 |
+
"required": {
|
| 166 |
+
"prompt_embeds": ("CONDITIONING",),
|
| 167 |
+
"method": (["PCA", "TSNE", "UMAP"],),
|
| 168 |
+
"width": ("INT", {"default": 800, "min": 256, "max": 2048}),
|
| 169 |
+
"height": ("INT", {"default": 800, "min": 256, "max": 2048}),
|
| 170 |
+
}
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
RETURN_TYPES = ("IMAGE",)
|
| 174 |
+
FUNCTION = "visualize"
|
| 175 |
+
CATEGORY = "conditioning/visualization"
|
| 176 |
+
|
| 177 |
+
def visualize(self, prompt_embeds, method, width, height):
|
| 178 |
+
try:
|
| 179 |
+
import numpy as np
|
| 180 |
+
from sklearn.decomposition import PCA
|
| 181 |
+
import matplotlib.pyplot as plt
|
| 182 |
+
from matplotlib.figure import Figure
|
| 183 |
+
from io import BytesIO
|
| 184 |
+
from PIL import Image
|
| 185 |
+
except ImportError:
|
| 186 |
+
raise ImportError("This node requires scikit-learn, matplotlib, and PIL. Please install them.")
|
| 187 |
+
|
| 188 |
+
# Extract embeddings from the conditioning
|
| 189 |
+
embeddings = prompt_embeds[0][0]
|
| 190 |
+
|
| 191 |
+
# Flatten and convert to numpy
|
| 192 |
+
embeddings_np = embeddings[0].reshape(embeddings.shape[1], -1).cpu().numpy()
|
| 193 |
+
|
| 194 |
+
# Apply dimensionality reduction
|
| 195 |
+
if method == "PCA":
|
| 196 |
+
reducer = PCA(n_components=2)
|
| 197 |
+
reduced_data = reducer.fit_transform(embeddings_np)
|
| 198 |
+
elif method == "TSNE":
|
| 199 |
+
try:
|
| 200 |
+
from sklearn.manifold import TSNE
|
| 201 |
+
reducer = TSNE(n_components=2, init='pca', random_state=42)
|
| 202 |
+
reduced_data = reducer.fit_transform(embeddings_np)
|
| 203 |
+
except ImportError:
|
| 204 |
+
raise ImportError("TSNE requires scikit-learn to be installed.")
|
| 205 |
+
elif method == "UMAP":
|
| 206 |
+
try:
|
| 207 |
+
import umap
|
| 208 |
+
reducer = umap.UMAP()
|
| 209 |
+
reduced_data = reducer.fit_transform(embeddings_np)
|
| 210 |
+
except ImportError:
|
| 211 |
+
raise ImportError("UMAP requires umap-learn to be installed.")
|
| 212 |
+
|
| 213 |
+
# Create visualization
|
| 214 |
+
fig = Figure(figsize=(width/100, height/100), dpi=100)
|
| 215 |
+
ax = fig.add_subplot(111)
|
| 216 |
+
|
| 217 |
+
scatter = ax.scatter(reduced_data[:, 0], reduced_data[:, 1],
|
| 218 |
+
c=np.arange(reduced_data.shape[0]),
|
| 219 |
+
cmap='viridis',
|
| 220 |
+
alpha=0.8)
|
| 221 |
+
|
| 222 |
+
# Add labels for tokens if not too many
|
| 223 |
+
if reduced_data.shape[0] < 30:
|
| 224 |
+
for i in range(reduced_data.shape[0]):
|
| 225 |
+
ax.annotate(str(i), (reduced_data[i, 0], reduced_data[i, 1]))
|
| 226 |
+
|
| 227 |
+
ax.set_title(f'CLIP Embeddings ({method})')
|
| 228 |
+
ax.set_xlabel('Dimension 1')
|
| 229 |
+
ax.set_ylabel('Dimension 2')
|
| 230 |
+
fig.colorbar(scatter, ax=ax, label='Token Index')
|
| 231 |
+
|
| 232 |
+
# Convert figure to image
|
| 233 |
+
buf = BytesIO()
|
| 234 |
+
fig.savefig(buf, format='png')
|
| 235 |
+
buf.seek(0)
|
| 236 |
+
|
| 237 |
+
# Convert to ComfyUI image format
|
| 238 |
+
pil_image = Image.open(buf)
|
| 239 |
+
image_tensor = torch.from_numpy(np.array(pil_image).astype(np.float32) / 255.0).unsqueeze(0)
|
| 240 |
+
|
| 241 |
+
return (image_tensor,)
|
| 242 |
+
|
| 243 |
+
# Register the nodes
|
| 244 |
+
NODE_CLASS_MAPPINGS = {
|
| 245 |
+
"SD3WeightedEmbeddings": SD3WeightedEmbeddings,
|
| 246 |
+
"SD3EmbeddingVisualizer": SD3EmbeddingVisualizer
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 250 |
+
"SD3WeightedEmbeddings": "SD3 Weighted Embeddings",
|
| 251 |
+
"SD3EmbeddingVisualizer": "SD3 Embedding Visualizer"
|
| 252 |
+
}
|