sd_hijack_clip.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. def empty_chunk(self):
  33. """creates an empty PromptChunk and returns it"""
  34. chunk = PromptChunk()
  35. chunk.tokens = [self.id_start] + [self.id_end] * (self.chunk_length + 1)
  36. chunk.multipliers = [1.0] * (self.chunk_length + 2)
  37. return chunk
  38. def get_target_prompt_token_count(self, token_count):
  39. """returns the maximum number of tokens a prompt of a known length can have before it requires one more PromptChunk to be represented"""
  40. return math.ceil(max(token_count, 1) / self.chunk_length) * self.chunk_length
  41. def tokenize(self, texts):
  42. """Converts a batch of texts into a batch of token ids"""
  43. raise NotImplementedError
  44. def encode_with_transformers(self, tokens):
  45. """
  46. converts a batch of token ids (in python lists) into a single tensor with numeric respresentation of those tokens;
  47. All python lists with tokens are assumed to have same length, usually 77.
  48. 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
  49. model - can be 768 and 1024.
  50. Among other things, this call will read self.hijack.fixes, apply it to its inputs, and clear it (setting it to None).
  51. """
  52. raise NotImplementedError
  53. def encode_embedding_init_text(self, init_text, nvpt):
  54. """Converts text into a tensor with this text's tokens' embeddings. Note that those are embeddings before they are passed through
  55. transformers. nvpt is used as a maximum length in tokens. If text produces less teokens than nvpt, only this many is returned."""
  56. raise NotImplementedError
  57. def tokenize_line(self, line):
  58. """
  59. this transforms a single prompt into a list of PromptChunk objects - as many as needed to
  60. represent the prompt.
  61. Returns the list and the total number of tokens in the prompt.
  62. """
  63. if opts.enable_emphasis:
  64. parsed = prompt_parser.parse_prompt_attention(line)
  65. else:
  66. parsed = [[line, 1.0]]
  67. tokenized = self.tokenize([text for text, _ in parsed])
  68. chunks = []
  69. chunk = PromptChunk()
  70. token_count = 0
  71. last_comma = -1
  72. def next_chunk(is_last=False):
  73. """puts current chunk into the list of results and produces the next one - empty;
  74. if is_last is true, tokens <end-of-text> tokens at the end won't add to token_count"""
  75. nonlocal token_count
  76. nonlocal last_comma
  77. nonlocal chunk
  78. if is_last:
  79. token_count += len(chunk.tokens)
  80. else:
  81. token_count += self.chunk_length
  82. to_add = self.chunk_length - len(chunk.tokens)
  83. if to_add > 0:
  84. chunk.tokens += [self.id_end] * to_add
  85. chunk.multipliers += [1.0] * to_add
  86. chunk.tokens = [self.id_start] + chunk.tokens + [self.id_end]
  87. chunk.multipliers = [1.0] + chunk.multipliers + [1.0]
  88. last_comma = -1
  89. chunks.append(chunk)
  90. chunk = PromptChunk()
  91. for tokens, (text, weight) in zip(tokenized, parsed):
  92. if text == 'BREAK' and weight == -1:
  93. next_chunk()
  94. continue
  95. position = 0
  96. while position < len(tokens):
  97. token = tokens[position]
  98. if token == self.comma_token:
  99. last_comma = len(chunk.tokens)
  100. # 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
  101. # 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.
  102. 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:
  103. break_location = last_comma + 1
  104. reloc_tokens = chunk.tokens[break_location:]
  105. reloc_mults = chunk.multipliers[break_location:]
  106. chunk.tokens = chunk.tokens[:break_location]
  107. chunk.multipliers = chunk.multipliers[:break_location]
  108. next_chunk()
  109. chunk.tokens = reloc_tokens
  110. chunk.multipliers = reloc_mults
  111. if len(chunk.tokens) == self.chunk_length:
  112. next_chunk()
  113. embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, position)
  114. if embedding is None:
  115. chunk.tokens.append(token)
  116. chunk.multipliers.append(weight)
  117. position += 1
  118. continue
  119. emb_len = int(embedding.vec.shape[0])
  120. if len(chunk.tokens) + emb_len > self.chunk_length:
  121. next_chunk()
  122. chunk.fixes.append(PromptChunkFix(len(chunk.tokens), embedding))
  123. chunk.tokens += [0] * emb_len
  124. chunk.multipliers += [weight] * emb_len
  125. position += embedding_length_in_tokens
  126. if chunk.tokens or not chunks:
  127. next_chunk(is_last=True)
  128. return chunks, token_count
  129. def process_texts(self, texts):
  130. """
  131. Accepts a list of texts and calls tokenize_line() on each, with cache. Returns the list of results and maximum
  132. length, in tokens, of all texts.
  133. """
  134. token_count = 0
  135. cache = {}
  136. batch_chunks = []
  137. for line in texts:
  138. if line in cache:
  139. chunks = cache[line]
  140. else:
  141. chunks, current_token_count = self.tokenize_line(line)
  142. token_count = max(current_token_count, token_count)
  143. cache[line] = chunks
  144. batch_chunks.append(chunks)
  145. return batch_chunks, token_count
  146. def forward(self, texts):
  147. """
  148. Accepts an array of texts; Passes texts through transformers network to create a tensor with numerical representation of those texts.
  149. 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
  150. be a multiple of 77; and C is dimensionality of each token - for SD1 it's 768, and for SD2 it's 1024.
  151. An example shape returned by this function can be: (2, 77, 768).
  152. 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
  153. is when you do prompt editing: "a picture of a [cat:dog:0.4] eating ice cream"
  154. """
  155. if opts.use_old_emphasis_implementation:
  156. import modules.sd_hijack_clip_old
  157. return modules.sd_hijack_clip_old.forward_old(self, texts)
  158. batch_chunks, token_count = self.process_texts(texts)
  159. used_embeddings = {}
  160. chunk_count = max([len(x) for x in batch_chunks])
  161. zs = []
  162. for i in range(chunk_count):
  163. batch_chunk = [chunks[i] if i < len(chunks) else self.empty_chunk() for chunks in batch_chunks]
  164. tokens = [x.tokens for x in batch_chunk]
  165. multipliers = [x.multipliers for x in batch_chunk]
  166. self.hijack.fixes = [x.fixes for x in batch_chunk]
  167. for fixes in self.hijack.fixes:
  168. for _position, embedding in fixes:
  169. used_embeddings[embedding.name] = embedding
  170. z = self.process_tokens(tokens, multipliers)
  171. zs.append(z)
  172. if len(used_embeddings) > 0:
  173. embeddings_list = ", ".join([f'{name} [{embedding.checksum()}]' for name, embedding in used_embeddings.items()])
  174. self.hijack.comments.append(f"Used embeddings: {embeddings_list}")
  175. return torch.hstack(zs)
  176. def process_tokens(self, remade_batch_tokens, batch_multipliers):
  177. """
  178. sends one single prompt chunk to be encoded by transformers neural network.
  179. remade_batch_tokens is a batch of tokens - a list, where every element is a list of tokens; usually
  180. there are exactly 77 tokens in the list. batch_multipliers is the same but for multipliers instead of tokens.
  181. Multipliers are used to give more or less weight to the outputs of transformers network. Each multiplier
  182. corresponds to one token.
  183. """
  184. tokens = torch.asarray(remade_batch_tokens).to(devices.device)
  185. # this is for SD2: SD1 uses the same token for padding and end of text, while SD2 uses different ones.
  186. if self.id_end != self.id_pad:
  187. for batch_pos in range(len(remade_batch_tokens)):
  188. index = remade_batch_tokens[batch_pos].index(self.id_end)
  189. tokens[batch_pos, index+1:tokens.shape[1]] = self.id_pad
  190. z = self.encode_with_transformers(tokens)
  191. # restoring original mean is likely not correct, but it seems to work well to prevent artifacts that happen otherwise
  192. batch_multipliers = torch.asarray(batch_multipliers).to(devices.device)
  193. original_mean = z.mean()
  194. z = z * batch_multipliers.reshape(batch_multipliers.shape + (1,)).expand(z.shape)
  195. new_mean = z.mean()
  196. z = z * (original_mean / new_mean)
  197. return z
  198. class FrozenCLIPEmbedderWithCustomWords(FrozenCLIPEmbedderWithCustomWordsBase):
  199. def __init__(self, wrapped, hijack):
  200. super().__init__(wrapped, hijack)
  201. self.tokenizer = wrapped.tokenizer
  202. vocab = self.tokenizer.get_vocab()
  203. self.comma_token = vocab.get(',</w>', None)
  204. self.token_mults = {}
  205. tokens_with_parens = [(k, v) for k, v in vocab.items() if '(' in k or ')' in k or '[' in k or ']' in k]
  206. for text, ident in tokens_with_parens:
  207. mult = 1.0
  208. for c in text:
  209. if c == '[':
  210. mult /= 1.1
  211. if c == ']':
  212. mult *= 1.1
  213. if c == '(':
  214. mult *= 1.1
  215. if c == ')':
  216. mult /= 1.1
  217. if mult != 1.0:
  218. self.token_mults[ident] = mult
  219. self.id_start = self.wrapped.tokenizer.bos_token_id
  220. self.id_end = self.wrapped.tokenizer.eos_token_id
  221. self.id_pad = self.id_end
  222. def tokenize(self, texts):
  223. tokenized = self.wrapped.tokenizer(texts, truncation=False, add_special_tokens=False)["input_ids"]
  224. return tokenized
  225. def encode_with_transformers(self, tokens):
  226. outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=-opts.CLIP_stop_at_last_layers)
  227. if opts.CLIP_stop_at_last_layers > 1:
  228. z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers]
  229. z = self.wrapped.transformer.text_model.final_layer_norm(z)
  230. else:
  231. z = outputs.last_hidden_state
  232. return z
  233. def encode_embedding_init_text(self, init_text, nvpt):
  234. embedding_layer = self.wrapped.transformer.text_model.embeddings
  235. ids = self.wrapped.tokenizer(init_text, max_length=nvpt, return_tensors="pt", add_special_tokens=False)["input_ids"]
  236. embedded = embedding_layer.token_embedding.wrapped(ids.to(embedding_layer.token_embedding.wrapped.weight.device)).squeeze(0)
  237. return embedded