this error come in comfyui when i use pulid : TypeError: forward_orig() takes from 7 to 9 positional arguments but 10 were given
Assistant
The error message you're encountering in ComfyUI indicates that a function is being called with the wrong number of arguments. Specifically, the function forward_orig() is expecting between 7 and 9 positional arguments, but it is receiving 10.
Here are some steps to diagnose and potentially resolve the issue:
Check Function Signature:
Review the definition of the forward_orig() function within the ComfyUI codebase or relevant library to understand the expected arguments and their order.
Trace the Call:
Identify where forward_orig() is being called in the code. Look for the line that triggers this error and examine which values are being passed to the function call.
Adjust the Arguments:
Ensure you're passing the correct number of arguments. Compare the arguments in the function call to the function signature and remove or adjust arguments as necessary.
Check for Updates:
If you are using an external library or plugin within ComfyUI, make sure it’s up to date. Sometimes such errors arise from mismatches between different versions of software components.
Review Recent Changes:
If this error started appearing after recent changes (e.g., updates, new plugins, code modifications), consider reviewing those changes as they might have introduced the discrepancy.
Consult Documentation:
If applicable, consult the documentation for ComfyUI or any integrated libraries or frameworks to understand if there has been an update or change in function signatures.
Check Community Forums:
If you're still stuck, consider reaching out to community forums or support channels for ComfyUI. It's possible others have encountered and resolved the same issue.
Unit Testing:
If possible, write or check existing unit tests for the function to better isolate what might be going wrong in the function call.
If you provide more context or code snippets around the forward_orig() call, I can try to offer more specific guidance.
User
some one do this and i cant understand iwant to send 2 codes that may you can help me
Assistant
Of course! Please provide the two code snippets, and I'll do my best to help you understand what's going wrong or suggest potential fixes.
User
this is : @@ -96,7 +96,9 @@ def forward_orig(
y: Tensor,
guidance: Tensor = None,
control=None,
transformer_options={},
) -> Tensor:
patches_replace = transformer_options.get("patches_replace", {})
if img.ndim != 3 or txt.ndim != 3:
raise ValueError("Input img and txt tensors must have 3 dimensions.")
for i, block in enumerate(self.single_blocks):
img = block(img, vec=vec, pe=pe)
if ("single_block", i) in blocks_replace:
def block_wrap(args):
out = {}
out["img"] = block(args["img"], vec=args["vec"], pe=args["pe"])
return out
out = blocks_replace[("single_block", i)]({"img": img, "vec": vec, "pe": pe}, {"original_block": block_wrap})
img = out["img"]
else:
img = block(img, vec=vec, pe=pe)
if control is not None: # Controlnet
control_o = control.get("output")
Assistant
It seems like you've shared a diff output showing changes made to some functions within a codebase, possibly in a PyTorch or similar framework. Particularly, you've shown changes related to forward_orig() and forward() functions, with modifications including transformer_options as a new argument and some changes in the internal logic related to block replacements.
Observations:
Changes in forward_orig:
Added transformer_options to forward() and forward_orig():
This additional parameter allows for passing customizable options, likely meant for transformer-specific configurations.
Handling blocks_replace:
The logic for handling blocks_replace has been added, allowing dynamic replacement and manipulation of block outputs based on keys like "single_block" and "double_block". This seems like advanced customization for model behavior.
Adjustments for control variable (ControlNet):
If control is provided, it includes conditions to integrate control inputs/outputs, which could be for advanced control flow or auxiliary data influencing results.
Error Diagnosis:
The error you mentioned ("TypeError: forward_orig() takes from 7 to 9 positional arguments but 10 were given") suggests a mismatch between what forward_orig() expects and what's being passed to it.
Potential Issue:
It seems like after changes, forward_orig should now accept transformer_options. Ensure calls to forward_orig in the code provide this argument if it's been incorporated there.
Suggestions:
Verify Calls:
Check all calls to forward_orig ensure they are updated to include the newly added transformer_options argument where expected.
Default Arguments:
Consider using a default empty dictionary or handling its absence gracefully within forward_orig to avoid issues with calls that might not include it.
Comprehensive Testing:
Since these appear to be significant changes, comprehensive testing or unit tests for function interfaces can prevent such issues from occurring.
Review All Invocation Points:
Make sure every place in your code that invokes forward_orig matches the expected signature. Look for other similar pattern functions.
If you still encounter issues or specific lines are suspected to be the cause, feel free to provide additional context or code sections where forward_orig is called.
User
i m begginer and i want you to say a solution that i copy paste in notepad ++ of comfyui lines considering above code
Assistant
To help you resolve the error you're encountering, I’ll provide a modified version of the relevant code snippet that you should be able to copy and paste directly into your script. Since your error message ("forward_orig() takes from 7 to 9 positional arguments but 10 were given") implies there's a mismatch in the number of arguments being passed, we need to ensure that the calls to forward_orig match its definition.
Here's a breakdown of necessary changes considering a typical scenario:
Adjust the forward_orig() Function Definition:
Ensure that the new parameter transformer_options is correctly added to the function and accounted for in all calls.
Update the Calls to forward_orig():
Make sure every call to forward_orig() includes the transformer_options parameter.
python
# Ensure this section defines the function correctly
def forward_orig(
img: Tensor,
img_ids: Tensor,
context: Tensor,
txt_ids: Tensor,
timestep: Tensor,
y: Tensor,
guidance: Tensor = None,
control=None,
transformer_options={}, # add the transformer_options parameter
) -> Tensor:
"""Your function logic remains unchanged."""
patches_replace = transformer_options.get("patches_replace", {})
# ... (rest of your original function logic)
# Ensure all calls to this function are updated as follows:
# Modify the call inside the forward function
def forward(self, x, timestep, context, y, guidance, control=None, transformer_options={}, **kwargs):
bs, c, h, w = x.shape
patch_size = 2
x = comfy.ldm.common_dit.pad_to_patch_size(x, (patch_size, patch_size))
img = "Derived from x"
img_ids = "Constructed img_ids"
txt_ids = torch.zeros((bs, context.shape[1], 3), device=x.device, dtype=x.dtype)
# Correctly calling forward_orig with transformer_options
out = self.forward_orig(img, img_ids, context, txt_ids, timestep, y, guidance, control, transformer_options)
return rearrange(out, "b (h w) (c ph pw) -> b c (h ph) (w pw)", h=h_len, w=w_len, ph=2, pw=2)[:, :, :h, :w]
User
can you high light in yello the changes? that i can copy past them to code lines?
Assistant
I'm unable to visually highlight text directly here, but I can show you the necessary changes by marking them clearly in comments. When you copy the code into a tool like Notepad++, you can manually highlight those lines or simply look for the # CHANGED comment at the end of each relevant line to identify modifications.
python
# Ensure this section defines the function correctly
def forward_orig(
img: Tensor,
img_ids: Tensor,
context: Tensor,
txt_ids: Tensor,
timestep: Tensor,
y: Tensor,
guidance: Tensor = None,
control=None,
transformer_options={}, # CHANGED: Added transformer_options parameter
) -> Tensor:
# Function logic remains unchanged
patches_replace = transformer_options.get("patches_replace", {})
# ... (rest of your original function logic)
# Ensure all calls to this function are updated as follows:
# Modify the call inside the forward function
def forward(self, x, timestep, context, y, guidance, control=None, transformer_options={}, **kwargs): # CHANGED: Added transformer_options parameter
bs, c, h, w = x.shape
patch_size = 2
x = comfy.ldm.common_dit.pad_to_patch_size(x, (patch_size, patch_size))
img = "Derived from x" # Assume your logic fills this in
img_ids = "Constructed img_ids" # Assume your logic fills this in
txt_ids = torch.zeros((bs, context.shape[1], 3), device=x.device, dtype=x.dtype)
# Correctly calling forward_orig with transformer_options
out = self.forward_orig(img, img_ids, context, txt_ids, timestep, y, guidance, control, transformer_options) # CHANGED: Added transformer_options argument
return rearrange(out, "b (h w) (c ph pw) -> b c (h ph) (w pw)", h=h_len, w=w_len, ph=2, pw=2)[:, :, :h, :w]
Explanation of Changes:
forward_orig() function definition:
Added transformer_options to the function signature.
forward() function definition:
Added transformer_options to the signature.
Call to forward_orig() inside forward():
Included transformer_options in the argument list.
If you're using a tool like Notepad++, you can search for the # CHANGED comment to quickly locate and mark these specific lines as modified or highlighted.
User
this is my code help me to correct it : def forward_orig(
self,
img: Tensor,
img_ids: Tensor,
txt: Tensor,
txt_ids: Tensor,
timesteps: Tensor,
y: Tensor,
guidance: Tensor = None,
control=None,
) -> Tensor:
if img.ndim != 3 or txt.ndim != 3:
raise ValueError("Input img and txt tensors must have 3 dimensions.")
code
# running on sequences img
img = self.img_in(img)
vec = self.time_in(timestep_embedding(timesteps, 256).to(img.dtype))
if self.params.guidance_embed:
if guidance is None:
raise ValueError("Didn't get guidance strength for guidance distilled model.")
vec = vec + self.guidance_in(timestep_embedding(guidance, 256).to(img.dtype))
vec = vec + self.vector_in(y)
txt = self.txt_in(txt)
ids = torch.cat((txt_ids, img_ids), dim=1)
pe = self.pe_embedder(ids)
ca_idx = 0
for i, block in enumerate(self.double_blocks):
img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
if control is not None: # Controlnet
control_i = control.get("input")
if i < len(control_i):
add = control_i[i]
if add is not None:
img += add
# PuLID attention
if self.pulid_data:
if i % self.pulid_double_interval == 0:
# Will calculate influence of all pulid nodes at once
for _, node_data in self.pulid_data.items():
if torch.any((node_data['sigma_start'] >= timesteps) & (timesteps >= node_data['sigma_end'])):
img = img + node_data['weight'] * self.pulid_ca[ca_idx](node_data['embedding'], img)
ca_idx += 1
img = torch.cat((txt, img), 1)
for i, block in enumerate(self.single_blocks):
img = block(img, vec=vec, pe=pe)
if control is not None: # Controlnet
control_o = control.get("output")
if i < len(control_o):
add = control_o[i]
if add is not None:
img[:, txt.shape[1] :, ...] += add
# PuLID attention
if self.pulid_data:
real_img, txt = img[:, txt.shape[1]:, ...], img[:, :txt.shape[1], ...]
if i % self.pulid_single_interval == 0:
# Will calculate influence of all nodes at once
for _, node_data in self.pulid_data.items():
if torch.any((node_data['sigma_start'] >= timesteps) & (timesteps >= node_data['sigma_end'])):
real_img = real_img + node_data['weight'] * self.pulid_ca[ca_idx](node_data['embedding'], real_img)
ca_idx += 1
img = torch.cat((txt, real_img), 1)
img = img[:, txt.shape[1] :, ...]
img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
return img
Assistant
Based on your provided code, it appears the issue might stem from needing to pass additional parameters (such as transformer_options) that were expected in your modified function signature. Let's revise your functions to ensure parameters match across definitions and calls.
Revised forward_orig Function
To resolve your issue, ensure all calls to forward_orig include any extra arguments needed. I'll show how you can modify the code while respecting the context you've provided. We'll add transformer_options in case it’s needed like in your previous context:
python
User
i do them and still not working and same error
Assistant
Let's go through the process of solving the error step by step to ensure consistency between the function definition and its calls. Since the error you're encountering states that forward_orig() is getting more arguments than expected, we need to double-check both the function signature and how it's being called.
To diagnose and fix the issue:
Function Definition:
Ensure the forward_orig() function definition is updated to include all necessary arguments, including any new ones like transformer_options.
Check All Calls to forward_orig():
Locate every call to forward_orig() in your codebase and ensure they match the function's signature. Specifically, make sure they do not pass more arguments than the function expects.
Here's a general approach:
Review of forward_orig()
python
def forward_orig(
self,
img: Tensor,
img_ids: Tensor,
txt: Tensor,
txt_ids: Tensor,
timesteps: Tensor,
y: Tensor,
guidance: Tensor = None,
control=None,
# If this parameter was added, ensure its use:
transformer_options={}, # Include transformer_options if needed
) -> Tensor:
# Function logic remains as intended...
# ensure all functionality accessing new parameters uses defaults as required
Check Calling Code
Look for every place in your code where you call forward_orig() and make sure the number of arguments aligns with its definition.
Example if called from another method:
python
# Example of ensuring the call matches the newly defined forward_orig
out = self.forward_orig(img, img_ids, txt, txt_ids, timesteps, y, guidance, control)
# Make sure not to pass transformer_options if not necessary
# OR if transformer_options should be passed, include it
out = self.forward_orig(img, img_ids, txt, txt_ids, timesteps, y, guidance, control, transformer_options)
User
Make sure not to pass transformer_options if not necessary
OR if transformer_options should be passed, include it should type in code?
Assistant
The comments provided were meant to guide you on potential solutions, depending on whether or not transformer_options is an intended parameter for your forward_orig() calls. If the intention isn't clear from your current code context, here's how you can manage both scenarios:
Scenario 1: transformer_options is Not Required
If transformer_options is not necessary for your function logic, make sure you are not passing it accidentally in any call. Ensure that the calls to forward_orig() only include the arguments explicitly defined in its signature and omit unnecessary extras.
Example Call:
python
# Call without transformer_options if not required
out = self.forward_orig(img, img_ids, txt, txt_ids, timesteps, y, guidance, control)
Scenario 2: transformer_options is Required
If transformer_options is indeed required and should be included in the function signature, ensure it is consistently passed from all places where you call forward_orig().
Example Call:
python
# Call with transformer_options if it needs to be included
out = self.forward_orig(img, img_ids, txt, txt_ids, timesteps, y, guidance, control, transformer_options)
Implement in Your Code
Depending on which of these scenarios applies to your code, ensure you adjust each call to forward_orig() across your codebase to match the target function signature. Here is how you could include this logic directly in your script:
Updated Code Snippet
Make sure your function call matches your intended scenario:
python
# Define the function assuming transformer_options is necessary
def forward_orig(
self,
img: Tensor,
img_ids: Tensor,
txt: Tensor,
txt_ids: Tensor,
timesteps: Tensor,
y: Tensor,
guidance: Tensor = None,
control=None,
transformer_options={}, # Assuming this should be part of function signature
) -> Tensor:
# Function logic...
pass
# Make sure every call matches the function's signature
out = self.forward_orig(
img, img_ids, txt, txt_ids, timesteps, y, guidance, control
# Add transformer_options here if it applies, otherwise, exclude it
)
Summary
The key is to ensure that your function calls match the expected number of arguments in your function definition. If a parameter like transformer_options is needed, include it consistently in both the definition and calls. If you find it's unnecessary, double-check that it's not being passed accidentally.
User
ok still not work
Assistant
I understand that this can be frustrating, especially when debugging code with complex functions. Let's approach this step-by-step to isolate the issue. Here's how you can tackle this systematically:
Step-by-Step Debugging Strategy
Verify Function Signature:
Double-check the definition of forward_orig to ensure it accurately reflects the parameters you intend to pass. Here’s what it should look like if transformer_options is needed:
Search your entire codebase for every instance where forward_orig is called. Ensure all calls match the function signature in terms of both the number and order of arguments.
python
# If transformer_options is not needed
out = self.forward_orig(img, img_ids, txt, txt_ids, timesteps, y, guidance, control)
# If transformer_options is needed
out = self.forward_orig(img, img_ids, txt, txt_ids, timesteps, y, guidance, control, transformer_options)
Check Error Tracebacks:
Run your code and carefully read the complete error traceback. It should tell you exactly where the function is being called incorrectly.
Use Debugging Prints:
Place print statements before each forward_orig call to display what’s being passed for each variable. This can help you confirm the number and types of arguments being sent.
def forward(self, x, timestep, context, y, guidance, control=None, **kwargs):
def forward(self, x, timestep, context, y, guidance, control=None, transformer_options={}, **kwargs):
bs, c, h, w = x.shape
patch_size = 2
x = comfy.ldm.common_dit.pad_to_patch_size(x, (patch_size, patch_size))
@@ -156,5 +178,5 @@ def forward(self, x, timestep, context, y, guidance, control=None, **kwargs):
img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
code
txt_ids = torch.zeros((bs, context.shape[1], 3), device=x.device, dtype=x.dtype)
out = self.forward_orig(img, img_ids, context, txt_ids, timestep, y, guidance, control)
out = self.forward_orig(img, img_ids, context, txt_ids, timestep, y, guidance, control, transformer_options)
return rearrange(out, "b (h w) (c ph pw) -> b c (h ph) (w pw)", h=h_len, w=w_len, ph=2, pw=2)[:,:,:h,:w]
1 change: 1 addition & 0 deletions1
comfy/utils.py
Original file line number Diff line number Diff line change
@@ -853,6 +853,7 @@ def reshape_mask(input_mask, output_shape):
dims = len(output_shape) - 2
code
if dims == 1:
mask = input_mask
scale_mode = "linear"
if dims == 2:
5 changes: 3 additions & 2 deletions5
comfy_extras/nodes_sd3.py
Original file line number Diff line number Diff line change
@@ -130,6 +130,9 @@ def skip(args, extra_args):
sigma_start = model_sampling.percent_to_sigma(start_percent)
sigma_end = model_sampling.percent_to_sigma(end_percent)
code
layers = re.findall(r'\d+', layers)
layers = [int(i) for i in layers]
def post_cfg_function(args):
model = args["model"]
cond_pred = args["cond_denoised"]
layers = re.findall(r'\d+', layers)
layers = [int(i) for i in layers]
m = model.clone()
m.set_model_sampler_post_cfg_function(post_cfg_function)
1 change: 1 addition & 0 deletions1
main.py
Original file line number Diff line number Diff line change
@@ -71,6 +71,7 @@ def execute_script(script_path):
if name == "main":
if args.cuda_device is not None:
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
os.environ['HIP_VISIBLE_DEVICES'] = str(args.cuda_device)
logging.info("Set cuda device to: {}".format(args.cuda_device))
code
if args.deterministic: and this is : @@ -96,7 +96,9 @@ def forward_orig(
y: Tensor,
guidance: Tensor = None,
control=None,
transformer_options={},
) -> Tensor:
patches_replace = transformer_options.get("patches_replace", {})
if img.ndim != 3 or txt.ndim != 3:
raise ValueError("Input img and txt tensors must have 3 dimensions.")
for i, block in enumerate(self.single_blocks):
img = block(img, vec=vec, pe=pe)
if ("single_block", i) in blocks_replace:
def block_wrap(args):
out = {}
out["img"] = block(args["img"], vec=args["vec"], pe=args["pe"])
return out
out = blocks_replace[("single_block", i)]({"img": img, "vec": vec, "pe": pe}, {"original_block": block_wrap})
img = out["img"]
else:
img = block(img, vec=vec, pe=pe)
if control is not None: # Controlnet
control_o = control.get("output")
def forward(self, x, timestep, context, y, guidance, control=None, **kwargs):
def forward(self, x, timestep, context, y, guidance, control=None, transformer_options={}, **kwargs):
bs, c, h, w = x.shape
patch_size = 2
x = comfy.ldm.common_dit.pad_to_patch_size(x, (patch_size, patch_size))
@@ -156,5 +178,5 @@ def forward(self, x, timestep, context, y, guidance, control=None, **kwargs):
img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
code
txt_ids = torch.zeros((bs, context.shape[1], 3), device=x.device, dtype=x.dtype)
out = self.forward_orig(img, img_ids, context, txt_ids, timestep, y, guidance, control)
out = self.forward_orig(img, img_ids, context, txt_ids, timestep, y, guidance, control, transformer_options)
return rearrange(out, "b (h w) (c ph pw) -> b c (h ph) (w pw)", h=h_len, w=w_len, ph=2, pw=2)[:,:,:h,:w]
1 change: 1 addition & 0 deletions1
comfy/utils.py
Original file line number Diff line number Diff line change
@@ -853,6 +853,7 @@ def reshape_mask(input_mask, output_shape):
dims = len(output_shape) - 2
code
if dims == 1:
mask = input_mask
scale_mode = "linear"
if dims == 2:
5 changes: 3 additions & 2 deletions5
comfy_extras/nodes_sd3.py
Original file line number Diff line number Diff line change
@@ -130,6 +130,9 @@ def skip(args, extra_args):
sigma_start = model_sampling.percent_to_sigma(start_percent)
sigma_end = model_sampling.percent_to_sigma(end_percent)
code
layers = re.findall(r'\d+', layers)
layers = [int(i) for i in layers]
def post_cfg_function(args):
model = args["model"]
cond_pred = args["cond_denoised"]
layers = re.findall(r'\d+', layers)
layers = [int(i) for i in layers]
m = model.clone()
m.set_model_sampler_post_cfg_function(post_cfg_function)
1 change: 1 addition & 0 deletions1
main.py
Original file line number Diff line number Diff line change
@@ -71,6 +71,7 @@ def execute_script(script_path):
if name == "main":
if args.cuda_device is not None:
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
os.environ['HIP_VISIBLE_DEVICES'] = str(args.cuda_device)
logging.info("Set cuda device to: {}".format(args.cuda_device))
code
if args.deterministic:
Key Points:
Function Signature: The function forward_orig should now include transformer_options.
Call Adjustments: Every call to forward_orig in your application should now pass transformer_options.
General Advice:
Consistent Function Signatures: Make sure the parameters in function definitions are consistently used in their respective calls throughout your project.
Learning and Debugging: Familiarize yourself with structured logging or debugging to trace parameter values, which can help catch these kinds of errors early on.
Let me know if there's anything specific you'd like me to clarify further!
def to_gray(img):
x = 0.299 * img[:, 0:1] + 0.587 * img[:, 1:2] + 0.114 * img[:, 2:3]
x = x.repeat(1, 3, 1, 1)
return x
"""
code
Nodes
"""
class PulidFluxModelLoader:
@classmethod
def INPUT_TYPES(s):
return {"required": {"pulid_file": (folder_paths.get_filename_list("pulid"), )}}
code
RETURN_TYPES = ("PULIDFLUX",)
FUNCTION = "load_model"
CATEGORY = "pulid"
def load_model(self, pulid_file):
model_path = folder_paths.get_full_path("pulid", pulid_file)
# Also initialize the model, takes longer to load but then it doesn't have to be done every time you change parameters in the apply node
model = PulidFluxModel()
logging.info("Loading PuLID-Flux model.")
model.from_pretrained(path=model_path)
return (model,)
RETURN_TYPES = ("MODEL",)
FUNCTION = "apply_pulid_flux"
CATEGORY = "pulid"
def __init__(self):
self.pulid_data_dict = None
def apply_pulid_flux(self, model, pulid_flux, eva_clip, face_analysis, image, weight, start_at, end_at, attn_mask=None, unique_id=None):
device = comfy.model_management.get_torch_device()
# Why should I care what args say, when the unet model has a different dtype?!
# Am I missing something?!
#dtype = comfy.model_management.unet_dtype()
dtype = model.model.diffusion_model.dtype
# Because of 8bit models we must check what cast type does the unet uses
# ZLUDA (Intel, AMD) & GPUs with compute capability < 8.0 don't support bfloat16 etc.
# Issue: https://github.com/balazik/ComfyUI-PuLID-Flux/issues/6
if model.model.manual_cast_dtype is not None:
dtype = model.model.manual_cast_dtype
eva_clip.to(device, dtype=dtype)
pulid_flux.to(device, dtype=dtype)
# TODO: Add masking support!
if attn_mask is not None:
if attn_mask.dim() > 3:
attn_mask = attn_mask.squeeze(-1)
elif attn_mask.dim() < 3:
attn_mask = attn_mask.unsqueeze(0)
attn_mask = attn_mask.to(device, dtype=dtype)
image = tensor_to_image(image)
face_helper = FaceRestoreHelper(
upscale_factor=1,
face_size=512,
crop_ratio=(1, 1),
det_model='retinaface_resnet50',
save_ext='png',
device=device,
)
face_helper.face_parse = None
face_helper.face_parse = init_parsing_model(model_name='bisenet', device=device)
bg_label = [0, 16, 18, 7, 8, 9, 14, 15]
cond = []
# Analyse multiple images at multiple sizes and combine largest area embeddings
for i in range(image.shape[0]):
# get insightface embeddings
iface_embeds = None
for size in [(size, size) for size in range(640, 256, -64)]:
face_analysis.det_model.input_size = size
face_info = face_analysis.get(image[i])
if face_info:
# Only use the maximum face
# Removed the reverse=True from original code because we need the largest area not the smallest one!
# Sorts the list in ascending order (smallest to largest),
# then selects the last element, which is the largest face
face_info = sorted(face_info, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))[-1]
iface_embeds = torch.from_numpy(face_info.embedding).unsqueeze(0).to(device, dtype=dtype)
break
else:
# No face detected, skip this image
logging.warning(f'Warning: No face detected in image {str(i)}')
continue
# get eva_clip embeddings
face_helper.clean_all()
face_helper.read_image(image[i])
face_helper.get_face_landmarks_5(only_center_face=True)
face_helper.align_warp_face()
if len(face_helper.cropped_faces) == 0:
# No face detected, skip this image
continue
# Get aligned face image
align_face = face_helper.cropped_faces[0]
# Convert bgr face image to tensor
align_face = image_to_tensor(align_face).unsqueeze(0).permute(0, 3, 1, 2).to(device)
parsing_out = face_helper.face_parse(functional.normalize(align_face, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]))[0]
parsing_out = parsing_out.argmax(dim=1, keepdim=True)
bg = sum(parsing_out == i for i in bg_label).bool()
white_image = torch.ones_like(align_face)
# Only keep the face features
face_features_image = torch.where(bg, white_image, to_gray(align_face))
# Transform img before sending to eva_clip
# Apparently MPS only supports NEAREST interpolation?
face_features_image = functional.resize(face_features_image, eva_clip.image_size, transforms.InterpolationMode.BICUBIC if 'cuda' in device.type else transforms.InterpolationMode.NEAREST).to(device, dtype=dtype)
face_features_image = functional.normalize(face_features_image, eva_clip.image_mean, eva_clip.image_std)
# eva_clip
id_cond_vit, id_vit_hidden = eva_clip(face_features_image, return_all_features=False, return_hidden=True, shuffle=False)
id_cond_vit = id_cond_vit.to(device, dtype=dtype)
for idx in range(len(id_vit_hidden)):
id_vit_hidden[idx] = id_vit_hidden[idx].to(device, dtype=dtype)
id_cond_vit = torch.div(id_cond_vit, torch.norm(id_cond_vit, 2, 1, True))
# Combine embeddings
id_cond = torch.cat([iface_embeds, id_cond_vit], dim=-1)
# Pulid_encoder
cond.append(pulid_flux.get_embeds(id_cond, id_vit_hidden))
if not cond:
# No faces detected, return the original model
logging.warning("PuLID warning: No faces detected in any of the given images, returning unmodified model.")
return (model,)
# average embeddings
cond = torch.cat(cond).to(device, dtype=dtype)
if cond.shape[0] > 1:
cond = torch.mean(cond, dim=0, keepdim=True)
sigma_start = model.get_model_object("model_sampling").percent_to_sigma(start_at)
sigma_end = model.get_model_object("model_sampling").percent_to_sigma(end_at)
# Patch the Flux model (original diffusion_model)
# Nah, I don't care for the official ModelPatcher because it's undocumented!
# I want the end result now, and I don’t mind if I break other custom nodes in the process. 😄
flux_model = model.model.diffusion_model
# Let's see if we already patched the underlying flux model, if not apply patch
if not hasattr(flux_model, "pulid_ca"):
# Add perceiver attention, variables and current node data (weight, embedding, sigma_start, sigma_end)
# The pulid_data is stored in Dict by unique node index,
# so we can chain multiple ApplyPulidFlux nodes!
flux_model.pulid_ca = pulid_flux.pulid_ca
flux_model.pulid_double_interval = pulid_flux.double_interval
flux_model.pulid_single_interval = pulid_flux.single_interval
flux_model.pulid_data = {}
# Replace model forward_orig with our own
new_method = forward_orig.__get__(flux_model, flux_model.__class__)
setattr(flux_model, 'forward_orig', new_method)
# Patch is already in place, add data (weight, embedding, sigma_start, sigma_end) under unique node index
flux_model.pulid_data[unique_id] = {
'weight': weight,
'embedding': cond,
'sigma_start': sigma_start,
'sigma_end': sigma_end,
}
# Keep a reference for destructor (if node is deleted the data will be deleted as well)
self.pulid_data_dict = {'data': flux_model.pulid_data, 'unique_id': unique_id}
return (model,)
def __del__(self):
# Destroy the data for this node
if self.pulid_data_dict:
del self.pulid_data_dict['data'][self.pulid_data_dict['unique_id']]
del self.pulid_data_dict
def forward_orig(
self,
img: Tensor,
img_ids: Tensor,
txt: Tensor,
txt_ids: Tensor,
timesteps: Tensor,
y: Tensor,
guidance: Tensor = None,
control=None,
transformer_options={}, # Ensure the function can accept transformer_options if necessary
) -> Tensor:
if img.ndim != 3 or txt.ndim != 3:
raise ValueError("Input img and txt tensors must have 3 dimensions.")
# running on sequences img
img = self.img_in(img)
vec = self.time_in(timestep_embedding(timesteps, 256).to(img.dtype))
if self.params.guidance_embed:
if guidance is None:
raise ValueError("Didn't get guidance strength for guidance distilled model.")
vec = vec + self.guidance_in(timestep_embedding(guidance, 256).to(img.dtype))
vec = vec + self.vector_in(y)
txt = self.txt_in(txt)
ids = torch.cat((txt_ids, img_ids), dim=1)
pe = self.pe_embedder(ids)
# Proceed with existing logic...
ca_idx = 0
for i, block in enumerate(self.double_blocks):
img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
if control is not None: # Controlnet
control_i = control.get("input")
if i < len(control_i):
add = control_i[i]
if add is not None:
img += add
# PuLID attention
if self.pulid_data:
if i % self.pulid_double_interval == 0:
for _, node_data in self.pulid_data.items():
if torch.any((node_data['sigma_start'] >= timesteps) & (timesteps >= node_data['sigma_end'])):
img = img + node_data['weight'] * self.pulid_ca[ca_idx](node_data['embedding'], img)
ca_idx += 1
img = torch.cat((txt, img), 1)
for i, block in enumerate(self.single_blocks):
img = block(img, vec=vec, pe=pe)
if control is not None: # Controlnet
control_o = control.get("output")
if i < len(control_o):
add = control_o[i]
if add is not None:
img[:, txt.shape[1]:, ...] += add
# PuLID attention
if self.pulid_data:
real_img, txt = img[:, txt.shape[1]:, ...], img[:, :txt.shape[1], ...]
if i % self.pulid_single_interval == 0:
for _, node_data in self.pulid_data.items():
if torch.any((node_data['sigma_start'] >= timesteps) & (timesteps >= node_data['sigma_end'])):
real_img = real_img + node_data['weight'] * self.pulid_ca[ca_idx](node_data['embedding'], real_img)
ca_idx += 1
img = torch.cat((txt, real_img), 1)
img = img[:, txt.shape[1]:, ...]
img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
return img
Adjustments for Usage
Ensure that every call to forward_orig in your other code provides transformer_options when needed. If you're calling forward_orig within another function (like forward), ensure to include transformer_options in those calls too, based on the structure reflected in your application's context.
Summary
Make sure all internal calls to forward_orig have their signatures updated to reflect these changes.
Validate that modifications such as adding placeholder parameters (like transformer_options) match across both definitions and usage instances.
Verify No Excess Arguments
Check for accidental addition of extra, unreferenced parameters in any call to forward_orig(). Ensure calls are limited to the defined parameters in forward_orig.
Debugging Steps
Print Statements: Before the call to forward_orig, you can add debug prints to check the variables being passed and to ensure they match expectations.
python
print("Arguments to forward_orig: ", img, img_ids, txt, txt_ids, timesteps, y, guidance, control, "transformer_options if applicable")
Error Traceback: Review the specific traceback from Python to locate exactly where the call to forward_orig() happens, as it might guide which code segment to adjust.
Parameter Defaulting: If you tried adding transformer_options as a new argument while it wasn’t intended, reconsider its necessity and if its presence breaks legacy calls.
If Issues Persist
Please verify that all changes are correctly saved and reflect across your working files.
Share the traceback of the error message to precisely spot faulty lines or points of mismatch.
print("Calling forward_orig with:")
print("img:", img.shape if isinstance(img, Tensor) else type(img))
print("img_ids:", img_ids.shape if isinstance(img_ids, Tensor) else type(img_ids))
print("txt:", txt.shape if isinstance(txt, Tensor) else type(txt))
print("txt_ids:", txt_ids.shape if isinstance(txt_ids, Tensor) else type(txt_ids))
print("timesteps:", timesteps if isinstance(timesteps, Tensor) else type(timesteps))
print("y:", y if isinstance(y, Tensor) else type(y))
print("guidance:", guidance if isinstance(guidance, Tensor) else type(guidance))
print("control:", control if control is not None else "None")
# Add transformer_options if relevant
print("transformer_options:", "Included" if 'transformer_options' in locals() else "Not included")
Simplifying the Problem:
Temporarily remove or comment out the optional parameters like transformer_options from forward_orig calls and the function definition to see if that resolves the issue, then add them back carefully.
Additional Considerations:
Ensure any default parameters (like transformer_options={}) in the function are correctly handled, so they don’t cause accidental additional argument inclusion during function calls.
By following these steps, you should be able to narrow down the root cause of the argument mismatch. If these debugging methods aren’t sufficient, consider sharing the specific Python traceback output—it might provide new clues to help pinpoint the problem.