RitaParadaRamos commited on
Commit
7c4b306
1 Parent(s): c881ec3

Upload 11 files

Browse files
Files changed (11) hide show
  1. extract_features.py +54 -0
  2. gpt2.py +167 -0
  3. gptj.py +0 -0
  4. opt.py +696 -0
  5. retrieve_caps.py +145 -0
  6. retrieve_caps2.py +178 -0
  7. template.txt +5 -0
  8. utils.py +131 -0
  9. utils_generate_retrieved_caps.py +135 -0
  10. vision_encoder_decoder.py +560 -0
  11. xglm.py +269 -0
extract_features.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import pandas as pd
4
+ import json
5
+ from tqdm import tqdm
6
+ from PIL import Image
7
+ import torch
8
+ from multiprocessing import Pool
9
+ import h5py
10
+ from transformers import logging
11
+ from transformers import CLIPFeatureExtractor, CLIPVisionModel
12
+ logging.set_verbosity_error()
13
+
14
+ data_dir = 'data/images/'
15
+ features_dir = 'features/'
16
+
17
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
+
19
+ encoder_name = 'openai/clip-vit-base-patch32'
20
+ feature_extractor = CLIPFeatureExtractor.from_pretrained(encoder_name)
21
+ clip_encoder = CLIPVisionModel.from_pretrained(encoder_name).to(device)
22
+
23
+ annotations = json.load(open('data/dataset_coco.json'))['images']
24
+
25
+ def load_data():
26
+ data = {'train': [], 'val': []}
27
+
28
+ for item in annotations:
29
+ file_name = item['filename'].split('_')[-1]
30
+ if item['split'] == 'train' or item['split'] == 'restval':
31
+ data['train'].append({'file_name': file_name, 'cocoid': item['cocoid']})
32
+ elif item['split'] == 'val':
33
+ data['val'].append({'file_name': file_name, 'cocoid': item['cocoid']})
34
+ return data
35
+
36
+ def encode_split(data, split):
37
+ df = pd.DataFrame(data[split])
38
+
39
+ bs = 256
40
+ h5py_file = h5py.File(features_dir + '{}.hdf5'.format(split), 'w')
41
+ for idx in tqdm(range(0, len(df), bs)):
42
+ cocoids = df['cocoid'][idx:idx + bs]
43
+ file_names = df['file_name'][idx:idx + bs]
44
+ images = [Image.open(data_dir + file_name).convert("RGB") for file_name in file_names]
45
+ with torch.no_grad():
46
+ pixel_values = feature_extractor(images, return_tensors='pt').pixel_values.to(device)
47
+ encodings = clip_encoder(pixel_values=pixel_values).last_hidden_state.cpu().numpy()
48
+ for cocoid, encoding in zip(cocoids, encodings):
49
+ h5py_file.create_dataset(str(cocoid), (50, 768), data=encoding)
50
+
51
+ data = load_data()
52
+
53
+ encode_split(data, 'train')
54
+ encode_split(data, 'val')
gpt2.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch OpenAI GPT-2 model."""
17
+
18
+ import math
19
+ import os
20
+ from dataclasses import dataclass
21
+ from typing import Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from packaging import version
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.models.gpt2.modeling_gpt2 import load_tf_weights_in_gpt2, GPT2LMHeadModel, GPT2MLP, GPT2Attention, GPT2Block, GPT2Model
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPastAndCrossAttentions,
34
+ CausalLMOutputWithCrossAttentions,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel, SequenceSummary
39
+ from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
40
+ from transformers.utils import (
41
+ ModelOutput,
42
+ logging,
43
+ )
44
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
45
+ from transformers.models.gpt2.configuration_gpt2 import GPT2Config
46
+
47
+
48
+ if version.parse(torch.__version__) >= version.parse("1.6"):
49
+ is_amp_available = True
50
+ from torch.cuda.amp import autocast
51
+ else:
52
+ is_amp_available = False
53
+
54
+
55
+ class ThisGPT2Config(GPT2Config):
56
+ model_type = "this_gpt2"
57
+
58
+ def __init__(
59
+ self,
60
+ cross_attention_reduce_factor = 1,
61
+ **kwargs,
62
+ ):
63
+ super().__init__(**kwargs)
64
+ self.cross_attention_reduce_factor = cross_attention_reduce_factor
65
+
66
+ class ThisGPT2Attention(GPT2Attention):
67
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
68
+ super().__init__(config, is_cross_attention, layer_idx)
69
+
70
+ #print("this gpt2")
71
+
72
+ #print("self.is_cross_attention = is_cross_attention", self.is_cross_attention, is_cross_attention)
73
+
74
+ self.cross_attention_reduce_factor = config.cross_attention_reduce_factor
75
+
76
+ if self.is_cross_attention:
77
+ self.c_attn = Conv1D(int(2 / self.cross_attention_reduce_factor * self.embed_dim),
78
+ self.embed_dim)
79
+ self.q_attn = Conv1D(int(self.embed_dim / self.cross_attention_reduce_factor), self.embed_dim)
80
+ self.c_proj = Conv1D(self.embed_dim, int(self.embed_dim / self.cross_attention_reduce_factor))
81
+ else:
82
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
83
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
84
+
85
+ def forward(
86
+ self,
87
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
88
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
89
+ attention_mask: Optional[torch.FloatTensor] = None,
90
+ head_mask: Optional[torch.FloatTensor] = None,
91
+ encoder_hidden_states: Optional[torch.Tensor] = None,
92
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
93
+ use_cache: Optional[bool] = False,
94
+ output_attentions: Optional[bool] = False,
95
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
96
+ if encoder_hidden_states is not None:
97
+ if not hasattr(self, "q_attn"):
98
+ raise ValueError(
99
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
100
+ "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
101
+ )
102
+ split_size = int(self.split_size / self.cross_attention_reduce_factor)
103
+ head_dim = int(self.head_dim / self.cross_attention_reduce_factor)
104
+
105
+ query = self.q_attn(hidden_states)
106
+ key, value = self.c_attn(encoder_hidden_states).split(split_size, dim=2)
107
+ attention_mask = encoder_attention_mask
108
+
109
+ query = self._split_heads(query, self.num_heads, head_dim)
110
+ key = self._split_heads(key, self.num_heads, head_dim)
111
+ value = self._split_heads(value, self.num_heads, head_dim)
112
+ else:
113
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
114
+
115
+ query = self._split_heads(query, self.num_heads, self.head_dim)
116
+ key = self._split_heads(key, self.num_heads, self.head_dim)
117
+ value = self._split_heads(value, self.num_heads, self.head_dim)
118
+
119
+ if layer_past is not None:
120
+ past_key, past_value = layer_past
121
+ key = torch.cat((past_key, key), dim=-2)
122
+ value = torch.cat((past_value, value), dim=-2)
123
+
124
+ if use_cache is True:
125
+ present = (key, value)
126
+ else:
127
+ present = None
128
+
129
+ if self.reorder_and_upcast_attn:
130
+ attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask, head_mask)
131
+ else:
132
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
133
+
134
+ attn_output = self._merge_heads(attn_output, self.num_heads, int(self.head_dim / self.cross_attention_reduce_factor))
135
+ attn_output = self.c_proj(attn_output)
136
+ attn_output = self.resid_dropout(attn_output)
137
+
138
+ outputs = (attn_output, present)
139
+ if output_attentions:
140
+ outputs += (attn_weights,)
141
+
142
+ return outputs # a, present, (attentions)
143
+
144
+
145
+ class ThisGPT2Block(GPT2Block):
146
+ def __init__(self, config, layer_idx=None):
147
+ super().__init__(config, layer_idx)
148
+ hidden_size = config.hidden_size
149
+
150
+ if config.add_cross_attention:
151
+ self.crossattention = ThisGPT2Attention(config, is_cross_attention=True, layer_idx=layer_idx)
152
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
153
+
154
+ class ThisGPT2Model(GPT2Model):
155
+
156
+ def __init__(self, config):
157
+ super().__init__(config)
158
+ self.h = nn.ModuleList([ThisGPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)])
159
+
160
+
161
+ class ThisGPT2LMHeadModel(GPT2LMHeadModel):
162
+ config_class = ThisGPT2Config
163
+
164
+ def __init__(self, config):
165
+ super().__init__(config)
166
+ self.transformer = ThisGPT2Model(config)
167
+
gptj.py ADDED
File without changes
opt.py ADDED
@@ -0,0 +1,696 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch OpenAI GPT-2 model."""
17
+
18
+ import math
19
+ import os
20
+ from dataclasses import dataclass
21
+ from typing import Optional, Tuple, Union
22
+ import random
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from packaging import version
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.models.gpt2.modeling_gpt2 import load_tf_weights_in_gpt2, GPT2LMHeadModel, GPT2MLP, GPT2Attention, GPT2Block, GPT2Model
31
+
32
+ from transformers.models.opt.modeling_opt import OPTForCausalLM, OPTAttention, OPTDecoderLayer, OPTModel, OPTDecoder
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPastAndCrossAttentions,
37
+ CausalLMOutputWithCrossAttentions,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+
42
+ from transformers.modeling_outputs import (
43
+ BaseModelOutputWithPast,
44
+ CausalLMOutputWithPast,
45
+ QuestionAnsweringModelOutput,
46
+ SequenceClassifierOutputWithPast,
47
+ )
48
+
49
+ from transformers.modeling_utils import PreTrainedModel, SequenceSummary
50
+ from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
51
+ from transformers.utils import (
52
+ ModelOutput,
53
+ logging,
54
+ )
55
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
56
+ from transformers.models.opt.configuration_opt import OPTConfig
57
+
58
+
59
+ if version.parse(torch.__version__) >= version.parse("1.6"):
60
+ is_amp_available = True
61
+ from torch.cuda.amp import autocast
62
+ else:
63
+ is_amp_available = False
64
+
65
+
66
+ class ThisOPTConfig(OPTConfig):
67
+ model_type = "this_opt"
68
+
69
+ def __init__(
70
+ self,
71
+ cross_attention_reduce_factor = 1,
72
+ **kwargs,
73
+ ):
74
+ super().__init__(**kwargs)
75
+ self.cross_attention_reduce_factor = cross_attention_reduce_factor
76
+
77
+
78
+ class ThisOPTAttention(OPTAttention):
79
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
80
+
81
+ def __init__(
82
+ self,
83
+ embed_dim,
84
+ num_heads,
85
+ dropout = 0.0,
86
+ is_decoder = False,
87
+ bias = True,
88
+ config=None,
89
+ is_cross_attention=False,
90
+ ):
91
+ super().__init__(embed_dim,num_heads, dropout,is_decoder,bias)
92
+ self.embed_dim = embed_dim
93
+ self.num_heads = num_heads
94
+ self.dropout = dropout
95
+ self.head_dim = embed_dim // num_heads
96
+
97
+ if (self.head_dim * num_heads) != self.embed_dim:
98
+ raise ValueError(
99
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
100
+ f" and `num_heads`: {num_heads})."
101
+ )
102
+ self.scaling = self.head_dim**-0.5
103
+ self.is_decoder = is_decoder
104
+
105
+ self.cross_attention_reduce_factor = config.cross_attention_reduce_factor
106
+ self.head_dim = int(self.head_dim / self.cross_attention_reduce_factor)
107
+
108
+
109
+ if is_cross_attention:
110
+ #print("self", int(embed_dim / self.cross_attention_reduce_factor))
111
+ self.k_proj = nn.Linear(768, int(embed_dim / self.cross_attention_reduce_factor), bias=bias)
112
+ #print("self.k_proj",self.k_proj)
113
+ self.v_proj = nn.Linear(768, int(embed_dim / self.cross_attention_reduce_factor), bias=bias)
114
+ self.q_proj = nn.Linear(embed_dim, int(embed_dim / self.cross_attention_reduce_factor), bias=bias)
115
+ self.out_proj = nn.Linear(int(embed_dim / self.cross_attention_reduce_factor),embed_dim, bias=bias)
116
+
117
+ self.embed_dim=int(embed_dim / self.cross_attention_reduce_factor)
118
+ else:
119
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
120
+ self.v_proj = nn.Linear(embed_dim, embed_dim , bias=bias)
121
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
122
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
123
+
124
+
125
+ def forward(
126
+ self,
127
+ hidden_states,
128
+ key_value_states = None,
129
+ past_key_value = None,
130
+ attention_mask = None,
131
+ layer_head_mask = None,
132
+ output_attentions= False,
133
+ ):
134
+ """Input shape: Batch x Time x Channel"""
135
+
136
+ # if key_value_states are provided this layer is used as a cross-attention layer
137
+ # for the decoder
138
+ is_cross_attention = key_value_states is not None
139
+
140
+ bsz, tgt_len, _ = hidden_states.size()
141
+
142
+ # get query proj
143
+ query_states = self.q_proj(hidden_states) * self.scaling
144
+ # get key, value proj
145
+ if is_cross_attention and past_key_value is not None:
146
+ # reuse k,v, cross_attentions
147
+ key_states = past_key_value[0]
148
+ value_states = past_key_value[1]
149
+ elif is_cross_attention:
150
+ # cross_attentions
151
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
152
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
153
+ elif past_key_value is not None:
154
+ # reuse k, v, self_attention
155
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
156
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
157
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
158
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
159
+ else:
160
+ # self_attention
161
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
162
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
163
+
164
+ if self.is_decoder:
165
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
166
+ # Further calls to cross_attention layer can then reuse all cross-attention
167
+ # key/value_states (first "if" case)
168
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
169
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
170
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
171
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
172
+ past_key_value = (key_states, value_states)
173
+
174
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
175
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
176
+ key_states = key_states.view(*proj_shape)
177
+ value_states = value_states.view(*proj_shape)
178
+
179
+ src_len = key_states.size(1)
180
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
181
+
182
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
183
+ raise ValueError(
184
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
185
+ f" {attn_weights.size()}"
186
+ )
187
+
188
+ if attention_mask is not None:
189
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
190
+ raise ValueError(
191
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
192
+ )
193
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
194
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
195
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
196
+
197
+ # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437
198
+ if attn_weights.dtype == torch.float16:
199
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16)
200
+ else:
201
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
202
+
203
+ if layer_head_mask is not None:
204
+ if layer_head_mask.size() != (self.num_heads,):
205
+ raise ValueError(
206
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
207
+ f" {layer_head_mask.size()}"
208
+ )
209
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
210
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
211
+
212
+ if output_attentions:
213
+ # this operation is a bit awkward, but it's required to
214
+ # make sure that attn_weights keeps its gradient.
215
+ # In order to do so, attn_weights have to be reshaped
216
+ # twice and have to be reused in the following
217
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
218
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
219
+ else:
220
+ attn_weights_reshaped = None
221
+
222
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
223
+
224
+ attn_output = torch.bmm(attn_probs, value_states)
225
+
226
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
227
+ raise ValueError(
228
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
229
+ f" {attn_output.size()}"
230
+ )
231
+
232
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
233
+ attn_output = attn_output.transpose(1, 2)
234
+
235
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
236
+ # partitioned aross GPUs when using tensor-parallelism.
237
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
238
+
239
+ attn_output = self.out_proj(attn_output)
240
+
241
+ return attn_output, attn_weights_reshaped, past_key_value
242
+
243
+
244
+ class ThisOPTDecoderLayer(OPTDecoderLayer):
245
+ def __init__(self, config):
246
+ super().__init__(config)
247
+
248
+ if config.add_cross_attention:
249
+ self.encoder_attn = ThisOPTAttention(
250
+ embed_dim=self.embed_dim,
251
+ num_heads=config.num_attention_heads,
252
+ dropout=config.attention_dropout,
253
+ is_decoder=True,
254
+ #bias=config.enable_bias,
255
+ config=config,
256
+ is_cross_attention=True
257
+ )
258
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim,elementwise_affine=config.layer_norm_elementwise_affine)
259
+
260
+
261
+ def forward(
262
+ self,
263
+ hidden_states,
264
+ attention_mask= None,
265
+ encoder_hidden_states = None,
266
+ encoder_attention_mask = None,
267
+ layer_head_mask = None,
268
+ cross_attn_head_mask = None,
269
+ output_attentions = False,
270
+ use_cache = False,
271
+ past_key_value = None,
272
+ ):
273
+ """
274
+ Args:
275
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
276
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
277
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
278
+ layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size
279
+ `(encoder_attention_heads,)`.
280
+ output_attentions (`bool`, *optional*):
281
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
282
+ returned tensors for more detail.
283
+ use_cache (`bool`, *optional*):
284
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
285
+ (see `past_key_values`).
286
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
287
+ """
288
+
289
+ residual = hidden_states
290
+
291
+ # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention
292
+ if self.do_layer_norm_before:
293
+ hidden_states = self.self_attn_layer_norm(hidden_states)
294
+
295
+ # Self Attention
296
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
297
+ hidden_states=hidden_states,
298
+ past_key_value=past_key_value,
299
+ attention_mask=attention_mask,
300
+ layer_head_mask=layer_head_mask,
301
+ output_attentions=output_attentions,
302
+ )
303
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
304
+ hidden_states = residual + hidden_states
305
+
306
+
307
+ # Cross-Attention Block
308
+ cross_attn_present_key_value = None
309
+ cross_attn_weights = None
310
+ if encoder_hidden_states is not None:
311
+ residual = hidden_states
312
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
313
+
314
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
315
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
316
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
317
+ hidden_states=hidden_states,
318
+ key_value_states=encoder_hidden_states,
319
+ attention_mask=encoder_attention_mask,
320
+ layer_head_mask=cross_attn_head_mask,
321
+ past_key_value=cross_attn_past_key_value,
322
+ output_attentions=output_attentions,
323
+ )
324
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
325
+ hidden_states = residual + hidden_states
326
+
327
+ # add cross-attn to positions 3,4 of present_key_value tuple
328
+ present_key_value = present_key_value + cross_attn_present_key_value
329
+
330
+
331
+
332
+ # 350m applies layer norm AFTER attention
333
+ if not self.do_layer_norm_before:
334
+ hidden_states = self.self_attn_layer_norm(hidden_states)
335
+
336
+ # Fully Connected
337
+ hidden_states_shape = hidden_states.shape
338
+ hidden_states = hidden_states.reshape(-1, hidden_states.size(-1))
339
+ residual = hidden_states
340
+
341
+ # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention
342
+ if self.do_layer_norm_before:
343
+ hidden_states = self.final_layer_norm(hidden_states)
344
+
345
+ hidden_states = self.fc1(hidden_states)
346
+ hidden_states = self.activation_fn(hidden_states)
347
+
348
+ hidden_states = self.fc2(hidden_states)
349
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
350
+
351
+ hidden_states = (residual + hidden_states).view(hidden_states_shape)
352
+
353
+ # 350m applies layer norm AFTER attention
354
+ if not self.do_layer_norm_before:
355
+ hidden_states = self.final_layer_norm(hidden_states)
356
+
357
+ outputs = (hidden_states,)
358
+
359
+ if output_attentions:
360
+ outputs += (self_attn_weights,)
361
+
362
+ if use_cache:
363
+ outputs += (present_key_value,)
364
+
365
+ return outputs
366
+
367
+ class ThisOPTDecoder(OPTDecoder):
368
+ def __init__(self, config):
369
+ super().__init__(config)
370
+ self.layers = nn.ModuleList([ThisOPTDecoderLayer(config) for _ in range(config.num_hidden_layers)])
371
+
372
+
373
+ def forward(
374
+ self,
375
+ input_ids = None,
376
+ attention_mask = None,
377
+ encoder_hidden_states=None,
378
+ encoder_attention_mask = None,
379
+ head_mask = None,
380
+ cross_attn_head_mask = None,
381
+ past_key_values = None,
382
+ inputs_embeds = None,
383
+ use_cache = None,
384
+ output_attentions = None,
385
+ output_hidden_states = None,
386
+ return_dict = None,
387
+ ):
388
+ r"""
389
+ Args:
390
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
391
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
392
+ provide it.
393
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
394
+ [`PreTrainedTokenizer.__call__`] for details.
395
+ [What are input IDs?](../glossary#input-ids)
396
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
397
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
398
+ - 1 for tokens that are **not masked**,
399
+ - 0 for tokens that are **masked**.
400
+ [What are attention masks?](../glossary#attention-mask)
401
+ head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*):
402
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
403
+ - 1 indicates the head is **not masked**,
404
+ - 0 indicates the head is **masked**.
405
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
406
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
407
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
408
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
409
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
410
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
411
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
412
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
413
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
414
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
415
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
416
+ than the model's internal embedding lookup matrix.
417
+ output_attentions (`bool`, *optional*):
418
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
419
+ returned tensors for more detail.
420
+ output_hidden_states (`bool`, *optional*):
421
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
422
+ for more detail.
423
+ return_dict (`bool`, *optional*):
424
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
425
+ """
426
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
427
+ output_hidden_states = (
428
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
429
+ )
430
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
431
+
432
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
433
+
434
+ # retrieve input_ids and inputs_embeds
435
+ if input_ids is not None and inputs_embeds is not None:
436
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
437
+ elif input_ids is not None:
438
+ input_shape = input_ids.size()
439
+ input_ids = input_ids.view(-1, input_shape[-1])
440
+ elif inputs_embeds is not None:
441
+ input_shape = inputs_embeds.size()[:-1]
442
+ else:
443
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
444
+
445
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
446
+
447
+ if inputs_embeds is None:
448
+ inputs_embeds = self.embed_tokens(input_ids)
449
+
450
+ # embed positions
451
+ if attention_mask is None:
452
+ attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device)
453
+ pos_embeds = self.embed_positions(attention_mask, past_key_values_length)
454
+
455
+ attention_mask = self._prepare_decoder_attention_mask(
456
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
457
+ )
458
+
459
+ if self.project_in is not None:
460
+ inputs_embeds = self.project_in(inputs_embeds)
461
+
462
+ hidden_states = inputs_embeds + pos_embeds
463
+
464
+ # decoder layers
465
+ all_hidden_states = () if output_hidden_states else None
466
+ all_self_attns = () if output_attentions else None
467
+ next_decoder_cache = () if use_cache else None
468
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
469
+
470
+
471
+ # check if head_mask has a correct number of layers specified if desired
472
+ for attn_mask, mask_name in zip([head_mask], ["head_mask"]):
473
+ if attn_mask is not None:
474
+ if attn_mask.size()[0] != (len(self.layers)):
475
+ raise ValueError(
476
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
477
+ f" {head_mask.size()[0]}."
478
+ )
479
+
480
+ for idx, decoder_layer in enumerate(self.layers):
481
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
482
+ if output_hidden_states:
483
+ all_hidden_states += (hidden_states,)
484
+
485
+ dropout_probability = random.uniform(0, 1)
486
+ if self.training and (dropout_probability < self.layerdrop):
487
+ continue
488
+
489
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
490
+
491
+ if self.gradient_checkpointing and self.training:
492
+
493
+ if use_cache:
494
+ logger.warning(
495
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
496
+ )
497
+ use_cache = False
498
+
499
+ def create_custom_forward(module):
500
+ def custom_forward(*inputs):
501
+ # None for past_key_value
502
+ return module(*inputs, output_attentions, None)
503
+
504
+ return custom_forward
505
+
506
+ layer_outputs = torch.utils.checkpoint.checkpoint(
507
+ create_custom_forward(decoder_layer),
508
+ hidden_states,
509
+ attention_mask,
510
+ head_mask[idx] if head_mask is not None else None,
511
+ None,
512
+ )
513
+ else:
514
+
515
+ layer_outputs = decoder_layer(
516
+ hidden_states,
517
+ encoder_attention_mask=encoder_attention_mask,
518
+ encoder_hidden_states=encoder_hidden_states,
519
+ cross_attn_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
520
+ attention_mask=attention_mask,
521
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
522
+ past_key_value=past_key_value,
523
+ output_attentions=output_attentions,
524
+ use_cache=use_cache,
525
+ )
526
+
527
+ hidden_states = layer_outputs[0]
528
+
529
+ if use_cache:
530
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
531
+
532
+ if output_attentions:
533
+ all_self_attns += (layer_outputs[1],)
534
+
535
+ if self.final_layer_norm is not None:
536
+ hidden_states = self.final_layer_norm(hidden_states)
537
+
538
+ if self.project_out is not None:
539
+ hidden_states = self.project_out(hidden_states)
540
+
541
+ # add hidden states from the last decoder layer
542
+ if output_hidden_states:
543
+ all_hidden_states += (hidden_states,)
544
+
545
+ if encoder_hidden_states is not None:
546
+ all_cross_attentions += (layer_outputs[2],)
547
+
548
+ next_cache = next_decoder_cache if use_cache else None
549
+ if not return_dict:
550
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
551
+ return BaseModelOutputWithPastAndCrossAttentions(
552
+ last_hidden_state=hidden_states,
553
+ past_key_values=next_cache,
554
+ hidden_states=all_hidden_states,
555
+ attentions=all_self_attns,
556
+ cross_attentions=all_cross_attentions,
557
+ )
558
+
559
+
560
+
561
+
562
+ class ThisOPTModel(OPTModel):
563
+
564
+ def __init__(self, config):
565
+ super().__init__(config)
566
+ self.decoder = ThisOPTDecoder(config)
567
+
568
+ def forward(
569
+ self,
570
+ input_ids = None,
571
+ attention_mask = None,
572
+ encoder_hidden_states=None,
573
+ encoder_attention_mask = None,
574
+ head_mask = None,
575
+ cross_attn_head_mask = None,
576
+ past_key_values = None,
577
+ inputs_embeds = None,
578
+ use_cache = None,
579
+ output_attentions = None,
580
+ output_hidden_states = None,
581
+ return_dict = None,
582
+ ):
583
+
584
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
585
+ output_hidden_states = (
586
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
587
+ )
588
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
589
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
590
+
591
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
592
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
593
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
594
+
595
+
596
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
597
+ decoder_outputs = self.decoder(
598
+ input_ids=input_ids,
599
+ attention_mask=attention_mask,
600
+ encoder_hidden_states=encoder_hidden_states,
601
+ encoder_attention_mask=encoder_attention_mask,
602
+ cross_attn_head_mask=(
603
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
604
+ ),
605
+ head_mask=head_mask,
606
+ past_key_values=past_key_values,
607
+ inputs_embeds=inputs_embeds,
608
+ use_cache=use_cache,
609
+ output_attentions=output_attentions,
610
+ output_hidden_states=output_hidden_states,
611
+ return_dict=return_dict,
612
+ )
613
+
614
+
615
+ if not return_dict:
616
+ return decoder_outputs
617
+
618
+ return BaseModelOutputWithPast(
619
+ last_hidden_state=decoder_outputs.last_hidden_state,
620
+ past_key_values=decoder_outputs.past_key_values,
621
+ hidden_states=decoder_outputs.hidden_states,
622
+ attentions=decoder_outputs.attentions,
623
+ )
624
+
625
+ class ThisOPTForCausalLM(OPTForCausalLM):
626
+ config_class = ThisOPTConfig
627
+
628
+ def __init__(self, config):
629
+ super().__init__(config)
630
+ self.model = ThisOPTModel(config)
631
+
632
+
633
+ def forward(
634
+ self,
635
+ input_ids = None,
636
+ attention_mask = None,
637
+ encoder_hidden_states=None,
638
+ encoder_attention_mask = None,
639
+ head_mask = None,
640
+ cross_attn_head_mask = None,
641
+ past_key_values = None,
642
+ inputs_embeds = None,
643
+ labels = None,
644
+ use_cache = None,
645
+ output_attentions = None,
646
+ output_hidden_states = None,
647
+ return_dict = None,
648
+ ) :
649
+
650
+
651
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
652
+ output_hidden_states = (
653
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
654
+ )
655
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
656
+
657
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
658
+ outputs = self.model.decoder(
659
+ input_ids=input_ids,
660
+ attention_mask=attention_mask,
661
+ encoder_hidden_states=encoder_hidden_states,
662
+ encoder_attention_mask = encoder_attention_mask,
663
+ cross_attn_head_mask = cross_attn_head_mask,
664
+ head_mask=head_mask,
665
+ past_key_values=past_key_values,
666
+ inputs_embeds=inputs_embeds,
667
+ use_cache=use_cache,
668
+ output_attentions=output_attentions,
669
+ output_hidden_states=output_hidden_states,
670
+ return_dict=return_dict,
671
+ )
672
+
673
+ logits = self.lm_head(outputs[0]).contiguous()
674
+
675
+ loss = None
676
+ if labels is not None:
677
+ # Shift so that tokens < n predict n
678
+ shift_logits = logits[..., :-1, :].contiguous()
679
+ shift_labels = labels[..., 1:].contiguous()
680
+ # Flatten the tokens
681
+ loss_fct = CrossEntropyLoss()
682
+ loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
683
+
684
+ if not return_dict:
685
+ output = (logits,) + outputs[1:]
686
+ return (loss,) + output if loss is not None else output
687
+
688
+ return CausalLMOutputWithCrossAttentions(
689
+ loss=loss,
690
+ logits=logits,
691
+ past_key_values=outputs.past_key_values,
692
+ hidden_states=outputs.hidden_states,
693
+ attentions=outputs.attentions,
694
+ cross_attentions=outputs.cross_attentions,
695
+ )
696
+
retrieve_caps.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from tqdm import tqdm
3
+ from transformers import AutoTokenizer
4
+ import clip
5
+ import torch
6
+ import faiss
7
+ import os
8
+ import numpy as np
9
+ from PIL import Image
10
+ from PIL import ImageFile
11
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
12
+
13
+ def load_coco_data(coco_data_path):
14
+ """We load in all images and only the train captions."""
15
+
16
+ annotations = json.load(open(coco_data_path))['images']
17
+ images = []
18
+ captions = []
19
+ for item in annotations:
20
+ if item['split'] == 'restval':
21
+ item['split'] = 'train'
22
+ if item['split'] == 'train':
23
+ for sentence in item['sentences']:
24
+ captions.append({'image_id': item['cocoid'], 'caption': ' '.join(sentence['tokens'])})
25
+ images.append({'image_id': item['cocoid'], 'file_name': item['filename'].split('_')[-1]})
26
+
27
+ return images, captions
28
+
29
+ def filter_captions(data):
30
+
31
+ decoder_name = 'gpt2'
32
+ tokenizer = AutoTokenizer.from_pretrained(decoder_name)
33
+ bs = 512
34
+
35
+ image_ids = [d['image_id'] for d in data]
36
+ caps = [d['caption'] for d in data]
37
+ encodings = []
38
+ for idx in range(0, len(data), bs):
39
+ encodings += tokenizer.batch_encode_plus(caps[idx:idx+bs], return_tensors='np')['input_ids'].tolist()
40
+
41
+ filtered_image_ids, filtered_captions = [], []
42
+
43
+ assert len(image_ids) == len(caps) and len(caps) == len(encodings)
44
+ for image_id, cap, encoding in zip(image_ids, caps, encodings):
45
+ if len(encoding) <= 25:
46
+ filtered_image_ids.append(image_id)
47
+ filtered_captions.append(cap)
48
+
49
+ return filtered_image_ids, filtered_captions
50
+
51
+ def encode_captions(captions, model, device):
52
+
53
+ bs = 256
54
+ encoded_captions = []
55
+
56
+ for idx in tqdm(range(0, len(captions), bs)):
57
+ with torch.no_grad():
58
+ input_ids = clip.tokenize(captions[idx:idx+bs]).to(device)
59
+ encoded_captions.append(model.encode_text(input_ids).cpu().numpy())
60
+
61
+ encoded_captions = np.concatenate(encoded_captions)
62
+
63
+ return encoded_captions
64
+
65
+ def encode_images(images, image_path, model, feature_extractor, device):
66
+
67
+ image_ids = [i['image_id'] for i in images]
68
+
69
+ bs = 64
70
+ image_features = []
71
+
72
+ for idx in tqdm(range(0, len(images), bs)):
73
+ image_input = [feature_extractor(Image.open(os.path.join(image_path, i['file_name'])))
74
+ for i in images[idx:idx+bs]]
75
+ with torch.no_grad():
76
+ image_features.append(model.encode_image(torch.tensor(np.stack(image_input)).to(device)).cpu().numpy())
77
+
78
+ image_features = np.concatenate(image_features)
79
+
80
+ return image_ids, image_features
81
+
82
+ def get_nns(captions, images, k=15):
83
+ xq = images.astype(np.float32)
84
+ xb = captions.astype(np.float32)
85
+ faiss.normalize_L2(xb)
86
+ index = faiss.IndexFlatIP(xb.shape[1])
87
+ index.add(xb)
88
+ faiss.normalize_L2(xq)
89
+ D, I = index.search(xq, k)
90
+
91
+ return index, I
92
+
93
+ def filter_nns(nns, xb_image_ids, captions, xq_image_ids):
94
+ """ We filter out nearest neighbors which are actual captions for the query image, keeping 7 neighbors per image."""
95
+ retrieved_captions = {}
96
+ for nns_list, image_id in zip(nns, xq_image_ids):
97
+ good_nns = []
98
+ for nn in zip(nns_list):
99
+ if xb_image_ids[nn] == image_id:
100
+ continue
101
+ good_nns.append(captions[nn])
102
+ if len(good_nns) == 7:
103
+ break
104
+ assert len(good_nns) == 7
105
+ retrieved_captions[image_id] = good_nns
106
+ return retrieved_captions
107
+
108
+ def main():
109
+
110
+ coco_data_path = 'data/dataset_coco.json' # path to Karpathy splits downloaded from Kaggle
111
+ image_path = 'data/images/'
112
+
113
+ print('Loading data')
114
+ images, captions = load_coco_data(coco_data_path)
115
+
116
+ device = "cuda" if torch.cuda.is_available() else "cpu"
117
+ clip_model, feature_extractor = clip.load("RN50x64", device=device)
118
+
119
+ print('Filtering captions')
120
+ xb_image_ids, captions = filter_captions(captions)
121
+
122
+ print('Encoding captions')
123
+ encoded_captions = encode_captions(captions, clip_model, device)
124
+
125
+ print('Encoding images')
126
+ xq_image_ids, encoded_images = encode_images(images, image_path, clip_model, feature_extractor, device)
127
+
128
+ print('Retrieving neighbors')
129
+ index, nns = get_nns(encoded_captions, encoded_images)
130
+ retrieved_caps = filter_nns(nns, xb_image_ids, captions, xq_image_ids)
131
+
132
+ print('Writing files')
133
+ faiss.write_index(index, "datastore/coco_index")
134
+ json.dump(captions, open('datastore/coco_index_captions.json', 'w'))
135
+
136
+ json.dump(retrieved_caps, open('data/retrieved_caps_resnet50x64.json', 'w'))
137
+
138
+ if __name__ == '__main__':
139
+ main()
140
+
141
+
142
+
143
+
144
+
145
+
retrieve_caps2.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import json
3
+ import os.path
4
+ import logging
5
+ import argparse
6
+ from tqdm import tqdm
7
+ import numpy as np
8
+ import torch
9
+ import torch.backends.cudnn as cudnn
10
+ import clip
11
+ from collections import defaultdict
12
+ from PIL import Image
13
+ import faiss
14
+ import os
15
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
+ cudnn.benchmark = True
17
+ torch.manual_seed(0)
18
+ if torch.cuda.is_available():
19
+ torch.cuda.manual_seed(0)
20
+
21
+ import gc
22
+
23
+
24
+
25
+ class ClipRetrieval():
26
+ def __init__(self, index_name):
27
+ self.datastore = faiss.read_index(index_name)
28
+ #self.datastore.nprobe=25
29
+
30
+ def get_nns(self, query_img, k=20):
31
+ #get k nearest image
32
+ D, I = self.datastore.search(query_img, k)
33
+ return D, I[:,:k]
34
+
35
+
36
+ class EvalDataset():
37
+
38
+ def __init__(self, dataset_splits, images_dir, images_names, clip_retrieval_processor, eval_split="val_images"):
39
+ super().__init__()
40
+
41
+ with open(dataset_splits) as f:
42
+ self.split = json.load(f)
43
+
44
+ self.split = self.split[eval_split]
45
+ self.images_dir= images_dir
46
+
47
+ with open(args.images_names) as f:
48
+ self.images_names = json.load(f)
49
+
50
+ self.clip_retrieval_processor = clip_retrieval_processor
51
+
52
+ def __getitem__(self, i):
53
+ coco_id = self.split[i]
54
+
55
+ image_filename= self.images_dir+self.images_names[coco_id]
56
+ img_open = Image.open(image_filename).copy()
57
+ img = np.array(img_open)
58
+ if len(img.shape) ==2 or img.shape[-1]!=3: #convert grey or CMYK to RGB
59
+ img_open = img_open.convert('RGB')
60
+ gc.collect()
61
+
62
+ print("img_open",np.array(img_open).shape)
63
+
64
+ #inputs_features_retrieval = self.clip_retrieval_processor(img_open).unsqueeze(0)
65
+ return self.clip_retrieval_processor(img_open).unsqueeze(0), coco_id
66
+
67
+ def __len__(self):
68
+ return len(self.split)
69
+
70
+
71
+ def evaluate(args):
72
+
73
+ #load data of the datastore (i.e., captions)
74
+ with open(args.index_captions) as f:
75
+ data_datastore = json.load(f)
76
+
77
+ datastore = ClipRetrieval(args.datastore_path)
78
+ datastore_name = args.datastore_path.split("/")[-1]
79
+
80
+ #load clip to encode the images that we want to retrieve captions for
81
+ clip_retrieval_model, clip_retrieval_feature_extractor = clip.load("RN50x64", device=device)
82
+ clip_retrieval_model.eval()
83
+ #data_loader to get images that we want to retrieve captions for
84
+ data_loader = torch.utils.data.DataLoader(
85
+ EvalDataset(
86
+ args.dataset_splits,
87
+ args.images_dir,
88
+ args.images_names,
89
+ clip_retrieval_feature_extractor,
90
+ args.split),
91
+ batch_size=1,
92
+ shuffle=True,
93
+ num_workers=1,
94
+ pin_memory=True
95
+ )
96
+
97
+ print("device",device)
98
+ nearest_caps={}
99
+ for data in tqdm(data_loader):
100
+
101
+ inputs_features_retrieval, coco_id = data
102
+ coco_id = coco_id[0]
103
+
104
+ #normalize images to retrieve (since datastore has also normalized captions)
105
+ inputs_features_retrieval = inputs_features_retrieval.to(device)
106
+ image_retrieval_features = clip_retrieval_model.encode_image(inputs_features_retrieval[0])
107
+ image_retrieval_features /= image_retrieval_features.norm(dim=-1, keepdim=True)
108
+ image_retrieval_features=image_retrieval_features.detach().cpu().numpy().astype(np.float32)
109
+
110
+ print("inputs_features_retrieval",inputs_features_retrieval.size())
111
+ print("image_retrieval_features",image_retrieval_features.shape)
112
+
113
+ D, nearest_ids=datastore.get_nns(image_retrieval_features, k=5)
114
+ print("D size", D.shape)
115
+ print("nea", nearest_ids.shape)
116
+ gc.collect()
117
+
118
+ #Since at inference batch is 1
119
+ D=D[0]
120
+ nearest_ids=nearest_ids[0]
121
+
122
+ list_of_similar_caps=defaultdict(list)
123
+ for index in range(len(nearest_ids)):
124
+ nearest_id = str(nearest_ids[index])
125
+ nearest_cap=data_datastore[nearest_id]
126
+
127
+ if len(nearest_cap.split()) > args.max_caption_len:
128
+ print("retrieve cap too big" )
129
+ continue
130
+
131
+ #distance=D[index]
132
+ #list_of_similar_caps[datastore_name].append((nearest_cap, str(distance)))
133
+ #list_of_similar_caps[datastore_name].append(nearest_cap)
134
+
135
+ #nearest_caps[str(coco_id)]=list_of_similar_caps
136
+
137
+
138
+ #save results
139
+ outputs_dir = os.path.join(args.output_path, "retrieved_caps")
140
+ if not os.path.exists(outputs_dir):
141
+ os.makedirs(outputs_dir)
142
+
143
+ data_name=dataset_splits.split("/")[-1]
144
+
145
+ name = "nearest_caps_"+data_name +"_w_"+datastore_name + "_"+ args.split
146
+ results_output_file_name = os.path.join(outputs_dir, name + ".json")
147
+ json.dump(nearest_caps, open(results_output_file_name, "w"))
148
+
149
+
150
+
151
+ def check_args(args):
152
+ parser = argparse.ArgumentParser()
153
+
154
+ #Info of the dataset to evaluate on (vizwiz, flick30k, msr-vtt)
155
+ parser.add_argument("--images_dir",help="Folder where the preprocessed image data is located", default="data/vizwiz/images")
156
+ parser.add_argument("--dataset_splits",help="File containing the dataset splits", default="data/vizwiz/dataset_splits.json")
157
+ parser.add_argument("--images_names",help="File containing the images names per id", default="data/vizwiz/images_names.json")
158
+ parser.add_argument("--split", default="val_images", choices=["val_images", "test_images"])
159
+ parser.add_argument("--max-caption-len", type=int, default=25)
160
+
161
+ #Which datastore to use (web, human)
162
+ parser.add_argument("--datastore_path", type=str, default="datastore2/vizwiz/vizwiz")
163
+ parser.add_argument("--index_captions",
164
+ help="File containing the captions of the datastore per id", default="datastore2/vizwiz/vizwiz.json")
165
+ parser.add_argument("--output-path",help="Folder where to store outputs", default="eval_vizwiz_with_datastore_from_vizwiz.json")
166
+
167
+ parsed_args = parser.parse_args(args)
168
+ return parsed_args
169
+
170
+
171
+ if __name__ == "__main__":
172
+ args = check_args(sys.argv[1:])
173
+ logging.basicConfig(
174
+ format='%(levelname)s: %(message)s', level=logging.INFO)
175
+
176
+ logging.info(args)
177
+ evaluate(args)
178
+
template.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Similar images show
2
+
3
+ ||
4
+
5
+ This image shows
utils.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.utils.data import Dataset
2
+ from PIL import Image
3
+ import torch
4
+ import json
5
+ import h5py
6
+ import bisect
7
+
8
+ CAPTION_LENGTH = 25
9
+ SIMPLE_PREFIX = "This image shows "
10
+
11
+ def prep_strings(text, tokenizer, template=None, retrieved_caps=None, k=None, is_test=False, max_length=None):
12
+
13
+ if is_test:
14
+ padding = False
15
+ truncation = False
16
+ else:
17
+ padding = True
18
+ truncation = True
19
+
20
+ if retrieved_caps is not None:
21
+ infix = '\n\n'.join(retrieved_caps[:k]) + '.'
22
+ prefix = template.replace('||', infix)
23
+ else:
24
+ prefix = SIMPLE_PREFIX
25
+
26
+ prefix_ids = tokenizer.encode(prefix)
27
+ len_prefix = len(prefix_ids)
28
+
29
+ text_ids = tokenizer.encode(text, add_special_tokens=False)
30
+ if truncation:
31
+ text_ids = text_ids[:CAPTION_LENGTH]
32
+ input_ids = prefix_ids + text_ids if not is_test else prefix_ids
33
+
34
+ # we ignore the prefix (minus one as the first subtoken in the prefix is not predicted)
35
+ label_ids = [-100] * (len_prefix - 1) + text_ids + [tokenizer.eos_token_id]
36
+ if padding:
37
+ input_ids += [tokenizer.pad_token_id] * (max_length - len(input_ids))
38
+ label_ids += [-100] * (max_length - len(label_ids))
39
+
40
+ if is_test:
41
+ return input_ids
42
+ else:
43
+ return input_ids, label_ids
44
+
45
+ def postprocess_preds(pred, tokenizer):
46
+ pred = pred.split(SIMPLE_PREFIX)[-1]
47
+ pred = pred.replace(tokenizer.pad_token, '')
48
+ if pred.startswith(tokenizer.bos_token):
49
+ pred = pred[len(tokenizer.bos_token):]
50
+ if pred.endswith(tokenizer.eos_token):
51
+ pred = pred[:-len(tokenizer.eos_token)]
52
+ return pred
53
+
54
+ class TrainDataset(Dataset):
55
+ def __init__(self, df, features_path, tokenizer, rag=False, template_path=None, k=None, max_caption_length=25):
56
+ self.df = df
57
+ self.tokenizer = tokenizer
58
+ self.features = h5py.File(features_path, 'r')
59
+
60
+ if rag:
61
+ self.template = open(template_path).read().strip() + ' '
62
+ self.max_target_length = (max_caption_length # target caption
63
+ + max_caption_length * k # retrieved captions
64
+ + len(tokenizer.encode(self.template)) # template
65
+ + len(tokenizer.encode('\n\n')) * (k-1) # separator between captions
66
+ )
67
+ assert k is not None
68
+ self.k = k
69
+ self.rag = rag
70
+
71
+ def __len__(self):
72
+ return len(self.df)
73
+
74
+ def __getitem__(self, idx):
75
+ text = self.df['text'][idx]
76
+ if self.rag:
77
+ caps = self.df['caps'][idx]
78
+ decoder_input_ids, labels = prep_strings(text, self.tokenizer, template=self.template,
79
+ retrieved_caps=caps, k=self.k, max_length=self.max_target_length)
80
+ else:
81
+ decoder_input_ids, labels = prep_strings(text, self.tokenizer, max_length=self.max_target_length)
82
+ # load precomputed features
83
+ encoder_outputs = self.features[self.df['cocoid'][idx]][()]
84
+ encoding = {"encoder_outputs": torch.tensor(encoder_outputs),
85
+ "decoder_input_ids": torch.tensor(decoder_input_ids),
86
+ "labels": torch.tensor(labels)}
87
+
88
+ return encoding
89
+
90
+
91
+ def load_data_for_training(annot_path, caps_path=None):
92
+ annotations = json.load(open(annot_path))['images']
93
+ if caps_path is not None:
94
+ retrieved_caps = json.load(open(caps_path))
95
+ data = {'train': [], 'val': []}
96
+
97
+ for item in annotations:
98
+ file_name = item['filename'].split('_')[-1]
99
+ if caps_path is not None:
100
+ caps = retrieved_caps[str(item['cocoid'])]
101
+ else:
102
+ caps = None
103
+ samples = []
104
+ for sentence in item['sentences']:
105
+ samples.append({'file_name': file_name, 'cocoid': str(item['cocoid']), 'caps': caps, 'text': ' '.join(sentence['tokens'])})
106
+ if item['split'] == 'train' or item['split'] == 'restval':
107
+ data['train'] += samples
108
+ elif item['split'] == 'val':
109
+ data['val'] += samples
110
+ return data
111
+
112
+ def load_data_for_inference(annot_path, caps_path=None):
113
+ annotations = json.load(open(annot_path))['images']
114
+ if caps_path is not None:
115
+ retrieved_caps = json.load(open(caps_path))
116
+ data = {'test': [], 'val': []}
117
+
118
+ for item in annotations:
119
+ file_name = item['filename'].split('_')[-1]
120
+ if caps_path is not None:
121
+ caps = retrieved_caps[str(item['cocoid'])]
122
+ else:
123
+ caps = None
124
+ image = {'file_name': file_name, 'caps': caps, 'image_id': str(item['cocoid'])}
125
+ if item['split'] == 'test':
126
+ data['test'].append(image)
127
+ elif item['split'] == 'val':
128
+ data['val'].append(image)
129
+
130
+ return data
131
+
utils_generate_retrieved_caps.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.utils.data import Dataset
2
+ from PIL import Image
3
+ import torch
4
+ import json
5
+ import h5py
6
+ import bisect
7
+
8
+ CAPTION_LENGTH = 25
9
+ SIMPLE_PREFIX = "This image shows "
10
+
11
+ def prep_strings(text, tokenizer, template=None, retrieved_caps=None, k=None, is_test=False, max_length=None):
12
+
13
+ if is_test:
14
+ padding = False
15
+ truncation = False
16
+ else:
17
+ padding = True
18
+ truncation = True
19
+
20
+ if retrieved_caps is not None:
21
+ infix = '\n\n'.join(retrieved_caps[:k]) + '.'
22
+ prefix = template.replace('||', infix)
23
+ else:
24
+ prefix = SIMPLE_PREFIX
25
+
26
+ prefix_ids = tokenizer.encode(prefix)
27
+ len_prefix = len(prefix_ids)
28
+
29
+ text_ids = tokenizer.encode(text, add_special_tokens=False)
30
+ if truncation:
31
+ text_ids = text_ids[:CAPTION_LENGTH]
32
+ input_ids = prefix_ids + text_ids if not is_test else prefix_ids
33
+
34
+ # we ignore the prefix (minus one as the first subtoken in the prefix is not predicted)
35
+ label_ids = [-100] * (len_prefix - 1) + text_ids + [tokenizer.eos_token_id]
36
+ if padding:
37
+ input_ids += [tokenizer.pad_token_id] * (max_length - len(input_ids))
38
+ label_ids += [-100] * (max_length - len(label_ids))
39
+
40
+ if is_test:
41
+ return input_ids
42
+ else:
43
+ return input_ids, label_ids
44
+
45
+ def postprocess_preds(pred, tokenizer):
46
+ pred = pred.split(SIMPLE_PREFIX)[-1]
47
+ pred = pred.replace(tokenizer.pad_token, '')
48
+ if pred.startswith(tokenizer.bos_token):
49
+ pred = pred[len(tokenizer.bos_token):]
50
+ if pred.endswith(tokenizer.eos_token):
51
+ pred = pred[:-len(tokenizer.eos_token)]
52
+ return pred
53
+
54
+ class TrainDataset(Dataset):
55
+ def __init__(self, df, features_path, tokenizer, rag=False, template_path=None, k=None, max_caption_length=25):
56
+ self.df = df
57
+ self.tokenizer = tokenizer
58
+ self.features = h5py.File(features_path, 'r')
59
+
60
+ if rag:
61
+ self.template = open(template_path).read().strip() + ' '
62
+ self.max_target_length = (max_caption_length # target caption
63
+ + max_caption_length * k # retrieved captions
64
+ + len(tokenizer.encode(self.template)) # template
65
+ + len(tokenizer.encode('\n\n')) * (k-1) # separator between captions
66
+ )
67
+ assert k is not None
68
+ self.k = k
69
+ self.rag = rag
70
+
71
+ def __len__(self):
72
+ return len(self.df)
73
+
74
+ def __getitem__(self, idx):
75
+ text = self.df['text'][idx]
76
+ if self.rag:
77
+ caps = self.df['caps'][idx]
78
+ decoder_input_ids, labels = prep_strings(text, self.tokenizer, template=self.template,
79
+ retrieved_caps=caps, k=self.k, max_length=self.max_target_length)
80
+ else:
81
+ decoder_input_ids, labels = prep_strings(text, self.tokenizer, max_length=self.max_target_length)
82
+ # load precomputed features
83
+ encoder_outputs = self.features[self.df['cocoid'][idx]][()]
84
+ encoding = {"encoder_outputs": torch.tensor(encoder_outputs),
85
+ "decoder_input_ids": torch.tensor(decoder_input_ids),
86
+ "labels": torch.tensor(labels)}
87
+
88
+ return encoding
89
+
90
+
91
+ def load_data_for_training(annot_path, caps_path=None):
92
+ annotations = json.load(open(annot_path))['images']
93
+ if caps_path is not None:
94
+ retrieved_caps = json.load(open(caps_path))
95
+ data = {'train': [], 'val': []}
96
+
97
+ for item in annotations:
98
+ file_name = item['filename'].split('_')[-1]
99
+ caps = retrieved_caps[str(item['cocoid'])]
100
+
101
+ samples = []
102
+ for sentence in item['sentences']:
103
+ print("how are the retrieved caps", caps + ' '.join(sentence['tokens']))
104
+
105
+ samples.append({'file_name': file_name, 'cocoid': str(item['cocoid']), 'caps': None, 'text': " ".join(caps) + ' '.join(sentence['tokens'])})
106
+ if item['split'] == 'train' or item['split'] == 'restval':
107
+ data['train'] += samples
108
+ elif item['split'] == 'val':
109
+ data['val'] += samples
110
+ return data
111
+
112
+
113
+
114
+
115
+
116
+ def load_data_for_inference(annot_path, caps_path=None):
117
+ annotations = json.load(open(annot_path))['images']
118
+ if caps_path is not None:
119
+ retrieved_caps = json.load(open(caps_path))
120
+ data = {'test': [], 'val': []}
121
+
122
+ for item in annotations:
123
+ file_name = item['filename'].split('_')[-1]
124
+ if caps_path is not None:
125
+ caps = retrieved_caps[str(item['cocoid'])]
126
+ else:
127
+ caps = None
128
+ image = {'file_name': file_name, 'caps': caps, 'image_id': str(item['cocoid'])}
129
+ if item['split'] == 'test':
130
+ data['test'].append(image)
131
+ elif item['split'] == 'val':
132
+ data['val'].append(image)
133
+
134
+ return data
135
+
vision_encoder_decoder.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Classes to support Vision-Encoder-Text-Decoder architectures"""
16
+ import timeit
17
+
18
+ from typing import Optional
19
+
20
+ import torch
21
+ from torch import nn
22
+ from torch.nn import CrossEntropyLoss
23
+ from transformers.configuration_utils import PretrainedConfig
24
+ from transformers.modeling_outputs import BaseModelOutput, Seq2SeqLMOutput
25
+ from transformers.modeling_utils import PreTrainedModel
26
+ #from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
27
+ from transformers.utils import logging
28
+ from transformers.models.auto.configuration_auto import AutoConfig
29
+ from transformers.models.auto.modeling_auto import AutoModel, AutoModelForCausalLM
30
+ from transformers.models.vision_encoder_decoder.configuration_vision_encoder_decoder import VisionEncoderDecoderConfig
31
+ import inspect
32
+
33
+ from .gpt2 import ThisGPT2LMHeadModel
34
+ from .gpt2 import ThisGPT2Config
35
+ from .xglm import ThisXGLMForCausalLM
36
+ from .xglm import ThisXGLMConfig
37
+ from .opt import ThisOPTForCausalLM
38
+ from .opt import ThisOPTConfig
39
+
40
+ # Copied from transformers.models.encoder_decoder.modeling_encoder_decoder.shift_tokens_right
41
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
42
+ """
43
+ Shift input ids one token to the right.
44
+ """
45
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
46
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
47
+ if decoder_start_token_id is None:
48
+ raise ValueError("Make sure to set the decoder_start_token_id attribute of the model's configuration.")
49
+ shifted_input_ids[:, 0] = decoder_start_token_id
50
+
51
+ if pad_token_id is None:
52
+ raise ValueError("Make sure to set the pad_token_id attribute of the model's configuration.")
53
+ # replace possible -100 values in labels by `pad_token_id`
54
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
55
+
56
+ return shifted_input_ids
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ _CONFIG_FOR_DOC = "SmallCapConfig"
62
+
63
+ VISION_ENCODER_DECODER_START_DOCSTRING = r"""
64
+ This class can be used to initialize an image-to-text-sequence model with any pretrained vision autoencoding model
65
+ as the encoder and any pretrained text autoregressive model as the decoder. The encoder is loaded via
66
+ [`~AutoModel.from_pretrained`] function and the decoder is loaded via [`~AutoModelForCausalLM.from_pretrained`]
67
+ function. Cross-attention layers are automatically added to the decoder and should be fine-tuned on a downstream
68
+ generative task, like image captioning.
69
+
70
+ The effectiveness of initializing sequence-to-sequence models with pretrained checkpoints for sequence generation
71
+ tasks was shown in [Leveraging Pre-trained Checkpoints for Sequence Generation
72
+ Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. Michael Matena, Yanqi
73
+ Zhou, Wei Li, Peter J. Liu.
74
+
75
+ Additionally, in [TrOCR: Transformer-based Optical Character Recognition with Pre-trained
76
+ Models](https://arxiv.org/abs/2109.10282) it is shown how leveraging large pretrained vision models for optical
77
+ character recognition (OCR) yields a significant performance improvement.
78
+
79
+ After such a Vision-Encoder-Text-Decoder model has been trained/fine-tuned, it can be saved/loaded just like any
80
+ other models (see the examples for more information).
81
+
82
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
83
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
84
+ etc.)
85
+
86
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
87
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
88
+ and behavior.
89
+
90
+ Parameters:
91
+ config ([`VisionEncoderDecoderConfig`]): Model configuration class with all the parameters of the model.
92
+ Initializing with a config file does not load the weights associated with the model, only the
93
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
94
+ """
95
+
96
+ VISION_ENCODER_DECODER_INPUTS_DOCSTRING = r"""
97
+ Args:
98
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
99
+ Pixel values. Pixel values can be obtained using a feature extractor (e.g. if you use ViT as the encoder,
100
+ you should use [`ViTFeatureExtractor`]). See [`ViTFeatureExtractor.__call__`] for details.
101
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
102
+ Indices of decoder input sequence tokens in the vocabulary.
103
+
104
+ Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
105
+ [`PreTrainedTokenizer.__call__`] for details.
106
+
107
+ [What are input IDs?](../glossary#input-ids)
108
+
109
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
110
+ `past_key_values`).
111
+
112
+ For training, `decoder_input_ids` are automatically created by the model by shifting the `labels` to the
113
+ right, replacing -100 by the `pad_token_id` and prepending them with the `decoder_start_token_id`.
114
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
115
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
116
+ be used by default.
117
+ encoder_outputs (`tuple(torch.FloatTensor)`, *optional*):
118
+ This tuple must consist of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
119
+ `last_hidden_state` (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) is a tensor
120
+ of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the
121
+ decoder.
122
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
123
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
124
+
125
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
126
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
127
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
128
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
129
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
130
+ representation. This is useful if you want more control over how to convert `decoder_input_ids` indices
131
+ into associated vectors than the model's internal embedding lookup matrix.
132
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
133
+ Labels for computing the masked language modeling loss for the decoder. Indices should be in `[-100, 0,
134
+ ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored
135
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
136
+ use_cache (`bool`, *optional*):
137
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
138
+ `past_key_values`).
139
+ output_attentions (`bool`, *optional*):
140
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
141
+ tensors for more detail.
142
+ output_hidden_states (`bool`, *optional*):
143
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
144
+ more detail.
145
+ return_dict (`bool`, *optional*):
146
+ If set to `True`, the model will return a [`~utils.Seq2SeqLMOutput`] instead of a plain tuple.
147
+ kwargs: (*optional*) Remaining dictionary of keyword arguments. Keyword arguments come in two flavors:
148
+
149
+ - Without a prefix which will be input as `**encoder_kwargs` for the encoder forward function.
150
+ - With a *decoder_* prefix which will be input as `**decoder_kwargs` for the decoder forward function.
151
+ """
152
+
153
+ class SmallCapConfig(VisionEncoderDecoderConfig):
154
+ model_type = "smallcap"
155
+
156
+ def __init__(
157
+ self,
158
+ **kwargs,
159
+ ):
160
+ super().__init__(**kwargs)
161
+
162
+
163
+ class SmallCap(PreTrainedModel):
164
+ r"""
165
+ [`VisionEncoderDecoderModel`] is a generic model class that will be instantiated as a transformer architecture with
166
+ one of the base vision model classes of the library as encoder and another one as decoder when created with the
167
+ :meth*~transformers.AutoModel.from_pretrained* class method for the encoder and
168
+ :meth*~transformers.AutoModelForCausalLM.from_pretrained* class method for the decoder.
169
+ """
170
+ config_class = SmallCapConfig
171
+ base_model_prefix = "smallcap"
172
+ main_input_name = "pixel_values"
173
+
174
+ def __init__(
175
+ self,
176
+ config: Optional[PretrainedConfig] = None,
177
+ encoder: Optional[PreTrainedModel] = None,
178
+ decoder: Optional[PreTrainedModel] = None,
179
+ ):
180
+ if config is None and (encoder is None or decoder is None):
181
+ raise ValueError("Either a configuration or an encoder and a decoder has to be provided.")
182
+ if config is None:
183
+ config = SmallCapConfig.from_encoder_decoder_configs(encoder.config, decoder.config)
184
+ else:
185
+ if not isinstance(config, self.config_class):
186
+ raise ValueError(f"Config: {config} has to be of type {self.config_class}")
187
+
188
+ if config.decoder.cross_attention_hidden_size is not None:
189
+ if config.decoder.cross_attention_hidden_size != config.encoder.hidden_size:
190
+ raise ValueError(
191
+ "If `cross_attention_hidden_size` is specified in the decoder's configuration, it has to be equal#"
192
+ f" to the encoder's `hidden_size`. Got {config.decoder.cross_attention_hidden_size} for"
193
+ f" `config.decoder.cross_attention_hidden_size` and {config.encoder.hidden_size} for"
194
+ " `config.encoder.hidden_size`."
195
+ )
196
+
197
+ # initialize with config
198
+ # make sure input & output embeddings is not tied
199
+ config.tie_word_embeddings = False
200
+ super().__init__(config)
201
+
202
+ if encoder is None:
203
+ encoder = AutoModel.from_config(config.encoder)
204
+
205
+ if decoder is None:
206
+ decoder = AutoModelForCausalLM.from_config(config.decoder)
207
+
208
+ self.encoder = encoder.vision_model
209
+ self.encoder.main_input_name = 'pixel_values'
210
+ self.decoder = decoder
211
+ # make sure that the individual model's config refers to the shared config
212
+ # so that the updates to the config will be synced
213
+ self.encoder.config = self.config.encoder
214
+ self.decoder.config = self.config.decoder
215
+
216
+ def get_encoder(self):
217
+ return self.encoder
218
+
219
+ def get_decoder(self):
220
+ return self.decoder
221
+
222
+ def get_output_embeddings(self):
223
+ return self.decoder.get_output_embeddings()
224
+
225
+ def set_output_embeddings(self, new_embeddings):
226
+ return self.decoder.set_output_embeddings(new_embeddings)
227
+
228
+ @classmethod
229
+ def from_pretrained(cls, *args, **kwargs):
230
+ # At the moment fast initialization is not supported for composite models
231
+ if kwargs.get("_fast_init", False):
232
+ logger.warning(
233
+ "Fast initialization is currently not supported for VisionEncoderDecoderModel. "
234
+ "Falling back to slow initialization..."
235
+ )
236
+ kwargs["_fast_init"] = False
237
+ return super().from_pretrained(*args, **kwargs)
238
+
239
+ @classmethod
240
+ def from_encoder_decoder_pretrained(
241
+ cls,
242
+ encoder_pretrained_model_name_or_path: str = None,
243
+ decoder_pretrained_model_name_or_path: str = None,
244
+ cross_attention_reduce_factor: int = None,
245
+ *model_args,
246
+ **kwargs
247
+ ) -> PreTrainedModel:
248
+ r"""
249
+ Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model
250
+ checkpoints.
251
+
252
+
253
+ The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
254
+ the model, you need to first set it back in training mode with `model.train()`.
255
+
256
+ Params:
257
+ encoder_pretrained_model_name_or_path (`str`, *optional*):
258
+ Information necessary to initiate the image encoder. Can be either:
259
+
260
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. An
261
+ example is `google/vit-base-patch16-224-in21k`.
262
+ - A path to a *directory* containing model weights saved using
263
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
264
+ - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
265
+ this case, `from_tf` should be set to `True` and a configuration object should be provided as
266
+ `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
267
+ PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
268
+
269
+ decoder_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
270
+ Information necessary to initiate the text decoder. Can be either:
271
+
272
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
273
+ Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
274
+ user or organization name, like `dbmdz/bert-base-german-cased`.
275
+ - A path to a *directory* containing model weights saved using
276
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
277
+ - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
278
+ this case, `from_tf` should be set to `True` and a configuration object should be provided as
279
+ `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
280
+ PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
281
+
282
+ model_args (remaining positional arguments, *optional*):
283
+ All remaning positional arguments will be passed to the underlying model's `__init__` method.
284
+
285
+ kwargs (remaining dictionary of keyword arguments, *optional*):
286
+ Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
287
+ `output_attentions=True`).
288
+
289
+ - To update the encoder configuration, use the prefix *encoder_* for each configuration parameter.
290
+ - To update the decoder configuration, use the prefix *decoder_* for each configuration parameter.
291
+ - To update the parent model configuration, do not use a prefix for each configuration parameter.
292
+
293
+ Behaves differently depending on whether a `config` is provided or automatically loaded.
294
+
295
+ Example:
296
+
297
+ ```python
298
+ >>> from transformers import VisionEncoderDecoderModel
299
+
300
+ >>> # initialize a vit-bert from a pretrained ViT and a pretrained BERT model. Note that the cross-attention layers will be randomly initialized
301
+ >>> model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(
302
+ ... "google/vit-base-patch16-224-in21k", "bert-base-uncased"
303
+ ... )
304
+ >>> # saving model after fine-tuning
305
+ >>> model.save_pretrained("./vit-bert")
306
+ >>> # load fine-tuned model
307
+ >>> model = VisionEncoderDecoderModel.from_pretrained("./vit-bert")
308
+ ```"""
309
+
310
+ kwargs_encoder = {
311
+ argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_")
312
+ }
313
+
314
+ kwargs_decoder = {
315
+ argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
316
+ }
317
+
318
+ # remove encoder, decoder kwargs from kwargs
319
+ for key in kwargs_encoder.keys():
320
+ del kwargs["encoder_" + key]
321
+ for key in kwargs_decoder.keys():
322
+ del kwargs["decoder_" + key]
323
+
324
+ # Load and initialize the encoder and decoder
325
+ # The distinction between encoder and decoder at the model level is made
326
+ # by the value of the flag `is_decoder` that we need to set correctly.
327
+ encoder = kwargs_encoder.pop("model", None)
328
+ if encoder is None:
329
+ if encoder_pretrained_model_name_or_path is None:
330
+ raise ValueError(
331
+ "If `encoder_model` is not defined as an argument, a `encoder_pretrained_model_name_or_path` has "
332
+ "to be defined."
333
+ )
334
+
335
+ if "config" not in kwargs_encoder:
336
+ encoder_config, kwargs_encoder = AutoConfig.from_pretrained(
337
+ encoder_pretrained_model_name_or_path, **kwargs_encoder, return_unused_kwargs=True
338
+ )
339
+
340
+ if encoder_config.is_decoder is True or encoder_config.add_cross_attention is True:
341
+ logger.info(
342
+ f"Initializing {encoder_pretrained_model_name_or_path} as a encoder model "
343
+ "from a decoder model. Cross-attention and casual mask are disabled."
344
+ )
345
+ encoder_config.is_decoder = False
346
+ encoder_config.add_cross_attention = False
347
+
348
+ kwargs_encoder["config"] = encoder_config
349
+
350
+ encoder = AutoModel.from_pretrained(encoder_pretrained_model_name_or_path, *model_args, **kwargs_encoder)
351
+
352
+ decoder = kwargs_decoder.pop("model", None)
353
+ if decoder is None:
354
+ if decoder_pretrained_model_name_or_path is None:
355
+ raise ValueError(
356
+ "If `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has "
357
+ "to be defined."
358
+ )
359
+
360
+ if "config" not in kwargs_decoder:
361
+ if "xglm" in decoder_pretrained_model_name_or_path:
362
+ decoder_config, kwargs_decoder = ThisXGLMConfig.from_pretrained(
363
+ decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True
364
+ )
365
+
366
+ elif "opt" in decoder_pretrained_model_name_or_path:
367
+ decoder_config, kwargs_decoder = ThisOPTConfig.from_pretrained(
368
+ decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True
369
+ )
370
+
371
+ else:
372
+ decoder_config, kwargs_decoder = ThisGPT2Config.from_pretrained(
373
+ decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True
374
+ )
375
+
376
+ if decoder_config.is_decoder is False or decoder_config.add_cross_attention is False:
377
+ logger.info(
378
+ f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model. Cross attention"
379
+ f" layers are added to {decoder_pretrained_model_name_or_path} and randomly initialized if"
380
+ f" {decoder_pretrained_model_name_or_path}'s architecture allows for cross attention layers."
381
+ )
382
+ decoder_config.is_decoder = True
383
+ decoder_config.add_cross_attention = True
384
+ decoder_config.encoder_hidden_size = encoder.config.vision_config.hidden_size
385
+ decoder_config.cross_attention_reduce_factor = cross_attention_reduce_factor
386
+ kwargs_decoder["config"] = decoder_config
387
+
388
+ if kwargs_decoder["config"].is_decoder is False or kwargs_decoder["config"].add_cross_attention is False:
389
+ logger.warning(
390
+ f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder. "
391
+ f"In order to initialize {decoder_pretrained_model_name_or_path} as a decoder, "
392
+ "make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` "
393
+ "passed to `.from_encoder_decoder_pretrained(...)` are set to `True` or do not pass a "
394
+ "`decoder_config` to `.from_encoder_decoder_pretrained(...)`"
395
+ )
396
+
397
+ #decoder = AutoModelForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder)
398
+ if "xglm" in decoder_pretrained_model_name_or_path:
399
+ decoder = ThisXGLMForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder)
400
+
401
+ elif "opt" in decoder_pretrained_model_name_or_path:
402
+ decoder = ThisOPTForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder)
403
+ else:
404
+ decoder = ThisGPT2LMHeadModel.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder)
405
+
406
+ # instantiate config with corresponding kwargs
407
+ config = SmallCapConfig.from_encoder_decoder_configs(encoder.config, decoder.config, **kwargs)
408
+
409
+ # make sure input & output embeddings is not tied
410
+ config.tie_word_embeddings = False
411
+ return cls(encoder=encoder, decoder=decoder, config=config)
412
+
413
+ def forward(
414
+ self,
415
+ pixel_values=None,
416
+ decoder_input_ids=None,
417
+ decoder_attention_mask=None,
418
+ encoder_outputs=None,
419
+ past_key_values=None,
420
+ decoder_inputs_embeds=None,
421
+ labels=None,
422
+ use_cache=None,
423
+ output_attentions=None,
424
+ output_hidden_states=None,
425
+ return_dict=None,
426
+ **kwargs,
427
+ ):
428
+ r"""
429
+ Returns:
430
+
431
+ Examples:
432
+
433
+ ```python
434
+ >>> from transformers import TrOCRProcessor, VisionEncoderDecoderModel
435
+ >>> import requests
436
+ >>> from PIL import Image
437
+ >>> import torch
438
+
439
+ >>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
440
+ >>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
441
+
442
+ >>> # load image from the IAM dataset
443
+ >>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
444
+ >>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
445
+
446
+ >>> # training
447
+ >>> model.config.decoder_start_token_id = processor.tokenizer.cls_token_id
448
+ >>> model.config.pad_token_id = processor.tokenizer.pad_token_id
449
+ >>> model.config.vocab_size = model.config.decoder.vocab_size
450
+
451
+ >>> pixel_values = processor(image, return_tensors="pt").pixel_values
452
+ >>> text = "hello world"
453
+ >>> labels = processor.tokenizer(text, return_tensors="pt").input_ids
454
+ >>> outputs = model(pixel_values=pixel_values, labels=labels)
455
+ >>> loss = outputs.loss
456
+
457
+ >>> # inference (generation)
458
+ >>> generated_ids = model.generate(pixel_values)
459
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
460
+ ```"""
461
+
462
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
463
+
464
+ kwargs_encoder = {argument: value for argument, value in kwargs.items() if not argument.startswith("decoder_")}
465
+
466
+ kwargs_decoder = {
467
+ argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
468
+ }
469
+ if encoder_outputs is None:
470
+ if pixel_values is None:
471
+ raise ValueError("You have to specify pixel_values")
472
+
473
+ encoder_outputs = self.encoder(
474
+ pixel_values=pixel_values,
475
+ output_attentions=output_attentions,
476
+ output_hidden_states=output_hidden_states,
477
+ return_dict=return_dict,
478
+ **kwargs_encoder,
479
+ )
480
+ elif isinstance(encoder_outputs, tuple):
481
+ encoder_outputs = BaseModelOutput(*encoder_outputs)
482
+ else:
483
+ encoder_outputs = BaseModelOutput(encoder_outputs, None)
484
+
485
+ encoder_hidden_states = encoder_outputs[0]
486
+
487
+ # else:
488
+ encoder_attention_mask = None
489
+ if (labels is not None) and (decoder_input_ids is None and decoder_inputs_embeds is None):
490
+ decoder_input_ids = shift_tokens_right(
491
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
492
+ )
493
+
494
+ # Decode
495
+ decoder_outputs = self.decoder(
496
+ input_ids=decoder_input_ids,
497
+ attention_mask=decoder_attention_mask,
498
+ encoder_hidden_states=encoder_hidden_states,
499
+ encoder_attention_mask=encoder_attention_mask,
500
+ inputs_embeds=decoder_inputs_embeds,
501
+ output_attentions=output_attentions,
502
+ output_hidden_states=output_hidden_states,
503
+ use_cache=use_cache,
504
+ past_key_values=past_key_values,
505
+ return_dict=return_dict,
506
+ **kwargs_decoder,
507
+ )
508
+
509
+ # Compute loss independent from decoder (as some shift the logits inside them)
510
+ loss = None
511
+ if labels is not None:
512
+ logits = decoder_outputs.logits if return_dict else decoder_outputs[0]
513
+ loss_fct = CrossEntropyLoss()
514
+ loss = loss_fct(logits.reshape(-1, self.decoder.config.vocab_size), labels.view(-1))
515
+
516
+ if not return_dict:
517
+ if loss is not None:
518
+ return (loss,) + decoder_outputs + encoder_outputs
519
+ else:
520
+ return decoder_outputs + encoder_outputs
521
+
522
+ return Seq2SeqLMOutput(
523
+ loss=loss,
524
+ logits=decoder_outputs.logits,
525
+ past_key_values=decoder_outputs.past_key_values,
526
+ decoder_hidden_states=decoder_outputs.hidden_states,
527
+ decoder_attentions=decoder_outputs.attentions,
528
+ cross_attentions=decoder_outputs.cross_attentions,
529
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
530
+ encoder_hidden_states=encoder_outputs.hidden_states,
531
+ encoder_attentions=encoder_outputs.attentions,
532
+ )
533
+
534
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
535
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
536
+
537
+ def prepare_inputs_for_generation(
538
+ self, input_ids, past=None, attention_mask=None, use_cache=None, encoder_outputs=None, **kwargs
539
+ ):
540
+ decoder_inputs = self.decoder.prepare_inputs_for_generation(input_ids, past=past)
541
+ decoder_attention_mask = decoder_inputs["attention_mask"] if "attention_mask" in decoder_inputs else None
542
+ input_dict = {
543
+ "attention_mask": attention_mask,
544
+ "decoder_attention_mask": decoder_attention_mask,
545
+ "decoder_input_ids": decoder_inputs["input_ids"],
546
+ "encoder_outputs": encoder_outputs,
547
+ "past_key_values": decoder_inputs["past_key_values"],
548
+ "use_cache": use_cache,
549
+ }
550
+ return input_dict
551
+
552
+ def resize_token_embeddings(self, *args, **kwargs):
553
+ raise NotImplementedError(
554
+ "Resizing the embedding layers via the VisionEncoderDecoderModel directly is not supported.Please use the"
555
+ " respective methods of the wrapped decoder object (model.decoder.resize_token_embeddings(...))"
556
+ )
557
+
558
+ def _reorder_cache(self, past, beam_idx):
559
+ # apply decoder cache reordering here
560
+ return self.decoder._reorder_cache(past, beam_idx)
xglm.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch OpenAI GPT-2 model."""
17
+
18
+ import math
19
+ import os
20
+ from dataclasses import dataclass
21
+ from typing import Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from packaging import version
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.models.gpt2.modeling_gpt2 import load_tf_weights_in_gpt2, GPT2LMHeadModel, GPT2MLP, GPT2Attention, GPT2Block, GPT2Model
30
+
31
+ from transformers.models.xglm.modeling_xglm import XGLMForCausalLM, XGLMAttention, XGLMDecoderLayer, XGLMModel
32
+
33
+ from transformers.activations import ACT2FN
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPastAndCrossAttentions,
36
+ CausalLMOutputWithCrossAttentions,
37
+ SequenceClassifierOutputWithPast,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel, SequenceSummary
41
+ from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
42
+ from transformers.utils import (
43
+ ModelOutput,
44
+ logging,
45
+ )
46
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
47
+ from transformers.models.xglm.configuration_xglm import XGLMConfig
48
+
49
+
50
+ if version.parse(torch.__version__) >= version.parse("1.6"):
51
+ is_amp_available = True
52
+ from torch.cuda.amp import autocast
53
+ else:
54
+ is_amp_available = False
55
+
56
+
57
+ class ThisXGLMConfig(XGLMConfig):
58
+ model_type = "this_xglm"
59
+
60
+ def __init__(
61
+ self,
62
+ cross_attention_reduce_factor = 1,
63
+ **kwargs,
64
+ ):
65
+ super().__init__(**kwargs)
66
+ self.cross_attention_reduce_factor = cross_attention_reduce_factor
67
+
68
+
69
+ class ThisXGLMAttention(XGLMAttention):
70
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
71
+
72
+ def __init__(
73
+ self,
74
+ embed_dim,
75
+ num_heads,
76
+ dropout= 0.0,
77
+ is_decoder= False,
78
+ bias= True,
79
+ config=None,
80
+ is_cross_attention=False,
81
+ ):
82
+ super().__init__(embed_dim,num_heads, dropout,is_decoder,bias)
83
+ self.embed_dim = embed_dim
84
+ self.num_heads = num_heads
85
+ self.dropout = dropout
86
+ self.head_dim = embed_dim // num_heads
87
+
88
+ if (self.head_dim * num_heads) != self.embed_dim:
89
+ raise ValueError(
90
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
91
+ f" and `num_heads`: {num_heads})."
92
+ )
93
+ self.scaling = self.head_dim**-0.5
94
+ self.is_decoder = is_decoder
95
+
96
+ self.cross_attention_reduce_factor = config.cross_attention_reduce_factor
97
+ self.head_dim = int(self.head_dim / self.cross_attention_reduce_factor)
98
+
99
+
100
+ if is_cross_attention:
101
+ #print("self", int(embed_dim / self.cross_attention_reduce_factor))
102
+ self.k_proj = nn.Linear(768, int(embed_dim / self.cross_attention_reduce_factor), bias=bias)
103
+ #print("self.k_proj",self.k_proj)
104
+ self.v_proj = nn.Linear(768, int(embed_dim / self.cross_attention_reduce_factor), bias=bias)
105
+ self.q_proj = nn.Linear(embed_dim, int(embed_dim / self.cross_attention_reduce_factor), bias=bias)
106
+ self.out_proj = nn.Linear(int(embed_dim / self.cross_attention_reduce_factor),embed_dim, bias=bias)
107
+
108
+ self.embed_dim=int(embed_dim / self.cross_attention_reduce_factor)
109
+ else:
110
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
111
+ self.v_proj = nn.Linear(embed_dim, embed_dim , bias=bias)
112
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
113
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
114
+
115
+ def forward(
116
+ self,
117
+ hidden_states,
118
+ key_value_states,
119
+ past_key_value,
120
+ attention_mask,
121
+ layer_head_mask,
122
+ output_attentions,
123
+ ):
124
+ """Input shape: Batch x Time x Channel"""
125
+
126
+ # if key_value_states are provided this layer is used as a cross-attention layer
127
+ # for the decoder
128
+ is_cross_attention = key_value_states is not None
129
+
130
+ bsz, tgt_len, _ = hidden_states.size()
131
+
132
+ # get query proj
133
+ query_states = self.q_proj(hidden_states) * self.scaling
134
+ # get key, value proj
135
+ if is_cross_attention and past_key_value is not None:
136
+ # reuse k,v, cross_attentions
137
+ key_states = past_key_value[0]
138
+ value_states = past_key_value[1]
139
+ elif is_cross_attention:
140
+ # cross_attentions
141
+ #print("key_value_states",key_value_states.size())
142
+ #print("self.k_proj(key_value_states)",self.k_proj(key_value_states).size())
143
+
144
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
145
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
146
+ elif past_key_value is not None:
147
+ # reuse k, v, self_attention
148
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
149
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
150
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
151
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
152
+ else:
153
+ # self_attention
154
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
155
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
156
+
157
+ if self.is_decoder:
158
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
159
+ # Further calls to cross_attention layer can then reuse all cross-attention
160
+ # key/value_states (first "if" case)
161
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
162
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
163
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
164
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
165
+ past_key_value = (key_states, value_states)
166
+
167
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
168
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
169
+ key_states = key_states.view(*proj_shape)
170
+ value_states = value_states.view(*proj_shape)
171
+
172
+ src_len = key_states.size(1)
173
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
174
+
175
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
176
+ raise ValueError(
177
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
178
+ f" {attn_weights.size()}"
179
+ )
180
+
181
+ if attention_mask is not None:
182
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
183
+ raise ValueError(
184
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
185
+ )
186
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
187
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
188
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
189
+
190
+ # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437
191
+ if attn_weights.dtype == torch.float16:
192
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16)
193
+ else:
194
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
195
+
196
+ if layer_head_mask is not None:
197
+ if layer_head_mask.size() != (self.num_heads,):
198
+ raise ValueError(
199
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
200
+ f" {layer_head_mask.size()}"
201
+ )
202
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
203
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
204
+
205
+ if output_attentions:
206
+ # this operation is a bit awkward, but it's required to
207
+ # make sure that attn_weights keeps its gradient.
208
+ # In order to do so, attn_weights have to be reshaped
209
+ # twice and have to be reused in the following
210
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
211
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
212
+ else:
213
+ attn_weights_reshaped = None
214
+
215
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
216
+
217
+ attn_output = torch.bmm(attn_probs, value_states)
218
+
219
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
220
+ raise ValueError(
221
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
222
+ f" {attn_output.size()}"
223
+ )
224
+
225
+ #print("boraaa self.head_dim",self.head_dim)
226
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
227
+
228
+ #print("attn_output bef",attn_output.size())
229
+ attn_output = attn_output.transpose(1, 2)
230
+ #print("attn_output",attn_output.size())
231
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
232
+ # partitioned aross GPUs when using tensor-parallelism.
233
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
234
+
235
+ #print("attn_output",attn_output.size())
236
+ attn_output = self.out_proj(attn_output)
237
+
238
+ return attn_output, attn_weights_reshaped, past_key_value
239
+
240
+
241
+ class ThisXGLMDecoderLayer(XGLMDecoderLayer):
242
+ def __init__(self, config):
243
+ super().__init__(config)
244
+
245
+ if config.add_cross_attention:
246
+ print("add cross")
247
+ self.encoder_attn = ThisXGLMAttention(
248
+ embed_dim=self.embed_dim,
249
+ num_heads=config.attention_heads,
250
+ dropout=config.attention_dropout,
251
+ is_decoder=True,
252
+ config=config,
253
+ is_cross_attention=True
254
+ )
255
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
256
+
257
+ class ThisXGLMModel(XGLMModel):
258
+
259
+ def __init__(self, config):
260
+ super().__init__(config)
261
+ self.layers = nn.ModuleList([ThisXGLMDecoderLayer(config) for _ in range(config.num_layers)])
262
+
263
+ class ThisXGLMForCausalLM(XGLMForCausalLM):
264
+ config_class = ThisXGLMConfig
265
+
266
+ def __init__(self, config):
267
+ super().__init__(config)
268
+ self.model = ThisXGLMModel(config)
269
+