Refactor this repo to properly use transformer_options["block_index"] rather than reimplementing every model in @patches.py . See C:\ComfyUI\comfy\ldm\wan\model.py and other relevant files for how transformer_options["block_index"] is defined.
--- Content from referenced files ---
Content from @patches.py:
import comfy
import torch
from comfy.ldm.wan.model import sinusoidal_embedding_1d
from tqdm import tqdm
_initialized = False
_original_functions = {}
if not _initialized:
_original_functions["orig_attention"] = comfy.ldm.modules.attention.optimized_attention
_initialized = True
# embeddings
x = self.patch_embedding(x.float()).to(x.dtype)
grid_sizes = x.shape[2:]
x = x.flatten(2).transpose(1, 2)
# time embeddings
e = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, t.flatten()).to(dtype=x[0].dtype))
e = e.reshape(t.shape[0], -1, e.shape[-1])
e0 = self.time_projection(e).unflatten(2, (6, self.dim))
full_ref = None
if self.ref_conv is not None:
full_ref = kwargs.get("reference_latent", None)
if full_ref is not None:
full_ref = self.ref_conv(full_ref).flatten(2).transpose(1, 2)
x = torch.concat((full_ref, x), dim=1)
# context
context = self.text_embedding(context)
context_img_len = None
if clip_fea is not None:
if self.img_emb is not None:
context_clip = self.img_emb(clip_fea) # bs x 257 x dim
context = torch.concat([context_clip, context], dim=1)
context_img_len = clip_fea.shape[-2]
patches_replace = transformer_options.get("patches_replace", {})
blocks_replace = patches_replace.get("dit", {})
# Unapply before the 0-th layer in case it's not unapplied because of interrupt previously
tqdm.write("Unapply radial attn")
comfy.ldm.wan.model.optimized_attention = _original_functions.get("orig_attention")
for i, block in enumerate(self.blocks):
if i == ra_options["dense_block"]:
tqdm.write(f"Apply radial attn from layer {i}")
comfy.ldm.wan.model.optimized_attention = ra_options["radial_attn_func"]
if ("double_block", i) in blocks_replace:
def block_wrap(args):
out = {}
out["img"] = block(
args["img"], context=args["txt"], e=args["vec"], freqs=args["pe"], context_img_len=context_img_len, transformer_options=args["transformer_options"]
)
return out
out = blocks_replace[("double_block", i)](
{"img": x, "txt": context, "vec": e0, "pe": freqs, "transformer_options": transformer_options}, {"original_block": block_wrap}
)
x = out["img"]
else:
x = block(x, e=e0, freqs=freqs, context=context, context_img_len=context_img_len, transformer_options=transformer_options)
tqdm.write("Unapply radial attn")
comfy.ldm.wan.model.optimized_attention = _original_functions.get("orig_attention")
# head
x = self.head(x, e)
if full_ref is not None:
x = x[:, full_ref.shape[1] :]
# unpatchify
x = self.unpatchify(x, grid_sizes)
return x
Assistant
I will read the relevant files to understand the current implementation and how transformer_options["block_index"] is utilized in the codebase.
Assistant
I will refactor patches.py to use transformer_options["block_index"] by dynamically patching comfy.ldm.wan.model.optimized_attention within a unet_wrapper_function. This approach avoids reimplementing the full forward pass of the models. I will remove the now unnecessary forward patch functions (_WanModel_forward_orig, etc.) and the instance patching logic. I will also update get_radial_attn_func to properly forward transformer_options and kwargs to the fallback attention function.
Assistant
I will read __init__.py and nodes.py to ensure that the project structure and imports are consistent with the changes made to patches.py.
Assistant
I will revert the changes to patches.py to contain only the necessary shared state (_original_functions) and remove the model reimplementations. Then, I will update nodes.py to include the corrected get_radial_attn_func and the new PatchRadialAttn implementation that utilizes dynamic patching.
Assistant
I have refactored the repository to properly use transformer_options["block_index"] instead of reimplementing model forward passes.
Changes:
Refactored nodes.py:
Implemented a unet_wrapper_function that dynamically patches comfy.ldm.wan.model.optimized_attention using unittest.mock.patch during model execution.
Added smart_attention logic which checks transformer_options["block_index"] to conditionally apply radial attention only for blocks after dense_block.
Updated get_radial_attn_func to correctly forward kwargs (including transformer_options) to the original attention function when falling back (e.g., for cross-attention).
Cleaned patches.py:
Removed all _WanModel_forward_orig, _HumoWanModel_forward_orig, _AnimateWanModel_forward_orig functions and the patched_forward dictionary.
It now only retains the _original_functions state to store the original reference.
Assistant
The refactoring is complete. The logic for applying radial attention now relies on transformer_options["block_index"] and dynamic patching of the attention function, eliminating the need for copy-pasted model forward methods.
Summary of changes:
nodes.py: Now contains the main logic. It installs a UNet wrapper that patches comfy.ldm.wan.model.optimized_attention with a smart_attention function. This function checks the block index and applies radial attention only when appropriate, falling back to the original attention otherwise.
patches.py: Cleaned up to only store the reference to the original optimized_attention function, removing all the bulky forward pass reimplementations.
# embeddings
x = self.patch_embedding(x.float()).to(x.dtype)
x, motion_vec = self.after_patch_embedding(x, pose_latents, face_pixel_values)
grid_sizes = x.shape[2:]
x = x.flatten(2).transpose(1, 2)
# time embeddings
e = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, t.flatten()).to(dtype=x[0].dtype))
e = e.reshape(t.shape[0], -1, e.shape[-1])
e0 = self.time_projection(e).unflatten(2, (6, self.dim))
full_ref = None
if self.ref_conv is not None:
full_ref = kwargs.get("reference_latent", None)
if full_ref is not None:
full_ref = self.ref_conv(full_ref).flatten(2).transpose(1, 2)
x = torch.concat((full_ref, x), dim=1)
# context
context = self.text_embedding(context)
context_img_len = None
if clip_fea is not None:
if self.img_emb is not None:
context_clip = self.img_emb(clip_fea) # bs x 257 x dim
context = torch.concat([context_clip, context], dim=1)
context_img_len = clip_fea.shape[-2]
patches_replace = transformer_options.get("patches_replace", {})
blocks_replace = patches_replace.get("dit", {})
# Unapply before the 0-th layer in case it's not unapplied because of interrupt previously
tqdm.write("Unapply radial attn")
comfy.ldm.wan.model.optimized_attention = _original_functions.get("orig_attention")
for i, block in enumerate(self.blocks):
if i == ra_options["dense_block"]:
tqdm.write(f"Apply radial attn from layer {i}")
comfy.ldm.wan.model.optimized_attention = ra_options["radial_attn_func"]
if ("double_block", i) in blocks_replace:
def block_wrap(args):
out = {}
out["img"] = block(
args["img"], context=args["txt"], e=args["vec"], freqs=args["pe"], context_img_len=context_img_len, transformer_options=args["transformer_options"]
)
return out
out = blocks_replace[("double_block", i)](
{"img": x, "txt": context, "vec": e0, "pe": freqs, "transformer_options": transformer_options}, {"original_block": block_wrap}
)
x = out["img"]
else:
x = block(x, e=e0, freqs=freqs, context=context, context_img_len=context_img_len, transformer_options=transformer_options)
if i % 5 == 0 and motion_vec is not None:
# Disable radial_attn on face_adapter
_optimized_attention = comfy.ldm.wan.model.optimized_attention
_optimized_attention = _original_functions.get("orig_attention")
x = x + self.face_adapter.fuser_blocks[i // 5](x, motion_vec)
comfy.ldm.wan.model.optimized_attention = _optimized_attention
tqdm.write("Unapply radial attn")
comfy.ldm.wan.model.optimized_attention = _original_functions.get("orig_attention")
# head
x = self.head(x, e)
if full_ref is not None:
x = x[:, full_ref.shape[1] :]
# unpatchify
x = self.unpatchify(x, grid_sizes)
return x
patched_forward["AnimateWanModel"] = _AnimateWanModel_forward_orig
--- End of content ---
optimized_attention
This solution avoids code duplication and is compatible with different WanModel variants without needing specific forward patches for each.