[Bug]: Qwen 2.5-VL fails in TextGenerate node (missing `stop_tokens`, `lm_head`, and MRoPE `position_ids`)
Custom Node Testing
- I have tried disabling custom nodes and the issue persists (see how to disable custom nodes if you need help)
Expected Behavior
Loading a Qwen 2.5-VL model (e.g., qwen_2.5_vl_7b_fp8_scaled.safetensors) using CLIPLoader (type: qwen_image) and connecting it to a TextGenerate node should generate text responses and describe connected images using multimodal vision-language understanding.
Actual Behavior
- Immediate Crash: The workflow crashes immediately with an
AttributeErrorbecauseQwen25_7BVLI_Configlacks thestop_tokensattribute. - Missing
lm_head(Garbled Tokens): Even if the attribute error is bypassed,Qwen25_7BVLI_Confighardcodeslm_head: bool = False, andcomfy/sd.pylacks thelm_head.->model.lm_head.state dict prefix replacement. Because Qwen 2.5-VL 7B has an untied prediction head ([152064, 3584]), falling back toembed_tokens.weightcauses the model to emit random garbled tokens. - Missing MRoPE Position IDs for Vision:
Qwen25_7BVLIModelfalls back toSDClipModel.generate(), which discardsembeds_infoand generates tokens withposition_ids = None. Without 3D MRoPE position IDs, visual tokens lack 2D spatial coordinates. - Ignored Image Input:
QwenImageTokenizer.tokenize_with_weightsignoresimagepassed viakwargsfromTextGenerate.
Steps to Reproduce
- Add a
CLIPLoadernode:clip_name:qwen_2.5_vl_7b_fp8_scaled.safetensorstype:qwen_image
- Connect
CLIPoutput to aTextGeneratenode. - (Optional) Connect an image to the
imageinput ofTextGenerate. - Queue Prompt.
Debug Logs
Traceback (most recent call last):
File "comfy_extras/nodes_textgen.py", line 67, in execute
generated_ids = clip.generate(
^^^^^^^^^^^^^^
File "comfy/sd.py", line 484, in generate
return self.cond_stage_model.generate(...)
File "comfy/sd1_clip.py", line 750, in generate
return getattr(self, self.clip).generate(...)
File "comfy/sd1_clip.py", line 318, in generate
return self.transformer.generate(embeds, ...)
File "comfy/text_encoders/llama.py", line 1113, in generate
stop_tokens = self.model.config.stop_tokens
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Qwen25_7BVLI_Config' object has no attribute 'stop_tokens'Other
Here is the root cause breakdown and verified patch:
- comfy/text_encoders/llama.py: -Set lm_head: bool = True and add stop_tokens = [151643, 151645] to Qwen25_7BVLI_Config. -Factor out build_position_ids on Qwen25_7BVLI so MRoPE position IDs can be computed for both forward() and generate().
- comfy/sd.py: -Add prefix replacement clip_data[0] = comfy.utils.state_dict_prefix_replace(clip_data[0], {"lm_head.": "model.lm_head."}) under TEModel.QWEN25_7B.
- comfy/text_encoders/qwen_image.py: -In QwenImageTokenizer.tokenize_with_weights, extract image from kwargs and format conversational prompt templates when called by TextGenerate (preserving diffusion conditioning templates). -In Qwen25_7BVLIModel, implement generate() to build position_ids from embeds_info and pass them to self.transformer.generate().
diff --git a/comfy/sd.py b/comfy/sd.py index ea42f6a4..14153a50 100644 --- a/comfy/sd.py +++ b/comfy/sd.py @@ -1889,6 +1889,7 @@ def load_text_encoder_state_dicts(state_dicts=[], embedding_directory=None, clip clip_target.clip = comfy.text_encoders.omnigen2.te(**llama_detect(clip_data)) clip_target.tokenizer = comfy.text_encoders.omnigen2.Omnigen2Tokenizer elif te_model == TEModel.QWEN25_7B:
clip_data[0] = comfy.utils.state_dict_prefix_replace(clip_data[0], {"lm_head.": "model.lm_head."}) if clip_type == CLIPType.HUNYUAN_IMAGE: clip_target.clip = comfy.text_encoders.hunyuan_image.te(byt5=False, **llama_detect(clip_data)) clip_target.tokenizer = comfy.text_encoders.hunyuan_image.HunyuanImageTokenizer
diff --git a/comfy/text_encoders/llama.py b/comfy/text_encoders/llama.py index 96577011..47ddca63 100644 --- a/comfy/text_encoders/llama.py +++ b/comfy/text_encoders/llama.py @@ -409,7 +409,8 @@ class Qwen25_7BVLI_Config: k_norm = None rope_scale = None final_norm: bool = True
- lm_head: bool = False
- lm_head: bool = True
- stop_tokens = [151643, 151645]
@dataclass class Gemma2_2B_Config: @@ -1371,7 +1372,7 @@ class Qwen25_7BVLI(BaseLlama, BaseGenerate, torch.nn.Module): return self.visual(image.to(device, dtype=torch.float32), grid), grid return None, None
- def forward(self, x, attention_mask=None, embeds=None, num_tokens=None, intermediate_output=None, final_layer_norm_intermediate=True, dtype=None, embeds_info=[]):
- def build_position_ids(self, embeds, embeds_info=[], attention_mask=None): grid = None position_ids = None offset = 0
@@ -1400,9 +1401,10 @@ class Qwen25_7BVLI(BaseLlama, BaseGenerate, torch.nn.Module): position_ids[2, start:end] = torch.arange(start + offset, start + max_d + offset, device=embeds.device).unsqueeze(0).repeat(math.ceil((end - start) / max_d), 1).flatten(0)[:end - start] offset += len_max - (end - start)
if grid is None:position_ids = None
return position_idsdef forward(self, x, attention_mask=None, embeds=None, num_tokens=None, intermediate_output=None, final_layer_norm_intermediate=True, dtype=None, embeds_info=[]):
position_ids = self.build_position_ids(embeds, embeds_info, attention_mask) 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)
class Gemma2_2B(BaseLlama, BaseGenerate, torch.nn.Module): diff --git a/comfy/text_encoders/qwen_image.py b/comfy/text_encoders/qwen_image.py index 5c14dec2..1a8fc093 100644 --- a/comfy/text_encoders/qwen_image.py +++ b/comfy/text_encoders/qwen_image.py @@ -18,24 +18,31 @@ class QwenImageTokenizer(sd1_clip.SD1Tokenizer): self.llama_template_images = "<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>{}<|im_end|>\n<|im_start|>assistant\n"
def tokenize_with_weights(self, text, return_word_ids=False, llama_template=None, images=[], prevent_empty_text=False, **kwargs):
skip_template = Falseif text.startswith('<|im_start|>'):skip_template = Trueif text.startswith('<|start_header_id|>'):skip_template = True
image = kwargs.get("image", None)if image is not None and len(images) == 0:images = [image[i:i + 1] for i in range(image.shape[0])]skip_template = kwargs.get("skip_template", False) or text.startswith('<|im_start|>') or text.startswith('<|start_header_id|>') if prevent_empty_text and text == '': text = ' ' if skip_template: llama_text = text else:
if llama_template is None:
if llama_template is not None:llama_text = llama_template.format(text)elif "thinking" in kwargs:# TextGenerate pathif len(images) > 0:llama_text = f"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>{text}<|im_end|>\n<|im_start|>assistant\n"else:llama_text = f"<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n"else:# Diffusion conditioning path if len(images) > 0: llama_text = self.llama_template_images.format(text) else: llama_text = self.llama_template.format(text)
else:llama_text = llama_template.format(text) tokens = super().tokenize_with_weights(llama_text, return_word_ids=return_word_ids, disable_weights=True, **kwargs) key_name = next(iter(tokens)) embed_count = 0
@@ -53,6 +60,14 @@ class Qwen25_7BVLIModel(sd1_clip.SDClipModel): def init(self, device="cpu", layer="last", layer_idx=None, dtype=None, attention_mask=True, model_options={}): super().init(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config={}, dtype=dtype, special_tokens={"pad": 151643}, layer_norm_hidden_state=False, model_class=comfy.text_encoders.llama.Qwen25_7BVLI, enable_attention_masks=attention_mask, return_attention_masks=attention_mask, model_options=model_options)
- def generate(self, tokens, do_sample, max_length, temperature, top_k, top_p, min_p, repetition_penalty, seed, presence_penalty=0.0, mtp=True):
if isinstance(tokens, dict):tokens = next(iter(tokens.values()))tokens_only = [[t[0] for t in b] for b in tokens]embeds, _, _, embeds_info = self.process_tokens(tokens_only, self.execution_device)position_ids = self.transformer.build_position_ids(embeds, embeds_info) if hasattr(self.transformer, "build_position_ids") else Nonereturn self.transformer.generate(embeds, do_sample, max_length, temperature, top_k, top_p, min_p, repetition_penalty, seed, presence_penalty=presence_penalty, position_ids=position_ids)
class QwenImageTEModel(sd1_clip.SD1ClipModel): def init(self, device="cpu", dtype=None, model_options={}):
Source: Comfy-Org/ComfyUI