codingutf8 2021 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license gpt neo model configuration from collections import ordereddict from typing import any mapping optional from import pretrainedtokenizer tensortype istorchavailable from configurationutils import pretrainedconfig from onnx import onnxconfigwithpast from utils import logging logger logging getloggername gptneopretrainedconfigarchivemap eleutheraigptneo1 3b https huggingface coeleutheraigptneo1 3bresolvemainconfig json see all gptneo models at https huggingface comodels filtergptneo class gptneoconfigpretrainedconfig r this is the configuration class to store the configuration of a gptneomodel it is used to instantiate a gpt neo model according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the gptneo eleutheraigptneo1 3bhttps huggingface coeleutheraigptneo1 3b architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args vocabsize int optional defaults to 50257 vocabulary size of the gpt neo model defines the number of different tokens that can be represented by the inputsids passed when calling gptneomodel vocabulary size of the model defines the different tokens that can be represented by the inputsids passed to the forward method of gptneomodel maxpositionembeddings int optional defaults to 2048 the maximum sequence length that this model might ever be used with typically set this to something large just in case e g 512 or 1024 or 2048 hiddensize int optional defaults to 2048 dimensionality of the encoder layers and the pooler layer numlayers int optional defaults to 24 number of hidden layers in the transformer encoder attentiontypes list optional defaults to global local 12 the type of attention for each layer in a list of the following format attentiontype numlayerss e g for a 24 layer model global 24 or global local 12 choose the value of attentiontype from global local numheads int optional defaults to 16 number of attention heads for each attention layer in the transformer encoder intermediatesize int optional defaults to 8192 dimensionality of the intermediate i e feedforward layer in the transformer encoder windowsize int optional defaults to 256 the size of the sliding window for local attention activationfunction str or function optional defaults to gelunew the nonlinear activation function function or string in the encoder and pooler if string gelu relu selu and gelunew are supported residdropout float optional defaults to 0 0 residual dropout used in the attention pattern embeddropout float optional defaults to 0 0 the dropout probabilitiy for all fully connected layers in the embeddings encoder and pooler attentiondropout float optional defaults to 0 0 the dropout ratio for the attention probabilities classifierdropout float optional defaults to 0 1 argument used when doing token classification used in the model gptneofortokenclassification the dropout ratio for the hidden layer layernormepsilon float optional defaults to 1e05 the epsilon used by the layer normalization layers initializerrange float optional defaults to 0 02 the standard deviation of the truncatednormalinitializer for initializing all weight matrices usecache bool optional defaults to true whether or not the model should return the last keyvalues attentions not used by all models only relevant if config isdecodertrue bostokenid int optional defaults to 50256 the id of the beginning of sentence token in the vocabulary eostokenid int optional defaults to 50256 the id of the end of sentence token in the vocabulary example python from transformers import gptneoconfig gptneomodel initializing a gptneo eleutheraigptneo1 3b style configuration configuration gptneoconfig initializing a model with random weights from the eleutheraigptneo1 3b style configuration model gptneomodelconfiguration accessing the model configuration configuration model config modeltype gptneo keystoignoreatinference pastkeyvalues attributemap numattentionheads numheads numhiddenlayers numlayers def init self vocabsize50257 maxpositionembeddings2048 hiddensize2048 numlayers24 attentiontypesglobal local 12 numheads16 intermediatesizenone windowsize256 activationfunctiongelunew residdropout0 0 embeddropout0 0 attentiondropout0 0 classifierdropout0 1 layernormepsilon1e5 initializerrange0 02 usecachetrue bostokenid50256 eostokenid50256 kwargs self vocabsize vocabsize self maxpositionembeddings maxpositionembeddings self hiddensize hiddensize self numlayers numlayers self numheads numheads self intermediatesize intermediatesize self windowsize windowsize self activationfunction activationfunction self residdropout residdropout self embeddropout embeddropout self attentiondropout attentiondropout self classifierdropout classifierdropout self layernormepsilon layernormepsilon self initializerrange initializerrange self usecache usecache self bostokenid bostokenid self eostokenid eostokenid self attentiontypes attentiontypes self attentionlayers self expandattentiontypesparamsattentiontypes if lenself attentionlayers self numlayers raise valueerror configuration for convolutional module is incorrect it is required that lenconfig attentionlayers config numlayers fbut is lenconfig attentionlayers lenself attentionlayers fconfig numlayers self numlayers config attentionlayers is prepared using config attentiontypes please verify the value of config attentiontypes argument super initbostokenidbostokenid eostokenideostokenid kwargs staticmethod def expandattentiontypesparamsattentiontypes attentions for item in attentiontypes for in rangeitem1 attentions extenditem0 return attentions def customunfoldinput dimension size step custom implementation for gptneoattentionmixin getblocklengthandnumblocks to enable the export to onnx as original implementation uses python variables and control flow we need to order the input in the way they appears in the forward need to add the pastkeys not using the same length for pastkeyvalues coding utf 8 2021 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license gpt neo model configuration see all gptneo models at https huggingface co models filter gpt_neo this is the configuration class to store the configuration of a gptneomodel it is used to instantiate a gpt neo model according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the gptneo eleutherai gpt neo 1 3b https huggingface co eleutherai gpt neo 1 3b architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args vocab_size int optional defaults to 50257 vocabulary size of the gpt neo model defines the number of different tokens that can be represented by the inputs_ids passed when calling gptneomodel vocabulary size of the model defines the different tokens that can be represented by the inputs_ids passed to the forward method of gptneomodel max_position_embeddings int optional defaults to 2048 the maximum sequence length that this model might ever be used with typically set this to something large just in case e g 512 or 1024 or 2048 hidden_size int optional defaults to 2048 dimensionality of the encoder layers and the pooler layer num_layers int optional defaults to 24 number of hidden layers in the transformer encoder attention_types list optional defaults to global local 12 the type of attention for each layer in a list of the following format attention_type num_layerss e g for a 24 layer model global 24 or global local 12 choose the value of attention_type from global local num_heads int optional defaults to 16 number of attention heads for each attention layer in the transformer encoder intermediate_size int optional defaults to 8192 dimensionality of the intermediate i e feed forward layer in the transformer encoder window_size int optional defaults to 256 the size of the sliding window for local attention activation_function str or function optional defaults to gelu_new the non linear activation function function or string in the encoder and pooler if string gelu relu selu and gelu_new are supported resid_dropout float optional defaults to 0 0 residual dropout used in the attention pattern embed_dropout float optional defaults to 0 0 the dropout probabilitiy for all fully connected layers in the embeddings encoder and pooler attention_dropout float optional defaults to 0 0 the dropout ratio for the attention probabilities classifier_dropout float optional defaults to 0 1 argument used when doing token classification used in the model gptneofortokenclassification the dropout ratio for the hidden layer layer_norm_epsilon float optional defaults to 1e 05 the epsilon used by the layer normalization layers initializer_range float optional defaults to 0 02 the standard deviation of the truncated_normal_initializer for initializing all weight matrices use_cache bool optional defaults to true whether or not the model should return the last key values attentions not used by all models only relevant if config is_decoder true bos_token_id int optional defaults to 50256 the id of the beginning of sentence token in the vocabulary eos_token_id int optional defaults to 50256 the id of the end of sentence token in the vocabulary example python from transformers import gptneoconfig gptneomodel initializing a gptneo eleutherai gpt neo 1 3b style configuration configuration gptneoconfig initializing a model with random weights from the eleutherai gpt neo 1 3b style configuration model gptneomodel configuration accessing the model configuration configuration model config custom torch tensor unfold implementation to enable the export to onnx custom implementation for gptneoattentionmixin _get_block_length_and_num_blocks to enable the export to onnx as original implementation uses python variables and control flow we need to order the input in the way they appears in the forward need to add the past_keys not using the same length for past_key_values
from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging


logger = logging.get_logger(__name__)

GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "EleutherAI/gpt-neo-1.3B": "https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json",
    
}


class GPTNeoConfig(PretrainedConfig):
    r

    model_type = "gpt_neo"
    keys_to_ignore_at_inference = ["past_key_values"]
    attribute_map = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}

    def __init__(
        self,
        vocab_size=50257,
        max_position_embeddings=2048,
        hidden_size=2048,
        num_layers=24,
        attention_types=[[["global", "local"], 12]],
        num_heads=16,
        intermediate_size=None,
        window_size=256,
        activation_function="gelu_new",
        resid_dropout=0.0,
        embed_dropout=0.0,
        attention_dropout=0.0,
        classifier_dropout=0.1,
        layer_norm_epsilon=1e-5,
        initializer_range=0.02,
        use_cache=True,
        bos_token_id=50256,
        eos_token_id=50256,
        **kwargs,
    ):
        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.num_heads = num_heads
        self.intermediate_size = intermediate_size
        self.window_size = window_size
        self.activation_function = activation_function
        self.resid_dropout = resid_dropout
        self.embed_dropout = embed_dropout
        self.attention_dropout = attention_dropout
        self.classifier_dropout = classifier_dropout
        self.layer_norm_epsilon = layer_norm_epsilon
        self.initializer_range = initializer_range
        self.use_cache = use_cache

        self.bos_token_id = bos_token_id
        self.eos_token_id = eos_token_id

        self.attention_types = attention_types
        self.attention_layers = self.expand_attention_types_params(attention_types)

        if len(self.attention_layers) != self.num_layers:
            raise ValueError(
                "Configuration for convolutional module is incorrect. "
                "It is required that `len(config.attention_layers)` == `config.num_layers` "
                f"but is `len(config.attention_layers) = {len(self.attention_layers)}`, "
                f"`config.num_layers = {self.num_layers}`. "
                "`config.attention_layers` is prepared using `config.attention_types`. "
                "Please verify the value of `config.attention_types` argument."
            )

        super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)

    @staticmethod
    def expand_attention_types_params(attention_types):
        attentions = []
        for item in attention_types:
            for _ in range(item[1]):
                attentions.extend(item[0])
        return attentions


def custom_unfold(input, dimension, size, step):
    
    import torch

    shape = input.size()
    rank = len(shape)
    sizedim = shape[dimension]

    low_indices = torch.arange(0, sizedim, step)
    min_length = torch.div(sizedim - size, step, rounding_mode="floor") + 1
    indices = torch.arange(size) + low_indices[:min_length][:, None]

    s = [slice(None)] * rank
    s[dimension] = indices
    sliced = input[s]

    perm = list(range(0, rank + 1))
    perm.append(perm.pop(dimension + 1))

    return sliced.permute(perm)


def custom_get_block_length_and_num_blocks(seq_length, window_size):
    
    import torch

    candidates = torch.arange(1, window_size)
    remainders = torch.remainder(seq_length, candidates)
    divisor_indices = remainders == 0
    divisors = candidates[divisor_indices]
    largest_divisor = torch.max(divisors)
    return largest_divisor, torch.div(seq_length, largest_divisor, rounding_mode="floor")


class GPTNeoOnnxConfig(OnnxConfigWithPast):
    @property
    def inputs(self) -> Mapping[str, Mapping[int, str]]:
        common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
        if self.use_past:
            self.fill_with_past_key_values_(common_inputs, direction="inputs")
            common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
        else:
            common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}

        return common_inputs

    @property
    def num_attention_heads(self) -> int:
        return self._config.num_heads

    def generate_dummy_inputs(
        self,
        tokenizer: PreTrainedTokenizer,
        batch_size: int = -1,
        seq_length: int = -1,
        is_pair: bool = False,
        framework: Optional[TensorType] = None,
    ) -> Mapping[str, Any]:
        common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
            tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
        )

        
        ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})

        
        if self.use_past:
            if not is_torch_available():
                raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
            else:
                import torch

                batch, seqlen = common_inputs["input_ids"].shape
                
                past_key_values_length = seqlen + 2
                past_shape = (
                    batch,
                    self.num_attention_heads,
                    past_key_values_length,
                    self._config.hidden_size // self.num_attention_heads,
                )
                ordered_inputs["past_key_values"] = [
                    (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
                ]

        ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
        if self.use_past:
            mask_dtype = ordered_inputs["attention_mask"].dtype
            ordered_inputs["attention_mask"] = torch.cat(
                [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
            )

        return ordered_inputs

    @property
    def default_onnx_opset(self) -> int:
        return 13