Guest User

Untitled

a guest
Mar 1st, 2023
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.68 KB | None | 0 0
  1. import math
  2. from collections import namedtuple
  3.  
  4. import torch
  5.  
  6. from modules import prompt_parser, devices, sd_hijack
  7. from modules.shared import opts
  8.  
  9.  
  10. class PromptChunk:
  11.     """
  12.    This object contains token ids, weight (multipliers:1.4) and textual inversion embedding info for a chunk of prompt.
  13.    If a prompt is short, it is represented by one PromptChunk, otherwise, multiple are necessary.
  14.    Each PromptChunk contains an exact amount of tokens - 77, which includes one for start and end token,
  15.    so just 75 tokens from prompt.
  16.    """
  17.  
  18.     def __init__(self):
  19.         self.tokens = []
  20.         self.multipliers = []
  21.         self.fixes = []
  22.  
  23.  
  24. PromptChunkFix = namedtuple('PromptChunkFix', ['offset', 'embedding'])
  25. """An object of this type is a marker showing that textual inversion embedding's vectors have to placed at offset in the prompt
  26. chunk. Thos objects are found in PromptChunk.fixes and, are placed into FrozenCLIPEmbedderWithCustomWordsBase.hijack.fixes, and finally
  27. are applied by sd_hijack.EmbeddingsWithFixes's forward function."""
  28.  
  29.  
  30. class FrozenCLIPEmbedderWithCustomWordsBase(torch.nn.Module):
  31.     """A pytorch module that is a wrapper for FrozenCLIPEmbedder module. it enhances FrozenCLIPEmbedder, making it possible to
  32.    have unlimited prompt length and assign weights to tokens in prompt.
  33.    """
  34.  
  35.     def __init__(self, wrapped, hijack):
  36.         super().__init__()
  37.  
  38.         self.wrapped = wrapped
  39.         """Original FrozenCLIPEmbedder module; can also be FrozenOpenCLIPEmbedder or xlmr.BertSeriesModelWithTransformation,
  40.        depending on model."""
  41.  
  42.         self.hijack: sd_hijack.StableDiffusionModelHijack = hijack
  43.         self.chunk_length = 75
  44.  
  45.     def empty_chunk(self):
  46.         """creates an empty PromptChunk and returns it"""
  47.  
  48.         chunk = PromptChunk()
  49.         chunk.tokens = [self.id_start] + [self.id_end] * (self.chunk_length + 1)
  50.         chunk.multipliers = [1.0] * (self.chunk_length + 2)
  51.         return chunk
  52.  
  53.     def get_target_prompt_token_count(self, token_count):
  54.         """returns the maximum number of tokens a prompt of a known length can have before it requires one more PromptChunk to be represented"""
  55.  
  56.         return math.ceil(max(token_count, 1) / self.chunk_length) * self.chunk_length
  57.  
  58.     def tokenize(self, texts):
  59.         """Converts a batch of texts into a batch of token ids"""
  60.  
  61.         raise NotImplementedError
  62.  
  63.     def encode_with_transformers(self, tokens):
  64.         """
  65.        converts a batch of token ids (in python lists) into a single tensor with numeric respresentation of those tokens;
  66.        All python lists with tokens are assumed to have same length, usually 77.
  67.        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
  68.        model - can be 768 and 1024.
  69.        Among other things, this call will read self.hijack.fixes, apply it to its inputs, and clear it (setting it to None).
  70.        """
  71.  
  72.         raise NotImplementedError
  73.  
  74.     def encode_embedding_init_text(self, init_text, nvpt):
  75.         """Converts text into a tensor with this text's tokens' embeddings. Note that those are embeddings before they are passed through
  76.        transformers. nvpt is used as a maximum length in tokens. If text produces less teokens than nvpt, only this many is returned."""
  77.  
  78.         raise NotImplementedError
  79.  
  80.     def tokenize_line(self, line):
  81.         """
  82.        this transforms a single prompt into a list of PromptChunk objects - as many as needed to
  83.        represent the prompt.
  84.        Returns the list and the total number of tokens in the prompt.
  85.        """
  86.  
  87.         if opts.enable_emphasis:
  88.             parsed = prompt_parser.parse_prompt_attention(line)
  89.         else:
  90.             parsed = [[line, 1.0]]
  91.  
  92.         tokenized = self.tokenize([text for text, _ in parsed])
  93.  
  94.         chunks = []
  95.         chunk = PromptChunk()
  96.         token_count = 0
  97.         last_comma = -1
  98.  
  99.         def next_chunk(is_last=False):
  100.             """puts current chunk into the list of results and produces the next one - empty;
  101.            if is_last is true, tokens <end-of-text> tokens at the end won't add to token_count"""
  102.             nonlocal token_count
  103.             nonlocal last_comma
  104.             nonlocal chunk
  105.  
  106.             if is_last:
  107.                 token_count += len(chunk.tokens)
  108.             else:
  109.                 token_count += self.chunk_length
  110.  
  111.             to_add = self.chunk_length - len(chunk.tokens)
  112.             if to_add > 0:
  113.                 chunk.tokens += [self.id_end] * to_add
  114.                 chunk.multipliers += [1.0] * to_add
  115.  
  116.             chunk.tokens = [self.id_start] + chunk.tokens + [self.id_end]
  117.             chunk.multipliers = [1.0] + chunk.multipliers + [1.0]
  118.  
  119.             last_comma = -1
  120.             chunks.append(chunk)
  121.             chunk = PromptChunk()
  122.  
  123.         for tokens, (text, weight) in zip(tokenized, parsed):
  124.             if text == 'BREAK' and weight == -1:
  125.                 next_chunk()
  126.                 continue
  127.  
  128.             position = 0
  129.             while position < len(tokens):
  130.                 token = tokens[position]
  131.  
  132.                 if token == self.comma_token:
  133.                     last_comma = len(chunk.tokens)
  134.  
  135.                 # 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
  136.                 # 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.
  137.                 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:
  138.                     break_location = last_comma + 1
  139.  
  140.                     reloc_tokens = chunk.tokens[break_location:]
  141.                     reloc_mults = chunk.multipliers[break_location:]
  142.  
  143.                     chunk.tokens = chunk.tokens[:break_location]
  144.                     chunk.multipliers = chunk.multipliers[:break_location]
  145.  
  146.                     next_chunk()
  147.                     chunk.tokens = reloc_tokens
  148.                     chunk.multipliers = reloc_mults
  149.  
  150.                 if len(chunk.tokens) == self.chunk_length:
  151.                     next_chunk()
  152.  
  153.                 embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, position)
  154.                 if embedding is None:
  155.                     chunk.tokens.append(token)
  156.                     chunk.multipliers.append(weight)
  157.                     position += 1
  158.                     continue
  159.  
  160.                 emb_len = int(embedding.vec.shape[0])
  161.                 if len(chunk.tokens) + emb_len > self.chunk_length:
  162.                     next_chunk()
  163.  
  164.                 chunk.fixes.append(PromptChunkFix(len(chunk.tokens), embedding))
  165.  
  166.                 chunk.tokens += [0] * emb_len
  167.                 chunk.multipliers += [weight] * emb_len
  168.                 position += embedding_length_in_tokens
  169.  
  170.         if len(chunk.tokens) > 0 or len(chunks) == 0:
  171.             next_chunk(is_last=True)
  172.  
  173.         return chunks, token_count
  174.  
  175.     def process_texts(self, texts):
  176.         """
  177.        Accepts a list of texts and calls tokenize_line() on each, with cache. Returns the list of results and maximum
  178.        length, in tokens, of all texts.
  179.        """
  180.  
  181.         token_count = 0
  182.  
  183.         cache = {}
  184.         batch_chunks = []
  185.         for line in texts:
  186.             if line in cache:
  187.                 chunks = cache[line]
  188.             else:
  189.                 chunks, current_token_count = self.tokenize_line(line)
  190.                 token_count = max(current_token_count, token_count)
  191.  
  192.                 cache[line] = chunks
  193.  
  194.             batch_chunks.append(chunks)
  195.  
  196.         return batch_chunks, token_count
  197.  
  198.     def forward(self, texts):
  199.         """
  200.        Accepts an array of texts; Passes texts through transformers network to create a tensor with numerical representation of those texts.
  201.        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
  202.        be a multiple of 77; and C is dimensionality of each token - for SD1 it's 768, and for SD2 it's 1024.
  203.        An example shape returned by this function can be: (2, 77, 768).
  204.        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
  205.        is when you do prompt editing: "a picture of a [cat:dog:0.4] eating ice cream"
  206.        """
  207.  
  208.         if opts.use_old_emphasis_implementation:
  209.             import modules.sd_hijack_clip_old
  210.             return modules.sd_hijack_clip_old.forward_old(self, texts)
  211.  
  212.         batch_chunks, token_count = self.process_texts(texts)
  213.  
  214.         used_embeddings = {}
  215.         chunk_count = max([len(x) for x in batch_chunks])
  216.  
  217.         zs = []
  218.         for i in range(chunk_count):
  219.             batch_chunk = [chunks[i] if i < len(chunks) else self.empty_chunk() for chunks in batch_chunks]
  220.  
  221.             tokens = [x.tokens for x in batch_chunk]
  222.             multipliers = [x.multipliers for x in batch_chunk]
  223.             self.hijack.fixes = [x.fixes for x in batch_chunk]
  224.  
  225.             for fixes in self.hijack.fixes:
  226.                 for position, embedding in fixes:
  227.                     used_embeddings[embedding.name] = embedding
  228.  
  229.             if opts.CLIP_stop_at_last_layers<=2:
  230.                 z = self.process_tokens(tokens, multipliers, opts.CLIP_stop_at_last_layers)
  231.                 zs.append(z)
  232.             if opts.CLIP_stop_at_last_layers==3:
  233.                 z1 = self.process_tokens(tokens, multipliers, 1)
  234.                 z2 = self.process_tokens(tokens, multipliers, 2)
  235.                 zs.append((z1*0.5+z2*0.5))
  236.             if opts.CLIP_stop_at_last_layers==4:
  237.                 z1 = self.process_tokens(tokens, multipliers, 1)
  238.                 z2 = self.process_tokens(tokens, multipliers, 2)
  239.                 zs.append(z1)
  240.                 zs.append(z2)
  241.  
  242.  
  243.         if len(used_embeddings) > 0:
  244.             embeddings_list = ", ".join([f'{name} [{embedding.checksum()}]' for name, embedding in used_embeddings.items()])
  245.             self.hijack.comments.append(f"Used embeddings: {embeddings_list}")
  246.  
  247.         return torch.hstack(zs)
  248.  
  249.     def process_tokens(self, remade_batch_tokens, batch_multipliers, skip):
  250.         """
  251.        sends one single prompt chunk to be encoded by transformers neural network.
  252.        remade_batch_tokens is a batch of tokens - a list, where every element is a list of tokens; usually
  253.        there are exactly 77 tokens in the list. batch_multipliers is the same but for multipliers instead of tokens.
  254.        Multipliers are used to give more or less weight to the outputs of transformers network. Each multiplier
  255.        corresponds to one token.
  256.        """
  257.         tokens = torch.asarray(remade_batch_tokens).to(devices.device)
  258.  
  259.         # this is for SD2: SD1 uses the same token for padding and end of text, while SD2 uses different ones.
  260.         if self.id_end != self.id_pad:
  261.             for batch_pos in range(len(remade_batch_tokens)):
  262.                 index = remade_batch_tokens[batch_pos].index(self.id_end)
  263.                 tokens[batch_pos, index+1:tokens.shape[1]] = self.id_pad
  264.  
  265.         z = self.encode_with_transformers(tokens, skip)
  266.  
  267.         # restoring original mean is likely not correct, but it seems to work well to prevent artifacts that happen otherwise
  268.         batch_multipliers = torch.asarray(batch_multipliers).to(devices.device)
  269.         original_mean = z.mean()
  270.         z = z * batch_multipliers.reshape(batch_multipliers.shape + (1,)).expand(z.shape)
  271.         new_mean = z.mean()
  272.         z = z * (original_mean / new_mean)
  273.  
  274.         return z
  275.  
  276.  
  277. class FrozenCLIPEmbedderWithCustomWords(FrozenCLIPEmbedderWithCustomWordsBase):
  278.     def __init__(self, wrapped, hijack):
  279.         super().__init__(wrapped, hijack)
  280.         self.tokenizer = wrapped.tokenizer
  281.  
  282.         vocab = self.tokenizer.get_vocab()
  283.  
  284.         self.comma_token = vocab.get(',</w>', None)
  285.  
  286.         self.token_mults = {}
  287.         tokens_with_parens = [(k, v) for k, v in vocab.items() if '(' in k or ')' in k or '[' in k or ']' in k]
  288.         for text, ident in tokens_with_parens:
  289.             mult = 1.0
  290.             for c in text:
  291.                 if c == '[':
  292.                     mult /= 1.1
  293.                 if c == ']':
  294.                     mult *= 1.1
  295.                 if c == '(':
  296.                     mult *= 1.1
  297.                 if c == ')':
  298.                     mult /= 1.1
  299.  
  300.             if mult != 1.0:
  301.                 self.token_mults[ident] = mult
  302.  
  303.         self.id_start = self.wrapped.tokenizer.bos_token_id
  304.         self.id_end = self.wrapped.tokenizer.eos_token_id
  305.         self.id_pad = self.id_end
  306.  
  307.     def tokenize(self, texts):
  308.         tokenized = self.wrapped.tokenizer(texts, truncation=False, add_special_tokens=False)["input_ids"]
  309.  
  310.         return tokenized
  311.  
  312.     def encode_with_transformers(self, tokens, skip):
  313.         outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=-skip)
  314.  
  315.         if skip > 1:
  316.             z = outputs.hidden_states[-skip]
  317.             z = self.wrapped.transformer.text_model.final_layer_norm(z)
  318.         else:
  319.             z = outputs.last_hidden_state
  320.  
  321.         return z
  322.  
  323.     def encode_embedding_init_text(self, init_text, nvpt):
  324.         embedding_layer = self.wrapped.transformer.text_model.embeddings
  325.         ids = self.wrapped.tokenizer(init_text, max_length=nvpt, return_tensors="pt", add_special_tokens=False)["input_ids"]
  326.         embedded = embedding_layer.token_embedding.wrapped(ids.to(embedding_layer.token_embedding.wrapped.weight.device)).squeeze(0)
  327.  
  328.         return embedded
  329.  
Advertisement
Add Comment
Please, Sign In to add comment