ComfyUI icon indicating copy to clipboard operation
ComfyUI copied to clipboard

Cannot use TextEncodeQwenImageEdit node: RuntimeError: shape '[84, -1, 128]' is invalid for input of size 5175296

Open antonpetrovmain opened this issue 1 year ago • 27 comments

Custom Node Testing

Your question

I get an error when trying to use Qwen Image Edit model in ComfyUI:

This is my workflow: qwen-image-edit.json

Logs

(.venv) anton@Antons-Mac-Studio ComfyUI % python3 main.py 
[START] Security scan
[DONE] Security scan
## ComfyUI-Manager: installing dependencies done.
** ComfyUI startup time: 2025-08-19 11:32:59.666
** Platform: Darwin
** Python version: 3.13.5 (main, Jun 11 2025, 15:36:57) [Clang 17.0.0 (clang-1700.0.13.3)]
** Python executable: /Users/anton/tools/ComfyUI/.venv/bin/python3
** ComfyUI Path: /Users/anton/tools/ComfyUI
** ComfyUI Base Folder Path: /Users/anton/tools/ComfyUI
** User directory: /Users/anton/tools/ComfyUI/user
** ComfyUI-Manager config path: /Users/anton/tools/ComfyUI/user/default/ComfyUI-Manager/config.ini
** Log path: /Users/anton/tools/ComfyUI/user/comfyui.log

Prestartup times for custom nodes:
   0.2 seconds: /Users/anton/tools/ComfyUI/custom_nodes/comfyui-manager

Checkpoint files will always be loaded safely.
Total VRAM 98304 MB, total RAM 98304 MB
pytorch version: 2.8.0
Mac Version (15, 6)
Set vram state to: SHARED
Device: mps
Using sub quadratic optimization for attention, if you have memory or speed issues try using: --use-split-cross-attention
Python version: 3.13.5 (main, Jun 11 2025, 15:36:57) [Clang 17.0.0 (clang-1700.0.13.3)]
ComfyUI version: 0.3.50
ComfyUI frontend version: 1.25.9
[Prompt Server] web root: /Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/comfyui_frontend_package/static
### Loading: ComfyUI-Manager (V3.36)
[ComfyUI-Manager] network_mode: public
### ComfyUI Version: v0.3.50-27-g4977f203 | Released on '2025-08-18'
ComfyUI-GGUF: Allowing full torch compile

Import times for custom nodes:
   0.0 seconds: /Users/anton/tools/ComfyUI/custom_nodes/websocket_image_save.py
   0.0 seconds: /Users/anton/tools/ComfyUI/custom_nodes/ComfyUI-GGUF
   0.1 seconds: /Users/anton/tools/ComfyUI/custom_nodes/comfyui-manager

[ComfyUI-Manager] default cache updated: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/model-list.json
[ComfyUI-Manager] default cache updated: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/alter-list.json
[ComfyUI-Manager] default cache updated: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/github-stats.json
[ComfyUI-Manager] default cache updated: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/custom-node-list.json
[ComfyUI-Manager] default cache updated: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/extension-node-map.json
Context impl SQLiteImpl.
Will assume non-transactional DDL.
No target revision found.
Starting server

To see the GUI go to: http://127.0.0.1:8188
FETCH ComfyRegistry Data: 5/94
FETCH ComfyRegistry Data: 10/94
FETCH ComfyRegistry Data: 15/94
FETCH ComfyRegistry Data: 20/94
FETCH ComfyRegistry Data: 25/94
FETCH ComfyRegistry Data: 30/94
FETCH ComfyRegistry Data: 35/94
FETCH ComfyRegistry Data: 40/94
FETCH ComfyRegistry Data: 45/94
got prompt
Using split attention in VAE
Using split attention in VAE
VAE load device: mps, offload device: cpu, dtype: torch.bfloat16
Using scaled fp8: fp8 matrix mult: False, scale input: False
Requested to load QwenImageTEModel_
loaded completely 9.5367431640625e+25 7909.737449645996 True
CLIP/text encoder model load device: cpu, offload device: cpu, current: cpu, dtype: torch.float16
FETCH ComfyRegistry Data: 50/94
Requested to load WanVAE
loaded completely 9.5367431640625e+25 242.02829551696777 True
FETCH ComfyRegistry Data: 55/94
FETCH ComfyRegistry Data: 60/94
!!! Exception during processing !!! shape '[84, -1, 128]' is invalid for input of size 5175296
Traceback (most recent call last):
  File "/Users/anton/tools/ComfyUI/execution.py", line 496, 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, hidden_inputs=hidden_inputs)
                                                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/execution.py", line 315, 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, hidden_inputs=hidden_inputs)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/execution.py", line 289, in _async_map_node_over_list
    await process_inputs(input_dict, i)
  File "/Users/anton/tools/ComfyUI/execution.py", line 277, in process_inputs
    result = f(**inputs)
  File "/Users/anton/tools/ComfyUI/comfy_extras/nodes_qwen.py", line 55, in encode
    conditioning = clip.encode_from_tokens_scheduled(tokens)
  File "/Users/anton/tools/ComfyUI/comfy/sd.py", line 170, in encode_from_tokens_scheduled
    pooled_dict = self.encode_from_tokens(tokens, return_pooled=return_pooled, return_dict=True)
  File "/Users/anton/tools/ComfyUI/comfy/sd.py", line 232, in encode_from_tokens
    o = self.cond_stage_model.encode_token_weights(tokens)
  File "/Users/anton/tools/ComfyUI/comfy/text_encoders/qwen_image.py", line 51, in encode_token_weights
    out, pooled, extra = super().encode_token_weights(token_weight_pairs)
                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/comfy/sd1_clip.py", line 686, in encode_token_weights
    out = getattr(self, self.clip).encode_token_weights(token_weight_pairs)
  File "/Users/anton/tools/ComfyUI/comfy/sd1_clip.py", line 45, in encode_token_weights
    o = self.encode(to_encode)
  File "/Users/anton/tools/ComfyUI/comfy/sd1_clip.py", line 291, in encode
    return self(tokens)
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl
    return forward_call(*args, **kwargs)
  File "/Users/anton/tools/ComfyUI/comfy/sd1_clip.py", line 264, in forward
    outputs = self.transformer(None, attention_mask_model, embeds=embeds, num_tokens=num_tokens, intermediate_output=intermediate_output, final_layer_norm_intermediate=self.layer_norm_hidden_state, dtype=torch.float32, embeds_info=embeds_info)
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl
    return forward_call(*args, **kwargs)
  File "/Users/anton/tools/ComfyUI/comfy/text_encoders/llama.py", line 408, in forward
    return super().forward(x, attention_mask=attention_mask, embeds=embeds, num_tokens=num_tokens, intermediate_output=intermediate_output, final_layer_norm_intermediate=final_layer_norm_intermediate, dtype=dtype, position_ids=position_ids)
           ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/comfy/text_encoders/llama.py", line 350, in forward
    return self.model(input_ids, *args, **kwargs)
           ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl
    return forward_call(*args, **kwargs)
  File "/Users/anton/tools/ComfyUI/comfy/text_encoders/llama.py", line 321, in forward
    x = layer(
        x=x,
    ...<2 lines>...
        optimized_attention=optimized_attention,
    )
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl
    return forward_call(*args, **kwargs)
  File "/Users/anton/tools/ComfyUI/comfy/text_encoders/llama.py", line 199, in forward
    x = self.self_attn(
        hidden_states=x,
    ...<2 lines>...
        optimized_attention=optimized_attention,
    )
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/Users/anton/tools/ComfyUI/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl
    return forward_call(*args, **kwargs)
  File "/Users/anton/tools/ComfyUI/comfy/text_encoders/llama.py", line 163, in forward
    output = optimized_attention(xq, xk, xv, self.num_heads, mask=attention_mask, skip_reshape=True)
  File "/Users/anton/tools/ComfyUI/comfy/ldm/modules/attention.py", line 107, in attention_basic
    q, k, v = map(
    ^^^^^^^
  File "/Users/anton/tools/ComfyUI/comfy/ldm/modules/attention.py", line 108, in <lambda>
    lambda t: t.reshape(b * heads, -1, dim_head),
              ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: shape '[84, -1, 128]' is invalid for input of size 5175296

Prompt executed in 11.89 seconds

Other

Image

antonpetrovmain avatar Aug 19 '25 08:08 antonpetrovmain

This is an issue with text encoder. With original qwen_2.5_vl_7b in fp16 everything works, but not with GGUF and fp8 scaled variants.

wcde avatar Aug 19 '25 08:08 wcde

Thank you for the rapid response! I am downloading now https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/blob/main/split_files/text_encoders/qwen_2.5_vl_7b.safetensors and will comment on whether it worked or not.

antonpetrovmain avatar Aug 19 '25 08:08 antonpetrovmain

try running comfy without split attention and without sage attention and report back if you have same error, i am currently using FP8 scaled clip on my machine

Saganaki22 avatar Aug 19 '25 08:08 Saganaki22

removed sage-attention , tried quad-cross, then removed all attention flags, comfy is using sub quad by default and all of those still give this error.

patientx avatar Aug 19 '25 09:08 patientx

This is an issue with text encoder. With original qwen_2.5_vl_7b in fp16 everything works, but not with GGUF and fp8 scaled variants.

Same error: shape '[84, -1, 128]' is invalid for input of size 5175296

Image

antonpetrovmain avatar Aug 19 '25 09:08 antonpetrovmain

This is an issue with text encoder. With original qwen_2.5_vl_7b in fp16 everything works, but not with GGUF and fp8 scaled variants.

Same error: shape '[84, -1, 128]' is invalid for input of size 5175296

Image

Are you on NVIDIA GPU and have you tried removing attn flags?

Image

Saganaki22 avatar Aug 19 '25 09:08 Saganaki22

I'm on a Mac Studio M3 Ultra 96GB. I tried now with python3 main.py --use-pytorch-cross-attention and it started generating something..

antonpetrovmain avatar Aug 19 '25 09:08 antonpetrovmain

even fp16 clip didn't work, gave the same error .and no we shouldn't have to change attention types to make something work.

patientx avatar Aug 19 '25 09:08 patientx

OK, the hat is off :) It's working with the --use-pytorch-cross-attention flag

Image

antonpetrovmain avatar Aug 19 '25 09:08 antonpetrovmain

#offtopic Can somebody please help me understand the impact of setting different attentions?

antonpetrovmain avatar Aug 19 '25 09:08 antonpetrovmain

even fp16 clip didn't work, gave the same error .and no we shouldn't have to change attention types to make something work.

even original qwen image had a bug with sageattn/split attn when it was first released but as you can see it has worked for me and antonpetrovmain

Saganaki22 avatar Aug 19 '25 10:08 Saganaki22

#offtopic Can somebody please help me understand the impact of setting different attentions?

Split Attention (ComfyUI's implementation):

Breaks the attention computation into smaller chunks to reduce memory usage Instead of computing the full attention matrix at once, it processes it in segments Trades computation time for memory efficiency Still O(n²) complexity but uses less VRAM

Cross Attention:

Standard transformer attention mechanism where queries come from one sequence and keys/values from another Used when text conditions image generation (text tokens attend to image features) Q = queries, K = keys, V = values can be from different modalities Core mechanism in diffusion models for text-to-image

Sage Attention:

Newer optimization technique that reduces attention complexity Uses approximation methods to avoid computing the full attention matrix Aims for sub-quadratic complexity (better than O(n²)) More mathematically sophisticated than simple chunking

Key differences:

Split: Memory optimization of standard attention Cross: Architecture pattern (different input sources) Sage: Algorithmic optimization for speed/memory

Saganaki22 avatar Aug 19 '25 10:08 Saganaki22

pytorch attention is the only attention type which doesn't work at all with hip on windows. so amd users can't use it with zluda or native torch's. (it "works" but gives oom even with fp8 model "torch.OutOfMemoryError: HIP out of memory. Tried to allocate 8.20 GiB. GPU 0 has a total capacity of 15.98 GiB of which 0 bytes is free. Of the allocated memory 21.99 GiB is allocated by PyTorch, and 82.19 MiB is reserved by PyTorch but unallocated.") so it is unusable , not just here with this model but generally.

patientx avatar Aug 19 '25 10:08 patientx

pytorch attention is the only attention type which doesn't work at all with hip on windows. so amd users can't use it with zluda or native torch's. (it "works" but gives oom even with fp8 model "torch.OutOfMemoryError: HIP out of memory. Tried to allocate 8.20 GiB. GPU 0 has a total capacity of 15.98 GiB of which 0 bytes is free. Of the allocated memory 21.99 GiB is allocated by PyTorch, and 82.19 MiB is reserved by PyTorch but unallocated.") so it is unusable , not just here with this model but generally.

I get that support varies depending on hardware, with NVIDIA usually being the priority, but until there’s proper AMD support one possible workaround is to force PyTorch into math-based attention:

import torch

torch.backends.cuda.enable_flash_sdp(False)
torch.backends.cuda.enable_mem_efficient_sdp(False)
torch.backends.cuda.enable_math_sdp(True)

print("[INFO] Forced PyTorch to use math attention (no flash/mem-efficient).")

Not ideal performance-wise, but could you give it a try?

Forgot to mention if you do try force math attn then lower your resolution by half on the latent as it will oom faster

Saganaki22 avatar Aug 19 '25 10:08 Saganaki22

Image

献丑了各位老师

chenpipi0807 avatar Aug 19 '25 10:08 chenpipi0807

Image 献丑了各位老师

I don't have this checkbox. =(

BahamutRU avatar Aug 19 '25 13:08 BahamutRU

OK, the hat is off :) It's working with the --pytorch-cross-attention flag

Sorry if I'm being slow but, where do you all get that node? I'm on 0.3.50 and I don't have that node ??

phoebdroid avatar Aug 19 '25 17:08 phoebdroid

Sorry if I'm being slow but, where do you all get that node? I'm on 0.3.50 and I don't have that node ??

It's of course --use-pytorch-cross-attention (use --help)

For me this isn't a solution since my AMD GPU always runs out of memory when using cross-attention (RX 6800 XT)

Som-anon avatar Aug 19 '25 17:08 Som-anon

OK, the hat is off :) It's working with the --pytorch-cross-attention flag

Sorry if I'm being slow but, where do you all get that node? I'm on 0.3.50 and I don't have that node ??

It's not yet available in the Desktop version, I believe. (could be wrong, I don't have my machine in front of me). I am running Comfy UI from source (git repo)

antonpetrovmain avatar Aug 19 '25 18:08 antonpetrovmain

It's not yet available in the Desktop version, I believe. (could be wrong, I don't have my machine in front of me). I am running Comfy UI from source (git repo)

yes I've figured in the meantime, will probably drop soon, thanks

phoebdroid avatar Aug 19 '25 19:08 phoebdroid