| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| """PyTorch BERT model. """ |
|
|
|
|
| from typing import Optional, Tuple, Union |
|
|
|
|
| import torch |
| import torch.nn as nn |
| import torch.utils.checkpoint |
| from torch.nn import CrossEntropyLoss, Linear |
| import math |
|
|
| from transformers.activations import ACT2FN |
| from transformers.modeling_outputs import ( |
| BaseModelOutputWithPoolingAndCrossAttentions, |
| BaseModelOutputWithCrossAttentions, |
| MaskedLMOutput, |
| ) |
| from transformers import BertPreTrainedModel |
| from transformers.modeling_utils import ( |
| apply_chunking_to_forward, |
| find_pruneable_heads_and_indices, |
| prune_linear_layer, |
| ) |
|
|
|
|
| class BertPooler(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.dense = nn.Linear(config.hidden_size, config.hidden_size) |
| self.activation = nn.Tanh() |
|
|
| def forward(self, hidden_states): |
| |
| |
| first_token_tensor = hidden_states[:, 0] |
| pooled_output = self.dense(first_token_tensor) |
| pooled_output = self.activation(pooled_output) |
| return pooled_output |
|
|
|
|
| class BertPredictionHeadTransform(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.dense = nn.Linear(config.hidden_size, config.hidden_size) |
| if isinstance(config.hidden_act, str): |
| self.transform_act_fn = ACT2FN[config.hidden_act] |
| else: |
| self.transform_act_fn = config.hidden_act |
| self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
|
|
| def forward(self, hidden_states): |
| hidden_states = self.dense(hidden_states) |
| hidden_states = self.transform_act_fn(hidden_states) |
| hidden_states = self.LayerNorm(hidden_states) |
| return hidden_states |
|
|
|
|
| class BertLMPredictionHead(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.transform = BertPredictionHeadTransform(config) |
|
|
| |
| |
| self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) |
|
|
| self.bias = nn.Parameter(torch.zeros(config.vocab_size)) |
|
|
| |
| self.decoder.bias = self.bias |
|
|
| def forward(self, hidden_states, embedings=None, bias=None): |
| hidden_states = self.transform(hidden_states) |
| if bias is not None and embedings is not None: |
| hidden_states = ( |
| torch.matmul(hidden_states, embedings.t().to(hidden_states)) + bias |
| ) |
| else: |
| hidden_states = self.decoder(hidden_states) |
| return hidden_states |
|
|
|
|
| class BertOnlyMLMHead(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.predictions = BertLMPredictionHead(config) |
|
|
| def forward(self, sequence_output, embedings=None, bias=None): |
| prediction_scores = self.predictions(sequence_output, embedings, bias) |
| return prediction_scores |
|
|
|
|
| class BertSelfAttention(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| if config.hidden_size % config.num_attention_heads != 0 and not hasattr( |
| config, "embedding_size" |
| ): |
| raise ValueError( |
| "The hidden size (%d) is not a multiple of the number of attention " |
| "heads (%d)" % (config.hidden_size, config.num_attention_heads) |
| ) |
|
|
| self.num_attention_heads = config.num_attention_heads |
| self.attention_head_size = int(config.hidden_size / config.num_attention_heads) |
| self.all_head_size = self.num_attention_heads * self.attention_head_size |
|
|
| self.query = nn.Linear(config.hidden_size, self.all_head_size) |
| self.key = nn.Linear(config.hidden_size, self.all_head_size) |
| self.value = nn.Linear(config.hidden_size, self.all_head_size) |
|
|
| self.dropout = nn.Dropout(config.attention_probs_dropout_prob) |
|
|
| def transpose_for_scores(self, x): |
| new_x_shape = x.size()[:-1] + ( |
| self.num_attention_heads, |
| self.attention_head_size, |
| ) |
| x = x.view(*new_x_shape) |
| return x.permute(0, 2, 1, 3) |
|
|
| def forward( |
| self, |
| hidden_states, |
| attention_mask=None, |
| head_mask=None, |
| encoder_hidden_states=None, |
| encoder_attention_mask=None, |
| output_attentions=False, |
| ): |
| mixed_query_layer = self.query(hidden_states) |
|
|
| |
| |
| |
| if encoder_hidden_states is not None: |
| mixed_key_layer = self.key(encoder_hidden_states) |
| mixed_value_layer = self.value(encoder_hidden_states) |
| attention_mask = encoder_attention_mask |
| else: |
| mixed_key_layer = self.key(hidden_states) |
| mixed_value_layer = self.value(hidden_states) |
|
|
| query_layer = self.transpose_for_scores(mixed_query_layer) |
| key_layer = self.transpose_for_scores(mixed_key_layer) |
| value_layer = self.transpose_for_scores(mixed_value_layer) |
|
|
| |
| attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) |
| attention_scores = attention_scores / math.sqrt(self.attention_head_size) |
| if attention_mask is not None: |
| |
| attention_scores = attention_scores + attention_mask |
|
|
| |
| attention_probs = nn.Softmax(dim=-1)(attention_scores) |
|
|
| |
| |
| attention_probs = self.dropout(attention_probs) |
|
|
| |
| if head_mask is not None: |
| attention_probs = attention_probs * head_mask |
|
|
| context_layer = torch.matmul(attention_probs, value_layer) |
|
|
| context_layer = context_layer.permute(0, 2, 1, 3).contiguous() |
| new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) |
| context_layer = context_layer.view(*new_context_layer_shape) |
|
|
| outputs = ( |
| (context_layer, attention_probs) if output_attentions else (context_layer,) |
| ) |
| return outputs |
|
|
|
|
| class BertIntermediate(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.dense = nn.Linear(config.hidden_size, config.intermediate_size) |
| if isinstance(config.hidden_act, str): |
| self.intermediate_act_fn = ACT2FN[config.hidden_act] |
| else: |
| self.intermediate_act_fn = config.hidden_act |
|
|
| def forward(self, hidden_states): |
| hidden_states = self.dense(hidden_states) |
| hidden_states = self.intermediate_act_fn(hidden_states) |
| return hidden_states |
|
|
|
|
| class BertEmbeddings(nn.Module): |
| """Construct the embeddings from word, position and token_type embeddings.""" |
|
|
| def __init__(self, config, features_dim): |
| super().__init__() |
| self.word_embeddings = nn.Embedding( |
| config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id |
| ) |
| self.position_embeddings = nn.Embedding( |
| config.max_position_embeddings, config.hidden_size |
| ) |
| self.token_type_embeddings = nn.Embedding( |
| config.type_vocab_size, config.hidden_size |
| ) |
|
|
| |
| |
| self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
| self.dropout = nn.Dropout(config.hidden_dropout_prob) |
|
|
| |
| self.register_buffer( |
| "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) |
| ) |
|
|
| self.features_dim = features_dim |
| if self.features_dim: |
| self.linear_video = Linear(features_dim, config.hidden_size) |
|
|
| def get_video_embedding(self, video=None): |
| video = self.linear_video(video) |
| return video |
|
|
| def forward( |
| self, |
| input_ids=None, |
| token_type_ids=None, |
| position_ids=None, |
| inputs_embeds=None, |
| video=None, |
| ): |
| if input_ids is not None: |
| input_shape = input_ids.size() |
| else: |
| input_shape = inputs_embeds.size()[:-1] |
|
|
| if inputs_embeds is None: |
| inputs_embeds = self.word_embeddings(input_ids) |
| if self.features_dim and video is not None: |
| video = self.get_video_embedding(video) |
| inputs_embeds = torch.cat([video, inputs_embeds], 1) |
| input_shape = inputs_embeds[:, :, 0].shape |
|
|
| seq_length = input_shape[1] |
|
|
| if position_ids is None: |
| position_ids = self.position_ids[:, :seq_length] |
|
|
| if token_type_ids is None: |
| token_type_ids = torch.zeros( |
| input_shape, dtype=torch.long, device=self.position_ids.device |
| ) |
|
|
| position_embeddings = self.position_embeddings(position_ids) |
| token_type_embeddings = self.token_type_embeddings(token_type_ids) |
|
|
| embeddings = inputs_embeds + position_embeddings + token_type_embeddings |
| embeddings = self.LayerNorm(embeddings) |
| embeddings = self.dropout(embeddings) |
| return embeddings |
|
|
|
|
| class BertSelfOutput(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.dense = nn.Linear(config.hidden_size, config.hidden_size) |
| self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
| self.dropout = nn.Dropout(config.hidden_dropout_prob) |
|
|
| def forward(self, hidden_states, input_tensor): |
| hidden_states = self.dense(hidden_states) |
| hidden_states = self.dropout(hidden_states) |
| hidden_states = self.LayerNorm(hidden_states + input_tensor) |
| return hidden_states |
|
|
|
|
| class BertAttention(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.self = BertSelfAttention(config) |
| self.output = BertSelfOutput(config) |
| self.pruned_heads = set() |
|
|
| def prune_heads(self, heads): |
| if len(heads) == 0: |
| return |
| heads, index = find_pruneable_heads_and_indices( |
| heads, |
| self.self.num_attention_heads, |
| self.self.attention_head_size, |
| self.pruned_heads, |
| ) |
|
|
| |
| self.self.query = prune_linear_layer(self.self.query, index) |
| self.self.key = prune_linear_layer(self.self.key, index) |
| self.self.value = prune_linear_layer(self.self.value, index) |
| self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) |
|
|
| |
| self.self.num_attention_heads = self.self.num_attention_heads - len(heads) |
| self.self.all_head_size = ( |
| self.self.attention_head_size * self.self.num_attention_heads |
| ) |
| self.pruned_heads = self.pruned_heads.union(heads) |
|
|
| def forward( |
| self, |
| hidden_states, |
| attention_mask=None, |
| head_mask=None, |
| encoder_hidden_states=None, |
| encoder_attention_mask=None, |
| output_attentions=False, |
| ): |
| self_outputs = self.self( |
| hidden_states, |
| attention_mask, |
| head_mask, |
| encoder_hidden_states, |
| encoder_attention_mask, |
| output_attentions, |
| ) |
| attention_output = self.output(self_outputs[0], hidden_states) |
| outputs = (attention_output,) + self_outputs[ |
| 1: |
| ] |
| return outputs |
|
|
|
|
| class BertOutput(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.dense = nn.Linear(config.intermediate_size, config.hidden_size) |
| self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
| self.dropout = nn.Dropout(config.hidden_dropout_prob) |
|
|
| def forward(self, hidden_states, input_tensor): |
| hidden_states = self.dense(hidden_states) |
| hidden_states = self.dropout(hidden_states) |
| hidden_states = self.LayerNorm(hidden_states + input_tensor) |
| return hidden_states |
|
|
|
|
| class BertLayer(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.chunk_size_feed_forward = config.chunk_size_feed_forward |
| self.seq_len_dim = 1 |
| self.attention = BertAttention(config) |
| self.is_decoder = config.is_decoder |
| self.add_cross_attention = config.add_cross_attention |
| if self.add_cross_attention: |
| assert ( |
| self.is_decoder |
| ), f"{self} should be used as a decoder model if cross attention is added" |
| self.crossattention = BertAttention(config) |
| self.intermediate = BertIntermediate(config) |
| self.output = BertOutput(config) |
|
|
| def forward( |
| self, |
| hidden_states, |
| attention_mask=None, |
| head_mask=None, |
| encoder_hidden_states=None, |
| encoder_attention_mask=None, |
| output_attentions=False, |
| ): |
| self_attention_outputs = self.attention( |
| hidden_states, |
| attention_mask, |
| head_mask, |
| output_attentions=output_attentions, |
| ) |
| attention_output = self_attention_outputs[0] |
| outputs = self_attention_outputs[ |
| 1: |
| ] |
|
|
| if self.is_decoder and encoder_hidden_states is not None: |
| assert hasattr( |
| self, "crossattention" |
| ), f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`" |
| cross_attention_outputs = self.crossattention( |
| attention_output, |
| attention_mask, |
| head_mask, |
| encoder_hidden_states, |
| encoder_attention_mask, |
| output_attentions, |
| ) |
| attention_output = cross_attention_outputs[0] |
| outputs = ( |
| outputs + cross_attention_outputs[1:] |
| ) |
|
|
| layer_output = apply_chunking_to_forward( |
| self.feed_forward_chunk, |
| self.chunk_size_feed_forward, |
| self.seq_len_dim, |
| attention_output, |
| ) |
| outputs = (layer_output,) + outputs |
| return outputs |
|
|
| def feed_forward_chunk(self, attention_output): |
| intermediate_output = self.intermediate(attention_output) |
| layer_output = self.output(intermediate_output, attention_output) |
| return layer_output |
|
|
|
|
| class BertEncoder(nn.Module): |
| def __init__(self, config): |
| super().__init__() |
| self.config = config |
| self.layer = nn.ModuleList( |
| [BertLayer(config) for _ in range(config.num_hidden_layers)] |
| ) |
|
|
| def forward( |
| self, |
| hidden_states, |
| attention_mask=None, |
| head_mask=None, |
| encoder_hidden_states=None, |
| encoder_attention_mask=None, |
| output_attentions=False, |
| output_hidden_states=False, |
| return_dict=False, |
| ): |
| all_hidden_states = () if output_hidden_states else None |
| all_self_attentions = () if output_attentions else None |
| all_cross_attentions = ( |
| () if output_attentions and self.config.add_cross_attention else None |
| ) |
| for i, layer_module in enumerate(self.layer): |
| if output_hidden_states: |
| all_hidden_states = all_hidden_states + (hidden_states,) |
|
|
| layer_head_mask = head_mask[i] if head_mask is not None else None |
|
|
| if getattr(self.config, "gradient_checkpointing", False): |
|
|
| def create_custom_forward(module): |
| def custom_forward(*inputs): |
| return module(*inputs, output_attentions) |
|
|
| return custom_forward |
|
|
| layer_outputs = torch.utils.checkpoint.checkpoint( |
| create_custom_forward(layer_module), |
| hidden_states, |
| attention_mask, |
| layer_head_mask, |
| encoder_hidden_states, |
| encoder_attention_mask, |
| ) |
| else: |
| layer_outputs = layer_module( |
| hidden_states, |
| attention_mask, |
| layer_head_mask, |
| encoder_hidden_states, |
| encoder_attention_mask, |
| output_attentions, |
| ) |
| hidden_states = layer_outputs[0] |
| if output_attentions: |
| all_self_attentions = all_self_attentions + (layer_outputs[1],) |
| if self.config.add_cross_attention: |
| all_cross_attentions = all_cross_attentions + (layer_outputs[2],) |
|
|
| if output_hidden_states: |
| all_hidden_states = all_hidden_states + (hidden_states,) |
|
|
| if not return_dict: |
| return tuple( |
| v |
| for v in [ |
| hidden_states, |
| all_hidden_states, |
| all_self_attentions, |
| all_cross_attentions, |
| ] |
| if v is not None |
| ) |
| return BaseModelOutputWithCrossAttentions( |
| last_hidden_state=hidden_states, |
| hidden_states=all_hidden_states, |
| attentions=all_self_attentions, |
| cross_attentions=all_cross_attentions, |
| ) |
|
|
|
|
| class BertModel(BertPreTrainedModel): |
| """ |
| |
| The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of |
| cross-attention is added between the self-attention layers, following the architecture described in `Attention is |
| all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, |
| Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. |
| |
| To behave as an decoder the model needs to be initialized with the :obj:`is_decoder` argument of the configuration |
| set to :obj:`True`. To be used in a Seq2Seq model, the model needs to initialized with both :obj:`is_decoder` |
| argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an |
| input to the forward pass. |
| """ |
|
|
| def __init__( |
| self, |
| config, |
| add_pooling_layer=True, |
| max_feats=10, |
| features_dim=768, |
| freeze_lm=False, |
| ft_ln=False, |
| ): |
| super().__init__(config) |
| self.config = config |
|
|
| self.embeddings = BertEmbeddings(config, features_dim) |
| self.encoder = BertEncoder(config) |
|
|
| self.pooler = BertPooler(config) if add_pooling_layer else None |
|
|
| self.features_dim = features_dim |
| self.max_feats = max_feats |
| if freeze_lm: |
| for n, p in self.named_parameters(): |
| if (not "linear_video" in n) and (not "adapter" in n): |
| if ft_ln and "LayerNorm" in n: |
| continue |
| else: |
| p.requires_grad_(False) |
|
|
| self.init_weights() |
|
|
| def get_input_embeddings(self): |
| return self.embeddings.word_embeddings |
|
|
| def set_input_embeddings(self, value): |
| self.embeddings.word_embeddings = value |
|
|
| def _prune_heads(self, heads_to_prune): |
| """ |
| Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base |
| class PreTrainedModel |
| """ |
| for layer, heads in heads_to_prune.items(): |
| self.encoder.layer[layer].attention.prune_heads(heads) |
|
|
| def forward( |
| self, |
| video=None, |
| video_mask=None, |
| input_ids=None, |
| attention_mask=None, |
| token_type_ids=None, |
| position_ids=None, |
| head_mask=None, |
| inputs_embeds=None, |
| encoder_hidden_states=None, |
| encoder_attention_mask=None, |
| output_attentions=None, |
| output_hidden_states=None, |
| return_dict=None, |
| ): |
| r""" |
| encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): |
| Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if |
| the model is configured as a decoder. |
| encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): |
| Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in |
| the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: |
| |
| - 1 for tokens that are **not masked**, |
| - 0 for tokens that are **masked**. |
| """ |
| output_attentions = ( |
| output_attentions |
| if output_attentions is not None |
| else self.config.output_attentions |
| ) |
| output_hidden_states = ( |
| output_hidden_states |
| if output_hidden_states is not None |
| else self.config.output_hidden_states |
| ) |
| return_dict = ( |
| return_dict if return_dict is not None else self.config.use_return_dict |
| ) |
|
|
| if input_ids is not None and inputs_embeds is not None: |
| raise ValueError( |
| "You cannot specify both input_ids and inputs_embeds at the same time" |
| ) |
| elif input_ids is not None: |
| input_shape = input_ids.size() |
| elif inputs_embeds is not None: |
| input_shape = inputs_embeds.size()[:-1] |
| else: |
| raise ValueError("You have to specify either input_ids or inputs_embeds") |
|
|
| device = input_ids.device if input_ids is not None else inputs_embeds.device |
|
|
| if attention_mask is None: |
| attention_mask = torch.ones(input_shape, device=device) |
|
|
| if self.features_dim and video is not None: |
| if video_mask is None: |
| video_shape = video[:, :, 0].size() |
| video_mask = torch.ones(video_shape, device=device) |
| attention_mask = torch.cat([video_mask, attention_mask], 1) |
| input_shape = attention_mask.size() |
|
|
| if token_type_ids is None: |
| token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) |
|
|
| |
| |
| extended_attention_mask: torch.Tensor = self.get_extended_attention_mask( |
| attention_mask, input_shape, device |
| ) |
|
|
| |
| |
| if self.config.is_decoder and encoder_hidden_states is not None: |
| ( |
| encoder_batch_size, |
| encoder_sequence_length, |
| _, |
| ) = encoder_hidden_states.size() |
| encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) |
| if encoder_attention_mask is None: |
| encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) |
| encoder_extended_attention_mask = self.invert_attention_mask( |
| encoder_attention_mask |
| ) |
| else: |
| encoder_extended_attention_mask = None |
|
|
| |
| |
| |
| |
| |
| head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) |
|
|
| embedding_output = self.embeddings( |
| input_ids=input_ids, |
| position_ids=position_ids, |
| token_type_ids=token_type_ids, |
| inputs_embeds=inputs_embeds, |
| video=video, |
| ) |
|
|
| encoder_outputs = self.encoder( |
| embedding_output, |
| attention_mask=extended_attention_mask, |
| head_mask=head_mask, |
| encoder_hidden_states=encoder_hidden_states, |
| encoder_attention_mask=encoder_extended_attention_mask, |
| output_attentions=output_attentions, |
| output_hidden_states=output_hidden_states, |
| return_dict=return_dict, |
| ) |
| sequence_output = encoder_outputs[0] |
| pooled_output = ( |
| self.pooler(sequence_output) if self.pooler is not None else None |
| ) |
|
|
| if not return_dict: |
| return (sequence_output, pooled_output) + encoder_outputs[1:] |
|
|
| return BaseModelOutputWithPoolingAndCrossAttentions( |
| last_hidden_state=sequence_output, |
| pooler_output=pooled_output, |
| hidden_states=encoder_outputs.hidden_states, |
| attentions=encoder_outputs.attentions, |
| cross_attentions=encoder_outputs.cross_attentions, |
| ) |
|
|
|
|
| class BertForMaskedLM(BertPreTrainedModel): |
|
|
| _keys_to_ignore_on_load_unexpected = [r"pooler"] |
| _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] |
|
|
| def __init__( |
| self, |
| config, |
| features_dim, |
| max_feats, |
| freeze_lm, |
| ft_ln, |
| freeze_mlm, |
| n_ans, |
| freeze_last, |
| ): |
| """ |
| :param config: BiLM configuration |
| :param max_feats: maximum number of frames used by the model |
| :param features_dim: embedding dimension of the visual features |
| :param freeze_lm: whether to freeze or not the language model (Transformer encoder + token embedder) |
| :param freeze_mlm: whether to freeze or not the MLM head |
| :param ft_ln: whether to finetune or not the normalization layers |
| :param dropout: dropout probability in the adapter |
| :param n_ans: number of answers in the downstream vocabulary, set = 0 during cross-modal training |
| :param freeze_last: whether to freeze or not the answer embedding module |
| """ |
| super().__init__(config) |
|
|
| if config.is_decoder: |
| print( |
| "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for " |
| "bi-directional self-attention." |
| ) |
| self.features_dim = features_dim |
| self.max_feats = max_feats |
| self.bert = BertModel( |
| config, |
| add_pooling_layer=False, |
| max_feats=max_feats, |
| features_dim=features_dim, |
| freeze_lm=freeze_lm, |
| ft_ln=ft_ln, |
| ) |
| self.cls = BertOnlyMLMHead(config) |
| if freeze_mlm: |
| for p in self.cls.parameters(): |
| p.requires_grad_(False) |
|
|
| |
| self.post_init() |
| self.n_ans = n_ans |
| if n_ans: |
| self.answer_embeddings = nn.Embedding(n_ans, self.config.hidden_size) |
| self.answer_bias = nn.Parameter(torch.zeros(n_ans)) |
| if freeze_last: |
| self.answer_embeddings.requires_grad_(False) |
| self.answer_bias.requires_grad_(False) |
|
|
| def get_output_embeddings(self): |
| return self.cls.predictions.decoder |
|
|
| def set_output_embeddings(self, new_embeddings): |
| self.cls.predictions.decoder = new_embeddings |
|
|
| def set_answer_embeddings(self, a2tok, freeze_last=True): |
| a2v = self.bert.embeddings.word_embeddings(a2tok) |
| pad_token_id = getattr(self.config, "pad_token_id", 0) |
| sum_tokens = (a2tok != pad_token_id).sum(1, keepdims=True) |
| if len(a2v) != self.n_ans: |
| assert not self.training |
| self.n_ans = len(a2v) |
| self.answer_embeddings = nn.Embedding( |
| self.n_ans, self.config.hidden_size |
| ).to(self.device) |
| self.answer_bias.requires_grad = False |
| self.answer_bias.resize_(self.n_ans) |
| self.answer_embeddings.weight.data = torch.div( |
| (a2v * (a2tok != pad_token_id).float()[:, :, None]).sum(1), |
| sum_tokens.clamp(min=1), |
| ) |
| a2b = self.cls.predictions.bias[a2tok] |
| self.answer_bias.weight = torch.div( |
| (a2b * (a2tok != pad_token_id).float()).sum(1), sum_tokens.clamp(min=1) |
| ) |
| if freeze_last: |
| self.answer_embeddings.requires_grad_(False) |
| self.answer_bias.requires_grad_(False) |
|
|
| def forward( |
| self, |
| video=None, |
| video_mask=None, |
| input_ids: Optional[torch.Tensor] = None, |
| attention_mask: Optional[torch.Tensor] = None, |
| token_type_ids: Optional[torch.Tensor] = None, |
| position_ids: Optional[torch.Tensor] = None, |
| head_mask: Optional[torch.Tensor] = None, |
| inputs_embeds: Optional[torch.Tensor] = None, |
| encoder_hidden_states: Optional[torch.Tensor] = None, |
| encoder_attention_mask: Optional[torch.Tensor] = None, |
| labels: Optional[torch.Tensor] = None, |
| output_attentions: Optional[bool] = None, |
| output_hidden_states: Optional[bool] = None, |
| return_dict: Optional[bool] = None, |
| mlm=False, |
| ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]: |
| r""" |
| labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): |
| Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., |
| config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the |
| loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` |
| """ |
|
|
| return_dict = ( |
| return_dict if return_dict is not None else self.config.use_return_dict |
| ) |
|
|
| outputs = self.bert( |
| video=video, |
| video_mask=video_mask, |
| input_ids=input_ids, |
| attention_mask=attention_mask, |
| token_type_ids=token_type_ids, |
| position_ids=position_ids, |
| head_mask=head_mask, |
| inputs_embeds=inputs_embeds, |
| encoder_hidden_states=encoder_hidden_states, |
| encoder_attention_mask=encoder_attention_mask, |
| output_attentions=output_attentions, |
| output_hidden_states=output_hidden_states, |
| return_dict=return_dict, |
| ) |
|
|
| sequence_output = outputs[0] |
| embeddings, bias = None, None |
| if self.n_ans and (not mlm): |
| embeddings = self.answer_embeddings.weight |
| bias = self.answer_bias |
| prediction_scores = self.cls(sequence_output, embeddings, bias) |
|
|
| masked_lm_loss = None |
| if labels is not None: |
| if ( |
| self.features_dim and video is not None |
| ): |
| video_shape = video[:, :, 0].size() |
| video_labels = torch.tensor( |
| [[-100] * video_shape[1]] * video_shape[0], |
| dtype=torch.long, |
| device=labels.device, |
| ) |
| labels = torch.cat([video_labels, labels], 1) |
| loss_fct = CrossEntropyLoss() |
| masked_lm_loss = loss_fct( |
| prediction_scores.view(-1, self.config.vocab_size), labels.view(-1) |
| ) |
|
|
| if not return_dict: |
| output = (prediction_scores,) + outputs[2:] |
| return ( |
| ((masked_lm_loss,) + output) if masked_lm_loss is not None else output |
| ) |
|
|
| return MaskedLMOutput( |
| loss=masked_lm_loss, |
| logits=prediction_scores, |
| hidden_states=outputs.hidden_states, |
| attentions=outputs.attentions, |
| ) |
|
|