Leofames's picture
Upload folder using huggingface_hub
f1725f0 verified
Raw History Blame Contribute Delete
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
@torch.no_grad()
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()