sd_hijack_clip.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import math
  2. from collections import namedtuple
  3. import torch
  4. from modules import prompt_parser, devices, sd_hijack, sd_emphasis
  5. from modules.shared import opts
  6. class PromptChunk:
  7. """
  8. This object contains token ids, weight (multipliers:1.4) and textual inversion embedding info for a chunk of prompt.
  9. If a prompt is short, it is represented by one PromptChunk, otherwise, multiple are necessary.
  10. Each PromptChunk contains an exact amount of tokens - 77, which includes one for start and end token,
  11. so just 75 tokens from prompt.
  12. """
  13. def __init__(self):
  14. self.tokens = []
  15. self.multipliers = []
  16. self.fixes = []
  17. PromptChunkFix = namedtuple('PromptChunkFix', ['offset', 'embedding'])
  18. """An object of this type is a marker showing that textual inversion embedding's vectors have to placed at offset in the prompt
  19. chunk. Those objects are found in PromptChunk.fixes and, are placed into FrozenCLIPEmbedderWithCustomWordsBase.hijack.fixes, and finally
  20. are applied by sd_hijack.EmbeddingsWithFixes's forward function."""
  21. class TextConditionalModel(torch.nn.Module):
  22. def __init__(self):
  23. super().__init__()
  24. self.hijack = sd_hijack.model_hijack
  25. self.chunk_length = 75
  26. self.is_trainable = False
  27. self.input_key = 'txt'
  28. self.return_pooled = False
  29. self.comma_token = None
  30. self.id_start = None
  31. self.id_end = None
  32. self.id_pad = None
  33. def empty_chunk(self):
  34. """creates an empty PromptChunk and returns it"""
  35. chunk = PromptChunk()
  36. chunk.tokens = [self.id_start] + [self.id_end] * (self.chunk_length + 1)
  37. chunk.multipliers = [1.0] * (self.chunk_length + 2)
  38. return chunk
  39. def get_target_prompt_token_count(self, token_count):
  40. """returns the maximum number of tokens a prompt of a known length can have before it requires one more PromptChunk to be represented"""
  41. return math.ceil(max(token_count, 1) / self.chunk_length) * self.chunk_length
  42. def tokenize(self, texts):
  43. """Converts a batch of texts into a batch of token ids"""
  44. raise NotImplementedError
  45. def encode_with_transformers(self, tokens):
  46. """
  47. converts a batch of token ids (in python lists) into a single tensor with numeric representation of those tokens;
  48. All python lists with tokens are assumed to have same length, usually 77.
  49. if input is a list with B elements and each element has T tokens, expected output shape is (B, T, C), where C depends on
  50. model - can be 768 and 1024.
  51. Among other things, this call will read self.hijack.fixes, apply it to its inputs, and clear it (setting it to None).
  52. """
  53. raise NotImplementedError
  54. def encode_embedding_init_text(self, init_text, nvpt):
  55. """Converts text into a tensor with this text's tokens' embeddings. Note that those are embeddings before they are passed through
  56. transformers. nvpt is used as a maximum length in tokens. If text produces less teokens than nvpt, only this many is returned."""
  57. raise NotImplementedError
  58. def tokenize_line(self, line):
  59. """
  60. this transforms a single prompt into a list of PromptChunk objects - as many as needed to
  61. represent the prompt.
  62. Returns the list and the total number of tokens in the prompt.
  63. """
  64. if opts.emphasis != "None":
  65. parsed = prompt_parser.parse_prompt_attention(line)
  66. else:
  67. parsed = [[line, 1.0]]
  68. tokenized = self.tokenize([text for text, _ in parsed])
  69. chunks = []
  70. chunk = PromptChunk()
  71. token_count = 0
  72. last_comma = -1
  73. def next_chunk(is_last=False):
  74. """puts current chunk into the list of results and produces the next one - empty;
  75. if is_last is true, tokens <end-of-text> tokens at the end won't add to token_count"""
  76. nonlocal token_count
  77. nonlocal last_comma
  78. nonlocal chunk
  79. if is_last:
  80. token_count += len(chunk.tokens)
  81. else:
  82. token_count += self.chunk_length
  83. to_add = self.chunk_length - len(chunk.tokens)
  84. if to_add > 0:
  85. chunk.tokens += [self.id_end] * to_add
  86. chunk.multipliers += [1.0] * to_add
  87. chunk.tokens = [self.id_start] + chunk.tokens + [self.id_end]
  88. chunk.multipliers = [1.0] + chunk.multipliers + [1.0]
  89. last_comma = -1
  90. chunks.append(chunk)
  91. chunk = PromptChunk()
  92. for tokens, (text, weight) in zip(tokenized, parsed):
  93. if text == 'BREAK' and weight == -1:
  94. next_chunk()
  95. continue
  96. position = 0
  97. while position < len(tokens):
  98. token = tokens[position]
  99. if token == self.comma_token:
  100. last_comma = len(chunk.tokens)
  101. # this is when we are at the end of allotted 75 tokens for the current chunk, and the current token is not a comma. opts.comma_padding_backtrack
  102. # is a setting that specifies that if there is a comma nearby, the text after the comma should be moved out of this chunk and into the next.
  103. elif opts.comma_padding_backtrack != 0 and len(chunk.tokens) == self.chunk_length and last_comma != -1 and len(chunk.tokens) - last_comma <= opts.comma_padding_backtrack:
  104. break_location = last_comma + 1
  105. reloc_tokens = chunk.tokens[break_location:]
  106. reloc_mults = chunk.multipliers[break_location:]
  107. chunk.tokens = chunk.tokens[:break_location]
  108. chunk.multipliers = chunk.multipliers[:break_location]
  109. next_chunk()
  110. chunk.tokens = reloc_tokens
  111. chunk.multipliers = reloc_mults
  112. if len(chunk.tokens) == self.chunk_length:
  113. next_chunk()
  114. embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, position)
  115. if embedding is None:
  116. chunk.tokens.append(token)
  117. chunk.multipliers.append(weight)
  118. position += 1
  119. continue
  120. emb_len = int(embedding.vectors)
  121. if len(chunk.tokens) + emb_len > self.chunk_length:
  122. next_chunk()
  123. chunk.fixes.append(PromptChunkFix(len(chunk.tokens), embedding))
  124. chunk.tokens += [0] * emb_len
  125. chunk.multipliers += [weight] * emb_len
  126. position += embedding_length_in_tokens
  127. if chunk.tokens or not chunks:
  128. next_chunk(is_last=True)
  129. return chunks, token_count
  130. def process_texts(self, texts):
  131. """
  132. Accepts a list of texts and calls tokenize_line() on each, with cache. Returns the list of results and maximum
  133. length, in tokens, of all texts.
  134. """
  135. token_count = 0
  136. cache = {}
  137. batch_chunks = []
  138. for line in texts:
  139. if line in cache:
  140. chunks = cache[line]
  141. else:
  142. chunks, current_token_count = self.tokenize_line(line)
  143. token_count = max(current_token_count, token_count)
  144. cache[line] = chunks
  145. batch_chunks.append(chunks)
  146. return batch_chunks, token_count
  147. def forward(self, texts):
  148. """
  149. Accepts an array of texts; Passes texts through transformers network to create a tensor with numerical representation of those texts.
  150. Returns a tensor with shape of (B, T, C), where B is length of the array; T is length, in tokens, of texts (including padding) - T will
  151. be a multiple of 77; and C is dimensionality of each token - for SD1 it's 768, for SD2 it's 1024, and for SDXL it's 1280.
  152. An example shape returned by this function can be: (2, 77, 768).
  153. For SDXL, instead of returning one tensor avobe, it returns a tuple with two: the other one with shape (B, 1280) with pooled values.
  154. Webui usually sends just one text at a time through this function - the only time when texts is an array with more than one element
  155. is when you do prompt editing: "a picture of a [cat:dog:0.4] eating ice cream"
  156. """
  157. batch_chunks, token_count = self.process_texts(texts)
  158. used_embeddings = {}
  159. chunk_count = max([len(x) for x in batch_chunks])
  160. zs = []
  161. for i in range(chunk_count):
  162. batch_chunk = [chunks[i] if i < len(chunks) else self.empty_chunk() for chunks in batch_chunks]
  163. tokens = [x.tokens for x in batch_chunk]
  164. multipliers = [x.multipliers for x in batch_chunk]
  165. self.hijack.fixes = [x.fixes for x in batch_chunk]
  166. for fixes in self.hijack.fixes:
  167. for _position, embedding in fixes:
  168. used_embeddings[embedding.name] = embedding
  169. devices.torch_npu_set_device()
  170. z = self.process_tokens(tokens, multipliers)
  171. zs.append(z)
  172. if opts.textual_inversion_add_hashes_to_infotext and used_embeddings:
  173. hashes = []
  174. for name, embedding in used_embeddings.items():
  175. shorthash = embedding.shorthash
  176. if not shorthash:
  177. continue
  178. name = name.replace(":", "").replace(",", "")
  179. hashes.append(f"{name}: {shorthash}")
  180. if hashes:
  181. if self.hijack.extra_generation_params.get("TI hashes"):
  182. hashes.append(self.hijack.extra_generation_params.get("TI hashes"))
  183. self.hijack.extra_generation_params["TI hashes"] = ", ".join(hashes)
  184. if any(x for x in texts if "(" in x or "[" in x) and opts.emphasis != "Original":
  185. self.hijack.extra_generation_params["Emphasis"] = opts.emphasis
  186. if self.return_pooled:
  187. return torch.hstack(zs), zs[0].pooled
  188. else:
  189. return torch.hstack(zs)
  190. def process_tokens(self, remade_batch_tokens, batch_multipliers):
  191. """
  192. sends one single prompt chunk to be encoded by transformers neural network.
  193. remade_batch_tokens is a batch of tokens - a list, where every element is a list of tokens; usually
  194. there are exactly 77 tokens in the list. batch_multipliers is the same but for multipliers instead of tokens.
  195. Multipliers are used to give more or less weight to the outputs of transformers network. Each multiplier
  196. corresponds to one token.
  197. """
  198. tokens = torch.asarray(remade_batch_tokens).to(devices.device)
  199. # this is for SD2: SD1 uses the same token for padding and end of text, while SD2 uses different ones.
  200. if self.id_end != self.id_pad:
  201. for batch_pos in range(len(remade_batch_tokens)):
  202. index = remade_batch_tokens[batch_pos].index(self.id_end)
  203. tokens[batch_pos, index+1:tokens.shape[1]] = self.id_pad
  204. z = self.encode_with_transformers(tokens)
  205. pooled = getattr(z, 'pooled', None)
  206. emphasis = sd_emphasis.get_current_option(opts.emphasis)()
  207. emphasis.tokens = remade_batch_tokens
  208. emphasis.multipliers = torch.asarray(batch_multipliers).to(devices.device)
  209. emphasis.z = z
  210. emphasis.after_transformers()
  211. z = emphasis.z
  212. if pooled is not None:
  213. z.pooled = pooled
  214. return z
  215. class FrozenCLIPEmbedderWithCustomWordsBase(TextConditionalModel):
  216. """A pytorch module that is a wrapper for FrozenCLIPEmbedder module. it enhances FrozenCLIPEmbedder, making it possible to
  217. have unlimited prompt length and assign weights to tokens in prompt.
  218. """
  219. def __init__(self, wrapped, hijack):
  220. super().__init__()
  221. self.hijack = hijack
  222. self.wrapped = wrapped
  223. """Original FrozenCLIPEmbedder module; can also be FrozenOpenCLIPEmbedder or xlmr.BertSeriesModelWithTransformation,
  224. depending on model."""
  225. self.is_trainable = getattr(wrapped, 'is_trainable', False)
  226. self.input_key = getattr(wrapped, 'input_key', 'txt')
  227. self.return_pooled = getattr(self.wrapped, 'return_pooled', False)
  228. self.legacy_ucg_val = None # for sgm codebase
  229. def forward(self, texts):
  230. if opts.use_old_emphasis_implementation:
  231. import modules.sd_hijack_clip_old
  232. return modules.sd_hijack_clip_old.forward_old(self, texts)
  233. return super().forward(texts)
  234. class FrozenCLIPEmbedderWithCustomWords(FrozenCLIPEmbedderWithCustomWordsBase):
  235. def __init__(self, wrapped, hijack):
  236. super().__init__(wrapped, hijack)
  237. self.tokenizer = wrapped.tokenizer
  238. vocab = self.tokenizer.get_vocab()
  239. self.comma_token = vocab.get(',</w>', None)
  240. self.token_mults = {}
  241. tokens_with_parens = [(k, v) for k, v in vocab.items() if '(' in k or ')' in k or '[' in k or ']' in k]
  242. for text, ident in tokens_with_parens:
  243. mult = 1.0
  244. for c in text:
  245. if c == '[':
  246. mult /= 1.1
  247. if c == ']':
  248. mult *= 1.1
  249. if c == '(':
  250. mult *= 1.1
  251. if c == ')':
  252. mult /= 1.1
  253. if mult != 1.0:
  254. self.token_mults[ident] = mult
  255. self.id_start = self.wrapped.tokenizer.bos_token_id
  256. self.id_end = self.wrapped.tokenizer.eos_token_id
  257. self.id_pad = self.id_end
  258. def tokenize(self, texts):
  259. tokenized = self.wrapped.tokenizer(texts, truncation=False, add_special_tokens=False)["input_ids"]
  260. return tokenized
  261. def encode_with_transformers(self, tokens):
  262. outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=-opts.CLIP_stop_at_last_layers)
  263. if opts.CLIP_stop_at_last_layers > 1:
  264. z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers]
  265. z = self.wrapped.transformer.text_model.final_layer_norm(z)
  266. else:
  267. z = outputs.last_hidden_state
  268. return z
  269. def encode_embedding_init_text(self, init_text, nvpt):
  270. embedding_layer = self.wrapped.transformer.text_model.embeddings
  271. ids = self.wrapped.tokenizer(init_text, max_length=nvpt, return_tensors="pt", add_special_tokens=False)["input_ids"]
  272. embedded = embedding_layer.token_embedding.wrapped(ids.to(embedding_layer.token_embedding.wrapped.weight.device)).squeeze(0)
  273. return embedded
  274. class FrozenCLIPEmbedderForSDXLWithCustomWords(FrozenCLIPEmbedderWithCustomWords):
  275. def __init__(self, wrapped, hijack):
  276. super().__init__(wrapped, hijack)
  277. def encode_with_transformers(self, tokens):
  278. outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=self.wrapped.layer == "hidden")
  279. if opts.sdxl_clip_l_skip is True:
  280. z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers]
  281. elif self.wrapped.layer == "last":
  282. z = outputs.last_hidden_state
  283. else:
  284. z = outputs.hidden_states[self.wrapped.layer_idx]
  285. return z