Add trout/text_encoder.py
Browse files- trout/text_encoder.py +86 -0
trout/text_encoder.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen CLIP text encoder + shared tokenisation for data prep and inference."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from typing import Sequence, Tuple
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
DEFAULT_TEXT_ENCODER = "openai/clip-vit-base-patch32"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _local_override(name: str):
|
| 15 |
+
"""If TROUT_CLIP_LOCAL is set, serve `name` from a local directory (offline training)."""
|
| 16 |
+
local = os.environ.get("TROUT_CLIP_LOCAL")
|
| 17 |
+
if local and name == DEFAULT_TEXT_ENCODER and os.path.isdir(local):
|
| 18 |
+
return local
|
| 19 |
+
return None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_tokenizer(name: str):
|
| 23 |
+
from transformers import AutoTokenizer
|
| 24 |
+
local = _local_override(name)
|
| 25 |
+
if local:
|
| 26 |
+
return AutoTokenizer.from_pretrained(local, local_files_only=True)
|
| 27 |
+
return AutoTokenizer.from_pretrained(name)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def tokenize_texts(tokenizer, texts: Sequence[str], text_len: int, batch: int = 65536) -> Tuple[np.ndarray, np.ndarray]:
|
| 31 |
+
"""Tokenise to a fixed length. Padding uses the pad id; over-long prompts are
|
| 32 |
+
truncated while keeping the final EOS token.
|
| 33 |
+
|
| 34 |
+
Returns (ids int32 (n, text_len), true_lengths int32 (n,)).
|
| 35 |
+
"""
|
| 36 |
+
eos = tokenizer.eos_token_id
|
| 37 |
+
pad = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else eos
|
| 38 |
+
n = len(texts)
|
| 39 |
+
out = np.full((n, text_len), pad, dtype=np.int32)
|
| 40 |
+
lengths = np.zeros(n, dtype=np.int32)
|
| 41 |
+
for s in range(0, n, batch):
|
| 42 |
+
chunk = [t if isinstance(t, str) else "" for t in texts[s:s + batch]]
|
| 43 |
+
enc = tokenizer(chunk, add_special_tokens=True, truncation=False)["input_ids"]
|
| 44 |
+
for i, ids in enumerate(enc):
|
| 45 |
+
lengths[s + i] = len(ids)
|
| 46 |
+
if len(ids) > text_len:
|
| 47 |
+
ids = list(ids[:text_len - 1]) + [eos]
|
| 48 |
+
out[s + i, :len(ids)] = ids
|
| 49 |
+
return out, lengths
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class FrozenTextEncoder:
|
| 53 |
+
"""Wraps a HF CLIP text tower. Deliberately not an nn.Module so its weights never
|
| 54 |
+
end up inside the trainable model, optimizer or checkpoints."""
|
| 55 |
+
|
| 56 |
+
def __init__(self, name: str = DEFAULT_TEXT_ENCODER, text_len: int = 24,
|
| 57 |
+
device="cpu", dtype: torch.dtype = torch.float32):
|
| 58 |
+
from transformers import CLIPTextModel
|
| 59 |
+
from transformers.utils import logging as hf_logging
|
| 60 |
+
self.name = name
|
| 61 |
+
self.text_len = text_len
|
| 62 |
+
self.device = torch.device(device)
|
| 63 |
+
self.dtype = dtype
|
| 64 |
+
self.tokenizer = load_tokenizer(name)
|
| 65 |
+
local = _local_override(name)
|
| 66 |
+
prev = hf_logging.get_verbosity()
|
| 67 |
+
hf_logging.set_verbosity_error() # full CLIP checkpoint has vision weights we skip on purpose
|
| 68 |
+
try:
|
| 69 |
+
model = CLIPTextModel.from_pretrained(local or name, local_files_only=bool(local))
|
| 70 |
+
finally:
|
| 71 |
+
hf_logging.set_verbosity(prev)
|
| 72 |
+
self.model = model.to(device=self.device, dtype=dtype).eval().requires_grad_(False)
|
| 73 |
+
self.dim = int(model.config.hidden_size)
|
| 74 |
+
|
| 75 |
+
def tokenize(self, texts: Sequence[str]) -> torch.Tensor:
|
| 76 |
+
ids, _ = tokenize_texts(self.tokenizer, list(texts), self.text_len)
|
| 77 |
+
return torch.from_numpy(ids).long().to(self.device)
|
| 78 |
+
|
| 79 |
+
@torch.no_grad()
|
| 80 |
+
def __call__(self, ids: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 81 |
+
out = self.model(input_ids=ids.long().to(self.device))
|
| 82 |
+
return out.last_hidden_state, out.pooler_output
|
| 83 |
+
|
| 84 |
+
@torch.no_grad()
|
| 85 |
+
def encode(self, texts: Sequence[str]) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 86 |
+
return self(self.tokenize(texts))
|