sd_hijack_xlmr.py 1.4 KB

1234567891011121314151617181920212223242526272829303132
  1. import torch
  2. from modules import sd_hijack_clip, devices
  3. class FrozenXLMREmbedderWithCustomWords(sd_hijack_clip.FrozenCLIPEmbedderWithCustomWords):
  4. def __init__(self, wrapped, hijack):
  5. super().__init__(wrapped, hijack)
  6. self.id_start = wrapped.config.bos_token_id
  7. self.id_end = wrapped.config.eos_token_id
  8. self.id_pad = wrapped.config.pad_token_id
  9. self.comma_token = self.tokenizer.get_vocab().get(',', None) # alt diffusion doesn't have </w> bits for comma
  10. def encode_with_transformers(self, tokens):
  11. # there's no CLIP Skip here because all hidden layers have size of 1024 and the last one uses a
  12. # trained layer to transform those 1024 into 768 for unet; so you can't choose which transformer
  13. # layer to work with - you have to use the last
  14. attention_mask = (tokens != self.id_pad).to(device=tokens.device, dtype=torch.int64)
  15. features = self.wrapped(input_ids=tokens, attention_mask=attention_mask)
  16. z = features['projection_state']
  17. return z
  18. def encode_embedding_init_text(self, init_text, nvpt):
  19. embedding_layer = self.wrapped.roberta.embeddings
  20. ids = self.wrapped.tokenizer(init_text, max_length=nvpt, return_tensors="pt", add_special_tokens=False)["input_ids"]
  21. embedded = embedding_layer.token_embedding.wrapped(ids.to(devices.device)).squeeze(0)
  22. return embedded