CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
modeling_splinter.py863 linesDownload Raw Back to splinter
1# coding=utf-82# Copyright 2021 Tel AViv University, AllenAI and The HuggingFace Inc. team. All rights reserved.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 at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# 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 and14# limitations under the License.15"""PyTorch Splinter model."""16 17from dataclasses import dataclass18from typing import Callable, Optional, Union19 20import torch21from torch import nn22from torch.nn import CrossEntropyLoss23 24from ...activations import ACT2FN25from ...modeling_layers import GradientCheckpointingLayer26from ...modeling_outputs import BaseModelOutput, ModelOutput, QuestionAnsweringModelOutput27from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel28from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer29from ...utils import (30    auto_docstring,31    can_return_tuple,32    logging,33)34from .configuration_splinter import SplinterConfig35 36 37logger = logging.get_logger(__name__)38 39 40class SplinterEmbeddings(nn.Module):41    """Construct the embeddings from word, position and token_type embeddings."""42 43    def __init__(self, config):44        super().__init__()45        self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)46        self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)47        self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)48 49        # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load50        # any TensorFlow checkpoint file51        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)52        self.dropout = nn.Dropout(config.hidden_dropout_prob)53 54        # position_ids (1, len position emb) is contiguous in memory and exported when serialized55        self.register_buffer(56            "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False57        )58        self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")59 60    def forward(61        self,62        input_ids: Optional[torch.LongTensor] = None,63        token_type_ids: Optional[torch.LongTensor] = None,64        position_ids: Optional[torch.LongTensor] = None,65        inputs_embeds: Optional[torch.FloatTensor] = None,66    ) -> tuple:67        if input_ids is not None:68            input_shape = input_ids.size()69        else:70            input_shape = inputs_embeds.size()[:-1]71 72        seq_length = input_shape[1]73 74        if position_ids is None:75            position_ids = self.position_ids[:, :seq_length]76 77        if token_type_ids is None:78            token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)79 80        if inputs_embeds is None:81            inputs_embeds = self.word_embeddings(input_ids)82        token_type_embeddings = self.token_type_embeddings(token_type_ids)83 84        embeddings = inputs_embeds + token_type_embeddings85        if self.position_embedding_type == "absolute":86            position_embeddings = self.position_embeddings(position_ids)87            embeddings += position_embeddings88        embeddings = self.LayerNorm(embeddings)89        embeddings = self.dropout(embeddings)90        return embeddings91 92 93# Copied from transformers.models.align.modeling_align.eager_attention_forward94def eager_attention_forward(95    module: nn.Module,96    query: torch.Tensor,97    key: torch.Tensor,98    value: torch.Tensor,99    attention_mask: Optional[torch.Tensor],100    scaling: float,101    dropout: float = 0.0,102    head_mask: Optional[torch.Tensor] = None,103    **kwargs,104):105    attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling106    if attention_mask is not None:107        causal_mask = attention_mask[:, :, :, : key.shape[-2]]108        attn_weights = attn_weights + causal_mask109 110    attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)111    attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)112 113    if head_mask is not None:114        attn_weights = attn_weights * head_mask.view(1, -1, 1, 1)115 116    attn_output = torch.matmul(attn_weights, value)117    attn_output = attn_output.transpose(1, 2).contiguous()118    return attn_output, attn_weights119 120 121# Copied from transformers.models.align.modeling_align.AlignTextSelfAttention with AlignText->Splinter122class SplinterSelfAttention(nn.Module):123    def __init__(self, config):124        super().__init__()125        if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):126            raise ValueError(127                f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "128                f"heads ({config.num_attention_heads})"129            )130 131        self.config = config132        self.num_attention_heads = config.num_attention_heads133        self.attention_head_size = int(config.hidden_size / config.num_attention_heads)134        self.all_head_size = self.num_attention_heads * self.attention_head_size135 136        self.query = nn.Linear(config.hidden_size, self.all_head_size)137        self.key = nn.Linear(config.hidden_size, self.all_head_size)138        self.value = nn.Linear(config.hidden_size, self.all_head_size)139 140        self.dropout = nn.Dropout(config.attention_probs_dropout_prob)141        self.attention_dropout = config.attention_probs_dropout_prob142        self.scaling = self.attention_head_size**-0.5143 144    def forward(145        self,146        hidden_states: torch.Tensor,147        attention_mask: Optional[torch.FloatTensor] = None,148        head_mask: Optional[torch.FloatTensor] = None,149        output_attentions: Optional[bool] = False,150        **kwargs,151    ) -> tuple[torch.Tensor]:152        input_shape = hidden_states.shape[:-1]153        hidden_shape = (*input_shape, -1, self.attention_head_size)154 155        query_states = self.query(hidden_states).view(hidden_shape).transpose(1, 2)156        key_states = self.key(hidden_states).view(hidden_shape).transpose(1, 2)157        value_states = self.value(hidden_states).view(hidden_shape).transpose(1, 2)158 159        attention_interface: Callable = eager_attention_forward160        if self.config._attn_implementation != "eager":161            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]162 163        attn_output, attn_weights = attention_interface(164            self,165            query_states,166            key_states,167            value_states,168            attention_mask,169            dropout=0.0 if not self.training else self.attention_dropout,170            scaling=self.scaling,171            head_mask=head_mask,172            **kwargs,173        )174 175        attn_output = attn_output.reshape(*input_shape, -1).contiguous()176        outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)177        return outputs178 179 180# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Splinter181class SplinterSelfOutput(nn.Module):182    def __init__(self, config):183        super().__init__()184        self.dense = nn.Linear(config.hidden_size, config.hidden_size)185        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)186        self.dropout = nn.Dropout(config.hidden_dropout_prob)187 188    def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:189        hidden_states = self.dense(hidden_states)190        hidden_states = self.dropout(hidden_states)191        hidden_states = self.LayerNorm(hidden_states + input_tensor)192        return hidden_states193 194 195# Copied from transformers.models.align.modeling_align.AlignTextAttention with AlignText->Splinter196class SplinterAttention(nn.Module):197    def __init__(self, config):198        super().__init__()199        self.self = SplinterSelfAttention(config)200        self.output = SplinterSelfOutput(config)201        self.pruned_heads = set()202 203    def prune_heads(self, heads):204        if len(heads) == 0:205            return206        heads, index = find_pruneable_heads_and_indices(207            heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads208        )209 210        # Prune linear layers211        self.self.query = prune_linear_layer(self.self.query, index)212        self.self.key = prune_linear_layer(self.self.key, index)213        self.self.value = prune_linear_layer(self.self.value, index)214        self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)215 216        # Update hyper params and store pruned heads217        self.self.num_attention_heads = self.self.num_attention_heads - len(heads)218        self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads219        self.pruned_heads = self.pruned_heads.union(heads)220 221    def forward(222        self,223        hidden_states: torch.Tensor,224        attention_mask: Optional[torch.FloatTensor] = None,225        head_mask: Optional[torch.FloatTensor] = None,226        output_attentions: Optional[bool] = False,227        **kwargs,228    ) -> tuple[torch.Tensor]:229        self_outputs = self.self(230            hidden_states,231            attention_mask=attention_mask,232            head_mask=head_mask,233            output_attentions=output_attentions,234            **kwargs,235        )236        attention_output = self.output(self_outputs[0], hidden_states)237        outputs = (attention_output,) + self_outputs[1:]  # add attentions if we output them238        return outputs239 240 241# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Splinter242class SplinterIntermediate(nn.Module):243    def __init__(self, config):244        super().__init__()245        self.dense = nn.Linear(config.hidden_size, config.intermediate_size)246        if isinstance(config.hidden_act, str):247            self.intermediate_act_fn = ACT2FN[config.hidden_act]248        else:249            self.intermediate_act_fn = config.hidden_act250 251    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:252        hidden_states = self.dense(hidden_states)253        hidden_states = self.intermediate_act_fn(hidden_states)254        return hidden_states255 256 257# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Splinter258class SplinterOutput(nn.Module):259    def __init__(self, config):260        super().__init__()261        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)262        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)263        self.dropout = nn.Dropout(config.hidden_dropout_prob)264 265    def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:266        hidden_states = self.dense(hidden_states)267        hidden_states = self.dropout(hidden_states)268        hidden_states = self.LayerNorm(hidden_states + input_tensor)269        return hidden_states270 271 272# Copied from transformers.models.align.modeling_align.AlignTextLayer with AlignText->Splinter273class SplinterLayer(GradientCheckpointingLayer):274    def __init__(self, config):275        super().__init__()276        self.chunk_size_feed_forward = config.chunk_size_feed_forward277        self.seq_len_dim = 1278        self.attention = SplinterAttention(config)279        self.intermediate = SplinterIntermediate(config)280        self.output = SplinterOutput(config)281 282    def forward(283        self,284        hidden_states: torch.Tensor,285        attention_mask: Optional[torch.FloatTensor] = None,286        head_mask: Optional[torch.FloatTensor] = None,287        output_attentions: Optional[bool] = False,288        **kwargs,289    ) -> tuple[torch.Tensor]:290        self_attention_outputs = self.attention(291            hidden_states,292            attention_mask=attention_mask,293            head_mask=head_mask,294            output_attentions=output_attentions,295            **kwargs,296        )297        attention_output = self_attention_outputs[0]298 299        outputs = self_attention_outputs[1:]  # add self attentions if we output attention weights300        layer_output = apply_chunking_to_forward(301            self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output302        )303        outputs = (layer_output,) + outputs304 305        return outputs306 307    def feed_forward_chunk(self, attention_output):308        intermediate_output = self.intermediate(attention_output)309        layer_output = self.output(intermediate_output, attention_output)310        return layer_output311 312 313# Copied from transformers.models.align.modeling_align.AlignTextEncoder with AlignText->Splinter314class SplinterEncoder(nn.Module):315    def __init__(self, config):316        super().__init__()317        self.config = config318        self.layer = nn.ModuleList([SplinterLayer(config) for i in range(config.num_hidden_layers)])319        self.gradient_checkpointing = False320 321    @can_return_tuple322    def forward(323        self,324        hidden_states: torch.Tensor,325        attention_mask: Optional[torch.FloatTensor] = None,326        head_mask: Optional[torch.FloatTensor] = None,327        output_attentions: Optional[bool] = False,328        output_hidden_states: Optional[bool] = False,329        return_dict: Optional[bool] = True,330        **kwargs,331    ) -> Union[tuple[torch.Tensor], BaseModelOutput]:332        all_hidden_states = () if output_hidden_states else None333        all_self_attentions = () if output_attentions else None334 335        for i, layer_module in enumerate(self.layer):336            if output_hidden_states:337                all_hidden_states = all_hidden_states + (hidden_states,)338 339            layer_head_mask = head_mask[i] if head_mask is not None else None340 341            layer_outputs = layer_module(342                hidden_states=hidden_states,343                attention_mask=attention_mask,344                head_mask=layer_head_mask,345                output_attentions=output_attentions,346                **kwargs,347            )348 349            hidden_states = layer_outputs[0]350            if output_attentions:351                all_self_attentions = all_self_attentions + (layer_outputs[1],)352 353        if output_hidden_states:354            all_hidden_states = all_hidden_states + (hidden_states,)355 356        return BaseModelOutput(357            last_hidden_state=hidden_states,358            hidden_states=all_hidden_states,359            attentions=all_self_attentions,360        )361 362 363@auto_docstring364class SplinterPreTrainedModel(PreTrainedModel):365    config: SplinterConfig366    base_model_prefix = "splinter"367    supports_gradient_checkpointing = True368 369    def _init_weights(self, module):370        """Initialize the weights"""371        if isinstance(module, nn.Linear):372            # Slightly different from the TF version which uses truncated_normal for initialization373            # cf https://github.com/pytorch/pytorch/pull/5617374            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)375            if module.bias is not None:376                module.bias.data.zero_()377        elif isinstance(module, nn.Embedding):378            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)379            if module.padding_idx is not None:380                module.weight.data[module.padding_idx].zero_()381        elif isinstance(module, nn.LayerNorm):382            module.bias.data.zero_()383            module.weight.data.fill_(1.0)384 385 386@auto_docstring387class SplinterModel(SplinterPreTrainedModel):388    """389    The model is an encoder (with only self-attention) following the architecture described in [Attention is all you390    need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones,391    Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.392    """393 394    def __init__(self, config):395        super().__init__(config)396        self.config = config397 398        self.embeddings = SplinterEmbeddings(config)399        self.encoder = SplinterEncoder(config)400 401        # Initialize weights and apply final processing402        self.post_init()403 404    def get_input_embeddings(self):405        return self.embeddings.word_embeddings406 407    def set_input_embeddings(self, value):408        self.embeddings.word_embeddings = value409 410    def _prune_heads(self, heads_to_prune):411        """412        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base413        class PreTrainedModel414        """415        for layer, heads in heads_to_prune.items():416            self.encoder.layer[layer].attention.prune_heads(heads)417 418    @can_return_tuple419    @auto_docstring420    def forward(421        self,422        input_ids: Optional[torch.Tensor] = None,423        attention_mask: Optional[torch.Tensor] = None,424        token_type_ids: Optional[torch.Tensor] = None,425        position_ids: Optional[torch.Tensor] = None,426        head_mask: Optional[torch.Tensor] = None,427        inputs_embeds: Optional[torch.Tensor] = None,428        output_attentions: Optional[bool] = None,429        output_hidden_states: Optional[bool] = None,430        return_dict: Optional[bool] = None,431    ) -> Union[tuple, BaseModelOutput]:432        r"""433        token_type_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):434            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,435            1]`:436 437            - 0 corresponds to a *sentence A* token,438            - 1 corresponds to a *sentence B* token.439 440            [What are token type IDs?](../glossary#token-type-ids)441        position_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):442            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,443            config.max_position_embeddings - 1]`.444 445            [What are position IDs?](../glossary#position-ids)446        """447        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions448        output_hidden_states = (449            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states450        )451        return_dict = return_dict if return_dict is not None else self.config.use_return_dict452 453        if input_ids is not None and inputs_embeds is not None:454            raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")455        elif input_ids is not None:456            self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)457            input_shape = input_ids.size()458        elif inputs_embeds is not None:459            input_shape = inputs_embeds.size()[:-1]460        else:461            raise ValueError("You have to specify either input_ids or inputs_embeds")462 463        batch_size, seq_length = input_shape464        device = input_ids.device if input_ids is not None else inputs_embeds.device465 466        if attention_mask is None:467            attention_mask = torch.ones(((batch_size, seq_length)), device=device)468        if token_type_ids is None:469            token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)470 471        # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]472        # ourselves in which case we just need to make it broadcastable to all heads.473        extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)474 475        # Prepare head mask if needed476        # 1.0 in head_mask indicate we keep the head477        # attention_probs has shape bsz x n_heads x N x N478        # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]479        # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]480        head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)481 482        embedding_output = self.embeddings(483            input_ids=input_ids,484            position_ids=position_ids,485            token_type_ids=token_type_ids,486            inputs_embeds=inputs_embeds,487        )488        encoder_outputs = self.encoder(489            embedding_output,490            attention_mask=extended_attention_mask,491            head_mask=head_mask,492            output_attentions=output_attentions,493            output_hidden_states=output_hidden_states,494            return_dict=True,495        )496        sequence_output = encoder_outputs[0]497 498        return BaseModelOutput(499            last_hidden_state=sequence_output,500            hidden_states=encoder_outputs.hidden_states,501            attentions=encoder_outputs.attentions,502        )503 504 505class SplinterFullyConnectedLayer(nn.Module):506    def __init__(self, input_dim, output_dim, hidden_act="gelu"):507        super().__init__()508 509        self.input_dim = input_dim510        self.output_dim = output_dim511 512        self.dense = nn.Linear(self.input_dim, self.output_dim)513        self.act_fn = ACT2FN[hidden_act]514        self.LayerNorm = nn.LayerNorm(self.output_dim)515 516    def forward(self, inputs: torch.Tensor) -> torch.Tensor:517        hidden_states = self.dense(inputs)518        hidden_states = self.act_fn(hidden_states)519        hidden_states = self.LayerNorm(hidden_states)520        return hidden_states521 522 523class QuestionAwareSpanSelectionHead(nn.Module):524    """525    Implementation of Question-Aware Span Selection (QASS) head, described in Splinter's paper:526 527    """528 529    def __init__(self, config):530        super().__init__()531 532        self.query_start_transform = SplinterFullyConnectedLayer(config.hidden_size, config.hidden_size)533        self.query_end_transform = SplinterFullyConnectedLayer(config.hidden_size, config.hidden_size)534        self.start_transform = SplinterFullyConnectedLayer(config.hidden_size, config.hidden_size)535        self.end_transform = SplinterFullyConnectedLayer(config.hidden_size, config.hidden_size)536 537        self.start_classifier = nn.Linear(config.hidden_size, config.hidden_size, bias=False)538        self.end_classifier = nn.Linear(config.hidden_size, config.hidden_size, bias=False)539 540    def forward(self, inputs, positions):541        _, _, dim = inputs.size()542        index = positions.unsqueeze(-1).repeat(1, 1, dim)  # [batch_size, num_positions, dim]543        gathered_reps = torch.gather(inputs, dim=1, index=index)  # [batch_size, num_positions, dim]544 545        query_start_reps = self.query_start_transform(gathered_reps)  # [batch_size, num_positions, dim]546        query_end_reps = self.query_end_transform(gathered_reps)  # [batch_size, num_positions, dim]547        start_reps = self.start_transform(inputs)  # [batch_size, seq_length, dim]548        end_reps = self.end_transform(inputs)  # [batch_size, seq_length, dim]549 550        hidden_states = self.start_classifier(query_start_reps)  # [batch_size, num_positions, dim]551        start_reps = start_reps.permute(0, 2, 1)  # [batch_size, dim, seq_length]552        start_logits = torch.matmul(hidden_states, start_reps)553 554        hidden_states = self.end_classifier(query_end_reps)555        end_reps = end_reps.permute(0, 2, 1)556        end_logits = torch.matmul(hidden_states, end_reps)557 558        return start_logits, end_logits559 560 561@auto_docstring562class SplinterForQuestionAnswering(SplinterPreTrainedModel):563    def __init__(self, config):564        super().__init__(config)565 566        self.splinter = SplinterModel(config)567        self.splinter_qass = QuestionAwareSpanSelectionHead(config)568        self.question_token_id = config.question_token_id569 570        # Initialize weights and apply final processing571        self.post_init()572 573    @auto_docstring574    def forward(575        self,576        input_ids: Optional[torch.Tensor] = None,577        attention_mask: Optional[torch.Tensor] = None,578        token_type_ids: Optional[torch.Tensor] = None,579        position_ids: Optional[torch.Tensor] = None,580        head_mask: Optional[torch.Tensor] = None,581        inputs_embeds: Optional[torch.Tensor] = None,582        start_positions: Optional[torch.LongTensor] = None,583        end_positions: Optional[torch.LongTensor] = None,584        output_attentions: Optional[bool] = None,585        output_hidden_states: Optional[bool] = None,586        return_dict: Optional[bool] = None,587        question_positions: Optional[torch.LongTensor] = None,588    ) -> Union[tuple, QuestionAnsweringModelOutput]:589        r"""590        token_type_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):591            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,592            1]`:593 594            - 0 corresponds to a *sentence A* token,595            - 1 corresponds to a *sentence B* token.596 597            [What are token type IDs?](../glossary#token-type-ids)598        position_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):599            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,600            config.max_position_embeddings - 1]`.601 602            [What are position IDs?](../glossary#position-ids)603        question_positions (`torch.LongTensor` of shape `(batch_size, num_questions)`, *optional*):604            The positions of all question tokens. If given, start_logits and end_logits will be of shape `(batch_size,605            num_questions, sequence_length)`. If None, the first question token in each sequence in the batch will be606            the only one for which start_logits and end_logits are calculated and they will be of shape `(batch_size,607            sequence_length)`.608        """609        return_dict = return_dict if return_dict is not None else self.config.use_return_dict610 611        question_positions_were_none = False612        if question_positions is None:613            if input_ids is not None:614                question_position_for_each_example = torch.argmax(615                    (torch.eq(input_ids, self.question_token_id)).int(), dim=-1616                )617            else:618                question_position_for_each_example = torch.zeros(619                    inputs_embeds.size(0), dtype=torch.long, layout=inputs_embeds.layout, device=inputs_embeds.device620                )621            question_positions = question_position_for_each_example.unsqueeze(-1)622            question_positions_were_none = True623 624        outputs = self.splinter(625            input_ids,626            attention_mask=attention_mask,627            token_type_ids=token_type_ids,628            position_ids=position_ids,629            head_mask=head_mask,630            inputs_embeds=inputs_embeds,631            output_attentions=output_attentions,632            output_hidden_states=output_hidden_states,633            return_dict=return_dict,634        )635 636        sequence_output = outputs[0]637        start_logits, end_logits = self.splinter_qass(sequence_output, question_positions)638 639        if question_positions_were_none:640            start_logits, end_logits = start_logits.squeeze(1), end_logits.squeeze(1)641 642        if attention_mask is not None:643            start_logits = start_logits + (1 - attention_mask) * torch.finfo(start_logits.dtype).min644            end_logits = end_logits + (1 - attention_mask) * torch.finfo(end_logits.dtype).min645 646        total_loss = None647        if start_positions is not None and end_positions is not None:648            # If we are on multi-GPU, split add a dimension649            if len(start_positions.size()) > 1:650                start_positions = start_positions.squeeze(-1)651            if len(end_positions.size()) > 1:652                end_positions = end_positions.squeeze(-1)653            # sometimes the start/end positions are outside our model inputs, we ignore these terms654            ignored_index = start_logits.size(1)655            start_positions.clamp_(0, ignored_index)656            end_positions.clamp_(0, ignored_index)657 658            loss_fct = CrossEntropyLoss(ignore_index=ignored_index)659            start_loss = loss_fct(start_logits, start_positions)660            end_loss = loss_fct(end_logits, end_positions)661            total_loss = (start_loss + end_loss) / 2662 663        if not return_dict:664            output = (start_logits, end_logits) + outputs[1:]665            return ((total_loss,) + output) if total_loss is not None else output666 667        return QuestionAnsweringModelOutput(668            loss=total_loss,669            start_logits=start_logits,670            end_logits=end_logits,671            hidden_states=outputs.hidden_states,672            attentions=outputs.attentions,673        )674 675 676@dataclass677@auto_docstring(678    custom_intro="""679    Class for outputs of Splinter as a span selection model.680    """681)682class SplinterForPreTrainingOutput(ModelOutput):683    r"""684    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when start and end positions are provided):685        Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.686    start_logits (`torch.FloatTensor` of shape `(batch_size, num_questions, sequence_length)`):687        Span-start scores (before SoftMax).688    end_logits (`torch.FloatTensor` of shape `(batch_size, num_questions, sequence_length)`):689        Span-end scores (before SoftMax).690    """691 692    loss: Optional[torch.FloatTensor] = None693    start_logits: Optional[torch.FloatTensor] = None694    end_logits: Optional[torch.FloatTensor] = None695    hidden_states: Optional[tuple[torch.FloatTensor]] = None696    attentions: Optional[tuple[torch.FloatTensor]] = None697 698 699@auto_docstring(700    custom_intro="""701    Splinter Model for the recurring span selection task as done during the pretraining. The difference to the QA task702    is that we do not have a question, but multiple question tokens that replace the occurrences of recurring spans703    instead.704    """705)706class SplinterForPreTraining(SplinterPreTrainedModel):707    def __init__(self, config):708        super().__init__(config)709 710        self.splinter = SplinterModel(config)711        self.splinter_qass = QuestionAwareSpanSelectionHead(config)712        self.question_token_id = config.question_token_id713 714        # Initialize weights and apply final processing715        self.post_init()716 717    @auto_docstring718    def forward(719        self,720        input_ids: Optional[torch.Tensor] = None,721        attention_mask: Optional[torch.Tensor] = None,722        token_type_ids: Optional[torch.Tensor] = None,723        position_ids: Optional[torch.Tensor] = None,724        head_mask: Optional[torch.Tensor] = None,725        inputs_embeds: Optional[torch.Tensor] = None,726        start_positions: Optional[torch.LongTensor] = None,727        end_positions: Optional[torch.LongTensor] = None,728        output_attentions: Optional[bool] = None,729        output_hidden_states: Optional[bool] = None,730        return_dict: Optional[bool] = None,731        question_positions: Optional[torch.LongTensor] = None,732    ) -> Union[tuple, SplinterForPreTrainingOutput]:733        r"""734        input_ids (`torch.LongTensor` of shape `(batch_size, num_questions, sequence_length)`):735            Indices of input sequence tokens in the vocabulary.736 737            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and738            [`PreTrainedTokenizer.__call__`] for details.739 740            [What are input IDs?](../glossary#input-ids)741        token_type_ids (`torch.LongTensor` of shape `batch_size, num_questions, sequence_length`, *optional*):742            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,743            1]`:744 745            - 0 corresponds to a *sentence A* token,746            - 1 corresponds to a *sentence B* token.747 748            [What are token type IDs?](../glossary#token-type-ids)749        position_ids (`torch.LongTensor` of shape `batch_size, num_questions, sequence_length`, *optional*):750            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,751            config.max_position_embeddings - 1]`.752 753            [What are position IDs?](../glossary#position-ids)754        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_questions, sequence_length, hidden_size)`, *optional*):755            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This756            is useful if you want more control over how to convert *input_ids* indices into associated vectors than the757            model's internal embedding lookup matrix.758        start_positions (`torch.LongTensor` of shape `(batch_size, num_questions)`, *optional*):759            Labels for position (index) of the start of the labelled span for computing the token classification loss.760            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence761            are not taken into account for computing the loss.762        end_positions (`torch.LongTensor` of shape `(batch_size, num_questions)`, *optional*):763            Labels for position (index) of the end of the labelled span for computing the token classification loss.764            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence765            are not taken into account for computing the loss.766        question_positions (`torch.LongTensor` of shape `(batch_size, num_questions)`, *optional*):767            The positions of all question tokens. If given, start_logits and end_logits will be of shape `(batch_size,768            num_questions, sequence_length)`. If None, the first question token in each sequence in the batch will be769            the only one for which start_logits and end_logits are calculated and they will be of shape `(batch_size,770            sequence_length)`.771        """772        return_dict = return_dict if return_dict is not None else self.config.use_return_dict773 774        if question_positions is None and start_positions is not None and end_positions is not None:775            raise TypeError("question_positions must be specified in order to calculate the loss")776 777        elif question_positions is None and input_ids is None:778            raise TypeError("question_positions must be specified when input_embeds is used")779 780        elif question_positions is None:781            question_positions = self._prepare_question_positions(input_ids)782 783        outputs = self.splinter(784            input_ids,785            attention_mask=attention_mask,786            token_type_ids=token_type_ids,787            position_ids=position_ids,788            head_mask=head_mask,789            inputs_embeds=inputs_embeds,790            output_attentions=output_attentions,791            output_hidden_states=output_hidden_states,792            return_dict=return_dict,793        )794 795        sequence_output = outputs[0]796        batch_size, sequence_length, dim = sequence_output.size()797        # [batch_size, num_questions, sequence_length]798        start_logits, end_logits = self.splinter_qass(sequence_output, question_positions)799 800        num_questions = question_positions.size(1)801        if attention_mask is not None:802            attention_mask_for_each_question = attention_mask.unsqueeze(1).expand(803                batch_size, num_questions, sequence_length804            )805            start_logits = start_logits + (1 - attention_mask_for_each_question) * torch.finfo(start_logits.dtype).min806            end_logits = end_logits + (1 - attention_mask_for_each_question) * torch.finfo(end_logits.dtype).min807 808        total_loss = None809        # [batch_size, num_questions, sequence_length]810        if start_positions is not None and end_positions is not None:811            # sometimes the start/end positions are outside our model inputs, we ignore these terms812            start_positions.clamp_(0, max(0, sequence_length - 1))813            end_positions.clamp_(0, max(0, sequence_length - 1))814 815            # Ignore zero positions in the loss. Splinter never predicts zero816            # during pretraining and zero is used for padding question817            # tokens as well as for start and end positions of padded818            # question tokens.819            loss_fct = CrossEntropyLoss(ignore_index=self.config.pad_token_id)820            start_loss = loss_fct(821                start_logits.view(batch_size * num_questions, sequence_length),822                start_positions.view(batch_size * num_questions),823            )824            end_loss = loss_fct(825                end_logits.view(batch_size * num_questions, sequence_length),826                end_positions.view(batch_size * num_questions),827            )828            total_loss = (start_loss + end_loss) / 2829 830        if not return_dict:831            output = (start_logits, end_logits) + outputs[1:]832            return ((total_loss,) + output) if total_loss is not None else output833 834        return SplinterForPreTrainingOutput(835            loss=total_loss,836            start_logits=start_logits,837            end_logits=end_logits,838            hidden_states=outputs.hidden_states,839            attentions=outputs.attentions,840        )841 842    def _prepare_question_positions(self, input_ids: torch.Tensor) -> torch.Tensor:843        rows, flat_positions = torch.where(input_ids == self.config.question_token_id)844        num_questions = torch.bincount(rows)845        positions = torch.full(846            (input_ids.size(0), num_questions.max()),847            self.config.pad_token_id,848            dtype=torch.long,849            device=input_ids.device,850        )851        cols = torch.cat([torch.arange(n) for n in num_questions])852        positions[rows, cols] = flat_positions853        return positions854 855 856__all__ = [857    "SplinterForQuestionAnswering",858    "SplinterForPreTraining",859    "SplinterLayer",860    "SplinterModel",861    "SplinterPreTrainedModel",862]863 
Aluode/PerceptionLabPortable · CoolFace