|
| 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_ |
0 commit comments