Create model.py
Browse files
model.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# model.py
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
from transformers import AutoModelForSeq2SeqLM
|
6 |
+
from torchvision import models
|
7 |
+
|
8 |
+
class ImageToTextProjector(nn.Module):
|
9 |
+
def __init__(self, image_embedding_dim, text_embedding_dim):
|
10 |
+
super(ImageToTextProjector, self).__init__()
|
11 |
+
self.fc = nn.Linear(image_embedding_dim, text_embedding_dim)
|
12 |
+
self.activation = nn.ReLU()
|
13 |
+
self.dropout = nn.Dropout(p=0.5)
|
14 |
+
|
15 |
+
def forward(self, x):
|
16 |
+
x = self.fc(x)
|
17 |
+
x = self.activation(x)
|
18 |
+
x = self.dropout(x)
|
19 |
+
return x
|
20 |
+
|
21 |
+
class CombinedModel(nn.Module):
|
22 |
+
def __init__(self, video_model, report_generator, num_classes, projector):
|
23 |
+
super(CombinedModel, self).__init__()
|
24 |
+
self.video_model = video_model
|
25 |
+
self.report_generator = report_generator
|
26 |
+
self.classifier = nn.Linear(512, num_classes)
|
27 |
+
self.projector = projector
|
28 |
+
self.dropout = nn.Dropout(p=0.5)
|
29 |
+
|
30 |
+
def forward(self, images, labels=None):
|
31 |
+
video_embeddings = self.video_model(images)
|
32 |
+
video_embeddings = self.dropout(video_embeddings)
|
33 |
+
class_outputs = self.classifier(video_embeddings)
|
34 |
+
projected_embeddings = self.projector(video_embeddings)
|
35 |
+
encoder_inputs = projected_embeddings.unsqueeze(1)
|
36 |
+
|
37 |
+
if labels is not None:
|
38 |
+
outputs = self.report_generator(
|
39 |
+
inputs_embeds=encoder_inputs,
|
40 |
+
labels=labels
|
41 |
+
)
|
42 |
+
gen_loss = outputs.loss
|
43 |
+
generated_report = None
|
44 |
+
else:
|
45 |
+
generated_report_ids = self.report_generator.generate(
|
46 |
+
inputs_embeds=encoder_inputs,
|
47 |
+
max_length=512,
|
48 |
+
num_beams=4,
|
49 |
+
early_stopping=True
|
50 |
+
)
|
51 |
+
generated_report = report_generator_tokenizer.batch_decode(
|
52 |
+
generated_report_ids, skip_special_tokens=True
|
53 |
+
)
|
54 |
+
gen_loss = None
|
55 |
+
|
56 |
+
return class_outputs, generated_report, gen_loss
|