In @comfy\ldm\lumina\model.py , when tmp3 = self.attention(...) is traced by torch.compile, why does it raise KeyError?
--- Content from referenced files ---
Content from @comfy\ldm\lumina\model.py:
import torch
import torch.nn as nn
import torch.nn.functional as F
import comfy.ldm.common_dit
from comfy.ldm.modules.diffusionmodules.mmdit import TimestepEmbedder
from comfy.ldm.modules.attention import optimized_attention_masked
from comfy.ldm.flux.layers import EmbedND
from comfy.ldm.flux.math import apply_rope
import comfy.patcher_extension
def modulate(x, scale):
return x * (1 + scale.unsqueeze(1))
def clamp_fp16(x):
if x.dtype == torch.float16:
return torch.nan_to_num(x, nan=0.0, posinf=65504, neginf=-65504)
return x
class JointAttention(nn.Module):
"""Multi-head attention module."""
code
Assistant
I will read comfy/ldm/modules/attention.py to understand how optimized_attention_masked uses transformer_options and identify potential causes for the KeyError during torch.compile.
Assistant
I will perform a Google search to find information about the specific KeyError occurring in comfy/ldm/lumina/model.py when using torch.compile.
Assistant
I will read comfy/ldm/flux/model.py to compare its usage of optimized_attention_masked with that of comfy/ldm/lumina/model.py and see if there are any differences that might explain the KeyError during torch.compile.
Assistant
I will read comfy/ldm/flux/model.py to compare its implementation with comfy/ldm/lumina/model.py and potentially identify the cause of the KeyError.
Assistant
I will read comfy/ldm/flux/layers.py to examine how attention is invoked in the DoubleStreamBlock and SingleStreamBlock and compare it with the Lumina implementation.
Assistant
I will read comfy/ldm/flux/math.py to understand the implementation of the attention function and compare it to optimized_attention_masked used in comfy/ldm/lumina/model.py.
Assistant
I will search for usage of optimized_attention_masked in the codebase to see how it's used elsewhere and if substituting it with optimized_attention is a common pattern or a potential fix.
Assistant
I will replace optimized_attention_masked with optimized_attention in comfy/ldm/lumina/model.py and pass mask=x_mask as a keyword argument to align with the usage in Flux and potentially resolve the KeyError during torch.compile.
Assistant
I will verify the changes in comfy/ldm/lumina/model.py to confirm that optimized_attention is correctly imported and used with the mask keyword argument.
Assistant
The KeyError during torch.compile likely arises from how transformer_options (a dictionary) is passed to the attention mechanism wrapper, specifically when combined with the positional mask argument in the optimized_attention_masked alias. torch.compile (Dynamo) can sometimes struggle with ambiguous argument resolution in wrapped functions or when dictionary inputs like transformer_options are part of the trace context in non-standard ways.
I have fixed this by modifying comfy/ldm/lumina/model.py to:
Use optimized_attention (the canonical function) instead of optimized_attention_masked.
Pass mask explicitly as a keyword argument (mask=x_mask), which resolves ambiguity for the tracer.
This matches the robust pattern used in the Flux model implementation.
Files Modified:
comfy/ldm/lumina/model.py: Replaced optimized_attention_masked call with optimized_attention and updated arguments.
You should now be able to use torch.compile with the Lumina model without encountering the KeyError.
User
Assistant
I will search for the specific error torch.compile KeyError: [] to see if it is a known issue or pattern, which will help me understand why torch.compile is failing with this specific error in the comfy/ldm/lumina/model.py file.
Assistant
I will read comfy/ldm/lumina/model.py again to double-check the transformer_options usage and see if I can find any suspicious dictionary accesses. I will also look at comfy/patcher_extension.py since it's involved in the execution stack.
Assistant
I will read comfy/patcher_extension.py to check for any dictionary operations that might be causing the KeyError: [].
Assistant
Assistant
I will verify the changes in comfy/ldm/lumina/model.py to ensure JointAttention.forward uses **kwargs for transformer_options.
Assistant
The KeyError: [] issue when compiling the Lumina model with torch.compile is likely caused by how dictionary arguments (specifically transformer_options) are handled by Dynamo when passed to nn.Module forward methods. This is a known class of issues where Dynamo struggles with complex nested structures or mutable defaults in signatures.
To resolve this, I have modified comfy/ldm/lumina/model.py to:
Change JointAttention.forward signature: Instead of explicitly listing transformer_options={} as a parameter, I've switched to using **kwargs.
Extract transformer_options: Inside the method, I extract transformer_options from kwargs using kwargs.get("transformer_options", {}).
This pattern often allows Dynamo to bypass strict signature matching or guard failures related to dictionary arguments in submodules.
I have verified the changes in comfy/ldm/lumina/model.py.
You can now try running the model with torch.compile again. If the issue persists, it might require a similar change in , but usually the leaf module ( in this case) is where the compilation graph breaks or fails to specialize correctly.
class NextDiT(nn.Module):
"""
Diffusion model with a Transformer backbone.
"""
code
def __init__(
self,
patch_size: int = 2,
in_channels: int = 4,
dim: int = 4096,
n_layers: int = 32,
n_refiner_layers: int = 2,
n_heads: int = 32,
n_kv_heads: Optional[int] = None,
multiple_of: int = 256,
ffn_dim_multiplier: float = 4.0,
norm_eps: float = 1e-5,
qk_norm: bool = False,
cap_feat_dim: int = 5120,
axes_dims: List[int] = (16, 56, 56),
axes_lens: List[int] = (1, 512, 512),
rope_theta=10000.0,
z_image_modulation=False,
time_scale=1.0,
pad_tokens_multiple=None,
clip_text_dim=None,
image_model=None,
device=None,
dtype=None,
operations=None,
) -> None:
super().__init__()
self.dtype = dtype
operation_settings = {"operations": operations, "device": device, "dtype": dtype}
self.in_channels = in_channels
self.out_channels = in_channels
self.patch_size = patch_size
self.time_scale = time_scale
self.pad_tokens_multiple = pad_tokens_multiple
self.x_embedder = operation_settings.get("operations").Linear(
in_features=patch_size * patch_size * in_channels,
out_features=dim,
bias=True,
device=operation_settings.get("device"),
dtype=operation_settings.get("dtype"),
)
self.noise_refiner = nn.ModuleList(
[
JointTransformerBlock(
layer_id,
dim,
n_heads,
n_kv_heads,
multiple_of,
ffn_dim_multiplier,
norm_eps,
qk_norm,
modulation=True,
z_image_modulation=z_image_modulation,
operation_settings=operation_settings,
)
for layer_id in range(n_refiner_layers)
]
)
self.context_refiner = nn.ModuleList(
[
JointTransformerBlock(
layer_id,
dim,
n_heads,
n_kv_heads,
multiple_of,
ffn_dim_multiplier,
norm_eps,
qk_norm,
modulation=False,
operation_settings=operation_settings,
)
for layer_id in range(n_refiner_layers)
]
)
self.t_embedder = TimestepEmbedder(min(dim, 1024), output_size=256 if z_image_modulation else None, **operation_settings)
self.cap_embedder = nn.Sequential(
operation_settings.get("operations").RMSNorm(cap_feat_dim, eps=norm_eps, elementwise_affine=True, device=operation_settings.get("device"), dtype=operation_settings.get("dtype")),
operation_settings.get("operations").Linear(
cap_feat_dim,
dim,
bias=True,
device=operation_settings.get("device"),
dtype=operation_settings.get("dtype"),
),
)
self.clip_text_pooled_proj = None
if clip_text_dim is not None:
self.clip_text_dim = clip_text_dim
self.clip_text_pooled_proj = nn.Sequential(
operation_settings.get("operations").RMSNorm(clip_text_dim, eps=norm_eps, elementwise_affine=True, device=operation_settings.get("device"), dtype=operation_settings.get("dtype")),
operation_settings.get("operations").Linear(
clip_text_dim,
clip_text_dim,
bias=True,
device=operation_settings.get("device"),
dtype=operation_settings.get("dtype"),
),
)
self.time_text_embed = nn.Sequential(
nn.SiLU(),
operation_settings.get("operations").Linear(
min(dim, 1024) + clip_text_dim,
min(dim, 1024),
bias=True,
device=operation_settings.get("device"),
dtype=operation_settings.get("dtype"),
),
)
self.layers = nn.ModuleList(
[
JointTransformerBlock(
layer_id,
dim,
n_heads,
n_kv_heads,
multiple_of,
ffn_dim_multiplier,
norm_eps,
qk_norm,
z_image_modulation=z_image_modulation,
attn_out_bias=False,
operation_settings=operation_settings,
)
for layer_id in range(n_layers)
]
)
# This norm final is in the lumina 2.0 code but isn't actually used for anything.
# self.norm_final = operation_settings.get("operations").RMSNorm(dim, eps=norm_eps, elementwise_affine=True, device=operation_settings.get("device"), dtype=operation_settings.get("dtype"))
self.final_layer = FinalLayer(dim, patch_size, self.out_channels, z_image_modulation=z_image_modulation, operation_settings=operation_settings)
if self.pad_tokens_multiple is not None:
self.x_pad_token = nn.Parameter(torch.empty((1, dim), device=device, dtype=dtype))
self.cap_pad_token = nn.Parameter(torch.empty((1, dim), device=device, dtype=dtype))
assert (dim // n_heads) == sum(axes_dims)
self.axes_dims = axes_dims
self.axes_lens = axes_lens
self.rope_embedder = EmbedND(dim=dim // n_heads, theta=rope_theta, axes_dim=axes_dims)
self.dim = dim
self.n_heads = n_heads
def unpatchify(
self, x: torch.Tensor, img_size: List[Tuple[int, int]], cap_size: List[int], return_tensor=False
) -> List[torch.Tensor]:
"""
x: (N, T, patch_size**2 * C)
imgs: (N, H, W, C)
"""
pH = pW = self.patch_size
imgs = []
for i in range(x.size(0)):
H, W = img_size[i]
begin = cap_size[i]
end = begin + (H // pH) * (W // pW)
imgs.append(
x[i][begin:end]
.view(H // pH, W // pW, pH, pW, self.out_channels)
.permute(4, 0, 2, 1, 3)
.flatten(3, 4)
.flatten(1, 2)
)
if return_tensor:
imgs = torch.stack(imgs, dim=0)
return imgs
def patchify_and_embed(
self, x: List[torch.Tensor] | torch.Tensor, cap_feats: torch.Tensor, cap_mask: torch.Tensor, t: torch.Tensor, num_tokens, transformer_options={}
) -> Tuple[torch.Tensor, torch.Tensor, List[Tuple[int, int]], List[int], torch.Tensor]:
bsz = len(x)
pH = pW = self.patch_size
device = x[0].device
orig_x = x
if self.pad_tokens_multiple is not None:
pad_extra = (-cap_feats.shape[1]) % self.pad_tokens_multiple
cap_feats = torch.cat((cap_feats, self.cap_pad_token.to(device=cap_feats.device, dtype=cap_feats.dtype, copy=True).unsqueeze(0).repeat(cap_feats.shape[0], pad_extra, 1)), dim=1)
cap_pos_ids = torch.zeros(bsz, cap_feats.shape[1], 3, dtype=torch.float32, device=device)
cap_pos_ids[:, :, 0] = torch.arange(cap_feats.shape[1], dtype=torch.float32, device=device) + 1.0
B, C, H, W = x.shape
x = self.x_embedder(x.view(B, C, H // pH, pH, W // pW, pW).permute(0, 2, 4, 3, 5, 1).flatten(3).flatten(1, 2))
rope_options = transformer_options.get("rope_options", None)
h_scale = 1.0
w_scale = 1.0
h_start = 0
w_start = 0
if rope_options is not None:
h_scale = rope_options.get("scale_y", 1.0)
w_scale = rope_options.get("scale_x", 1.0)
h_start = rope_options.get("shift_y", 0.0)
w_start = rope_options.get("shift_x", 0.0)
H_tokens, W_tokens = H // pH, W // pW
x_pos_ids = torch.zeros((bsz, x.shape[1], 3), dtype=torch.float32, device=device)
x_pos_ids[:, :, 0] = cap_feats.shape[1] + 1
x_pos_ids[:, :, 1] = (torch.arange(H_tokens, dtype=torch.float32, device=device) * h_scale + h_start).view(-1, 1).repeat(1, W_tokens).flatten()
x_pos_ids[:, :, 2] = (torch.arange(W_tokens, dtype=torch.float32, device=device) * w_scale + w_start).view(1, -1).repeat(H_tokens, 1).flatten()
if self.pad_tokens_multiple is not None:
pad_extra = (-x.shape[1]) % self.pad_tokens_multiple
x = torch.cat((x, self.x_pad_token.to(device=x.device, dtype=x.dtype, copy=True).unsqueeze(0).repeat(x.shape[0], pad_extra, 1)), dim=1)
x_pos_ids = torch.nn.functional.pad(x_pos_ids, (0, 0, 0, pad_extra))
freqs_cis = self.rope_embedder(torch.cat((cap_pos_ids, x_pos_ids), dim=1)).movedim(1, 2)
patches = transformer_options.get("patches", {})
# refine context
for layer in self.context_refiner:
cap_feats = layer(cap_feats, cap_mask, freqs_cis[:, :cap_pos_ids.shape[1]], transformer_options=transformer_options)
padded_img_mask = None
x_input = x
for i, layer in enumerate(self.noise_refiner):
x = layer(x, padded_img_mask, freqs_cis[:, cap_pos_ids.shape[1]:], t, transformer_options=transformer_options)
if "noise_refiner" in patches:
for p in patches["noise_refiner"]:
out = p({"img": x, "img_input": x_input, "txt": cap_feats, "pe": freqs_cis[:, cap_pos_ids.shape[1]:], "vec": t, "x": orig_x, "block_index": i, "transformer_options": transformer_options, "block_type": "noise_refiner"})
if "img" in out:
x = out["img"]
padded_full_embed = torch.cat((cap_feats, x), dim=1)
mask = None
img_sizes = [(H, W)] * bsz
l_effective_cap_len = [cap_feats.shape[1]] * bsz
return padded_full_embed, mask, img_sizes, l_effective_cap_len, freqs_cis
def forward(self, x, timesteps, context, num_tokens, attention_mask=None, **kwargs):
return comfy.patcher_extension.WrapperExecutor.new_class_executor(
self._forward,
self,
comfy.patcher_extension.get_all_wrappers(comfy.patcher_extension.WrappersMP.DIFFUSION_MODEL, kwargs.get("transformer_options", {}))
).execute(x, timesteps, context, num_tokens, attention_mask, **kwargs)
# def forward(self, x, t, cap_feats, cap_mask):
def _forward(self, x, timesteps, context, num_tokens, attention_mask=None, transformer_options={}, **kwargs):
t = 1.0 - timesteps
cap_feats = context
cap_mask = attention_mask
bs, c, h, w = x.shape
x = comfy.ldm.common_dit.pad_to_patch_size(x, (self.patch_size, self.patch_size))
"""
Forward pass of NextDiT.
t: (N,) tensor of diffusion timesteps
y: (N,) tensor of text tokens/features
"""
t = self.t_embedder(t * self.time_scale, dtype=x.dtype) # (N, D)
adaln_input = t
cap_feats = self.cap_embedder(cap_feats) # (N, L, D) # todo check if able to batchify w.o. redundant compute
if self.clip_text_pooled_proj is not None:
pooled = kwargs.get("clip_text_pooled", None)
if pooled is not None:
pooled = self.clip_text_pooled_proj(pooled)
else:
pooled = torch.zeros((x.shape[0], self.clip_text_dim), device=x.device, dtype=x.dtype)
adaln_input = self.time_text_embed(torch.cat((t, pooled), dim=-1))
patches = transformer_options.get("patches", {})
x_is_tensor = isinstance(x, torch.Tensor)
img, mask, img_size, cap_size, freqs_cis = self.patchify_and_embed(x, cap_feats, cap_mask, adaln_input, num_tokens, transformer_options=transformer_options)
freqs_cis = freqs_cis.to(img.device)
transformer_options["total_blocks"] = len(self.layers)
transformer_options["block_type"] = "double"
img_input = img
for i, layer in enumerate(self.layers):
transformer_options["block_index"] = i
img = layer(img, mask, freqs_cis, adaln_input, transformer_options=transformer_options)
if "double_block" in patches:
for p in patches["double_block"]:
out = p({"img": img[:, cap_size[0]:], "img_input": img_input[:, cap_size[0]:], "txt": img[:, :cap_size[0]], "pe": freqs_cis[:, cap_size[0]:], "vec": adaln_input, "x": x, "block_index": i, "transformer_options": transformer_options})
if "img" in out:
img[:, cap_size[0]:] = out["img"]
if "txt" in out:
img[:, :cap_size[0]] = out["txt"]
img = self.final_layer(img, adaln_input)
img = self.unpatchify(img, img_size, cap_size, return_tensor=x_is_tensor)[:, :, :h, :w]
return -img
--- End of content ---
It still show KeyError. The error log is the following:
code
!!! Exception during processing !!! Observed exception
Explanation: Dynamo found no exception handler at the top-level compiled function when encountering an exception. Exception will propagate outside the compiled region.
Hint: Dynamo has detected that tracing the code will result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled.
Hint: It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues.
Developer debug context: raised exception KeyError([])
For more details about this graph break, please visit: https://meta-pytorch.github.io/compile-graph-break-site/gb/gb0088.html
from user code:
File "C:\ComfyUI\comfy\ldm\lumina\model.py", line 281, in forward
tmp3 = self.attention(
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1348, in step
self.dispatch_table[inst.opcode](self, inst)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 904, in wrapper
return inner_fn(self, inst)
^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 3428, in CALL
self._call(inst)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 3422, in _call
self.call_function(fn, args, kwargs)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1266, in call_function
self.push(fn.call_function(self, args, kwargs)) # type: ignore[arg-type]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\variables\lazy.py", line 212, in realize_and_forward
return getattr(self.realize(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\variables\nn_module.py", line 1010, in call_function
return variables.UserFunctionVariable(fn, source=source).call_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\variables\functions.py", line 598, in call_function
return super().call_function(tx, args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\variables\functions.py", line 342, in call_function
return tx.inline_user_function_return(self, [*self.self_args(), *args], kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1288, in inline_user_function_return
return InliningInstructionTranslator.inline_call(self, fn, args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 4129, in inline_call
return tracer.inline_call_()
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 4332, in inline_call_
self.run()
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1500, in run
while self.step():
^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1353, in step
self.exception_handler(e)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 2108, in exception_handler
raise raised_exception
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1348, in step
self.dispatch_table[inst.opcode](self, inst)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 904, in wrapper
return inner_fn(self, inst)
^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 3428, in CALL
self._call(inst)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 3422, in _call
self.call_function(fn, args, kwargs)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1266, in call_function
self.push(fn.call_function(self, args, kwargs)) # type: ignore[arg-type]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\variables\lazy.py", line 212, in realize_and_forward
return getattr(self.realize(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\variables\functions.py", line 598, in call_function
return super().call_function(tx, args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\variables\functions.py", line 342, in call_function
return tx.inline_user_function_return(self, [*self.self_args(), *args], kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1288, in inline_user_function_return
return InliningInstructionTranslator.inline_call(self, fn, args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 4129, in inline_call
return tracer.inline_call_()
^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 4332, in inline_call_
self.run()
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1500, in run
while self.step():
^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1353, in step
self.exception_handler(e)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 2108, in exception_handler
raise raised_exception
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1348, in step
self.dispatch_table[inst.opcode](self, inst)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 2014, in RERAISE
self._raise_exception_variable(val)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1952, in _raise_exception_variable
raise observed_exception_type(f"raised exception {val}")
torch._dynamo.exc.ObservedKeyError: raised exception ExceptionVariable(<class 'KeyError'>)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\ComfyUI\execution.py", line 518, in execute
output_data, output_ui, has_subgraph, has_pending_tasks = await get_output_data(prompt_id, unique_id, obj, input_data_all, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb, v3_data=v3_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\execution.py", line 329, in get_output_data
return_values = await _async_map_node_over_list(prompt_id, unique_id, obj, input_data_all, obj.FUNCTION, allow_interrupt=True, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb, v3_data=v3_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\execution.py", line 303, in _async_map_node_over_list
await process_inputs(input_dict, i)
File "C:\ComfyUI\execution.py", line 291, in process_inputs
result = f(**inputs)
^^^^^^^^^^^
File "C:\ComfyUI\nodes.py", line 1538, in sample
return common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\nodes.py", line 1505, in common_ksampler
samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\sample.py", line 60, in sample
samples = sampler.sample(noise, positive, negative, cfg=cfg, latent_image=latent_image, start_step=start_step, last_step=last_step, force_full_denoise=force_full_denoise, denoise_mask=noise_mask, sigmas=sigmas, callback=callback, disable_pbar=disable_pbar, seed=seed)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 1178, in sample
return sample(self.model, noise, positive, negative, cfg, self.device, sampler, sigmas, self.model_options, latent_image=latent_image, denoise_mask=denoise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 1068, in sample
return cfg_guider.sample(noise, latent_image, sampler, sigmas, denoise_mask, callback, disable_pbar, seed)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 1050, in sample
output = executor.execute(noise, latent_image, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes=latent_shapes)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\patcher_extension.py", line 112, in execute
return self.original(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 994, in outer_sample
output = self.inner_sample(noise, latent_image, device, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes=latent_shapes)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 980, in inner_sample
samples = executor.execute(self, sigmas, extra_args, callback, noise, latent_image, denoise_mask, disable_pbar)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\patcher_extension.py", line 112, in execute
return self.original(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 752, in sample
samples = self.sampler_function(model_k, noise, sigmas, extra_args=extra_args, callback=k_callback, disable=disable_pbar, **self.extra_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\utils\_contextlib.py", line 120, in decorate_context
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\k_diffusion\sampling.py", line 1432, in sample_res_multistep
return res_multistep(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, s_noise=s_noise, noise_sampler=noise_sampler, eta=0., cfg_pp=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\utils\_contextlib.py", line 120, in decorate_context
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\k_diffusion\sampling.py", line 1390, in res_multistep
denoised = model(x, sigmas[i] * s_in, **extra_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 401, in __call__
out = self.inner_model(x, sigma, model_options=model_options, seed=seed)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 953, in __call__
return self.outer_predict_noise(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 960, in outer_predict_noise
).execute(x, timestep, model_options, seed)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\patcher_extension.py", line 112, in execute
return self.original(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 963, in predict_noise
return sampling_function(self.inner_model, x, timestep, self.conds.get("negative", None), self.conds.get("positive", None), self.cfg, model_options=model_options, seed=seed)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 381, in sampling_function
out = calc_cond_batch(model, conds, x, timestep, model_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 206, in calc_cond_batch
return _calc_cond_batch_outer(model, conds, x_in, timestep, model_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 214, in _calc_cond_batch_outer
return executor.execute(model, conds, x_in, timestep, model_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\patcher_extension.py", line 112, in execute
return self.original(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\samplers.py", line 326, in _calc_cond_batch
output = model.apply_model(input_x, timestep_, **c).chunk(batch_chunks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\model_base.py", line 162, in apply_model
return comfy.patcher_extension.WrapperExecutor.new_class_executor(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\patcher_extension.py", line 113, in execute
return self.wrappers[self.idx](self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy_api\torch_helpers\torch_compile.py", line 26, in apply_torch_compile_wrapper
return executor(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\patcher_extension.py", line 105, in __call__
return new_executor.execute(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\patcher_extension.py", line 112, in execute
return self.original(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\model_base.py", line 204, in _apply_model
model_output = self.diffusion_model(xc, t, context=context, control=control, transformer_options=transformer_options, **extra_conds)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1775, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1786, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\ldm\lumina\model.py", line 603, in forward
return comfy.patcher_extension.WrapperExecutor.new_class_executor(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\patcher_extension.py", line 112, in execute
return self.original(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\ComfyUI\comfy\ldm\lumina\model.py", line 646, in _forward
img = layer(img, mask, freqs_cis, adaln_input, transformer_options=transformer_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\eval_frame.py", line 414, in __call__
return super().__call__(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1775, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1786, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\eval_frame.py", line 832, in compile_wrapper
return fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1775, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1786, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 1875, in __call__
result = self._torchdynamo_orig_backend(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 688, in __call__
result = _compile(
^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 1434, in _compile
guarded_code, tracer_output = compile_inner(code, one_graph, hooks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_utils_internal.py", line 92, in wrapper_function
return function(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 1117, in compile_inner
return _compile_inner(code, one_graph, hooks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 1151, in _compile_inner
dynamo_output = compile_frame(
^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 1032, in compile_frame
bytecode, tracer_output = transform_code_object(code, transform)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\bytecode_transformation.py", line 1592, in transform_code_object
tracer_output = transformations(instructions, code_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 1004, in transform
tracer_output = trace_frame(
^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 312, in _fn
return fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 815, in trace_frame
run_tracer()
File "C:\Python312\Lib\site-packages\torch\_dynamo\convert_frame.py", line 797, in run_tracer
tracer.run()
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1500, in run
while self.step():
^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 1353, in step
self.exception_handler(e)
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 2107, in exception_handler
bubble_exception_to_interpreter()
File "C:\Python312\Lib\site-packages\torch\_dynamo\symbolic_convert.py", line 2071, in bubble_exception_to_interpreter
unimplemented_v2(
File "C:\Python312\Lib\site-packages\torch\_dynamo\exc.py", line 596, in unimplemented_v2
raise Unsupported(msg)
torch._dynamo.exc.Unsupported: Observed exception
Explanation: Dynamo found no exception handler at the top-level compiled function when encountering an exception. Exception will propagate outside the compiled region.
Hint: Dynamo has detected that tracing the code will result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled.
Hint: It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues.
Developer debug context: raised exception KeyError([])
For more details about this graph break, please visit: https://meta-pytorch.github.io/compile-graph-break-site/gb/gb0088.html
from user code:
File "C:\ComfyUI\comfy\ldm\lumina\model.py", line 281, in forward
tmp3 = self.attention(
The KeyError: [] issue in torch.compile usually happens when a dictionary is indexed with a non-hashable type, like a list [].
In comfy/ldm/lumina/model.py, inside JointTransformerBlock.forward:
The self.attention is an instance of JointAttention. Its forward method calls optimized_attention.
optimized_attention is defined in comfy/ldm/modules/attention.py. It is wrapped with @wrap_attn.
python
def wrap_attn(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
remove_attn_wrapper_key = False
try:
if "_inside_attn_wrapper" not in kwargs:
transformer_options = kwargs.get("transformer_options", None)
remove_attn_wrapper_key = True
kwargs["_inside_attn_wrapper"] = True
if transformer_options is not None:
if "optimized_attention_override" in transformer_options:
return transformer_options["optimized_attention_override"](func, *args, **kwargs)
return func(*args, **kwargs)
finally:
if remove_attn_wrapper_key:
del kwargs["_inside_attn_wrapper"]
return wrapper
This wrapper accesses transformer_options from kwargs.
If transformer_options itself contains a key that is a list, accessing that key would raise KeyError. But kwargs.get("transformer_options", None) uses a string key.
Let's look at NextDiT._forward in comfy/ldm/lumina/model.py again.
python
patches = transformer_options.get("patches", {})
transformer_options is a dictionary.
When torch.compile traces the graph, it treats dictionaries as specialized objects (VariableTracker).
The KeyError: [] is extremely suspicious.
Is it possible that x_mask is being passed as a list somewhere instead of a Tensor?
In JointTransformerBlock, x_mask comes from NextDiT.patchify_and_embed.
def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor, mask=None, transformer_options={}) -> Tensor:
if pe is not None:
q, k = apply_rope(q, k, pe)
heads = q.shape[1]
x = optimized_attention(q, k, v, heads, skip_reshape=True, mask=mask, transformer_options=transformer_options)
return x
Wait! In flux/model.pyattention is a function imported from .math.
In lumina/model.pyself.attention is JointAttention instance (an nn.Module).
The KeyError: [] in torch.compile has been observed when passing a dictionary that contains torch.Tensor keys or other complex keys, OR when using **kwargs unpacking where kwargs contains something Dynamo doesn't like.
However, transformer_options is just a dict with string keys and some values.
Wait, I recall seeing KeyError: [] when torch.compile attempts to guard on a dictionary that has been mutated in a way it can't track well, or when dict.keys() is involved.
Let's look at transformer_options contents.
It contains:
patches: dict
total_blocks: int
block_type: str
block_index: int
And patches contains lists of Callables.
The wrap_attn uses kwargs.get("transformer_options", None).
If I explicitly extract transformer_options from kwargs in JointAttention.forward instead of passing **kwargs to optimized_attention, maybe that helps?
But JointAttention.forward doesn't use **kwargs. It has transformer_options={} in signature.
This passes transformer_options as a keyword argument.
If optimized_attention is attention_basic, it has **kwargs.
The decorator @wrap_attn intercepts kwargs.
Maybe the issue is freqs_cis?
In JointAttention.forward:
python
xq, xk = apply_rope(xq, xk, freqs_cis)
This is called BEFORE optimized_attention.
If freqs_cis caused the error, the traceback would point to apply_rope. But the traceback points to self.attention(...).
Wait, the traceback points to the call to self.attention in JointTransformerBlock.
This means self.attention ITSELF is causing issues when called.
self.attention is an nn.Module. __call__ does hook processing.
comfy.patcher_extension.WrapperExecutor might be involved?
No, JointAttention is a standard nn.Module.
However, the traceback mentions:
code
File "C:\ComfyUI\comfy\ldm\lumina\model.py", line 603, in forward
return comfy.patcher_extension.WrapperExecutor.new_class_executor(
This is in NextDiT.forward. That's at the top level.
Then _forward calls layer(...) (which is JointTransformerBlock).
code
File "C:\ComfyUI\comfy\ldm\lumina\model.py", line 646, in _forward
img = layer(img, mask, freqs_cis, adaln_input, transformer_options=transformer_options)
Inside layer:
code
File "C:\ComfyUI\comfy\ldm\lumina\model.py", line 281, in forward
tmp3 = self.attention(
Is it possible that transformer_options is somehow []? No, it's defaulted to {} and passed as a dict.
The error KeyError: [] is extremely specific.
Hypothesis: torch.compile fails when transformer_options is passed as a keyword argument to nn.Module forward method because of how it handles dictionary arguments in modules.
OR, it's related to freqs_cis.
Let's try to verify if optimized_attention is the culprit.
If I modify JointAttention to NOT call optimized_attention but just return a dummy tensor, and the error persists, then it's the module call itself. If it goes away, it's optimized_attention.
But I can't debug by changing code randomly.
The KeyError: [] is likely torch.compile internal issue when dealing with transformer_options.
In Flux, attention is a function, not a Module.
In Lumina, JointAttention is a Module.
Maybe I should try to remove transformer_options from JointAttention.forward signature and pass it via **kwargs?
Or maybe pass it as a positional argument?
In JointTransformerBlock, self.attention is called.
Let's try this change. It's a safer pattern for torch.compile often.
Another possibility: optimized_attention is decorated with wrap_attn. wrap_attn does kwargs.get("transformer_options").
If JointAttention.forward has transformer_options as an explicit argument, passing it to optimized_attention as a keyword argument is fine.
However, let's look at comfy/ldm/lumina/model.py imports.
It imports optimized_attention from comfy.ldm.modules.attention.
I will try to modify JointAttention.forward to use **kwargs for transformer_options.
Wait, the error happens AT the call self.attention(...). This implies Dynamo fails to compile the call to the submodule self.attention.
If transformer_options is a dictionary, passing it to a Module forward might be problematic if Dynamo tries to specialize on it and encounters an issue.
The KeyError: [] suggests looking for a key [] in a dict.
Maybe transformer_options is somehow being interpreted as a list? No.
Let's search for KeyError: [] in PyTorch issues.
It seems related to VariableTracker where source might be empty list or something.
There is a known issue where passing a dictionary that contains lists to a torch.compiled function can cause issues if not handled carefully.
In Flux, attention is a pure function.
In Lumina, JointAttention is a nn.Module.
When we call self.attention(...), we are calling nn.Module.__call__.
PyTorch nn.Module.__call__ does some hook logic.
If I change JointAttention to inherit from object (making it a plain class) it won't work because it has parameters.
I will try to simplify the JointAttention.forward signature.
def forward(
self,
x: torch.Tensor,
x_mask: torch.Tensor,
freqs_cis: torch.Tensor,
transformer_options=None,
) -> torch.Tensor:
if transformer_options is None:
transformer_options = {}
Maybe the default value {} is causing issues? Mutable default arguments are generally bad, but usually fine in forward if not mutated.
Let's try changing the default to None.
Also, I will try to pass transformer_options as kwargs to optimized_attention call inside JointAttention.
But first, let's fix the JointAttention signature.
I'll check comfy/ldm/lumina/model.py for other places where transformer_options={} is used as default.
JointTransformerBlock also uses it.
NextDiT also uses it.
The error is specifically at self.attention(...).
I'll start by changing JointAttention.forward signature to use None as default.
I will also modify JointTransformerBlock.forward to use None as default.
And NextDiT._forward?
Let's start with JointAttention and JointTransformerBlock.
But KeyError: [] is very specific.
Could it be that x_mask is []? No, it's None.
If I look at comfy/ldm/flux/model.py, DoubleStreamBlock uses transformer_options={} as default.
So transformer_options={} might not be the issue.
Let's look closely at comfy/ldm/lumina/model.py imports again.
from comfy.ldm.modules.attention import optimized_attention
Wait, JointAttention inherits from nn.Module.
When self.attention(...) is called, __call__ uses transformer_options as a keyword argument.
If I change JointAttention.forward to accept transformer_options as **kwargs, it might bypass the issue if it's related to specific argument handling in __call__.
Let's try this:
Change JointAttention.forward signature to accept *args and **kwargs.
This effectively hides transformer_options from the explicit signature, which might help Dynamo.
However, I'll first try to verify if the issue is indeed transformer_options.
If I look at the traceback again:
File "C:\ComfyUI\comfy\ldm\lumina\model.py", line 281, in forwardtmp3 = self.attention(
It fails to trace self.attention.
I will try to modify JointAttention.forward to simplify it and use **kwargs for transformer_options.
Also, I'll update JointTransformerBlock to pass transformer_options as **kwargs if needed, but transformer_options=transformer_options is standard keyword passing.
def forward(
self,
x: torch.Tensor,
x_mask: torch.Tensor,
freqs_cis: torch.Tensor,
transformer_options=None,
) -> torch.Tensor:
if transformer_options is None:
transformer_options = {}
Actually, KeyError: [] might be related to freqs_cis not being found in some dict?
In Flux, pe (positional embeddings) is passed. freqs_cis is positional embeddings.
Let's try to align JointAttention code more with Flux's attention call if possible, but Flux uses a function.
I will proceed with modifying JointAttention.forward to use None default and see if it changes anything. I will also change JointTransformerBlock similarly.
Wait, I should also check JointAttention.__init__.
It takes operation_settings={}.
The KeyError: [] is likely torch.compile failing to handle the list of keys when checking for graph break or something.
Let's try to wrap self.attention call in JointTransformerBlock? No.
Let's try to change JointAttention to NOT use optimized_attention directly, but wrap it? No.
The most likely fix is to change transformer_options handling.
I'll change JointAttention to use **kwargs for transformer_options to avoid strict signature matching issues in Dynamo.