CoolFace
Modelpublic

bigcode/santacoder

sourceHugging Facebigcode-openrail-mupdated 3y agoView on Hugging Face
336likes10kdownloads
configuration_gpt2_mq.py202 linesDownload Raw Back to root
1# coding=utf-82# Copyright 2018 The OpenAI Team Authors and Hugging Face 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 at8#9#     http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# 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 and15# limitations under the License.16""" Custom GPT-2 configuration"""17from collections import OrderedDict18from typing import Any, List, Mapping, Optional19from enum import Enum20 21from transformers import PreTrainedTokenizer, TensorType, is_torch_available22 23from transformers.configuration_utils import PretrainedConfig24from transformers.onnx import OnnxConfigWithPast, PatchingSpec25from transformers.utils import logging26 27 28logger = logging.get_logger(__name__)29 30GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP = {31    "gpt2": "https://huggingface.co/gpt2/resolve/main/config.json",32    "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/config.json",33    "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/config.json",34    "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/config.json",35    "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/config.json",36}37 38MULTI_HEAD = "multihead"39MULTI_QUERY = "multiquery"40 41 42class GPT2CustomConfig(PretrainedConfig):43    """44    This is the configuration class to store the configuration of a [`GPT2Model`] or a [`TFGPT2Model`]. It is used to45    instantiate a GPT-2 model according to the specified arguments, defining the model architecture. Instantiating a46    configuration with the defaults will yield a similar configuration to that of the GPT-247    [gpt2](https://huggingface.co/gpt2) architecture.48 49    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the50    documentation from [`PretrainedConfig`] for more information.51 52 53    Args:54        vocab_size (`int`, *optional*, defaults to 50257):55            Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the56            `inputs_ids` passed when calling [`GPT2Model`] or [`TFGPT2Model`].57        n_positions (`int`, *optional*, defaults to 1024):58            The maximum sequence length that this model might ever be used with. Typically set this to something large59            just in case (e.g., 512 or 1024 or 2048).60        n_embd (`int`, *optional*, defaults to 768):61            Dimensionality of the embeddings and hidden states.62        n_layer (`int`, *optional*, defaults to 12):63            Number of hidden layers in the Transformer encoder.64        n_head (`int`, *optional*, defaults to 12):65            Number of attention heads for each attention layer in the Transformer encoder.66        n_inner (`int`, *optional*, defaults to None):67            Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd68        activation_function (`str`, *optional*, defaults to `"gelu"`):69            Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.70        resid_pdrop (`float`, *optional*, defaults to 0.1):71            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.72        embd_pdrop (`int`, *optional*, defaults to 0.1):73            The dropout ratio for the embeddings.74        attn_pdrop (`float`, *optional*, defaults to 0.1):75            The dropout ratio for the attention.76        layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):77            The epsilon to use in the layer normalization layers.78        initializer_range (`float`, *optional*, defaults to 0.02):79            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.80        summary_type (`string`, *optional*, defaults to `"cls_index"`):81            Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and82            [`TFGPT2DoubleHeadsModel`].83 84            Has to be one of the following options:85 86                - `"last"`: Take the last token hidden state (like XLNet).87                - `"first"`: Take the first token hidden state (like BERT).88                - `"mean"`: Take the mean of all tokens hidden states.89                - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).90                - `"attn"`: Not implemented now, use multi-head attention.91        summary_use_proj (`bool`, *optional*, defaults to `True`):92            Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and93            [`TFGPT2DoubleHeadsModel`].94 95            Whether or not to add a projection after the vector extraction.96        summary_activation (`str`, *optional*):97            Argument used when doing sequence summary. Used in for the multiple choice head in98            [`GPT2DoubleHeadsModel`].99 100            Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.101        summary_proj_to_labels (`bool`, *optional*, defaults to `True`):102            Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and103            [`TFGPT2DoubleHeadsModel`].104 105            Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.106        summary_first_dropout (`float`, *optional*, defaults to 0.1):107            Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and108            [`TFGPT2DoubleHeadsModel`].109 110            The dropout ratio to be used after the projection and activation.111        scale_attn_weights (`bool`, *optional*, defaults to `True`):112            Scale attention weights by dividing by sqrt(head_dim)..113        use_cache (`bool`, *optional*, defaults to `True`):114            Whether or not the model should return the last key/values attentions (not used by all models).115        scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):116            Whether to additionally scale attention weights by `1 / layer_idx + 1`.117        reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):118            Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention119            dot-product/softmax to float() when training with mixed precision.120 121    Example:122 123    ```python124    >>> from transformers import GPT2Config, GPT2Model125 126    >>> # Initializing a GPT2 configuration127    >>> configuration = GPT2Config()128 129    >>> # Initializing a model (with random weights) from the configuration130    >>> model = GPT2Model(configuration)131 132    >>> # Accessing the model configuration133    >>> configuration = model.config134    ```"""135 136    model_type = "gpt2"137    keys_to_ignore_at_inference = ["past_key_values"]138    attribute_map = {139        "hidden_size": "n_embd",140        "max_position_embeddings": "n_positions",141        "num_attention_heads": "n_head",142        "num_hidden_layers": "n_layer",143    }144 145    def __init__(146        self,147        vocab_size=50257,148        n_positions=1024,149        n_embd=768,150        n_layer=12,151        n_head=12,152        n_inner=None,153        activation_function="gelu_new",154        resid_pdrop=0.1,155        embd_pdrop=0.1,156        attn_pdrop=0.1,157        layer_norm_epsilon=1e-5,158        initializer_range=0.02,159        summary_type="cls_index",160        summary_use_proj=True,161        summary_activation=None,162        summary_proj_to_labels=True,163        summary_first_dropout=0.1,164        scale_attn_weights=True,165        use_cache=True,166        bos_token_id=50256,167        eos_token_id=50256,168        scale_attn_by_inverse_layer_idx=False,169        reorder_and_upcast_attn=False,170        attention_head_type=MULTI_HEAD,171        **kwargs,172    ):173        self.vocab_size = vocab_size174        self.n_positions = n_positions175        self.n_embd = n_embd176        self.n_layer = n_layer177        self.n_head = n_head178        self.n_inner = n_inner179        self.activation_function = activation_function180        self.resid_pdrop = resid_pdrop181        self.embd_pdrop = embd_pdrop182        self.attn_pdrop = attn_pdrop183        self.layer_norm_epsilon = layer_norm_epsilon184        self.initializer_range = initializer_range185        self.summary_type = summary_type186        self.summary_use_proj = summary_use_proj187        self.summary_activation = summary_activation188        self.summary_first_dropout = summary_first_dropout189        self.summary_proj_to_labels = summary_proj_to_labels190        self.scale_attn_weights = scale_attn_weights191        self.use_cache = use_cache192        self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx193        self.reorder_and_upcast_attn = reorder_and_upcast_attn194        self.attention_head_type = attention_head_type195        # assert attention_head_type in [AttentionType.MULTI_HEAD, AttentionType.MULTI_QUERY]196        assert attention_head_type in [MULTI_HEAD, MULTI_QUERY]197 198        self.bos_token_id = bos_token_id199        self.eos_token_id = eos_token_id200 201        super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)202