Skip to content

Commit ac4412d

Browse files
authored
Native LongCat-Image implementation (Comfy-Org#12597)
1 parent 94f1a1c commit ac4412d

7 files changed

Lines changed: 356 additions & 2 deletions

File tree

comfy/model_base.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,25 @@ def extra_conds_shapes(self, **kwargs):
925925
out['ref_latents'] = list([1, 16, sum(map(lambda a: math.prod(a.size()[2:]), ref_latents))])
926926
return out
927927

928+
class LongCatImage(Flux):
929+
def _apply_model(self, x, t, c_concat=None, c_crossattn=None, control=None, transformer_options={}, **kwargs):
930+
transformer_options = transformer_options.copy()
931+
rope_opts = transformer_options.get("rope_options", {})
932+
rope_opts = dict(rope_opts)
933+
rope_opts.setdefault("shift_t", 1.0)
934+
rope_opts.setdefault("shift_y", 512.0)
935+
rope_opts.setdefault("shift_x", 512.0)
936+
transformer_options["rope_options"] = rope_opts
937+
return super()._apply_model(x, t, c_concat, c_crossattn, control, transformer_options, **kwargs)
938+
939+
def encode_adm(self, **kwargs):
940+
return None
941+
942+
def extra_conds(self, **kwargs):
943+
out = super().extra_conds(**kwargs)
944+
out.pop('guidance', None)
945+
return out
946+
928947
class Flux2(Flux):
929948
def extra_conds(self, **kwargs):
930949
out = super().extra_conds(**kwargs)

comfy/model_detection.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,8 @@ def detect_unet_config(state_dict, key_prefix, metadata=None):
279279
dit_config["txt_norm"] = any_suffix_in(state_dict_keys, key_prefix, 'txt_norm.', ["weight", "scale"])
280280
if dit_config["yak_mlp"] and dit_config["txt_norm"]: # Ovis model
281281
dit_config["txt_ids_dims"] = [1, 2]
282+
if dit_config.get("context_in_dim") == 3584 and dit_config["vec_in_dim"] is None: # LongCat-Image
283+
dit_config["txt_ids_dims"] = [1, 2]
282284

283285
return dit_config
284286

comfy/sd.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
import comfy.text_encoders.newbie
6161
import comfy.text_encoders.anima
6262
import comfy.text_encoders.ace15
63+
import comfy.text_encoders.longcat_image
6364

6465
import comfy.model_patcher
6566
import comfy.lora
@@ -1160,6 +1161,7 @@ class CLIPType(Enum):
11601161
KANDINSKY5_IMAGE = 23
11611162
NEWBIE = 24
11621163
FLUX2 = 25
1164+
LONGCAT_IMAGE = 26
11631165

11641166

11651167
def load_clip(ckpt_paths, embedding_directory=None, clip_type=CLIPType.STABLE_DIFFUSION, model_options={}):
@@ -1372,6 +1374,9 @@ class EmptyClass:
13721374
if clip_type == CLIPType.HUNYUAN_IMAGE:
13731375
clip_target.clip = comfy.text_encoders.hunyuan_image.te(byt5=False, **llama_detect(clip_data))
13741376
clip_target.tokenizer = comfy.text_encoders.hunyuan_image.HunyuanImageTokenizer
1377+
elif clip_type == CLIPType.LONGCAT_IMAGE:
1378+
clip_target.clip = comfy.text_encoders.longcat_image.te(**llama_detect(clip_data))
1379+
clip_target.tokenizer = comfy.text_encoders.longcat_image.LongCatImageTokenizer
13751380
else:
13761381
clip_target.clip = comfy.text_encoders.qwen_image.te(**llama_detect(clip_data))
13771382
clip_target.tokenizer = comfy.text_encoders.qwen_image.QwenImageTokenizer

comfy/supported_models.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import comfy.text_encoders.z_image
2626
import comfy.text_encoders.anima
2727
import comfy.text_encoders.ace15
28+
import comfy.text_encoders.longcat_image
2829

2930
from . import supported_models_base
3031
from . import latent_formats
@@ -1678,6 +1679,37 @@ def clip_target(self, state_dict={}):
16781679
return supported_models_base.ClipTarget(comfy.text_encoders.ace15.ACE15Tokenizer, comfy.text_encoders.ace15.te(**detect))
16791680

16801681

1681-
models = [LotusD, Stable_Zero123, SD15_instructpix2pix, SD15, SD20, SD21UnclipL, SD21UnclipH, SDXL_instructpix2pix, SDXLRefiner, SDXL, SSD1B, KOALA_700M, KOALA_1B, Segmind_Vega, SD_X4Upscaler, Stable_Cascade_C, Stable_Cascade_B, SV3D_u, SV3D_p, SD3, StableAudio, AuraFlow, PixArtAlpha, PixArtSigma, HunyuanDiT, HunyuanDiT1, FluxInpaint, Flux, FluxSchnell, GenmoMochi, LTXV, LTXAV, HunyuanVideo15_SR_Distilled, HunyuanVideo15, HunyuanImage21Refiner, HunyuanImage21, HunyuanVideoSkyreelsI2V, HunyuanVideoI2V, HunyuanVideo, CosmosT2V, CosmosI2V, CosmosT2IPredict2, CosmosI2VPredict2, ZImage, Lumina2, WAN22_T2V, WAN21_T2V, WAN21_I2V, WAN21_FunControl2V, WAN21_Vace, WAN21_Camera, WAN22_Camera, WAN22_S2V, WAN21_HuMo, WAN22_Animate, WAN21_FlowRVS, Hunyuan3Dv2mini, Hunyuan3Dv2, Hunyuan3Dv2_1, HiDream, Chroma, ChromaRadiance, ACEStep, ACEStep15, Omnigen2, QwenImage, Flux2, Kandinsky5Image, Kandinsky5, Anima]
1682+
class LongCatImage(supported_models_base.BASE):
1683+
unet_config = {
1684+
"image_model": "flux",
1685+
"guidance_embed": False,
1686+
"vec_in_dim": None,
1687+
"context_in_dim": 3584,
1688+
"txt_ids_dims": [1, 2],
1689+
}
1690+
1691+
sampling_settings = {
1692+
}
1693+
1694+
unet_extra_config = {}
1695+
latent_format = latent_formats.Flux
1696+
1697+
memory_usage_factor = 2.5
1698+
1699+
supported_inference_dtypes = [torch.bfloat16, torch.float16, torch.float32]
1700+
1701+
vae_key_prefix = ["vae."]
1702+
text_encoder_key_prefix = ["text_encoders."]
1703+
1704+
def get_model(self, state_dict, prefix="", device=None):
1705+
out = model_base.LongCatImage(self, device=device)
1706+
return out
1707+
1708+
def clip_target(self, state_dict={}):
1709+
pref = self.text_encoder_key_prefix[0]
1710+
hunyuan_detect = comfy.text_encoders.hunyuan_video.llama_detect(state_dict, "{}qwen25_7b.transformer.".format(pref))
1711+
return supported_models_base.ClipTarget(comfy.text_encoders.longcat_image.LongCatImageTokenizer, comfy.text_encoders.longcat_image.te(**hunyuan_detect))
1712+
1713+
models = [LotusD, Stable_Zero123, SD15_instructpix2pix, SD15, SD20, SD21UnclipL, SD21UnclipH, SDXL_instructpix2pix, SDXLRefiner, SDXL, SSD1B, KOALA_700M, KOALA_1B, Segmind_Vega, SD_X4Upscaler, Stable_Cascade_C, Stable_Cascade_B, SV3D_u, SV3D_p, SD3, StableAudio, AuraFlow, PixArtAlpha, PixArtSigma, HunyuanDiT, HunyuanDiT1, FluxInpaint, Flux, LongCatImage, FluxSchnell, GenmoMochi, LTXV, LTXAV, HunyuanVideo15_SR_Distilled, HunyuanVideo15, HunyuanImage21Refiner, HunyuanImage21, HunyuanVideoSkyreelsI2V, HunyuanVideoI2V, HunyuanVideo, CosmosT2V, CosmosI2V, CosmosT2IPredict2, CosmosI2VPredict2, ZImage, Lumina2, WAN22_T2V, WAN21_T2V, WAN21_I2V, WAN21_FunControl2V, WAN21_Vace, WAN21_Camera, WAN22_Camera, WAN22_S2V, WAN21_HuMo, WAN22_Animate, WAN21_FlowRVS, Hunyuan3Dv2mini, Hunyuan3Dv2, Hunyuan3Dv2_1, HiDream, Chroma, ChromaRadiance, ACEStep, ACEStep15, Omnigen2, QwenImage, Flux2, Kandinsky5Image, Kandinsky5, Anima]
16821714

16831715
models += [SVD_img2vid]
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
import re
2+
import numbers
3+
import torch
4+
from comfy import sd1_clip
5+
from comfy.text_encoders.qwen_image import Qwen25_7BVLITokenizer, Qwen25_7BVLIModel
6+
import logging
7+
8+
logger = logging.getLogger(__name__)
9+
10+
QUOTE_PAIRS = [("'", "'"), ('"', '"'), ("\u2018", "\u2019"), ("\u201c", "\u201d")]
11+
QUOTE_PATTERN = "|".join(
12+
[
13+
re.escape(q1) + r"[^" + re.escape(q1 + q2) + r"]*?" + re.escape(q2)
14+
for q1, q2 in QUOTE_PAIRS
15+
]
16+
)
17+
WORD_INTERNAL_QUOTE_RE = re.compile(r"[a-zA-Z]+'[a-zA-Z]+")
18+
19+
20+
def split_quotation(prompt):
21+
matches = WORD_INTERNAL_QUOTE_RE.findall(prompt)
22+
mapping = []
23+
for i, word_src in enumerate(set(matches)):
24+
word_tgt = "longcat_$##$_longcat" * (i + 1)
25+
prompt = prompt.replace(word_src, word_tgt)
26+
mapping.append((word_src, word_tgt))
27+
28+
parts = re.split(f"({QUOTE_PATTERN})", prompt)
29+
result = []
30+
for part in parts:
31+
for word_src, word_tgt in mapping:
32+
part = part.replace(word_tgt, word_src)
33+
if not part:
34+
continue
35+
is_quoted = bool(re.match(QUOTE_PATTERN, part))
36+
result.append((part, is_quoted))
37+
return result
38+
39+
40+
class LongCatImageBaseTokenizer(Qwen25_7BVLITokenizer):
41+
def __init__(self, *args, **kwargs):
42+
super().__init__(*args, **kwargs)
43+
self.max_length = 512
44+
45+
def tokenize_with_weights(self, text, return_word_ids=False, **kwargs):
46+
parts = split_quotation(text)
47+
all_tokens = []
48+
for part_text, is_quoted in parts:
49+
if is_quoted:
50+
for char in part_text:
51+
ids = self.tokenizer(char, add_special_tokens=False)["input_ids"]
52+
all_tokens.extend(ids)
53+
else:
54+
ids = self.tokenizer(part_text, add_special_tokens=False)["input_ids"]
55+
all_tokens.extend(ids)
56+
57+
if len(all_tokens) > self.max_length:
58+
all_tokens = all_tokens[: self.max_length]
59+
logger.warning(f"Truncated prompt to {self.max_length} tokens")
60+
61+
output = [(t, 1.0) for t in all_tokens]
62+
# Pad to max length
63+
self.pad_tokens(output, self.max_length - len(output))
64+
return [output]
65+
66+
67+
class LongCatImageTokenizer(sd1_clip.SD1Tokenizer):
68+
def __init__(self, embedding_directory=None, tokenizer_data={}):
69+
super().__init__(
70+
embedding_directory=embedding_directory,
71+
tokenizer_data=tokenizer_data,
72+
name="qwen25_7b",
73+
tokenizer=LongCatImageBaseTokenizer,
74+
)
75+
self.longcat_template_prefix = "<|im_start|>system\nAs an image captioning expert, generate a descriptive text prompt based on an image content, suitable for input to a text-to-image model.<|im_end|>\n<|im_start|>user\n"
76+
self.longcat_template_suffix = "<|im_end|>\n<|im_start|>assistant\n"
77+
78+
def tokenize_with_weights(self, text, return_word_ids=False, **kwargs):
79+
skip_template = False
80+
if text.startswith("<|im_start|>"):
81+
skip_template = True
82+
if text.startswith("<|start_header_id|>"):
83+
skip_template = True
84+
if text == "":
85+
text = " "
86+
87+
base_tok = getattr(self, "qwen25_7b")
88+
if skip_template:
89+
tokens = super().tokenize_with_weights(
90+
text, return_word_ids=return_word_ids, disable_weights=True, **kwargs
91+
)
92+
else:
93+
prefix_ids = base_tok.tokenizer(
94+
self.longcat_template_prefix, add_special_tokens=False
95+
)["input_ids"]
96+
suffix_ids = base_tok.tokenizer(
97+
self.longcat_template_suffix, add_special_tokens=False
98+
)["input_ids"]
99+
100+
prompt_tokens = base_tok.tokenize_with_weights(
101+
text, return_word_ids=return_word_ids, **kwargs
102+
)
103+
prompt_pairs = prompt_tokens[0]
104+
105+
prefix_pairs = [(t, 1.0) for t in prefix_ids]
106+
suffix_pairs = [(t, 1.0) for t in suffix_ids]
107+
108+
combined = prefix_pairs + prompt_pairs + suffix_pairs
109+
tokens = {"qwen25_7b": [combined]}
110+
111+
return tokens
112+
113+
114+
class LongCatImageTEModel(sd1_clip.SD1ClipModel):
115+
def __init__(self, device="cpu", dtype=None, model_options={}):
116+
super().__init__(
117+
device=device,
118+
dtype=dtype,
119+
name="qwen25_7b",
120+
clip_model=Qwen25_7BVLIModel,
121+
model_options=model_options,
122+
)
123+
124+
def encode_token_weights(self, token_weight_pairs, template_end=-1):
125+
out, pooled, extra = super().encode_token_weights(token_weight_pairs)
126+
tok_pairs = token_weight_pairs["qwen25_7b"][0]
127+
count_im_start = 0
128+
if template_end == -1:
129+
for i, v in enumerate(tok_pairs):
130+
elem = v[0]
131+
if not torch.is_tensor(elem):
132+
if isinstance(elem, numbers.Integral):
133+
if elem == 151644 and count_im_start < 2:
134+
template_end = i
135+
count_im_start += 1
136+
137+
if out.shape[1] > (template_end + 3):
138+
if tok_pairs[template_end + 1][0] == 872:
139+
if tok_pairs[template_end + 2][0] == 198:
140+
template_end += 3
141+
142+
if template_end == -1:
143+
template_end = 0
144+
145+
suffix_start = None
146+
for i in range(len(tok_pairs) - 1, -1, -1):
147+
elem = tok_pairs[i][0]
148+
if not torch.is_tensor(elem) and isinstance(elem, numbers.Integral):
149+
if elem == 151645:
150+
suffix_start = i
151+
break
152+
153+
out = out[:, template_end:]
154+
155+
if "attention_mask" in extra:
156+
extra["attention_mask"] = extra["attention_mask"][:, template_end:]
157+
if extra["attention_mask"].sum() == torch.numel(extra["attention_mask"]):
158+
extra.pop("attention_mask")
159+
160+
if suffix_start is not None:
161+
suffix_len = len(tok_pairs) - suffix_start
162+
if suffix_len > 0 and out.shape[1] > suffix_len:
163+
out = out[:, :-suffix_len]
164+
if "attention_mask" in extra:
165+
extra["attention_mask"] = extra["attention_mask"][:, :-suffix_len]
166+
if extra["attention_mask"].sum() == torch.numel(
167+
extra["attention_mask"]
168+
):
169+
extra.pop("attention_mask")
170+
171+
return out, pooled, extra
172+
173+
174+
def te(dtype_llama=None, llama_quantization_metadata=None):
175+
class LongCatImageTEModel_(LongCatImageTEModel):
176+
def __init__(self, device="cpu", dtype=None, model_options={}):
177+
if llama_quantization_metadata is not None:
178+
model_options = model_options.copy()
179+
model_options["quantization_metadata"] = llama_quantization_metadata
180+
if dtype_llama is not None:
181+
dtype = dtype_llama
182+
super().__init__(device=device, dtype=dtype, model_options=model_options)
183+
184+
return LongCatImageTEModel_

nodes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -976,7 +976,7 @@ class CLIPLoader:
976976
@classmethod
977977
def INPUT_TYPES(s):
978978
return {"required": { "clip_name": (folder_paths.get_filename_list("text_encoders"), ),
979-
"type": (["stable_diffusion", "stable_cascade", "sd3", "stable_audio", "mochi", "ltxv", "pixart", "cosmos", "lumina2", "wan", "hidream", "chroma", "ace", "omnigen2", "qwen_image", "hunyuan_image", "flux2", "ovis"], ),
979+
"type": (["stable_diffusion", "stable_cascade", "sd3", "stable_audio", "mochi", "ltxv", "pixart", "cosmos", "lumina2", "wan", "hidream", "chroma", "ace", "omnigen2", "qwen_image", "hunyuan_image", "flux2", "ovis", "longcat_image"], ),
980980
},
981981
"optional": {
982982
"device": (["default", "cpu"], {"advanced": True}),

0 commit comments

Comments
 (0)