CoolFace
Modelpublic

InstaDeepAI/segment_nt

sourceHugging Facecc-by-nc-sa-4.0updated 9mo agoView on Hugging Face
9likes211downloads
segment_nt_config.py262 linesDownload Raw Back to root
1# coding=utf-82# Copyright 2022 Meta 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""" ESM model configuration"""16 17from dataclasses import asdict, dataclass18from typing import List, Optional19 20from transformers import PretrainedConfig, logging21 22logger = logging.get_logger(__name__)23 24# TODO Update this25ESM_PRETRAINED_CONFIG_ARCHIVE_MAP = {26    "facebook/esm-1b": "https://huggingface.co/facebook/esm-1b/resolve/main/config.json",27    # See all ESM models at https://huggingface.co/models?filter=esm28}29 30 31class SegmentNTConfig(PretrainedConfig):32    r"""33    This is the configuration class to store the configuration of a [`ESMModel`]. It is used to instantiate a ESM model34    according to the specified arguments, defining the model architecture. Instantiating a configuration with the35    defaults will yield a similar configuration to that of the ESM36    [facebook/esm-1b](https://huggingface.co/facebook/esm-1b) architecture.37 38    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the39    documentation from [`PretrainedConfig`] for more information.40 41 42    Args:43        vocab_size (`int`, *optional*):44            Vocabulary size of the ESM model. Defines the number of different tokens that can be represented by the45            `inputs_ids` passed when calling [`ESMModel`].46        mask_token_id (`int`, *optional*):47            The index of the mask token in the vocabulary. This must be included in the config because of the48            "mask-dropout" scaling trick, which will scale the inputs depending on the number of masked tokens.49        pad_token_id (`int`, *optional*):50            The index of the padding token in the vocabulary. This must be included in the config because certain parts51            of the ESM code use this instead of the attention mask.52        hidden_size (`int`, *optional*, defaults to 768):53            Dimensionality of the encoder layers and the pooler layer.54        num_hidden_layers (`int`, *optional*, defaults to 12):55            Number of hidden layers in the Transformer encoder.56        num_attention_heads (`int`, *optional*, defaults to 12):57            Number of attention heads for each attention layer in the Transformer encoder.58        intermediate_size (`int`, *optional*, defaults to 3072):59            Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.60        hidden_dropout_prob (`float`, *optional*, defaults to 0.1):61            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.62        attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):63            The dropout ratio for the attention probabilities.64        max_position_embeddings (`int`, *optional*, defaults to 1026):65            The maximum sequence length that this model might ever be used with. Typically set this to something large66            just in case (e.g., 512 or 1024 or 2048).67        initializer_range (`float`, *optional*, defaults to 0.02):68            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.69        layer_norm_eps (`float`, *optional*, defaults to 1e-12):70            The epsilon used by the layer normalization layers.71        position_embedding_type (`str`, *optional*, defaults to `"absolute"`):72            Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query", "rotary"`.73            For positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to74            [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).75            For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models76            with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).77        is_decoder (`bool`, *optional*, defaults to `False`):78            Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.79        use_cache (`bool`, *optional*, defaults to `True`):80            Whether or not the model should return the last key/values attentions (not used by all models). Only81            relevant if `config.is_decoder=True`.82        emb_layer_norm_before (`bool`, *optional*):83            Whether to apply layer normalization after embeddings but before the main stem of the network.84        token_dropout (`bool`, defaults to `False`):85            When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.86 87    Examples:88 89    ```python90    >>> from transformers import EsmModel, EsmConfig91 92    >>> # Initializing a ESM facebook/esm-1b style configuration >>> configuration = EsmConfig()93 94    >>> # Initializing a model from the configuration >>> model = ESMModel(configuration)95 96    >>> # Accessing the model configuration >>> configuration = model.config97    ```"""98    model_type = "esm"99 100    def __init__(101        self,102        features=None,103        vocab_size=None,104        mask_token_id=None,105        pad_token_id=None,106        hidden_size=768,107        num_hidden_layers=12,108        num_attention_heads=12,109        intermediate_size=3072,110        hidden_dropout_prob=0.1,111        attention_probs_dropout_prob=0.1,112        max_position_embeddings=1026,113        initializer_range=0.02,114        layer_norm_eps=1e-12,115        position_embedding_type="absolute",116        use_cache=True,117        emb_layer_norm_before=None,118        token_dropout=False,119        is_folding_model=False,120        esmfold_config=None,121        vocab_list=None,122        add_bias_fnn=True,123        rescaling_factor=None,124        num_layers_head=2,125        **kwargs,126    ):127        super().__init__(128            pad_token_id=pad_token_id, mask_token_id=mask_token_id, **kwargs129        )130 131        self.vocab_size = vocab_size132        self.hidden_size = hidden_size133        self.num_hidden_layers = num_hidden_layers134        self.num_attention_heads = num_attention_heads135        self.intermediate_size = intermediate_size136        self.hidden_dropout_prob = hidden_dropout_prob137        self.attention_probs_dropout_prob = attention_probs_dropout_prob138        self.max_position_embeddings = max_position_embeddings139        self.initializer_range = initializer_range140        self.layer_norm_eps = layer_norm_eps141        self.position_embedding_type = position_embedding_type142        self.use_cache = use_cache143        self.emb_layer_norm_before = emb_layer_norm_before144        self.token_dropout = token_dropout145        self.is_folding_model = is_folding_model146        # Arguments needed for dcnuc v2147        self.add_bias_fnn = add_bias_fnn148        # Arguments needed for Segment NT149        self.num_layers_head = num_layers_head150        self.features = features151        self.rescaling_factor = rescaling_factor152        if is_folding_model:153            if esmfold_config is None:154                logger.info(155                    "No esmfold_config supplied for folding model, using default values."156                )157                esmfold_config = EsmFoldConfig()158            elif isinstance(esmfold_config, dict):159                esmfold_config = EsmFoldConfig(**esmfold_config)160            self.esmfold_config = esmfold_config161            if vocab_list is None:162                logger.warning(163                    "No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!"164                )165                self.vocab_list = get_default_vocab_list()166            else:167                self.vocab_list = vocab_list168        else:169            self.esmfold_config = None170            self.vocab_list = None171        if self.esmfold_config is not None and getattr(172            self.esmfold_config, "use_esm_attn_map", False173        ):174            raise ValueError(175                "The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!"176            )177 178    def to_dict(self):179        """180        Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].181 182        Returns:183            `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,184        """185        output = super().to_dict()186        if isinstance(self.esmfold_config, EsmFoldConfig):187            output["esmfold_config"] = self.esmfold_config.to_dict()188        return output189 190 191@dataclass192class EsmFoldConfig:193    esm_type: str = None194    fp16_esm: bool = True195    use_esm_attn_map: bool = False196    esm_ablate_pairwise: bool = False197    esm_ablate_sequence: bool = False198    esm_input_dropout: float = 0199 200    embed_aa: bool = True201    bypass_lm: bool = False202 203    lddt_head_hid_dim: int = 128204    trunk: "TrunkConfig" = None205 206    def __post_init__(self):207        if self.trunk is None:208            self.trunk = TrunkConfig()209        elif isinstance(self.trunk, dict):210            self.trunk = TrunkConfig(**self.trunk)211 212    def to_dict(self):213        """214        Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].215 216        Returns:217            `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,218        """219        output = asdict(self)220        output["trunk"] = self.trunk.to_dict()221        return output222 223 224 225 226def get_default_vocab_list():227    return (228        "<cls>",229        "<pad>",230        "<eos>",231        "<unk>",232        "L",233        "A",234        "G",235        "V",236        "S",237        "E",238        "R",239        "T",240        "I",241        "D",242        "P",243        "K",244        "Q",245        "N",246        "F",247        "Y",248        "M",249        "H",250        "W",251        "C",252        "X",253        "B",254        "U",255        "Z",256        "O",257        ".",258        "-",259        "<null_1>",260        "<mask>",261    )262