sd_hijack_clip.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import math
  2. from collections import namedtuple
  3. import torch
  4. from modules import prompt_parser, devices, sd_hijack
  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. Thos 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 FrozenCLIPEmbedderWithCustomWordsBase(torch.nn.Module):
  22. """A pytorch module that is a wrapper for FrozenCLIPEmbedder module. it enhances FrozenCLIPEmbedder, making it possible to
  23. have unlimited prompt length and assign weights to tokens in prompt.
  24. """
  25. def __init__(self, wrapped, hijack):
  26. super().__init__()
  27. self.wrapped = wrapped
  28. """Original FrozenCLIPEmbedder module; can also be FrozenOpenCLIPEmbedder or xlmr.BertSeriesModelWithTransformation,
  29. depending on model."""
  30. self.hijack: sd_hijack.StableDiffusionModelHijack = hijack
  31. self.chunk_length = 75
  32. self.is_trainable = getattr(wrapped, 'is_trainable', False)
  33. self.input_key = getattr(wrapped, 'input_key', 'txt')
  34. self.legacy_ucg_val = None
  35. def empty_chunk(self):
  36. """creates an empty PromptChunk and returns it"""
  37. chunk = PromptChunk()
  38. chunk.tokens = [self.id_start] + [self.id_end] * (self.chunk_length + 1)
  39. chunk.multipliers = [1.0] * (self.chunk_length + 2)
  40. return chunk
  41. def get_target_prompt_token_count(self, token_count):
  42. """returns the maximum number of tokens a prompt of a known length can have before it requires one more PromptChunk to be represented"""
  43. return math.ceil(max(token_count, 1) / self.chunk_length) * self.chunk_length
  44. def tokenize(self, texts):
  45. """Converts a batch of texts into a batch of token ids"""
  46. raise NotImplementedError
  47. def encode_with_transformers(self, tokens):
  48. """
  49. converts a batch of token ids (in python lists) into a single tensor with numeric respresentation of those tokens;
  50. All python lists with tokens are assumed to have same length, usually 77.
  51. 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
  52. model - can be 768 and 1024.
  53. Among other things, this call will read self.hijack.fixes, apply it to its inputs, and clear it (setting it to None).
  54. """
  55. raise NotImplementedError
  56. def encode_embedding_init_text(self, init_text, nvpt):
  57. """Converts text into a tensor with this text's tokens' embeddings. Note that those are embeddings before they are passed through
  58. transformers. nvpt is used as a maximum length in tokens. If text produces less teokens than nvpt, only this many is returned."""
  59. raise NotImplementedError
  60. def tokenize_line(self, line):
  61. """
  62. this transforms a single prompt into a list of PromptChunk objects - as many as needed to
  63. represent the prompt.
  64. Returns the list and the total number of tokens in the prompt.
  65. """
  66. if opts.enable_emphasis:
  67. parsed = prompt_parser.parse_prompt_attention(line)
  68. else:
  69. parsed = [[line, 1.0]]
  70. tokenized = self.tokenize([text for text, _ in parsed])
  71. chunks = []
  72. chunk = PromptChunk()
  73. token_count = 0
  74. last_comma = -1
  75. def next_chunk(is_last=False):
  76. """puts current chunk into the list of results and produces the next one - empty;
  77. if is_last is true, tokens <end-of-text> tokens at the end won't add to token_count"""
  78. nonlocal token_count
  79. nonlocal last_comma
  80. nonlocal chunk
  81. if is_last:
  82. token_count += len(chunk.tokens)
  83. else:
  84. token_count += self.chunk_length
  85. to_add = self.chunk_length - len(chunk.tokens)
  86. if to_add > 0:
  87. chunk.tokens += [self.id_end] * to_add
  88. chunk.multipliers += [1.0] * to_add
  89. chunk.tokens = [self.id_start] + chunk.tokens + [self.id_end]
  90. chunk.multipliers = [1.0] + chunk.multipliers + [1.0]
  91. last_comma = -1
  92. chunks.append(chunk)
  93. chunk = PromptChunk()
  94. for tokens, (text, weight) in zip(tokenized, parsed):
  95. if text == 'BREAK' and weight == -1:
  96. next_chunk()
  97. continue
  98. position = 0
  99. while position < len(tokens):
  100. token = tokens[position]
  101. if token == self.comma_token:
  102. last_comma = len(chunk.tokens)
  103. # this is when we are at the end of alloted 75 tokens for the current chunk, and the current token is not a comma. opts.comma_padding_backtrack
  104. # 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.
  105. 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:
  106. break_location = last_comma + 1
  107. reloc_tokens = chunk.tokens[break_location:]
  108. reloc_mults = chunk.multipliers[break_location:]
  109. chunk.tokens = chunk.tokens[:break_location]
  110. chunk.multipliers = chunk.multipliers[:break_location]
  111. next_chunk()
  112. chunk.tokens = reloc_tokens
  113. chunk.multipliers = reloc_mults
  114. if len(chunk.tokens) == self.chunk_length:
  115. next_chunk()
  116. embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, position)
  117. if embedding is None:
  118. chunk.tokens.append(token)
  119. chunk.multipliers.append(weight)
  120. position += 1
  121. continue
  122. emb_len = int(embedding.vec.shape[0])
  123. if len(chunk.tokens) + emb_len > self.chunk_length:
  124. next_chunk()
  125. chunk.fixes.append(PromptChunkFix(len(chunk.tokens), embedding))
  126. chunk.tokens += [0] * emb_len
  127. chunk.multipliers += [weight] * emb_len
  128. position += embedding_length_in_tokens
  129. if chunk.tokens or not chunks:
  130. next_chunk(is_last=True)
  131. return chunks, token_count
  132. def process_texts(self, texts):
  133. """
  134. Accepts a list of texts and calls tokenize_line() on each, with cache. Returns the list of results and maximum
  135. length, in tokens, of all texts.
  136. """
  137. token_count = 0
  138. cache = {}
  139. batch_chunks = []
  140. for line in texts:
  141. if line in cache:
  142. chunks = cache[line]
  143. else:
  144. chunks, current_token_count = self.tokenize_line(line)
  145. token_count = max(current_token_count, token_count)
  146. cache[line] = chunks
  147. batch_chunks.append(chunks)
  148. return batch_chunks, token_count
  149. def forward(self, texts):
  150. """
  151. Accepts an array of texts; Passes texts through transformers network to create a tensor with numerical representation of those texts.
  152. 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
  153. 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.
  154. An example shape returned by this function can be: (2, 77, 768).
  155. For SDXL, instead of returning one tensor avobe, it returns a tuple with two: the other one with shape (B, 1280) with pooled values.
  156. Webui usually sends just one text at a time through this function - the only time when texts is an array with more than one elemenet
  157. is when you do prompt editing: "a picture of a [cat:dog:0.4] eating ice cream"
  158. """
  159. if opts.use_old_emphasis_implementation:
  160. import modules.sd_hijack_clip_old
  161. return modules.sd_hijack_clip_old.forward_old(self, texts)
  162. batch_chunks, token_count = self.process_texts(texts)
  163. used_embeddings = {}
  164. chunk_count = max([len(x) for x in batch_chunks])
  165. zs = []
  166. for i in range(chunk_count):
  167. batch_chunk = [chunks[i] if i < len(chunks) else self.empty_chunk() for chunks in batch_chunks]
  168. tokens = [x.tokens for x in batch_chunk]
  169. multipliers = [x.multipliers for x in batch_chunk]
  170. self.hijack.fixes = [x.fixes for x in batch_chunk]
  171. for fixes in self.hijack.fixes:
  172. for _position, embedding in fixes:
  173. used_embeddings[embedding.name] = embedding
  174. z = self.process_tokens(tokens, multipliers)
  175. zs.append(z)
  176. if opts.textual_inversion_add_hashes_to_infotext and used_embeddings:
  177. hashes = []
  178. for name, embedding in used_embeddings.items():
  179. shorthash = embedding.shorthash
  180. if not shorthash:
  181. continue
  182. name = name.replace(":", "").replace(",", "")
  183. hashes.append(f"{name}: {shorthash}")
  184. if hashes:
  185. self.hijack.extra_generation_params["TI hashes"] = ", ".join(hashes)
  186. if getattr(self.wrapped, 'return_pooled', False):
  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. # restoring original mean is likely not correct, but it seems to work well to prevent artifacts that happen otherwise
  207. batch_multipliers = torch.asarray(batch_multipliers).to(devices.device)
  208. original_mean = z.mean()
  209. z = z * batch_multipliers.reshape(batch_multipliers.shape + (1,)).expand(z.shape)
  210. new_mean = z.mean()
  211. z = z * (original_mean / new_mean)
  212. if pooled is not None:
  213. z.pooled = pooled
  214. return z
  215. class FrozenCLIPEmbedderWithCustomWords(FrozenCLIPEmbedderWithCustomWordsBase):
  216. def __init__(self, wrapped, hijack):
  217. super().__init__(wrapped, hijack)
  218. self.tokenizer = wrapped.tokenizer
  219. vocab = self.tokenizer.get_vocab()
  220. self.comma_token = vocab.get(',</w>', None)
  221. self.token_mults = {}
  222. tokens_with_parens = [(k, v) for k, v in vocab.items() if '(' in k or ')' in k or '[' in k or ']' in k]
  223. for text, ident in tokens_with_parens:
  224. mult = 1.0
  225. for c in text:
  226. if c == '[':
  227. mult /= 1.1
  228. if c == ']':
  229. mult *= 1.1
  230. if c == '(':
  231. mult *= 1.1
  232. if c == ')':
  233. mult /= 1.1
  234. if mult != 1.0:
  235. self.token_mults[ident] = mult
  236. self.id_start = self.wrapped.tokenizer.bos_token_id
  237. self.id_end = self.wrapped.tokenizer.eos_token_id
  238. self.id_pad = self.id_end
  239. def tokenize(self, texts):
  240. tokenized = self.wrapped.tokenizer(texts, truncation=False, add_special_tokens=False)["input_ids"]
  241. return tokenized
  242. def encode_with_transformers(self, tokens):
  243. outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=-opts.CLIP_stop_at_last_layers)
  244. if opts.CLIP_stop_at_last_layers > 1:
  245. z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers]
  246. z = self.wrapped.transformer.text_model.final_layer_norm(z)
  247. else:
  248. z = outputs.last_hidden_state
  249. return z
  250. def encode_embedding_init_text(self, init_text, nvpt):
  251. embedding_layer = self.wrapped.transformer.text_model.embeddings
  252. ids = self.wrapped.tokenizer(init_text, max_length=nvpt, return_tensors="pt", add_special_tokens=False)["input_ids"]
  253. embedded = embedding_layer.token_embedding.wrapped(ids.to(embedding_layer.token_embedding.wrapped.weight.device)).squeeze(0)
  254. return embedded
  255. class FrozenCLIPEmbedderForSDXLWithCustomWords(FrozenCLIPEmbedderWithCustomWords):
  256. def __init__(self, wrapped, hijack):
  257. super().__init__(wrapped, hijack)
  258. def encode_with_transformers(self, tokens):
  259. outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=self.wrapped.layer == "hidden")
  260. if self.wrapped.layer == "last":
  261. z = outputs.last_hidden_state
  262. else:
  263. z = outputs.hidden_states[self.wrapped.layer_idx]
  264. return z