Spaces:
Sleeping
Sleeping
Ziad Meligy
commited on
Commit
·
eb8805a
1
Parent(s):
e024132
Pushing deployment to space
Browse files- CNN_encoder.py +70 -0
- Dockerfile +13 -0
- configs.py +72 -0
- distil_gpt2.py +680 -0
- generate_report.py +69 -0
- generator.py +93 -0
- main.py +37 -0
- pretrained_visual_model/best_weights.h5 +3 -0
- pretrained_visual_model/best_weights.json +0 -0
- pretrained_visual_model/fine_tuned_chexnet.h5 +3 -0
- pretrained_visual_model/fine_tuned_chexnet.json +0 -0
CNN_encoder.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utility import load_model,get_layers
|
| 5 |
+
import tensorflow as tf
|
| 6 |
+
from tensorflow.keras.models import Model # type: ignore
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CNN_Encoder(nn.Module):
|
| 11 |
+
def __init__(self,model_path,model_name,pop_conv_layers,encoder_layers,tags_threshold,tags_embeddings=None,finetune_visual_model=False,num_tags=105):
|
| 12 |
+
super(CNN_Encoder,self).__init__()
|
| 13 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 14 |
+
if tags_embeddings is not None:
|
| 15 |
+
# Initialize embeddings and move them to the device
|
| 16 |
+
self.tags_embeddings = nn.Parameter(torch.tensor(tags_embeddings, dtype=torch.float32).to(self.device), requires_grad=True)
|
| 17 |
+
else:
|
| 18 |
+
# Initialize embeddings with ones and move them to the device
|
| 19 |
+
self.tags_embeddings = nn.Parameter(torch.ones((num_tags, 400), dtype=torch.float32).to(self.device), requires_grad=True)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
self.tags_threshold=tags_threshold
|
| 23 |
+
# visual_model.children() gets an iterator over child modules(layers) of the model (pretrained chexnet)
|
| 24 |
+
#list* => converts this iterator into a list of layers so it is easier to manipulate
|
| 25 |
+
# if pop_conv_layers is, it removes the last layer from the model
|
| 26 |
+
# nn.sequentail=> creates a new model that consists of all the layers up to the pop_conv_layers, stacks layers in a linear sequence
|
| 27 |
+
visual_model=load_model(model_path,model_name)
|
| 28 |
+
self.visual_model = Model(inputs=visual_model.input,
|
| 29 |
+
outputs=[visual_model.output, visual_model.layers[-pop_conv_layers - 1].output],
|
| 30 |
+
trainable=finetune_visual_model)
|
| 31 |
+
|
| 32 |
+
self.encoder_layers=get_layers(encoder_layers,'relu')
|
| 33 |
+
|
| 34 |
+
def get_visual_features(self, images):
|
| 35 |
+
images_np = images.cpu().numpy()
|
| 36 |
+
images_tf = tf.convert_to_tensor(images_np)
|
| 37 |
+
images_tf = tf.transpose(images_tf, perm=[0,2,3,1 ])
|
| 38 |
+
predictions, visual_features = self.visual_model(images_tf)
|
| 39 |
+
predictions = torch.tensor(predictions.numpy(), device=self.device, requires_grad=True)
|
| 40 |
+
visual_features = torch.tensor(visual_features.numpy(), device=self.device, requires_grad=True)
|
| 41 |
+
|
| 42 |
+
predictions = predictions.view(predictions.size(0), predictions.size(-1), -1)
|
| 43 |
+
visual_features = visual_features.view(visual_features.size(0), -1, visual_features.size(-1))
|
| 44 |
+
|
| 45 |
+
if self.tags_threshold >= 0:
|
| 46 |
+
predictions = (predictions >= self.tags_threshold).float()
|
| 47 |
+
|
| 48 |
+
return predictions, visual_features
|
| 49 |
+
|
| 50 |
+
def forward(self, images):
|
| 51 |
+
# print python version
|
| 52 |
+
print("Python version:", sys.version)
|
| 53 |
+
|
| 54 |
+
images=images.to(self.device)
|
| 55 |
+
tags_predictions, visual_features = self.get_visual_features(images)
|
| 56 |
+
if tags_predictions is not None:
|
| 57 |
+
tags_predictions=tags_predictions.to(self.device)
|
| 58 |
+
self.tags_embeddings = self.tags_embeddings.to(self.device)
|
| 59 |
+
tags_embed = tags_predictions * self.tags_embeddings
|
| 60 |
+
else:
|
| 61 |
+
tags_embed=None
|
| 62 |
+
|
| 63 |
+
for layer in self.encoder_layers:
|
| 64 |
+
visual_features = layer(visual_features)
|
| 65 |
+
if tags_embed is not None:
|
| 66 |
+
tags_embed = layer(tags_embed)
|
| 67 |
+
|
| 68 |
+
return visual_features, tags_embed
|
| 69 |
+
|
| 70 |
+
|
Dockerfile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.8.8-slim
|
| 2 |
+
|
| 3 |
+
RUN useradd -m -u 1000 user
|
| 4 |
+
USER user
|
| 5 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 6 |
+
|
| 7 |
+
WORKDIR /app
|
| 8 |
+
|
| 9 |
+
COPY --chown=user ./requirements.txt requirements.txt
|
| 10 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 11 |
+
|
| 12 |
+
COPY --chown=user . /app
|
| 13 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
configs.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tags import tags
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class argHandler(dict):
|
| 5 |
+
__getattr__ = dict.get
|
| 6 |
+
__setattr__ = dict.__setitem__
|
| 7 |
+
__delattr__ = dict.__delitem__
|
| 8 |
+
_descriptions = {'help, --h, -h': 'show this super helpful message and exit'}
|
| 9 |
+
def setDefaults(self):
|
| 10 |
+
self.define('train_csv', './IU-XRay/training_set.csv',
|
| 11 |
+
'path to training csv containing the images names and the labels')
|
| 12 |
+
self.define('test_csv', './IU-XRay/testing_set.csv',
|
| 13 |
+
'path to testing csv containing the images names and the labels')
|
| 14 |
+
self.define('all_data_csv', './IU-XRay/all_data.csv',
|
| 15 |
+
'path to all data csv containing the images names and the labels')
|
| 16 |
+
self.define('image_directory', './IU-XRay/images',
|
| 17 |
+
'path to folder containing the patient folders which containing the images')
|
| 18 |
+
self.define('output_images_folder', './outputs/CDGPT2',
|
| 19 |
+
'path to folder containing output images')
|
| 20 |
+
self.define('data_dir', './IU-XRay',
|
| 21 |
+
'path to folder containing the patient folders which containing the images')
|
| 22 |
+
# self.define('visual_model_name', 'fine_tuned_chexnet',
|
| 23 |
+
self.define('visual_model_name', 'fine_tuned_chexnet',
|
| 24 |
+
'path to folder containing the patient folders which containing the images')
|
| 25 |
+
self.define('finetune_visual_model', False,
|
| 26 |
+
'option if you want to finetune the visual model')
|
| 27 |
+
self.define('visual_model_pop_layers', 2,
|
| 28 |
+
'number of conv layers to pop to get visual features')
|
| 29 |
+
self.define('csv_label_columns', ['Caption'], 'the name of the label columns in the csv')
|
| 30 |
+
self.define('image_target_size', (224, 224, 3), 'the target size to resize the image')
|
| 31 |
+
|
| 32 |
+
self.define('max_sequence_length', 200,
|
| 33 |
+
'Maximum number of words in a sentence')
|
| 34 |
+
self.define('num_epochs', 100, 'maximum number of epochs')
|
| 35 |
+
self.define('encoder_layers', [0.4], 'a list describing the hidden layers of the encoder. Example [10,0.4,5] will create a hidden layer with size 10 then dropout wth drop prob 0.4, then hidden layer with size 5. If empty it will connect to output nodes directly.')
|
| 36 |
+
self.define('classifier_layers', [0.4], 'a list describing the hidden layers of the encoder. Example [10,0.4,5] will create a hidden layer with size 10 then dropout wth drop prob 0.4, then hidden layer with size 5. If empty it will connect to output nodes directly.')
|
| 37 |
+
self.define('tags_threshold', -1,
|
| 38 |
+
'The threshold from which to detect a tag. -1 will multiply the tags embeddings according to prediction')
|
| 39 |
+
self.define('tokenizer_vocab_size', 1001,
|
| 40 |
+
'The number of words to tokinze, the rest will be set as <unk>')
|
| 41 |
+
self.define('batch_size', 16, 'batch size for training and testing')
|
| 42 |
+
self.define('generator_workers', 8, 'The number of cpu workers generating batches.')
|
| 43 |
+
self.define('beam_width', 7, 'The beam search width during evaluation')
|
| 44 |
+
self.define('epochs_to_evaluate', 3, 'The number of epochs to train before evaluating on the test set.')
|
| 45 |
+
|
| 46 |
+
self.define('generator_queue_length', 24, 'The maximum number of batches in the queue to be trained on.')
|
| 47 |
+
|
| 48 |
+
self.define('ckpt_path', './checkpoints/CDGPT2/',
|
| 49 |
+
'where to save the checkpoints. The path will be created if it does not exist. The system saves every epoch by default')
|
| 50 |
+
self.define('continue_from_last_ckpt', True,
|
| 51 |
+
'continue training from last ckpt or not')
|
| 52 |
+
self.define('calculate_loss_after_epoch', False,
|
| 53 |
+
'if True it will calculate the train and test loss by passing over the data again and append it to losses_csv')
|
| 54 |
+
self.define('learning_rate', 1e-3, 'The optimizer learning rate')
|
| 55 |
+
self.define('optimizer_type', 'Adam', 'Choose from (Adam, SGD, RMSprop, Adagrad, Adadelta, Adamax, Nadam)')
|
| 56 |
+
self.define('tags', tags,
|
| 57 |
+
'the names of the tags')
|
| 58 |
+
|
| 59 |
+
def define(self, argName, default, description):
|
| 60 |
+
self[argName] = default
|
| 61 |
+
self._descriptions[argName] = description
|
| 62 |
+
|
| 63 |
+
def help(self):
|
| 64 |
+
print('Arguments:')
|
| 65 |
+
spacing = max([len(i) for i in self._descriptions.keys()]) + 2
|
| 66 |
+
for item in self._descriptions:
|
| 67 |
+
currentSpacing = spacing - len(item)
|
| 68 |
+
print(' --' + item + (' ' * currentSpacing) + self._descriptions[item])
|
| 69 |
+
exit()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
|
distil_gpt2.py
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from torch.nn import functional as F
|
| 5 |
+
import math
|
| 6 |
+
from transformers import GPT2Tokenizer
|
| 7 |
+
import tiktoken
|
| 8 |
+
from transformers import GPT2LMHeadModel
|
| 9 |
+
from transformers import PretrainedConfig
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass
|
| 13 |
+
class GPTConfig(PretrainedConfig):
|
| 14 |
+
visual_size: int = 1024
|
| 15 |
+
vocab_size: int = 50257
|
| 16 |
+
block_size: int = 1024
|
| 17 |
+
tags_embd: int = 400
|
| 18 |
+
n_embd: int = 768
|
| 19 |
+
n_layer: int = 6
|
| 20 |
+
n_head: int = 12
|
| 21 |
+
|
| 22 |
+
def __init__(self,**kwargs):
|
| 23 |
+
super().__init__(**kwargs)
|
| 24 |
+
self.hidden_size = self.n_embd
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class CasualSelfAttention(nn.Module):
|
| 28 |
+
def __init__(self, config: GPTConfig):
|
| 29 |
+
super().__init__()
|
| 30 |
+
assert config.n_embd % config.n_head == 0
|
| 31 |
+
self.c_attn = nn.Linear(config.n_embd, config.n_embd * 3)
|
| 32 |
+
self.visual_attn = nn.Linear(config.visual_size, config.n_embd * 2)
|
| 33 |
+
self.tags_attn = nn.Linear(config.tags_embd, config.n_embd * 2)
|
| 34 |
+
|
| 35 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
| 36 |
+
self.n_head = config.n_head
|
| 37 |
+
self.n_embed = config.n_embd
|
| 38 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 39 |
+
|
| 40 |
+
self.register_buffer(
|
| 41 |
+
'bias', torch.tril(torch.ones(199, 353))
|
| 42 |
+
.view(1, 1, 199, 353)
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
def forward(self, x: torch.Tensor, visual_features: torch.Tensor = None, tags_embedding: torch.Tensor = None) -> torch.Tensor:
|
| 46 |
+
|
| 47 |
+
B, T, C = x.size()
|
| 48 |
+
visual_features=visual_features.to(self.device)
|
| 49 |
+
tags_embedding=tags_embedding.to(self.device)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
qkv = self.c_attn(x) # the error happens here
|
| 53 |
+
|
| 54 |
+
q, k, v = qkv.split(self.n_embed, dim=2)
|
| 55 |
+
q = q.view(B, T, self.n_head, self.n_embed // self.n_head).transpose(1, 2)
|
| 56 |
+
k = k.view(B, T, self.n_head, self.n_embed // self.n_head).transpose(1, 2)
|
| 57 |
+
v = v.view(B, T, self.n_head, self.n_embed // self.n_head).transpose(1, 2)
|
| 58 |
+
# Handle visual input if provided
|
| 59 |
+
if visual_features is not None:
|
| 60 |
+
visual_kv = self.visual_attn(visual_features)
|
| 61 |
+
visual_k, visual_v = visual_kv.split(self.n_embed, dim=2)
|
| 62 |
+
visual_k = visual_k.view(B, visual_features.size(1), self.n_head, self.n_embed // self.n_head).transpose(1, 2)
|
| 63 |
+
visual_v = visual_v.view(B, visual_features.size(1), self.n_head, self.n_embed // self.n_head).transpose(1, 2)
|
| 64 |
+
|
| 65 |
+
k = torch.cat([k, visual_k], dim=-2)
|
| 66 |
+
v = torch.cat([v, visual_v], dim=-2)
|
| 67 |
+
|
| 68 |
+
if tags_embedding is not None:
|
| 69 |
+
tags_kv = self.tags_attn(tags_embedding)
|
| 70 |
+
tags_k, tags_v = tags_kv.split(self.n_embed, dim=2)
|
| 71 |
+
tags_k = tags_k.view(B, tags_embedding.size(1), self.n_head, self.n_embed // self.n_head).transpose(1, 2)
|
| 72 |
+
tags_v = tags_v.view(B, tags_embedding.size(1), self.n_head, self.n_embed // self.n_head).transpose(1, 2)
|
| 73 |
+
|
| 74 |
+
k = torch.cat([k, tags_k], dim=-2)
|
| 75 |
+
v = torch.cat([v, tags_v], dim=-2)
|
| 76 |
+
|
| 77 |
+
# Causal self-attention computation
|
| 78 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
| 79 |
+
device = att.device
|
| 80 |
+
query_seq_len, key_seq_len = T, k.size(-2)
|
| 81 |
+
|
| 82 |
+
# Text can attend to: previous text + all visual/tag tokens
|
| 83 |
+
text_mask = torch.tril(torch.ones(T, T, device=device)) # Text-to-text causal
|
| 84 |
+
non_text_mask = torch.ones(T, key_seq_len - T, device=device) # Text-to-other full
|
| 85 |
+
combined_mask = torch.cat([text_mask, non_text_mask], dim=1)
|
| 86 |
+
|
| 87 |
+
# Reshape for broadcasting
|
| 88 |
+
combined_mask = combined_mask.view(1, 1, T, key_seq_len)
|
| 89 |
+
att = att.masked_fill(combined_mask == 0, float('-inf'))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
att = F.softmax(att, dim=-1)
|
| 94 |
+
visual_att = att[..., :T, T:].mean().item() # Text → Visual attention
|
| 95 |
+
y = att @ v
|
| 96 |
+
y = y.transpose(1, 2).contiguous().view(B, T, self.n_head * (self.n_embed // self.n_head))
|
| 97 |
+
y = self.c_proj(y)
|
| 98 |
+
|
| 99 |
+
return y
|
| 100 |
+
|
| 101 |
+
class MLP(nn.Module):
|
| 102 |
+
def __init__(self, config: GPTConfig):
|
| 103 |
+
super(MLP, self).__init__()
|
| 104 |
+
self.c_fc = nn.Linear(config.n_embd, config.n_embd * 4) # c_fc means fully connected layer and c is for context
|
| 105 |
+
self.gelu = nn.GELU()
|
| 106 |
+
self.c_proj = nn.Linear(config.n_embd * 4, config.n_embd)
|
| 107 |
+
|
| 108 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 109 |
+
x = self.c_fc(x)
|
| 110 |
+
x = self.gelu(x)
|
| 111 |
+
x = self.c_proj(x)
|
| 112 |
+
return x
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class Block(nn.Module):
|
| 116 |
+
def __init__(self, config: GPTConfig):
|
| 117 |
+
super(Block, self).__init__()
|
| 118 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
| 119 |
+
self.attn = CasualSelfAttention(config)
|
| 120 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
| 121 |
+
self.mlp = MLP(config)
|
| 122 |
+
|
| 123 |
+
def forward(self, x: torch.Tensor,visual_features: torch.Tensor, tags_embedding: torch.Tensor) -> torch.Tensor:
|
| 124 |
+
x = x + self.attn(self.ln_1(x),visual_features, tags_embedding)
|
| 125 |
+
x = x + self.mlp(self.ln_2(x))
|
| 126 |
+
return x
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class DistilGPT2(GPT2LMHeadModel):
|
| 130 |
+
def __init__(self, config: GPTConfig):
|
| 131 |
+
super(DistilGPT2, self).__init__(config)
|
| 132 |
+
self.config = config
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
self.transformer = nn.ModuleDict(
|
| 136 |
+
{
|
| 137 |
+
'wte': nn.Embedding(config.vocab_size, config.n_embd),
|
| 138 |
+
'wpe': nn.Embedding(config.block_size, config.n_embd),
|
| 139 |
+
'h': nn.ModuleList(
|
| 140 |
+
[
|
| 141 |
+
Block(config) for _ in range(config.n_layer)
|
| 142 |
+
]
|
| 143 |
+
), # transformer blocks
|
| 144 |
+
'ln_f': nn.LayerNorm(config.n_embd) # final layer normalization
|
| 145 |
+
}
|
| 146 |
+
)
|
| 147 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # linear layer for projection from embedding to vocab size
|
| 148 |
+
|
| 149 |
+
def forward(self, idx: torch.Tensor, visual_features: torch.Tensor = None, tags_embedding: torch.Tensor = None, return_dict: bool = False) -> torch.Tensor:
|
| 150 |
+
idx=idx.to(self.device)
|
| 151 |
+
B, T = idx.size()
|
| 152 |
+
assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, Block size is {self.config.block_size}"
|
| 153 |
+
|
| 154 |
+
# forward the token and positional embeddings
|
| 155 |
+
pos = torch.arange(0, T, dtype=torch.long, device=idx.device)
|
| 156 |
+
pos_emb = self.transformer['wpe'](pos)
|
| 157 |
+
tok_emb = self.transformer['wte'](idx)
|
| 158 |
+
x = tok_emb + pos_emb
|
| 159 |
+
|
| 160 |
+
# forward the transformer
|
| 161 |
+
for block in self.transformer['h']:
|
| 162 |
+
x = block(x, visual_features=visual_features, tags_embedding=tags_embedding)
|
| 163 |
+
|
| 164 |
+
# forward the head
|
| 165 |
+
x = self.transformer['ln_f'](x)
|
| 166 |
+
logits = self.lm_head(x)
|
| 167 |
+
|
| 168 |
+
if return_dict:
|
| 169 |
+
return {'logits': logits}
|
| 170 |
+
else:
|
| 171 |
+
|
| 172 |
+
return logits
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def from_pretrained(cls, model_type: str):
|
| 177 |
+
"""Loads pre-trained GPT-2 model weights from Hugging Face and handles custom layers."""
|
| 178 |
+
from transformers import GPT2LMHeadModel
|
| 179 |
+
print(f"Loading weights from pre-trained GPT: {model_type}")
|
| 180 |
+
|
| 181 |
+
# Ensure the model type is supported
|
| 182 |
+
assert model_type in {'distilgpt2', 'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
|
| 183 |
+
|
| 184 |
+
# Define configurations based on the model type
|
| 185 |
+
config_args = {
|
| 186 |
+
'distilgpt2': dict(n_layer=6, n_head=12, n_embd=768),
|
| 187 |
+
'gpt2': dict(n_layer=12, n_head=12, n_embd=768),
|
| 188 |
+
'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024),
|
| 189 |
+
'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280),
|
| 190 |
+
'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600),
|
| 191 |
+
}[model_type]
|
| 192 |
+
config_args['vocab_size'] = 50257
|
| 193 |
+
config_args['block_size'] = 1024
|
| 194 |
+
|
| 195 |
+
# Initialize the custom model with the given configuration
|
| 196 |
+
config = GPTConfig(**config_args)
|
| 197 |
+
from transformers import GPT2Config
|
| 198 |
+
|
| 199 |
+
config = GPT2Config.from_pretrained('distilgpt2')
|
| 200 |
+
|
| 201 |
+
config.visual_size=1024
|
| 202 |
+
config.block_size=1024
|
| 203 |
+
config.tags_embd=400
|
| 204 |
+
config.n_embd=768
|
| 205 |
+
config.n_layer=6
|
| 206 |
+
config.n_head=12
|
| 207 |
+
|
| 208 |
+
model = cls(config)
|
| 209 |
+
|
| 210 |
+
# Load state dictionary from Hugging Face model
|
| 211 |
+
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
|
| 212 |
+
sd_hf = model_hf.state_dict()
|
| 213 |
+
|
| 214 |
+
# State dictionary of the custom model
|
| 215 |
+
sd = model.state_dict()
|
| 216 |
+
|
| 217 |
+
# Filter out custom keys that are not in the pre-trained model
|
| 218 |
+
custom_keys = {k for k in sd if 'visual_attn' in k or 'tags_attn' in k}
|
| 219 |
+
sd_keys_filtered = [k for k in sd if k not in custom_keys]
|
| 220 |
+
|
| 221 |
+
# Load matching keys
|
| 222 |
+
for k in sd_keys_filtered:
|
| 223 |
+
if k in sd_hf and sd_hf[k].shape == sd[k].shape:
|
| 224 |
+
with torch.no_grad():
|
| 225 |
+
sd[k].copy_(sd_hf[k])
|
| 226 |
+
|
| 227 |
+
# Initialize custom layers separately
|
| 228 |
+
for k in custom_keys:
|
| 229 |
+
with torch.no_grad():
|
| 230 |
+
print(f"Initializing custom layer: {k}")
|
| 231 |
+
sd[k].normal_(0.0, 0.02) # Adjust initialization method as needed
|
| 232 |
+
|
| 233 |
+
# Update the model's state dictionary
|
| 234 |
+
model.load_state_dict(sd, strict=False)
|
| 235 |
+
|
| 236 |
+
return model
|
| 237 |
+
|
| 238 |
+
def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
|
| 239 |
+
# Prepare inputs for autoregressive generation
|
| 240 |
+
inputs = {"idx": input_ids}
|
| 241 |
+
if past:
|
| 242 |
+
inputs["past_key_values"] = past # Include past key values for caching
|
| 243 |
+
|
| 244 |
+
# Include additional features like visual and tags if provided
|
| 245 |
+
if "visual_features" in kwargs:
|
| 246 |
+
inputs["visual_features"] = kwargs["visual_features"]
|
| 247 |
+
if "tags_embedding" in kwargs:
|
| 248 |
+
inputs["tags_embedding"] = kwargs["tags_embedding"]
|
| 249 |
+
|
| 250 |
+
return inputs
|
| 251 |
+
def generate(
|
| 252 |
+
self,
|
| 253 |
+
input_ids: torch.Tensor = None,
|
| 254 |
+
max_length: int = None,
|
| 255 |
+
min_length: int = None,
|
| 256 |
+
do_sample: bool = None,
|
| 257 |
+
early_stopping: bool = None,
|
| 258 |
+
num_beams: int = None,
|
| 259 |
+
temperature: float = None,
|
| 260 |
+
top_k: int = None,
|
| 261 |
+
top_p: float = None,
|
| 262 |
+
repetition_penalty: float = None,
|
| 263 |
+
bos_token_id: int = None,
|
| 264 |
+
pad_token_id: int = None,
|
| 265 |
+
eos_token_ids: int = None,
|
| 266 |
+
length_penalty: float = None,
|
| 267 |
+
no_repeat_ngram_size: int = None,
|
| 268 |
+
num_return_sequences: int = None,
|
| 269 |
+
attention_mask: torch.Tensor = None,
|
| 270 |
+
visual_features: torch.Tensor = None,
|
| 271 |
+
tags_embedding: torch.Tensor = None,
|
| 272 |
+
):
|
| 273 |
+
"""
|
| 274 |
+
Generate sequences using autoregressive decoding.
|
| 275 |
+
|
| 276 |
+
Args:
|
| 277 |
+
input_ids (torch.Tensor): Input tensor of token IDs.
|
| 278 |
+
max_length (int): Maximum length of the generated sequence.
|
| 279 |
+
min_length (int): Minimum length of the generated sequence.
|
| 280 |
+
do_sample (bool): Whether to use sampling; if False, uses greedy decoding.
|
| 281 |
+
early_stopping (bool): Whether to stop when all beams have finished.
|
| 282 |
+
num_beams (int): Number of beams for beam search.
|
| 283 |
+
temperature (float): Sampling temperature.
|
| 284 |
+
top_k (int): Top-k sampling.
|
| 285 |
+
top_p (float): Top-p (nucleus) sampling.
|
| 286 |
+
repetition_penalty (float): Penalty for repeated n-grams.
|
| 287 |
+
bos_token_id (int): Beginning of sequence token ID.
|
| 288 |
+
pad_token_id (int): Padding token ID.
|
| 289 |
+
eos_token_ids (int): End of sequence token ID.
|
| 290 |
+
length_penalty (float): Beam search length penalty.
|
| 291 |
+
no_repeat_ngram_size (int): Size of n-grams not to repeat.
|
| 292 |
+
num_return_sequences (int): Number of sequences to return.
|
| 293 |
+
attention_mask (torch.Tensor): Attention mask for padding tokens.
|
| 294 |
+
visual_features (torch.Tensor): Visual features for the transformer.
|
| 295 |
+
tags_embedding (torch.Tensor): Tags embeddings for the transformer.
|
| 296 |
+
|
| 297 |
+
Returns:
|
| 298 |
+
torch.Tensor: Generated sequences of token IDs.
|
| 299 |
+
"""
|
| 300 |
+
# Default values for unspecified parameters
|
| 301 |
+
max_length = max_length or self.config.block_size
|
| 302 |
+
min_length = min_length or 0
|
| 303 |
+
do_sample = do_sample or False
|
| 304 |
+
early_stopping = early_stopping or False
|
| 305 |
+
num_beams = num_beams or 1
|
| 306 |
+
temperature = temperature or 1.0
|
| 307 |
+
top_k = top_k or 0
|
| 308 |
+
top_p = top_p or 1.0
|
| 309 |
+
repetition_penalty = repetition_penalty or 1.0
|
| 310 |
+
bos_token_id = bos_token_id or self.config.bos_token_id
|
| 311 |
+
pad_token_id = pad_token_id or self.config.pad_token_id
|
| 312 |
+
eos_token_ids = eos_token_ids or self.config.eos_token_ids
|
| 313 |
+
length_penalty = length_penalty or 1.0
|
| 314 |
+
no_repeat_ngram_size = no_repeat_ngram_size or 0
|
| 315 |
+
num_return_sequences = num_return_sequences or 1
|
| 316 |
+
|
| 317 |
+
if input_ids is not None:
|
| 318 |
+
batch_size=input_ids.shape[0]
|
| 319 |
+
else:
|
| 320 |
+
batch_size=1
|
| 321 |
+
|
| 322 |
+
if input_ids is None:
|
| 323 |
+
assert isinstance(bos_token_id, int) and bos_token_id >= 0, (
|
| 324 |
+
"You should either supply a context to complete as `input_ids` input "
|
| 325 |
+
"or a `bos_token_id` (integer >= 0) as a first token to start the generation."
|
| 326 |
+
)
|
| 327 |
+
input_ids = torch.full((batch_size, 1), bos_token_id, dtype=torch.long)
|
| 328 |
+
|
| 329 |
+
else:
|
| 330 |
+
assert input_ids.dim() == 2, "Input prompt should be of shape (batch_size, sequence length)."
|
| 331 |
+
|
| 332 |
+
# Avoid duplicate outputs when greedy decoding
|
| 333 |
+
if not do_sample:
|
| 334 |
+
if num_beams == 1:
|
| 335 |
+
assert num_return_sequences == 1, (
|
| 336 |
+
"Greedy decoding will always produce the same output for num_beams == 1 "
|
| 337 |
+
"and num_return_sequences > 1. Please set num_return_sequences = 1."
|
| 338 |
+
)
|
| 339 |
+
else:
|
| 340 |
+
assert num_beams >= num_return_sequences, (
|
| 341 |
+
"Greedy beam search decoding cannot return more sequences than it has beams. "
|
| 342 |
+
"Please set num_beams >= num_return_sequences."
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
# Create attention mask if necessary
|
| 346 |
+
if attention_mask is None:
|
| 347 |
+
if pad_token_id is not None and pad_token_id in input_ids:
|
| 348 |
+
attention_mask = (input_ids != pad_token_id).long()
|
| 349 |
+
else:
|
| 350 |
+
attention_mask = torch.ones_like(input_ids)
|
| 351 |
+
|
| 352 |
+
# Set pad_token_id if not provided and eos_token_ids is available
|
| 353 |
+
if pad_token_id is None and eos_token_ids is not None:
|
| 354 |
+
pad_token_id = eos_token_ids
|
| 355 |
+
print(f"Setting `pad_token_id` to {pad_token_id} (first `eos_token_ids`) to generate sequence.")
|
| 356 |
+
|
| 357 |
+
# Current sequence length and vocabulary size
|
| 358 |
+
cur_len = input_ids.size(1)
|
| 359 |
+
vocab_size = self.config.vocab_size
|
| 360 |
+
|
| 361 |
+
# Adjust effective batch size and multiplier for sampling
|
| 362 |
+
if do_sample:
|
| 363 |
+
effective_batch_size = batch_size * num_return_sequences
|
| 364 |
+
effective_batch_mult = num_return_sequences
|
| 365 |
+
else:
|
| 366 |
+
effective_batch_size = batch_size
|
| 367 |
+
effective_batch_mult = 1
|
| 368 |
+
|
| 369 |
+
# Expand input_ids and attention_mask for beam search or multiple return sequences
|
| 370 |
+
if num_return_sequences > 1 or num_beams > 1:
|
| 371 |
+
input_ids_len = input_ids.size(-1)
|
| 372 |
+
|
| 373 |
+
# Expand dimensions and repeat for each beam and return sequence
|
| 374 |
+
input_ids = input_ids.unsqueeze(1).expand(batch_size, effective_batch_mult * num_beams, input_ids_len)
|
| 375 |
+
attention_mask = attention_mask.unsqueeze(1).expand(batch_size, effective_batch_mult * num_beams, input_ids_len)
|
| 376 |
+
|
| 377 |
+
# Reshape to combine batch and beam dimensions
|
| 378 |
+
input_ids = input_ids.reshape(effective_batch_size * num_beams, input_ids_len)
|
| 379 |
+
attention_mask = attention_mask.reshape(effective_batch_size * num_beams, input_ids_len)
|
| 380 |
+
|
| 381 |
+
if num_beams > 1:
|
| 382 |
+
output = self._generate_beam_search(
|
| 383 |
+
input_ids=input_ids,
|
| 384 |
+
attention_mask=attention_mask,
|
| 385 |
+
visual_features=visual_features,
|
| 386 |
+
tags_embedding=tags_embedding,
|
| 387 |
+
cur_len=input_ids.size(1),
|
| 388 |
+
max_length=max_length,
|
| 389 |
+
min_length=min_length,
|
| 390 |
+
do_sample=do_sample,
|
| 391 |
+
early_stopping=early_stopping,
|
| 392 |
+
temperature=temperature,
|
| 393 |
+
top_k=top_k,
|
| 394 |
+
top_p=top_p,
|
| 395 |
+
repetition_penalty=repetition_penalty,
|
| 396 |
+
no_repeat_ngram_size=no_repeat_ngram_size,
|
| 397 |
+
pad_token_id=pad_token_id,
|
| 398 |
+
eos_token_ids=eos_token_ids,
|
| 399 |
+
length_penalty=length_penalty,
|
| 400 |
+
num_return_sequences=num_return_sequences,
|
| 401 |
+
num_beams=num_beams,
|
| 402 |
+
)
|
| 403 |
+
else:
|
| 404 |
+
output = self._generate_no_beam_search(
|
| 405 |
+
input_ids=input_ids,
|
| 406 |
+
attention_mask=attention_mask,
|
| 407 |
+
visual_features=visual_features,
|
| 408 |
+
tags_embedding=tags_embedding,
|
| 409 |
+
cur_len=input_ids.size(1),
|
| 410 |
+
max_length=max_length,
|
| 411 |
+
min_length=min_length,
|
| 412 |
+
do_sample=do_sample,
|
| 413 |
+
temperature=temperature,
|
| 414 |
+
top_k=top_k,
|
| 415 |
+
top_p=top_p,
|
| 416 |
+
repetition_penalty=repetition_penalty,
|
| 417 |
+
no_repeat_ngram_size=no_repeat_ngram_size,
|
| 418 |
+
pad_token_id=pad_token_id,
|
| 419 |
+
eos_token_ids=eos_token_ids,
|
| 420 |
+
batch_size=batch_size,
|
| 421 |
+
vocab_size=vocab_size,
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
return output
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def _generate_no_beam_search(
|
| 428 |
+
self,
|
| 429 |
+
input_ids,
|
| 430 |
+
visual_features,
|
| 431 |
+
tags_embedding,
|
| 432 |
+
cur_len,
|
| 433 |
+
max_length,
|
| 434 |
+
min_length,
|
| 435 |
+
do_sample,
|
| 436 |
+
temperature,
|
| 437 |
+
top_k,
|
| 438 |
+
top_p,
|
| 439 |
+
repetition_penalty,
|
| 440 |
+
no_repeat_ngram_size,
|
| 441 |
+
pad_token_id,
|
| 442 |
+
eos_token_ids,
|
| 443 |
+
batch_size,
|
| 444 |
+
vocab_size,
|
| 445 |
+
attention_mask,
|
| 446 |
+
):
|
| 447 |
+
"""
|
| 448 |
+
Generate sequences for each example without beam search (num_beams == 1).
|
| 449 |
+
All returned sequences are generated independently.
|
| 450 |
+
"""
|
| 451 |
+
# Track unfinished sentences and their lengths
|
| 452 |
+
unfinished_sents=torch.ones_like(input_ids[:,0])
|
| 453 |
+
sent_lengths=torch.ones_like(input_ids[:,0])*max_length
|
| 454 |
+
|
| 455 |
+
past=None
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
while cur_len < max_length:
|
| 459 |
+
if past is None:
|
| 460 |
+
inputs = input_ids
|
| 461 |
+
else:
|
| 462 |
+
inputs = input_ids[:, -1].unsqueeze(1)
|
| 463 |
+
|
| 464 |
+
model_inputs = self.prepare_inputs_for_generation(
|
| 465 |
+
inputs, past=past, visual_features=visual_features, tags_embedding=tags_embedding
|
| 466 |
+
)
|
| 467 |
+
outputs = self(**model_inputs)
|
| 468 |
+
# next_token_logits = outputs[0][-1, :] # Extract logits for the last token, shape: [batch_size, vocab_size]
|
| 469 |
+
next_token_logits = outputs[:, -1, :]
|
| 470 |
+
|
| 471 |
+
# next_token_logits = next_token_logits.unsqueeze(0) # Add a new dimension: [1, batch_size, vocab_size]
|
| 472 |
+
next_token_logits = next_token_logits.expand(batch_size, vocab_size) # Expand to match batch size: [batch_size, vocab_size]
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
# if self._do_output_past(outputs): # we dont have this function implemented
|
| 476 |
+
# past = outputs[1]
|
| 477 |
+
|
| 478 |
+
# Apply repetition penalty
|
| 479 |
+
if repetition_penalty != 1.0:
|
| 480 |
+
next_token_logits_penalties=self._create_next_token_logits_penalties(input_ids,next_token_logits,repetition_penalty)
|
| 481 |
+
next_token_logits=next_token_logits @ next_token_logits_penalties.T # .T de mn 3ndy
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
# Prevent repetition of n-grams
|
| 485 |
+
if no_repeat_ngram_size > 0: # not checked generated by chat
|
| 486 |
+
banned_tokens=self.calc_banned_ngram_tokens(input_ids,batch_size,no_repeat_ngram_size,cur_len) # not checked generated by chat
|
| 487 |
+
banned_tokens_indices_mask=[]
|
| 488 |
+
|
| 489 |
+
for banned_tokens_slice in banned_tokens:
|
| 490 |
+
banned_tokens_indices_mask.append(
|
| 491 |
+
[True if token in banned_tokens_slice else False for token in range(vocab_size)]
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
banned_tokens_indices_mask=torch.tensor(banned_tokens_indices_mask,dtype=bool)
|
| 495 |
+
|
| 496 |
+
next_token_logits[banned_tokens_indices_mask]= -float('inf')
|
| 497 |
+
|
| 498 |
+
# Min length constraint for EOS
|
| 499 |
+
if eos_token_ids is not None and cur_len < min_length:
|
| 500 |
+
# create eos_token_id boolean mask
|
| 501 |
+
is_token_logit_eos_token = torch.arange(vocab_size, device=next_token_logits.device) == eos_token_ids
|
| 502 |
+
eos_token_indices_mask = is_token_logit_eos_token.unsqueeze(0).expand(batch_size, -1)
|
| 503 |
+
# next_token_logits=next_token_logits.unsqueeze(0).expand(batch_size,vocab_size)
|
| 504 |
+
|
| 505 |
+
next_token_logits = next_token_logits.masked_fill(eos_token_indices_mask, -float("inf"))
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
# Sampling or greedy decoding
|
| 512 |
+
if do_sample:
|
| 513 |
+
if temperature != 1.0:
|
| 514 |
+
next_token_logits = next_token_logits / temperature
|
| 515 |
+
|
| 516 |
+
next_token_logits=self.top_k_top_p_filtering(next_token_logits,top_k=top_k,top_p=top_p)
|
| 517 |
+
|
| 518 |
+
next_token = torch.multinomial(torch.softmax(next_token_logits, dim=-1), num_samples=1).squeeze(1)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
else:
|
| 522 |
+
next_token=torch.argmax(next_token_logits,dim=-1)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
if eos_token_ids is not None:
|
| 526 |
+
unfinished_sents=unfinished_sents.to(self.device)
|
| 527 |
+
tokens_to_add = next_token * unfinished_sents + pad_token_id * (1 - unfinished_sents)
|
| 528 |
+
|
| 529 |
+
else:
|
| 530 |
+
tokens_to_add = next_token
|
| 531 |
+
input_ids=input_ids.to(self.device)
|
| 532 |
+
input_ids = torch.cat([input_ids, tokens_to_add.unsqueeze(-1)], dim=1)
|
| 533 |
+
|
| 534 |
+
if eos_token_ids is not None:
|
| 535 |
+
eos_in_sents = tokens_to_add == eos_token_ids
|
| 536 |
+
# If sentence is unfinished and the token to add is eos, sent_lengths is filled with current length
|
| 537 |
+
is_sents_unfinished_and_token_to_add_is_eos = unfinished_sents * eos_in_sents.int()
|
| 538 |
+
sent_lengths=sent_lengths.to(self.device)
|
| 539 |
+
sent_lengths = (
|
| 540 |
+
sent_lengths * (1 - is_sents_unfinished_and_token_to_add_is_eos)
|
| 541 |
+
+ cur_len * is_sents_unfinished_and_token_to_add_is_eos
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
# Unfinished sentences are set to zero if eos is in the sentence
|
| 545 |
+
unfinished_sents -= is_sents_unfinished_and_token_to_add_is_eos
|
| 546 |
+
|
| 547 |
+
# Stop if there is a </s> in each sentence, or if we exceed the maximum length
|
| 548 |
+
if torch.max(unfinished_sents) == 0: # => this line is what keeps it stopping at 57 etc..
|
| 549 |
+
break
|
| 550 |
+
|
| 551 |
+
cur_len += 1
|
| 552 |
+
|
| 553 |
+
# Pad sequences if necessary
|
| 554 |
+
min_sent_length = sent_lengths.min()
|
| 555 |
+
max_sent_length = sent_lengths.max()
|
| 556 |
+
|
| 557 |
+
if min_sent_length != max_sent_length:
|
| 558 |
+
assert pad_token_id is not None, "`Pad_token_id` has to be defined if batches have different lengths"
|
| 559 |
+
padding = torch.ones((batch_size, max_sent_length), dtype=torch.int) * pad_token_id
|
| 560 |
+
broad_casted_sent_lengths = sent_lengths.unsqueeze(-1).expand(batch_size, max_sent_length)
|
| 561 |
+
broad_casted_range = torch.arange(max_sent_length).unsqueeze(0).expand(batch_size, max_sent_length).T
|
| 562 |
+
|
| 563 |
+
# Use torch.where to apply padding where necessary
|
| 564 |
+
decoded = torch.where(broad_casted_range < broad_casted_sent_lengths, input_ids, padding)
|
| 565 |
+
else:
|
| 566 |
+
decoded = input_ids
|
| 567 |
+
|
| 568 |
+
return decoded
|
| 569 |
+
|
| 570 |
+
def _create_next_token_logits_penalties(self,input_ids, logits, repetition_penalty):
|
| 571 |
+
"""
|
| 572 |
+
Create logit penalties for already seen input_ids based on repetition penalty.
|
| 573 |
+
|
| 574 |
+
Args:
|
| 575 |
+
input_ids (torch.Tensor): Tensor of shape (batch_size, seq_len) containing input token IDs.
|
| 576 |
+
logits (torch.Tensor): Tensor of shape (batch_size, vocab_size) containing next-token logits.
|
| 577 |
+
repetition_penalty (float): The penalty to apply for repeated tokens.
|
| 578 |
+
|
| 579 |
+
Returns:
|
| 580 |
+
torch.Tensor: Tensor of shape (batch_size, vocab_size) with applied penalties.
|
| 581 |
+
"""
|
| 582 |
+
token_penalties=torch.ones_like(logits)
|
| 583 |
+
prev_input_ids=[torch.unique(input_id) for input_id in input_ids]
|
| 584 |
+
|
| 585 |
+
for i, prev_input_id in enumerate(prev_input_ids):
|
| 586 |
+
logits_penalized=logits[i][prev_input_ids]
|
| 587 |
+
logit_penalties=torch.zeros_like(logits_penalized)
|
| 588 |
+
|
| 589 |
+
logit_penalties[logits_penalized<0]=repetition_penalty
|
| 590 |
+
logit_penalties[logits_penalized>0]=1/repetition_penalty
|
| 591 |
+
|
| 592 |
+
token_penalties[i].scatter_(0,prev_input_id,logit_penalties)
|
| 593 |
+
return token_penalties
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def top_k_top_p_filtering(self,logits, top_k=0, top_p=1.0, filter_value=-float("Inf"), min_tokens_to_keep=1):
|
| 597 |
+
"""
|
| 598 |
+
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering.
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
logits: Logits distribution of shape (batch size, vocabulary size).
|
| 602 |
+
top_k (int): Keep only top k tokens with the highest probability.
|
| 603 |
+
top_p (float): Keep the top tokens with cumulative probability >= top_p (nucleus filtering).
|
| 604 |
+
filter_value (float): Value to assign to filtered logits.
|
| 605 |
+
min_tokens_to_keep (int): Ensure at least this many tokens are kept.
|
| 606 |
+
|
| 607 |
+
Returns:
|
| 608 |
+
torch.Tensor: Filtered logits.
|
| 609 |
+
"""
|
| 610 |
+
logits_shape = logits.size()
|
| 611 |
+
|
| 612 |
+
# Top-k filtering
|
| 613 |
+
if top_k > 0:
|
| 614 |
+
top_k = min(max(top_k, min_tokens_to_keep), logits_shape[-1]) # Safety check
|
| 615 |
+
# Remove all tokens with a probability less than the last token of the top-k
|
| 616 |
+
top_k_values, _ = torch.topk(logits, top_k, dim=-1)
|
| 617 |
+
min_top_k_values = top_k_values[:, -1].unsqueeze(-1) # Minimum logit in top-k
|
| 618 |
+
logits = torch.where(logits < min_top_k_values, torch.full_like(logits, filter_value), logits)
|
| 619 |
+
|
| 620 |
+
# Top-p (nucleus) filtering
|
| 621 |
+
if top_p < 1.0:
|
| 622 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
|
| 623 |
+
cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
|
| 624 |
+
|
| 625 |
+
# Remove tokens with cumulative probability above the threshold
|
| 626 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 627 |
+
|
| 628 |
+
if min_tokens_to_keep > 1:
|
| 629 |
+
# Ensure we keep at least min_tokens_to_keep tokens
|
| 630 |
+
sorted_indices_to_remove[:, :min_tokens_to_keep] = 0
|
| 631 |
+
|
| 632 |
+
# Shift the indices to the right to keep also the first token above the threshold
|
| 633 |
+
sorted_indices_to_remove = sorted_indices_to_remove.roll(1, dims=-1)
|
| 634 |
+
sorted_indices_to_remove[:, 0] = 0
|
| 635 |
+
|
| 636 |
+
# Scatter sorted indices back to original indexing
|
| 637 |
+
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
|
| 638 |
+
logits = torch.where(indices_to_remove, torch.full_like(logits, filter_value), logits)
|
| 639 |
+
|
| 640 |
+
return logits
|
| 641 |
+
|
| 642 |
+
def calc_banned_ngram_tokens(self,prev_input_ids, num_hypos, no_repeat_ngram_size, cur_len):
|
| 643 |
+
"""
|
| 644 |
+
Calculate banned n-gram tokens for no-repeat n-gram constraints.
|
| 645 |
+
|
| 646 |
+
Args:
|
| 647 |
+
prev_input_ids (torch.Tensor): Tensor of shape (num_hypos, seq_len) containing token sequences.
|
| 648 |
+
num_hypos (int): Number of hypotheses in the batch.
|
| 649 |
+
no_repeat_ngram_size (int): Size of the n-grams to avoid repeating.
|
| 650 |
+
cur_len (int): Current length of the sequence being generated.
|
| 651 |
+
|
| 652 |
+
Returns:
|
| 653 |
+
List[List[int]]: List of banned tokens for each hypothesis.
|
| 654 |
+
"""
|
| 655 |
+
if cur_len + 1 < no_repeat_ngram_size:
|
| 656 |
+
# Return no banned tokens if not enough tokens have been generated
|
| 657 |
+
return [[] for _ in range(num_hypos)]
|
| 658 |
+
|
| 659 |
+
# Dictionary to store generated n-grams for each hypothesis
|
| 660 |
+
generated_ngrams = [{} for _ in range(num_hypos)]
|
| 661 |
+
|
| 662 |
+
# Populate the n-grams
|
| 663 |
+
for idx in range(num_hypos):
|
| 664 |
+
gen_tokens = prev_input_ids[idx].tolist()
|
| 665 |
+
generated_ngram = generated_ngrams[idx]
|
| 666 |
+
for ngram in zip(*[gen_tokens[i:] for i in range(no_repeat_ngram_size)]):
|
| 667 |
+
prev_ngram_tuple = tuple(ngram[:-1])
|
| 668 |
+
generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]]
|
| 669 |
+
|
| 670 |
+
def _get_generated_ngrams(hypo_idx):
|
| 671 |
+
# Get n-grams that have already appeared
|
| 672 |
+
start_idx = cur_len + 1 - no_repeat_ngram_size
|
| 673 |
+
ngram_idx = tuple(prev_input_ids[hypo_idx, start_idx:cur_len].tolist())
|
| 674 |
+
return generated_ngrams[hypo_idx].get(ngram_idx, [])
|
| 675 |
+
|
| 676 |
+
# Calculate banned tokens for each hypothesis
|
| 677 |
+
banned_tokens = [_get_generated_ngrams(hypo_idx) for hypo_idx in range(num_hypos)]
|
| 678 |
+
return banned_tokens
|
| 679 |
+
|
| 680 |
+
|
generate_report.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
import io
|
| 3 |
+
import torch
|
| 4 |
+
import os
|
| 5 |
+
import numpy as np
|
| 6 |
+
from CNN_encoder import CNN_Encoder
|
| 7 |
+
from distil_gpt2 import DistilGPT2
|
| 8 |
+
from configs import argHandler
|
| 9 |
+
from utils import load_image
|
| 10 |
+
from tokenizer_wrapper import TokenizerWrapper
|
| 11 |
+
from huggingface_hub import hf_hub_download
|
| 12 |
+
# from src.models.cnn_encoder import
|
| 13 |
+
# from src.models.distil_gpt2 import DistilGPT2
|
| 14 |
+
# from src.configs import argHandler
|
| 15 |
+
|
| 16 |
+
FLAGS = argHandler()
|
| 17 |
+
FLAGS.setDefaults()
|
| 18 |
+
tokenizer_wrapper = TokenizerWrapper( FLAGS.csv_label_columns[0], FLAGS.max_sequence_length, FLAGS.tokenizer_vocab_size)
|
| 19 |
+
|
| 20 |
+
encoder = CNN_Encoder('pretrained_visual_model', FLAGS.visual_model_name, FLAGS.visual_model_pop_layers,
|
| 21 |
+
FLAGS.encoder_layers, FLAGS.tags_threshold, num_tags=len(FLAGS.tags))
|
| 22 |
+
decoder = DistilGPT2.from_pretrained('distilgpt2')
|
| 23 |
+
|
| 24 |
+
optimizer = torch.optim.Adam(decoder.parameters(), lr=FLAGS.learning_rate)
|
| 25 |
+
# checkpoint_path = os.path.join(FLAGS.ckpt_path, "checkpoint.pth")
|
| 26 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
+
encoder.to(device)
|
| 28 |
+
decoder.to(device)
|
| 29 |
+
|
| 30 |
+
checkpoint_path = hf_hub_download(repo_id="TransformingBerry/CDGPT2_checkpoint", filename="checkpoint.pth")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if os.path.exists(checkpoint_path):
|
| 34 |
+
print(f"Restoring from checkpoint: {checkpoint_path}")
|
| 35 |
+
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=True)
|
| 36 |
+
encoder.load_state_dict(checkpoint['encoder_state_dict'])
|
| 37 |
+
decoder.load_state_dict(checkpoint['decoder_state_dict'])
|
| 38 |
+
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
|
| 39 |
+
else:
|
| 40 |
+
print("No checkpoint found. Starting from scratch.")
|
| 41 |
+
|
| 42 |
+
def generate_report(image_bytes):
|
| 43 |
+
image = Image.open(io.BytesIO(image_bytes))
|
| 44 |
+
image_tensor = load_image(image)
|
| 45 |
+
|
| 46 |
+
visual_features, tags_embedding = encoder(image_tensor)
|
| 47 |
+
|
| 48 |
+
dec_input = torch.unsqueeze(
|
| 49 |
+
torch.tensor(tokenizer_wrapper.GPT2_encode('startseq', pad=False)), 0
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
generation_config = {
|
| 53 |
+
"visual_features": visual_features,
|
| 54 |
+
"tags_embedding": tags_embedding,
|
| 55 |
+
"num_beams": 1,
|
| 56 |
+
"max_length": FLAGS.max_sequence_length,
|
| 57 |
+
"min_length": 3,
|
| 58 |
+
"eos_token_ids": tokenizer_wrapper.GPT2_eos_token_id(),
|
| 59 |
+
"pad_token_id": tokenizer_wrapper.GPT2_pad_token_id(),
|
| 60 |
+
"do_sample": False,
|
| 61 |
+
"early_stopping": True,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
tokens = decoder.generate(dec_input, **generation_config)
|
| 65 |
+
sentence = tokenizer_wrapper.GPT2_decode(tokens[0])
|
| 66 |
+
sentence = tokenizer_wrapper.filter_special_words(sentence)
|
| 67 |
+
print(sentence)
|
| 68 |
+
|
| 69 |
+
return {"report": sentence}
|
generator.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import os
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from torch.utils.data import Dataset, DataLoader
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from skimage.transform import resize
|
| 7 |
+
import torch
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class AugmentedImageSequence(Dataset):
|
| 12 |
+
"""
|
| 13 |
+
Thread-safe image generator with imgaug support in PyTorch
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def __init__(self, dataset_csv_file, class_names, source_image_dir, tokenizer_wrapper, batch_size=16,
|
| 17 |
+
target_size=(224, 224), augmenter=None, verbose=0, steps=None,
|
| 18 |
+
shuffle_on_epoch_end=True, random_state=1):
|
| 19 |
+
"""
|
| 20 |
+
:param dataset_csv_file: str, path of dataset csv file
|
| 21 |
+
:param class_names: list of str
|
| 22 |
+
:param batch_size: int
|
| 23 |
+
:param target_size: tuple(int, int)
|
| 24 |
+
:param augmenter: imgaug object. Do not specify resize in augmenter.
|
| 25 |
+
It will be done automatically according to input_shape of the model.
|
| 26 |
+
:param verbose: int
|
| 27 |
+
"""
|
| 28 |
+
self.dataset_df = pd.read_csv(dataset_csv_file)
|
| 29 |
+
self.source_image_dir = source_image_dir
|
| 30 |
+
self.batch_size = batch_size
|
| 31 |
+
self.target_size = target_size
|
| 32 |
+
self.augmenter = augmenter
|
| 33 |
+
self.tokenizer_wrapper = tokenizer_wrapper
|
| 34 |
+
self.verbose = verbose
|
| 35 |
+
self.shuffle = shuffle_on_epoch_end
|
| 36 |
+
self.random_state = random_state
|
| 37 |
+
self.class_names = class_names
|
| 38 |
+
self.prepare_dataset()
|
| 39 |
+
if steps is None:
|
| 40 |
+
self.steps = int(np.ceil(len(self.x_path) / float(self.batch_size)))
|
| 41 |
+
else:
|
| 42 |
+
self.steps = int(steps)
|
| 43 |
+
|
| 44 |
+
self.transform = transforms.Compose([
|
| 45 |
+
# transforms.ToTensor(),
|
| 46 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 47 |
+
])
|
| 48 |
+
|
| 49 |
+
def __len__(self):
|
| 50 |
+
return self.steps
|
| 51 |
+
|
| 52 |
+
def __getitem__(self, idx):
|
| 53 |
+
batch_x_path = self.x_path[idx * self.batch_size:(idx + 1) * self.batch_size]
|
| 54 |
+
batch_x = torch.stack([self.load_image(x_path) for x_path in batch_x_path])
|
| 55 |
+
batch_x = self.transform_batch_images(batch_x)
|
| 56 |
+
batch_y = torch.tensor(self.y[idx * self.batch_size:(idx + 1) * self.batch_size])
|
| 57 |
+
return batch_x, batch_y, batch_x_path.tolist()
|
| 58 |
+
|
| 59 |
+
def load_image(self, image_file):
|
| 60 |
+
image_path = os.path.join(self.source_image_dir, image_file)
|
| 61 |
+
image = Image.open(image_path).convert("RGB")
|
| 62 |
+
image_array = np.asarray(image) / 255.
|
| 63 |
+
image_array = resize(image_array, self.target_size)
|
| 64 |
+
image_tensor = torch.tensor(image_array, dtype=torch.float32).permute(2, 0, 1) # Convert to CxHxW
|
| 65 |
+
return image_tensor
|
| 66 |
+
|
| 67 |
+
def transform_batch_images(self, batch_x):
|
| 68 |
+
if self.augmenter is not None:
|
| 69 |
+
batch_x = torch.stack([torch.tensor(self.augmenter.augment_image(img.permute(1, 2, 0).numpy())) for img in batch_x])
|
| 70 |
+
batch_x = self.transform(batch_x)
|
| 71 |
+
return batch_x
|
| 72 |
+
|
| 73 |
+
def get_y_true(self):
|
| 74 |
+
"""
|
| 75 |
+
Use this function to get y_true for DataLoader.
|
| 76 |
+
Ensure shuffle_on_epoch_end is False before using.
|
| 77 |
+
"""
|
| 78 |
+
if self.shuffle:
|
| 79 |
+
raise ValueError("get_y_true() can only be used when shuffle_on_epoch_end is False.")
|
| 80 |
+
return torch.tensor(self.y[:self.steps * self.batch_size], dtype=torch.float32)
|
| 81 |
+
|
| 82 |
+
def prepare_dataset(self):
|
| 83 |
+
df = self.dataset_df.sample(frac=1., random_state=self.random_state)
|
| 84 |
+
## @TODO: tokenize the targets
|
| 85 |
+
self.x_path, self.y = df["Image Index"].values, self.tokenizer_wrapper.GPT2_encode(
|
| 86 |
+
df[self.class_names].values)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def on_epoch_end(self):
|
| 90 |
+
if self.shuffle:
|
| 91 |
+
self.random_state += 1
|
| 92 |
+
self.prepare_dataset()
|
| 93 |
+
|
main.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from generate_report import generate_report
|
| 4 |
+
from utils import convert_to_png
|
| 5 |
+
import io
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
app = FastAPI(title="FastAPI Example App", version="0.1.0")
|
| 9 |
+
app.add_middleware(
|
| 10 |
+
CORSMiddleware,
|
| 11 |
+
allow_origins=["*"],
|
| 12 |
+
allow_credentials=True,
|
| 13 |
+
allow_methods=["*"],
|
| 14 |
+
allow_headers=["*"],
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@app.get("/")
|
| 19 |
+
async def read_root():
|
| 20 |
+
return {"message": "Hello oopa"}
|
| 21 |
+
|
| 22 |
+
@app.post("/upload-image/")
|
| 23 |
+
async def upload_image(file: UploadFile = File(...)):
|
| 24 |
+
try:
|
| 25 |
+
image = await convert_to_png(file)
|
| 26 |
+
image_io = io.BytesIO()
|
| 27 |
+
image.save(image_io, format="PNG")
|
| 28 |
+
image_data = image_io.getvalue()
|
| 29 |
+
report = generate_report(image_data)
|
| 30 |
+
return {"report": report}
|
| 31 |
+
except Exception as e:
|
| 32 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
|
pretrained_visual_model/best_weights.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c299f950c6a69bb3c82f20afbcf312c0d53e800b27c2420eb4f1c1e7edf77b8
|
| 3 |
+
size 83811496
|
pretrained_visual_model/best_weights.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pretrained_visual_model/fine_tuned_chexnet.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6596d037bb3cc1c1959b7379f9fe8a4bf238963a09d11cd1bbe5d1688192c2c9
|
| 3 |
+
size 29517896
|
pretrained_visual_model/fine_tuned_chexnet.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|