-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcvt2distilgpt2_iu_x_ray_chen.py
305 lines (267 loc) · 11.4 KB
/
cvt2distilgpt2_iu_x_ray_chen.py
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import json
import os
from lightning.pytorch import LightningModule
import torch
import transformers
from torchvision import transforms
from transformers.configuration_utils import PretrainedConfig
from cvt2distilgpt2_mimic_cxr_chen import CvT2DistilGPT2MIMICXRChen
from tools.cvt import CvT
from tools.dataset.iu_x_ray_chen import TaskSubset
from tools.dataset.iu_x_ray_chen_tokenizer import TokenizerChen
from tools.encoder_projection import EncoderPermuteProject
from tools.metrics.chexbert import CheXbertMetrics
from tools.metrics.coco import COCOCaptionMetrics
from tools.metrics.report_logger import ReportLogger
from tools.multi_image import MultiImageInput, MultiImageOutput
class CvT2DistilGPT2IUXRayChen(CvT2DistilGPT2MIMICXRChen):
def __init__(
self,
warm_start_modules: bool,
exp_dir_trial: str,
dataset_dir: str,
ckpt_zoo_dir: str,
mbatch_size: int,
encoder_lr: float,
decoder_lr: float,
decoder_max_len: int,
num_test_beams: int,
prefetch_factor: int = 5,
num_workers: int = 0,
**kwargs,
):
LightningModule.__init__(self)
self.warm_start_modules = warm_start_modules
self.exp_dir_trial = exp_dir_trial
self.dataset_dir = dataset_dir
self.ckpt_zoo_dir = ckpt_zoo_dir
self.mbatch_size = mbatch_size
self.encoder_lr = encoder_lr
self.decoder_lr = decoder_lr
self.decoder_max_len = decoder_max_len
self.num_test_beams = num_test_beams
self.prefetch_factor = prefetch_factor
self.num_workers = num_workers
# Paths:
self.labels_file_path = os.path.join(self.dataset_dir, "iu_x-ray_chen", "annotation.json")
self.dataset_dir = os.path.join(self.dataset_dir, "iu_x-ray_chen", "images")
self.chen_tokenizer = TokenizerChen(
ann_path=self.labels_file_path,
threshold=3,
)
self.chen_max_seq_length = 60
"""
Evaluation metrics
These need to be defined correctly in order for them to be placed on the correct device:
https://torchmetrics.readthedocs.io/en/stable/pages/lightning.html#torchmetrics-in-pytorch-lightning
"""
self.val_coco_metrics = COCOCaptionMetrics(metrics=["bleu", "cider", "rouge"])
self.test_coco_metrics = COCOCaptionMetrics(metrics=["bleu", "cider", "meteor", "rouge"])
# CheXbert classification metrics:
self.val_chexbert_metrics = CheXbertMetrics(
bert_path='bert-base-uncased',
checkpoint_path='stanford/chexbert/chexbert.pth',
ckpt_dir=self.ckpt_zoo_dir,
mbatch_size=self.mbatch_size,
exp_dir=self.exp_dir_trial,
)
self.test_chexbert_metrics = CheXbertMetrics(
bert_path='bert-base-uncased',
checkpoint_path='stanford/chexbert/chexbert.pth',
ckpt_dir=self.ckpt_zoo_dir,
mbatch_size=self.mbatch_size,
exp_dir=self.exp_dir_trial,
)
# Report logging:
self.val_report_logger = ReportLogger(exp_dir=self.exp_dir_trial, split='val_reports')
self.test_report_logger = ReportLogger(exp_dir=self.exp_dir_trial, split='test_reports')
# Encoder:
self.encoder = CvT(
warm_start=self.warm_start_modules,
model_config='cvt-21-384x384',
ckpt_name='CvT-21-384x384-IN-22k',
ckpt_dir=self.ckpt_zoo_dir,
is_encoder=True,
)
self.encoder_projection = EncoderPermuteProject(
permute_encoder_last_hidden_state=[0, 2, 1],
encoder_last_hidden_state_size=384,
decoder_hidden_state_size=768,
)
# To handle the two views:
self.multi_input = MultiImageInput()
self.multi_output = MultiImageOutput()
# Decoder:
ckpt_name = 'distilgpt2'
config = transformers.GPT2Config.from_pretrained(
os.path.join(self.ckpt_zoo_dir, ckpt_name),
local_files_only=True,
)
config.add_cross_attention = True
config.is_decoder = True
if self.warm_start_modules:
decoder = transformers.GPT2LMHeadModel.from_pretrained(
os.path.join(self.ckpt_zoo_dir, ckpt_name),
local_files_only=True,
config=config,
)
else:
decoder = transformers.GPT2LMHeadModel(config=config)
# Resize GPT2 embedding to include padding and beginning of sentence token:
decoder.resize_token_embeddings(config.vocab_size + 2)
# Decoder tokenizer:
self.tokenizer = transformers.GPT2TokenizerFast.from_pretrained(
os.path.join(self.ckpt_zoo_dir, ckpt_name),
local_files_only=True,
)
self.tokenizer.add_special_tokens({"bos_token": "[BOS]", 'pad_token': '[PAD]'})
# Print the special tokens:
print('Description, Special token, Index')
for k, v in self.tokenizer.special_tokens_map.items():
if k != 'additional_special_tokens':
print(f'{k}, {v}, {getattr(self.tokenizer, k + "_id")}')
else:
for i, j in zip(self.tokenizer.additional_special_tokens, self.tokenizer.additional_special_tokens_ids):
print(f'additional_special_token, {i}, {j}')
# We don't actually want to use the encoder of the EncoderDecoderModel, create a dummy encoder:
class DummyEncoder:
main_input_name = 'dummy'
class DummyConfig(PretrainedConfig):
model_type = 'bert'
config = DummyConfig()
def __init__(self, hidden_size):
self.config.hidden_size = hidden_size
def get_output_embeddings(cls):
return None
def forward(self):
return None
# Use Hugging Face Transformers EncoderDecoderModel to generate conditionally:
dummy_encoder = DummyEncoder(hidden_size=decoder.config.hidden_size)
# To be compatible with previous the framework (and hence, the available checkpoint):
class Decoder(torch.nn.Module):
def __init__(self):
super().__init__()
self.encoder_decoder = transformers.EncoderDecoderModel(encoder=dummy_encoder, decoder=decoder)
self.decoder = Decoder()
# Image transformations:
self.train_transforms = transforms.Compose(
[
transforms.Resize(size=384 + 64),
transforms.RandomCrop(
size=[384, 384],
pad_if_needed=True,
),
transforms.RandomRotation(degrees=5),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225],
),
]
)
self.test_transforms = transforms.Compose(
[
transforms.Resize(size=384 + 64),
transforms.CenterCrop(size=[384, 384]),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225],
),
]
)
def setup(self, stage=None):
"""
https://pytorch-lightning.readthedocs.io/en/stable/common/lightning_module.html#setup
"""
with open(self.labels_file_path) as f:
examples = json.load(f)
# Dataset statistics:
images = set()
for i in examples["train"]:
images.update(i["image_path"])
print(
"Training set #images: {}, #studies: {}".format(
len(images), len(examples["train"])
)
)
images = set()
for i in examples["val"]:
images.update(i["image_path"])
print(
"Validation set #images: {}, #studies: {}".format(
len(images), len(examples["val"])
)
)
images = set()
for i in examples["test"]:
images.update(i["image_path"])
print(
"Test set #images: {}, #studies: {}".format(
len(images), len(examples["test"])
)
)
# Assign train & validation sets:
if stage == "fit" or stage is None:
self.train_set = TaskSubset(
examples=self.format_examples(examples["train"]),
tokenizer=self.tokenizer,
decoder_max_len=self.decoder_max_len,
colour_space='RGB',
transforms=self.train_transforms,
self_critical=False,
train=True,
add_bos_eos_manually=True,
num_samples=None,
)
self.val_set = TaskSubset(
examples=self.format_examples(examples["val"]),
tokenizer=self.tokenizer,
decoder_max_len=self.decoder_max_len,
colour_space='RGB',
transforms=self.test_transforms,
add_bos_eos_manually=True,
)
print(
"No. of training & validation examples: {} & {}.".format(
self.train_set.__len__(), self.val_set.__len__()
)
)
# Assign test set:
if stage == "test" or stage is None:
self.test_set = TaskSubset(
examples=self.format_examples(examples["test"]),
tokenizer=self.tokenizer,
decoder_max_len=self.decoder_max_len,
colour_space='RGB',
transforms=self.test_transforms,
add_bos_eos_manually=True,
)
print(
"No. of test examples: {}.".format(
self.test_set.__len__()
)
)
def format_examples(self, examples):
for i in examples:
i["image_file_path"] = i.pop("image_path")
i["label"] = i.pop("report")
i["image_file_path"] = [os.path.join(self.dataset_dir, j) for j in i["image_file_path"]]
i["label"] = self.chen_tokenizer(i["label"])[:self.chen_max_seq_length]
i["label"] = self.chen_tokenizer.decode(i["label"][1:])
return examples
def encoder_forward(self, images):
"""
Encoder forward propagation.
Argument/s:
images - a mini-batch of images.
image_batch_ids - batch index for each image.
Returns:
encoder_outputs - transformers.modeling_outputs.ModelOutput.
"""
views = self.multi_input(images)
image_features = self.encoder(views['images'])['last_hidden_state']
image_features = self.encoder_projection(image_features)['projected_encoder_last_hidden_state']
image_features = self.multi_output(image_features, views['images_per_example'])['last_hidden_state']
encoder_outputs = transformers.modeling_outputs.BaseModelOutput(last_hidden_state=image_features)
return encoder_outputs