Download text_encoder.py from Leofames/textpainting-precompute-chunks: direct link, hf CLI and curl.
- Browser
- Download file 1.04 kB
-
https://huggingface.co/datasets/Leofames/textpainting-precompute-chunks/resolve/main/text_encoder.py
- Command line
-
hf download hf://datasets/Leofames/textpainting-precompute-chunks/text_encoder.py
-
curl -L -o text_encoder.py https://huggingface.co/datasets/Leofames/textpainting-precompute-chunks/resolve/main/text_encoder.py
1.04 kB
| # text_encoder.py | |
| # One place for caption encoding, so precompute and sampling do EXACTLY the same thing. | |
| import torch | |
| from transformers import AutoTokenizer, AutoModel | |
| from config import TEXT_ENCODER_NAME, TEXT_SEQ_LEN | |
| def load_text_encoder(device): | |
| # XLM-R already has a proper <pad> token. (The old code set pad = eos, which made | |
| # padding look like a real end-of-sentence token. With the attention mask it no longer matters.) | |
| tokenizer = AutoTokenizer.from_pretrained(TEXT_ENCODER_NAME) | |
| model = AutoModel.from_pretrained(TEXT_ENCODER_NAME).to(device).eval().requires_grad_(False) | |
| return tokenizer, model | |
| def encode_captions(captions, tokenizer, model, device): | |
| """Returns (embeddings [B, 77, 768] float16, mask [B, 77] bool, True = real token).""" | |
| tok = tokenizer(list(captions), padding="max_length", max_length=TEXT_SEQ_LEN, | |
| truncation=True, return_tensors="pt").to(device) | |
| emb = model(**tok).last_hidden_state | |
| return emb.half(), tok["attention_mask"].bool() | |