File size: 4,703 Bytes
a04730e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | from __future__ import annotations
from dataclasses import dataclass
import torch
from torch import nn
from transformers import CLIPTextModel, CLIPTokenizer
@dataclass
class TextConditioningOutput:
"""
Output of the CLIP text encoder.
hidden_states:
Token-level CLIP embeddings.
Shape: [B, seq_len, hidden_dim]
attention_mask:
Token attention mask.
Shape: [B, seq_len]
pooled:
Optional pooled text embedding.
Shape: [B, hidden_dim]
"""
hidden_states: torch.Tensor
attention_mask: torch.Tensor
pooled: torch.Tensor | None = None
class FrozenCLIPTextEncoder(nn.Module):
"""
Frozen CLIP text encoder for latent diffusion conditioning
model:
openai/clip-vit-large-patch14
This gives:
context_dim = 768
max_length = 77
"""
def __init__(
self,
model_name: str = "openai/clip-vit-large-patch14",
max_length: int = 77,
freeze: bool = True,
use_last_hidden_state: bool = True,
cache_dir: str | None = None,
local_files_only: bool = False,
):
super().__init__()
self.model_name = model_name
self.max_length = max_length
self.freeze = freeze
self.use_last_hidden_state = use_last_hidden_state
self.cache_dir = cache_dir
self.local_files_only = local_files_only
self.tokenizer = CLIPTokenizer.from_pretrained(
model_name,
cache_dir=cache_dir,
local_files_only=local_files_only,
)
self.text_model = CLIPTextModel.from_pretrained(
model_name,
cache_dir=cache_dir,
local_files_only=local_files_only,
)
if self.freeze:
self.text_model.eval()
for p in self.text_model.parameters():
p.requires_grad = False
@property
def context_dim(self) -> int:
return int(self.text_model.config.hidden_size)
@property
def vocab_size(self) -> int:
return int(self.tokenizer.vocab_size)
@property
def pad_token_id(self) -> int:
return int(self.tokenizer.pad_token_id)
def train(self, mode: bool = True):
"""
Keep CLIP frozen/eval even if parent model calls .train().
"""
super().train(mode)
if self.freeze:
self.text_model.eval()
return self
def tokenize(
self,
captions: list[str] | tuple[str, ...],
device: torch.device | str | None = None,
) -> dict[str, torch.Tensor]:
"""
Tokenize captions into CLIP input tensors.
"""
tokens = self.tokenizer(
list(captions),
padding="max_length",
truncation=True,
max_length=self.max_length,
return_tensors="pt",
)
if device is not None:
tokens = {
key: value.to(device)
for key, value in tokens.items()
}
return tokens
def forward(
self,
captions: list[str] | tuple[str, ...],
device: torch.device | str | None = None,
) -> TextConditioningOutput:
"""
Produces CLIP textual embeddings as diffusion condition.
"""
if device is None:
device = next(self.text_model.parameters()).device
tokens = self.tokenize(
captions=captions,
device=device,
)
with torch.no_grad() if self.freeze else torch.enable_grad():
outputs = self.text_model(
input_ids=tokens["input_ids"],
attention_mask=tokens["attention_mask"],
output_hidden_states=not self.use_last_hidden_state,
return_dict=True,
)
if self.use_last_hidden_state:
hidden_states = outputs.last_hidden_state
else:
# Penultimate layer is sometimes used in diffusion models.
hidden_states = outputs.hidden_states[-2]
pooled = outputs.pooler_output
return TextConditioningOutput(
hidden_states=hidden_states,
attention_mask=tokens["attention_mask"],
pooled=pooled,
)
@torch.no_grad()
def encode(
self,
captions: list[str] | tuple[str, ...],
device: torch.device | str | None = None,
) -> torch.Tensor:
"""
Convenience function.
Returns only token-level context:
[B, seq_len, context_dim]
"""
return self.forward(
captions=captions,
device=device,
).hidden_states |