Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train.py 10 KB

You have to be logged in to leave a comment. Sign In
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
  1. # Standard Library Imports
  2. import argparse
  3. import os
  4. import time
  5. import matplotlib.pyplot as plt
  6. import numpy as np
  7. # External Library Imports
  8. import torch
  9. import torch.nn.functional as F
  10. import tqdm
  11. from PIL import Image
  12. from einops import rearrange
  13. from torch.utils.data import DataLoader
  14. from transformers import AutoProcessor, GroupViTVisionModel
  15. import settings
  16. import wandb
  17. # Local Module Imports
  18. from modelingEntityGrounder import FineGrainedSimilarityLoss, EntityGrounder, ImageProj
  19. from segment_merger import SegmentMerger
  20. from utils.embeddingDataset import EmbeddingDataset
  21. from utils.region_grouper import get_segments
  22. # Constants and Configuration
  23. torch.manual_seed(0)
  24. BATCH_SIZE = 32
  25. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  26. argparser = argparse.ArgumentParser()
  27. argparser.add_argument("--debug", action="store_true")
  28. argparser.add_argument("--wandb", action="store_true")
  29. DEBUG = argparser.parse_args().debug
  30. USE_LOGGING = argparser.parse_args().wandb
  31. class Trainer:
  32. def __init__(self, config):
  33. proj_dim = 256
  34. self.text_model: EntityGrounder = EntityGrounder(input_dim_text=256, lstm_hidden_dim=256, intermediate_dim=512, output_dim=proj_dim, hidden_dim=512, num_hidden=1).to(
  35. device)
  36. self.image_model: ImageProj = ImageProj(196, proj_dim, 512, 1).to(device)
  37. self.text_optimizer: torch.optim.AdamW = torch.optim.AdamW(self.text_model.parameters(), lr=0.0001, weight_decay=0.05)
  38. self.image_optimizer: torch.optim.AdamW = torch.optim.AdamW(self.image_model.parameters(), lr=0.0001, weight_decay=0.05)
  39. self.entity_grounder_loss: FineGrainedSimilarityLoss = FineGrainedSimilarityLoss(-0.5)
  40. self.segment_merger_loss: SegmentMerger = SegmentMerger(1, 64)
  41. self.config = config
  42. if DEBUG:
  43. self.train_data = EmbeddingDataset("val_data/val_data_images.pk", "val_data/data_text.pk", False, False)
  44. else:
  45. self.train_data = EmbeddingDataset("train_data/data_images.pk", "train_data/data_text.pk", True, False)
  46. self.validation_data = EmbeddingDataset("val_data/val_data_images.pk", "val_data/data_text.pk", False, True)
  47. self.train_data_loader: DataLoader = DataLoader(self.train_data, batch_size=BATCH_SIZE, shuffle=True)
  48. self.validation_data_loader: DataLoader = DataLoader(self.validation_data, batch_size=BATCH_SIZE, shuffle=True)
  49. self.image_processor = AutoProcessor.from_pretrained("nvidia/groupvit-gcc-yfcc")
  50. self.region_proposer = GroupViTVisionModel.from_pretrained("nvidia/groupvit-gcc-yfcc")
  51. ### metrics
  52. self.train_steps: int = 0
  53. self.epoch: int = 0
  54. def load_models(self, *, text_model_path=None, image_model_path=None):
  55. if text_model_path is not None:
  56. self.text_model.load_state_dict(torch.load(text_model_path))
  57. if image_model_path is not None:
  58. self.image_model.load_state_dict(torch.load(image_model_path))
  59. def forward(self, text_segments, image_segments):
  60. text_proj = self.text_model(text_segments)
  61. image_proj = self.image_model(image_segments)
  62. return image_proj, text_proj
  63. def backward(self, loss):
  64. self.text_optimizer.zero_grad()
  65. self.image_optimizer.zero_grad()
  66. loss.backward()
  67. self.text_optimizer.step()
  68. self.image_optimizer.step()
  69. def setup(self):
  70. if USE_LOGGING:
  71. wandb.init(project=self.config.TrainSettings.Logging.project_name)
  72. if not os.path.exists(f"{self.config.TrainSettings.Logging.model_dir}"):
  73. os.mkdir(self.config.TrainSettings.Logging.model_dir)
  74. os.mkdir(f"{self.config.TrainSettings.Logging.model_dir}/{wandb.run.name}")
  75. def save(self):
  76. if USE_LOGGING:
  77. torch.save(self.text_model.state_dict(), f"{self.config.TrainSettings.Logging.model_dir}/{wandb.run.name}/model_{self.epoch}-{int(time.time())}.pt")
  78. torch.save(self.image_model.state_dict(), f"{self.config.TrainSettings.Logging.model_dir}/{wandb.run.name}/model_image_proj_{self.epoch}-{int(time.time())}.pt")
  79. @staticmethod
  80. def log(args):
  81. if USE_LOGGING:
  82. wandb.log(args)
  83. def verifyEntityGrounder(trainer, num_val=10):
  84. """
  85. Verification function that processes image and text segments, generates a wandb table,
  86. and logs results for visualization.
  87. Args:
  88. - val_dataloader (DataLoader): The validation data loader.
  89. - model (torch.nn.Module): The main model for processing.
  90. - model_image (torch.nn.Module): The image processing model.
  91. - processor (AutoProcessor): Processor for the GroupViT model.
  92. - num_val (int): Number of validation instances to process.
  93. Returns:
  94. None
  95. """
  96. index = 0
  97. with torch.no_grad():
  98. for image_segs, text_segs, images, strings in trainer.validation_data_loader:
  99. if image_segs.size(0) != BATCH_SIZE:
  100. continue
  101. b = image_segs.size(0)
  102. text_segs = text_segs.to(device)
  103. image_segs = image_segs.to(device)
  104. mask = (text_segs != 0)
  105. text_segs = rearrange(text_segs, 'b c t d -> (b c) t d')
  106. image_proj, txt = trainer.forward(text_segs, image_segs)
  107. txt = rearrange(txt, '(b c) d -> b c d', b=b)
  108. table = wandb.Table(columns=["image", "heat_map", "caption", "cosine sim p"])
  109. sims = F.cosine_similarity(image_proj.unsqueeze(2), txt.unsqueeze(1), dim=-1).detach() # b, seg, text
  110. mask = rearrange(mask, 'b c t d -> b c (t d)')
  111. mask = mask.any(dim=-1) # Reduce the last dimension by checking if there's any non-zero value
  112. sims = sims * mask.unsqueeze(1).float()
  113. sims = sims.cpu()
  114. for i in range(16):
  115. pic = Image.open(images[i])
  116. # Get segmentations from attention outputs
  117. segs = get_segments(pic, trainer.image_processor, trainer.region_proposer).detach().cpu().numpy()
  118. # Construct tensor to hold image with segments colored by cosSim to the first noun
  119. color_seg = np.zeros((segs.shape[0], segs.shape[1], 3), dtype=np.uint8) # height, width, 3
  120. # Go through each segment, get the cosSim with the first noun, color with colormap
  121. for seg in range(64):
  122. viridis_color = plt.get_cmap("Blues")(sims[i, seg, 0])[0:3]
  123. viridis_color = np.array(viridis_color) * 255
  124. color_seg[segs == seg, :] = viridis_color
  125. # create plot of cosSimP (i b/c index into segment)
  126. fig, ax = plt.subplots()
  127. cos_p_fig = ax.matshow(sims[i].numpy(), cmap="viridis", vmin=-1, vmax=1)
  128. fig.colorbar(cos_p_fig)
  129. fig.savefig("cossimp.png")
  130. cossimpimg = Image.open("cossimp.png")
  131. cossimpimg = wandb.Image(cossimpimg, caption="cos sim p")
  132. plt.close(fig)
  133. img = wandb.Image(pic, caption=strings[0][i])
  134. pic = np.array(pic)
  135. img_to_hmap_scale = 0.1
  136. if len(pic.shape) == 2:
  137. pic = np.expand_dims(pic, axis=2)
  138. heat_map = np.array(pic * img_to_hmap_scale + color_seg * (1 - img_to_hmap_scale), dtype=np.uint8)
  139. heat_map = wandb.Image(heat_map)
  140. table.add_data(img, heat_map, strings[0][i], cossimpimg)
  141. index += 1
  142. if index >= num_val:
  143. break
  144. trainer.log({"entityGrounderExamples": table})
  145. def trainEntityGrounder(trainer):
  146. train_loss = 0.0
  147. pbar = tqdm.tqdm(trainer.train_data_loader, total=len(trainer.train_data_loader))
  148. index = 0
  149. for image_segs, text_segs, images, nouns in trainer.train_data_loader:
  150. if image_segs.size(0) != BATCH_SIZE:
  151. continue
  152. image_segs = image_segs.detach().to(device)
  153. text_segs = text_segs.detach().to(device)
  154. b = image_segs.size(0)
  155. mask = (text_segs != 0)
  156. mask = rearrange(mask, 'b c t d -> b c (t d)')
  157. mask = mask.any(dim=-1) # Reduce the last dimension by checking if there's any non-zero value
  158. text_segs = rearrange(text_segs, 'b c t d -> (b c) t d')
  159. image_proj, txt_proj = trainer.forward(text_segs, image_segs)
  160. txt_proj = rearrange(txt_proj, '(b c) d -> b c d', b=b)
  161. loss_finegrained = trainer.entity_grounder_loss(image_proj, txt_proj, trainer.text_model.tau, mask)
  162. trainer.backward(loss_finegrained)
  163. train_loss += loss_finegrained.item()
  164. pbar.update(1)
  165. index += 1
  166. pbar.set_description(f"epoch {trainer.epoch + 1} Entity Grounder Loss: {train_loss / index}")
  167. trainer.log({"entity_grounder_loss": loss_finegrained.item()})
  168. trainer.train_steps += 1
  169. trainer.epoch += 1
  170. def trainSegmentMerger(data, model, criterion, optimizer, epoch): # todo: refactor this function to use trainer class
  171. train_loss = 0.0
  172. pbar = tqdm.tqdm(data, total=len(data))
  173. index = 0
  174. for image_segs, text_segs, images, strings in data:
  175. if image_segs.size(0) != BATCH_SIZE:
  176. continue
  177. image_segs = image_segs.detach().to(device)
  178. text_segs = text_segs.detach().to(device)
  179. image_proj = model(image_segs, None)
  180. b = image_proj.size(0)
  181. # Assuming that the padding value is 0, generate a mask for non-padded elements
  182. text_segs = rearrange(text_segs, 'b c t d -> (b c) t d')
  183. txt_proj = model(None, text_segs)
  184. txt_proj = rearrange(txt_proj, '(b c) d -> b c d', b=b)
  185. txt_proj = txt_proj.detach().to(device)
  186. loss, sims = criterion(image_proj, txt_proj)
  187. optimizer.zero_grad()
  188. loss.backward()
  189. optimizer.step()
  190. train_loss += loss.item()
  191. pbar.update(1)
  192. index += 1
  193. pbar.set_description(f"epoch {epoch + 1} Segment Merger --- Loss: {train_loss / index}")
  194. wandb.log({"segment_merger_loss": loss.item()})
  195. return model
  196. def main():
  197. """
  198. The main function initializes the models, datasets, optimizers, and starts the training loop.
  199. Args:
  200. None
  201. Returns:
  202. None
  203. """
  204. print("done processing dataset")
  205. trainer = Trainer(settings)
  206. trainer.setup()
  207. for epoch in range(100):
  208. trainEntityGrounder(trainer)
  209. verifyEntityGrounder(trainer, 1)
  210. trainer.save()
  211. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...