Ruian7P commited on
Commit
cdd90c0
·
verified ·
1 Parent(s): b0ea269

upload baseline t5 small

Browse files
emuru_t5_small_2e-5_ech5/config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Emuru"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_emuru.EmuruConfig",
7
+ "AutoModel": "modeling_emuru.Emuru"
8
+ },
9
+ "model_type": "emuru",
10
+ "slices_per_query": 1,
11
+ "t5_name_or_path": "google-t5/t5-small",
12
+ "tokenizer_name_or_path": "google/byt5-small",
13
+ "torch_dtype": "float32",
14
+ "transformers_version": "4.54.0",
15
+ "vae_channels": 1,
16
+ "vae_name_or_path": "blowing-up-groundhogs/emuru_vae"
17
+ }
emuru_t5_small_2e-5_ech5/configuration_emuru.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class EmuruConfig(PretrainedConfig):
4
+ model_type = "emuru"
5
+
6
+ def __init__(self,
7
+ t5_name_or_path='google-t5/t5-large',
8
+ vae_name_or_path='blowing-up-groundhogs/emuru_vae',
9
+ tokenizer_name_or_path='google/byt5-small',
10
+ slices_per_query=1,
11
+ vae_channels=1,
12
+ **kwargs):
13
+ super().__init__(**kwargs)
14
+ self.t5_name_or_path = t5_name_or_path
15
+ self.vae_name_or_path = vae_name_or_path
16
+ self.tokenizer_name_or_path = tokenizer_name_or_path
17
+ self.slices_per_query = slices_per_query
18
+ self.vae_channels = vae_channels
emuru_t5_small_2e-5_ech5/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:426236d8b7147dc8b8c55b6f8b8a339c91e8e2c575778f81cc5670672fe3d0ed
3
+ size 232979496
emuru_t5_small_2e-5_ech5/modeling_emuru.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from transformers import PreTrainedModel, T5ForConditionalGeneration, T5Config, AutoTokenizer
4
+ from .configuration_emuru import EmuruConfig
5
+ from diffusers import AutoencoderKL
6
+ from einops.layers.torch import Rearrange
7
+ from einops import repeat
8
+ from torchvision.transforms import functional as F
9
+ from typing import Optional, Tuple, List, Any
10
+ from PIL import Image
11
+
12
+ class Emuru(PreTrainedModel):
13
+ """
14
+ Emuru is a conditional generative model that integrates a T5-based decoder with a VAE
15
+ for image generation conditioned on text and style images.
16
+ Attributes:
17
+ config_class (Type): Configuration class for the model.
18
+ tokenizer (AutoTokenizer): Tokenizer loaded from the provided tokenizer configuration.
19
+ T5 (T5ForConditionalGeneration): T5 model adapted for conditional generation.
20
+ sos (nn.Embedding): Start-of-sequence embedding.
21
+ vae_to_t5 (nn.Linear): Linear projection from VAE latent space to T5 hidden space.
22
+ t5_to_vae (nn.Linear): Linear projection from T5 hidden space back to VAE latent space.
23
+ padding_token (nn.Parameter): Non-trainable parameter for padding tokens.
24
+ padding_token_threshold (nn.Parameter): Non-trainable parameter for padding token threshold.
25
+ vae (AutoencoderKL): Pre-trained Variational Autoencoder.
26
+ query_rearrange (Rearrange): Layer to rearrange VAE latent representations for queries.
27
+ z_rearrange (Rearrange): Layer to rearrange T5 outputs back to VAE latent dimensions.
28
+ mse_criterion (nn.MSELoss): Mean squared error loss function.
29
+ """
30
+ config_class = EmuruConfig
31
+
32
+ def __init__(self, config: EmuruConfig) -> None:
33
+ """
34
+ Initialize the Emuru model.
35
+ Args:
36
+ config (EmuruConfig): Configuration object containing model hyperparameters and paths.
37
+ """
38
+ super().__init__(config)
39
+
40
+ self.tokenizer = AutoTokenizer.from_pretrained(config.tokenizer_name_or_path)
41
+
42
+ t5_config = T5Config.from_pretrained(config.t5_name_or_path)
43
+ t5_config.vocab_size = len(self.tokenizer)
44
+ self.T5 = T5ForConditionalGeneration(t5_config)
45
+ self.T5.lm_head = nn.Identity()
46
+ self.sos = nn.Embedding(1, t5_config.d_model)
47
+
48
+ vae_latent_size = 8 * config.vae_channels * config.slices_per_query
49
+ self.vae_to_t5 = nn.Linear(vae_latent_size, t5_config.d_model)
50
+ self.t5_to_vae = nn.Linear(t5_config.d_model, vae_latent_size, bias=False)
51
+
52
+ self.padding_token = nn.Parameter( torch.tensor([[-0.4951, 0.8021, 0.3429, 0.5622, 0.5271, 0.5756, 0.7194, 0.6150]]), requires_grad=False)
53
+ self.padding_token_threshold = nn.Parameter(torch.tensor(0.484982096850872), requires_grad=False)
54
+
55
+ self.query_rearrange = Rearrange('b c h (w q) -> b w (q c h)', q=config.slices_per_query)
56
+ self.z_rearrange = Rearrange('b w (q c h) -> b c h (w q)', c=config.vae_channels, q=config.slices_per_query)
57
+
58
+ self.mse_criterion = nn.MSELoss()
59
+ self.init_weights()
60
+
61
+ self.vae = AutoencoderKL.from_pretrained(config.vae_name_or_path)
62
+ self.set_training(self.vae, False)
63
+
64
+ def set_training(self, model: nn.Module, training: bool) -> None:
65
+ """
66
+ Set the training mode for a given model and freeze/unfreeze parameters accordingly.
67
+ Args:
68
+ model (nn.Module): The model to set the training mode for.
69
+ training (bool): If True, set the model to training mode; otherwise, evaluation mode.
70
+ """
71
+ model.train() if training else model.eval()
72
+ for param in model.parameters():
73
+ param.requires_grad = training
74
+
75
+ def forward(
76
+ self,
77
+ img: Optional[torch.Tensor] = None,
78
+ input_ids: Optional[torch.Tensor] = None,
79
+ attention_mask: Optional[torch.Tensor] = None,
80
+ noise: float = 0,
81
+ **kwargs: Any
82
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
83
+ """
84
+ Forward pass of the model.
85
+ Args:
86
+ img (Optional[torch.Tensor]): Input image tensor.
87
+ input_ids (Optional[torch.Tensor]): Tokenized input IDs.
88
+ attention_mask (Optional[torch.Tensor]): Attention mask for the inputs.
89
+ noise (float): Amount of noise to add in image encoding.
90
+ **kwargs: Additional arguments.
91
+ Returns:
92
+ Tuple containing:
93
+ - mse_loss (torch.Tensor): Mean squared error loss.
94
+ - pred_latent (torch.Tensor): Predicted latent representations.
95
+ - z (torch.Tensor): Sampled latent vector from VAE.
96
+ """
97
+ decoder_inputs_embeds, z_sequence, z = self._img_encode(img, noise)
98
+
99
+ output = self.T5(input_ids, attention_mask=attention_mask, decoder_inputs_embeds=decoder_inputs_embeds)
100
+ vae_latent = self.t5_to_vae(output.logits[:, :-1])
101
+ pred_latent = self.z_rearrange(vae_latent)
102
+
103
+ # Fix: Ensure sequence lengths match for loss computation
104
+ min_seq_len = min(vae_latent.size(1), z_sequence.size(1))
105
+ vae_latent_trimmed = vae_latent[:, :min_seq_len]
106
+ z_sequence_trimmed = z_sequence[:, :min_seq_len]
107
+
108
+ mse_loss = self.mse_criterion(vae_latent_trimmed, z_sequence_trimmed)
109
+ return mse_loss, pred_latent, z
110
+
111
+ @torch.inference_mode()
112
+ def generate(
113
+ self,
114
+ style_text: str,
115
+ gen_text: str,
116
+ style_img: torch.Tensor,
117
+ **kwargs: Any
118
+ ) -> Image.Image:
119
+ """
120
+ Generate an image by combining style and generation texts with a style image.
121
+ Args:
122
+ style_text (str): Style-related text prompt.
123
+ gen_text (str): Generation-related text prompt.
124
+ style_img (torch.Tensor): Style image tensor. Expected shape is either 3D or 4D.
125
+ **kwargs: Additional keyword arguments.
126
+ Returns:
127
+ Image.Image: Generated image as a PIL image.
128
+ """
129
+ if style_img.ndim == 3:
130
+ style_img = style_img.unsqueeze(0)
131
+ elif style_img.ndim == 4:
132
+ pass
133
+ else:
134
+ raise ValueError('style_img must be 3D or 4D')
135
+
136
+ texts = [style_text + ' ' + gen_text]
137
+ imgs, _, img_ends = self._generate(texts=texts, imgs=style_img, **kwargs)
138
+ imgs = (imgs + 1) / 2
139
+ return F.to_pil_image(imgs[0, ..., style_img.size(-1):img_ends.item()].detach().cpu())
140
+
141
+ @torch.inference_mode()
142
+ def generate_batch(
143
+ self,
144
+ style_texts: List[str],
145
+ gen_texts: List[str],
146
+ style_imgs: torch.Tensor,
147
+ lengths: List[int],
148
+ **kwargs: Any
149
+ ) -> List[Image.Image]:
150
+ """
151
+ Generate a batch of images from lists of style texts, generation texts, and style images.
152
+ Args:
153
+ style_texts (List[str]): List of style-related text prompts.
154
+ gen_texts (List[str]): List of generation-related text prompts.
155
+ style_imgs (torch.Tensor): Batch of style images (4D tensor).
156
+ lengths (List[int]): List of lengths corresponding to each image.
157
+ **kwargs: Additional keyword arguments.
158
+ Returns:
159
+ List[Image.Image]: List of generated images as PIL images.
160
+ """
161
+ assert style_imgs.ndim == 4, 'style_imgs must be 4D'
162
+ assert len(style_texts) == len(style_imgs), 'style_texts and style_imgs must have the same length'
163
+ assert len(gen_texts) == len(style_imgs), 'gen_texts and style_imgs must have the same length'
164
+ texts = [style_text + ' ' + gen_text for style_text, gen_text in zip(style_texts, gen_texts)]
165
+
166
+ imgs, _, img_ends = self._generate(texts=texts, imgs=style_imgs, lengths=lengths, **kwargs)
167
+ imgs = (imgs + 1) / 2
168
+
169
+ out_imgs = []
170
+ for i, end in enumerate(img_ends):
171
+ start = lengths[i]
172
+ out_imgs.append(F.to_pil_image(imgs[i, ..., start:end].detach().cpu()))
173
+ return out_imgs
174
+
175
+ def _generate(
176
+ self,
177
+ texts: Optional[List[str]] = None,
178
+ imgs: Optional[torch.Tensor] = None,
179
+ lengths: Optional[List[int]] = None,
180
+ input_ids: Optional[torch.Tensor] = None,
181
+ z_sequence: Optional[torch.Tensor] = None,
182
+ max_new_tokens: int = 256,
183
+ stopping_criteria: str = 'latent',
184
+ stopping_after: int = 10,
185
+ stopping_patience: int = 1
186
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
187
+ """
188
+ Internal generation routine that combines textual and visual inputs to iteratively generate
189
+ latent representations and decode them into images.
190
+ Args:
191
+ texts (Optional[List[str]]): List of text prompts.
192
+ imgs (Optional[torch.Tensor]): Input image tensor.
193
+ lengths (Optional[List[int]]): Desired lengths for each image in latent space.
194
+ input_ids (Optional[torch.Tensor]): Tokenized input IDs.
195
+ z_sequence (Optional[torch.Tensor]): Precomputed latent sequence.
196
+ max_new_tokens (int): Maximum tokens to generate.
197
+ stopping_criteria (str): Criteria for stopping ('latent' or 'none').
198
+ stopping_after (int): Number of tokens to check for stopping condition.
199
+ stopping_patience (int): Patience parameter for stopping condition.
200
+ Returns:
201
+ Tuple containing:
202
+ - imgs (torch.Tensor): Generated images.
203
+ - canvas_sequence (torch.Tensor): Generated latent canvas sequence.
204
+ - img_ends (torch.Tensor): End indices for each generated image.
205
+ """
206
+ assert texts is not None or input_ids is not None, 'Either texts or input_ids must be provided'
207
+ assert imgs is not None or z_sequence is not None, 'Either imgs or z_sequence must be provided'
208
+
209
+ if input_ids is None:
210
+ input_ids = self.tokenizer(texts, return_tensors='pt', padding=True).input_ids
211
+ input_ids = input_ids.to(self.device)
212
+
213
+ if z_sequence is None:
214
+ _, z_sequence, _ = self._img_encode(imgs)
215
+
216
+ if lengths is None:
217
+ lengths = [imgs.size(-1)] * imgs.size(0)
218
+ lengths = torch.tensor(lengths).to(self.device)
219
+ lengths = (lengths / 8).ceil().int()
220
+
221
+ z_sequence_mask = torch.zeros((z_sequence.size(0), lengths.max() + max_new_tokens))
222
+ z_sequence_mask = z_sequence_mask.bool().to(self.device)
223
+ for i, l in enumerate(lengths):
224
+ z_sequence_mask[i, :l] = True
225
+
226
+ canvas_sequence = z_sequence[:, :lengths.min()]
227
+ sos = repeat(self.sos.weight, '1 d -> b 1 d', b=input_ids.size(0))
228
+ pad_token = repeat(self.padding_token, '1 d -> b 1 d', b=input_ids.size(0))
229
+ seq_stops = torch.ones(z_sequence.size(0), dtype=torch.int) * -1
230
+
231
+ for token_idx in range(lengths.min(), lengths.max() + max_new_tokens):
232
+ if len(z_sequence) == 0:
233
+ decoder_inputs_embeds = sos
234
+ else:
235
+ decoder_inputs_embeds = self.vae_to_t5(canvas_sequence)
236
+ decoder_inputs_embeds = torch.cat([sos, decoder_inputs_embeds], dim=1)
237
+ output = self.T5(input_ids, decoder_inputs_embeds=decoder_inputs_embeds)
238
+ vae_latent = self.t5_to_vae(output.logits[:, -1:])
239
+
240
+ mask_slice = z_sequence_mask[:, token_idx].unsqueeze(-1)
241
+ if token_idx < z_sequence.size(1):
242
+ seq_slice = torch.where(mask_slice, z_sequence[:, token_idx], vae_latent[:, 0])
243
+ else:
244
+ seq_slice = vae_latent[:, 0]
245
+ canvas_sequence = torch.cat([canvas_sequence, seq_slice.unsqueeze(1)], dim=1)
246
+
247
+ if stopping_criteria == 'latent':
248
+ similarity = torch.nn.functional.cosine_similarity(canvas_sequence, pad_token, dim=-1)
249
+ windows = (similarity > self.padding_token_threshold).unfold(1, min(stopping_after, similarity.size(-1)), 1)
250
+ window_sums = windows.to(torch.int).sum(dim=2)
251
+
252
+ for i in range(similarity.size(0)):
253
+ idx = (window_sums[i] > (stopping_after - stopping_patience)).nonzero(as_tuple=True)[0]
254
+ if idx.numel() > 0:
255
+ seq_stops[i] = idx[0].item()
256
+
257
+ if torch.all(seq_stops >= 0):
258
+ break
259
+ elif stopping_criteria == 'none':
260
+ pass
261
+
262
+ imgs = torch.clamp(self.vae.decode(self.z_rearrange(canvas_sequence)).sample, -1, 1)
263
+ return imgs, canvas_sequence, seq_stops * 8
264
+
265
+ def _img_encode(
266
+ self,
267
+ img: torch.Tensor,
268
+ noise: float = 0
269
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
270
+ """
271
+ Encode the input image into a latent representation using the VAE.
272
+ Args:
273
+ img (torch.Tensor): Input image tensor.
274
+ noise (float): Standard deviation of noise to add to the latent sequence.
275
+ Returns:
276
+ Tuple containing:
277
+ - decoder_inputs_embeds (torch.Tensor): Embeddings to be used as T5 decoder inputs.
278
+ - z_sequence (torch.Tensor): Rearranged latent sequence from the VAE.
279
+ - z (torch.Tensor): Sampled latent vector from the VAE.
280
+ """
281
+ posterior = self.vae.encode(img.float())
282
+ z = posterior.latent_dist.sample()
283
+ z_sequence = self.query_rearrange(z)
284
+
285
+ noise_sequence = z_sequence
286
+ if noise > 0:
287
+ noise_sequence = z_sequence + torch.randn_like(z_sequence) * noise
288
+
289
+ decoder_inputs_embeds = self.vae_to_t5(noise_sequence)
290
+ sos = repeat(self.sos.weight, '1 d -> b 1 d', b=decoder_inputs_embeds.size(0))
291
+ decoder_inputs_embeds = torch.cat([sos, decoder_inputs_embeds], dim=1)
292
+ return decoder_inputs_embeds, z_sequence, z
293
+
294
+ def compute_padding_token(self) -> None:
295
+ """
296
+ Compute and update the padding token.
297
+ Raises:
298
+ NotImplementedError: This method must be implemented.
299
+ """
300
+ raise NotImplementedError("compute_padding_token not implemented")
301
+
302
+ def compute_padding_token_threshold(self) -> None:
303
+ """
304
+ Compute and update the padding token threshold.
305
+ Raises:
306
+ NotImplementedError: This method must be implemented.
307
+ """
308
+ raise NotImplementedError("compute_padding_token_threshold not implemented")