configuration_esm.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # coding=utf-8
  2. # 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 at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # 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 and
  14. # limitations under the License.
  15. """ESM model configuration"""
  16. from dataclasses import asdict, dataclass
  17. from typing import Optional
  18. from ...configuration_utils import PretrainedConfig
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. # TODO Update this
  22. class EsmConfig(PretrainedConfig):
  23. r"""
  24. This is the configuration class to store the configuration of a [`ESMModel`]. It is used to instantiate a ESM model
  25. according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  26. defaults will yield a similar configuration to that of the ESM
  27. [facebook/esm-1b](https://huggingface.co/facebook/esm-1b) architecture.
  28. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  29. documentation from [`PretrainedConfig`] for more information.
  30. Args:
  31. vocab_size (`int`, *optional*):
  32. Vocabulary size of the ESM model. Defines the number of different tokens that can be represented by the
  33. `inputs_ids` passed when calling [`ESMModel`].
  34. mask_token_id (`int`, *optional*):
  35. The index of the mask token in the vocabulary. This must be included in the config because of the
  36. "mask-dropout" scaling trick, which will scale the inputs depending on the number of masked tokens.
  37. pad_token_id (`int`, *optional*):
  38. The index of the padding token in the vocabulary. This must be included in the config because certain parts
  39. of the ESM code use this instead of the attention mask.
  40. hidden_size (`int`, *optional*, defaults to 768):
  41. Dimensionality of the encoder layers and the pooler layer.
  42. num_hidden_layers (`int`, *optional*, defaults to 12):
  43. Number of hidden layers in the Transformer encoder.
  44. num_attention_heads (`int`, *optional*, defaults to 12):
  45. Number of attention heads for each attention layer in the Transformer encoder.
  46. intermediate_size (`int`, *optional*, defaults to 3072):
  47. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  48. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  49. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  50. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  51. The dropout ratio for the attention probabilities.
  52. max_position_embeddings (`int`, *optional*, defaults to 1026):
  53. The maximum sequence length that this model might ever be used with. Typically set this to something large
  54. just in case (e.g., 512 or 1024 or 2048).
  55. initializer_range (`float`, *optional*, defaults to 0.02):
  56. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  57. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  58. The epsilon used by the layer normalization layers.
  59. position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
  60. Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query", "rotary"`.
  61. For positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
  62. [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
  63. For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
  64. with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
  65. is_decoder (`bool`, *optional*, defaults to `False`):
  66. Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
  67. use_cache (`bool`, *optional*, defaults to `True`):
  68. Whether or not the model should return the last key/values attentions (not used by all models). Only
  69. relevant if `config.is_decoder=True`.
  70. emb_layer_norm_before (`bool`, *optional*):
  71. Whether to apply layer normalization after embeddings but before the main stem of the network.
  72. token_dropout (`bool`, defaults to `False`):
  73. When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.
  74. Examples:
  75. ```python
  76. >>> from transformers import EsmModel, EsmConfig
  77. >>> # Initializing a ESM facebook/esm-1b style configuration
  78. >>> configuration = EsmConfig(vocab_size=33)
  79. >>> # Initializing a model from the configuration
  80. >>> model = EsmModel(configuration)
  81. >>> # Accessing the model configuration
  82. >>> configuration = model.config
  83. ```"""
  84. model_type = "esm"
  85. def __init__(
  86. self,
  87. vocab_size=None,
  88. mask_token_id=None,
  89. pad_token_id=None,
  90. hidden_size=768,
  91. num_hidden_layers=12,
  92. num_attention_heads=12,
  93. intermediate_size=3072,
  94. hidden_dropout_prob=0.1,
  95. attention_probs_dropout_prob=0.1,
  96. max_position_embeddings=1026,
  97. initializer_range=0.02,
  98. layer_norm_eps=1e-12,
  99. position_embedding_type="absolute",
  100. use_cache=True,
  101. emb_layer_norm_before=None,
  102. token_dropout=False,
  103. is_folding_model=False,
  104. esmfold_config=None,
  105. vocab_list=None,
  106. **kwargs,
  107. ):
  108. super().__init__(pad_token_id=pad_token_id, mask_token_id=mask_token_id, **kwargs)
  109. self.vocab_size = vocab_size
  110. self.hidden_size = hidden_size
  111. self.num_hidden_layers = num_hidden_layers
  112. self.num_attention_heads = num_attention_heads
  113. self.intermediate_size = intermediate_size
  114. self.hidden_dropout_prob = hidden_dropout_prob
  115. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  116. self.max_position_embeddings = max_position_embeddings
  117. self.initializer_range = initializer_range
  118. self.layer_norm_eps = layer_norm_eps
  119. self.position_embedding_type = position_embedding_type
  120. self.use_cache = use_cache
  121. self.emb_layer_norm_before = emb_layer_norm_before
  122. self.token_dropout = token_dropout
  123. self.is_folding_model = is_folding_model
  124. if is_folding_model:
  125. if esmfold_config is None:
  126. logger.info("No esmfold_config supplied for folding model, using default values.")
  127. esmfold_config = EsmFoldConfig()
  128. elif isinstance(esmfold_config, dict):
  129. esmfold_config = EsmFoldConfig(**esmfold_config)
  130. self.esmfold_config = esmfold_config
  131. if vocab_list is None:
  132. logger.warning("No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!")
  133. self.vocab_list = get_default_vocab_list()
  134. else:
  135. self.vocab_list = vocab_list
  136. else:
  137. self.esmfold_config = None
  138. self.vocab_list = None
  139. if self.esmfold_config is not None and getattr(self.esmfold_config, "use_esm_attn_map", False):
  140. raise ValueError("The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!")
  141. def to_dict(self):
  142. """
  143. Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
  144. Returns:
  145. `dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
  146. """
  147. output = super().to_dict()
  148. if isinstance(self.esmfold_config, EsmFoldConfig):
  149. output["esmfold_config"] = self.esmfold_config.to_dict()
  150. return output
  151. @dataclass
  152. class EsmFoldConfig:
  153. esm_type: Optional[str] = None
  154. fp16_esm: bool = True
  155. use_esm_attn_map: bool = False
  156. esm_ablate_pairwise: bool = False
  157. esm_ablate_sequence: bool = False
  158. esm_input_dropout: float = 0
  159. embed_aa: bool = True
  160. bypass_lm: bool = False
  161. lddt_head_hid_dim: int = 128
  162. trunk: "TrunkConfig" = None
  163. def __post_init__(self):
  164. if self.trunk is None:
  165. self.trunk = TrunkConfig()
  166. elif isinstance(self.trunk, dict):
  167. self.trunk = TrunkConfig(**self.trunk)
  168. def to_dict(self):
  169. """
  170. Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
  171. Returns:
  172. `dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
  173. """
  174. output = asdict(self)
  175. output["trunk"] = self.trunk.to_dict()
  176. return output
  177. @dataclass
  178. class TrunkConfig:
  179. num_blocks: int = 48
  180. sequence_state_dim: int = 1024
  181. pairwise_state_dim: int = 128
  182. sequence_head_width: int = 32
  183. pairwise_head_width: int = 32
  184. position_bins: int = 32
  185. dropout: float = 0
  186. layer_drop: float = 0
  187. cpu_grad_checkpoint: bool = False
  188. max_recycles: int = 4
  189. chunk_size: Optional[int] = 128
  190. structure_module: "StructureModuleConfig" = None
  191. def __post_init__(self):
  192. if self.structure_module is None:
  193. self.structure_module = StructureModuleConfig()
  194. elif isinstance(self.structure_module, dict):
  195. self.structure_module = StructureModuleConfig(**self.structure_module)
  196. if self.max_recycles <= 0:
  197. raise ValueError(f"`max_recycles` should be positive, got {self.max_recycles}.")
  198. if self.sequence_state_dim % self.sequence_state_dim != 0:
  199. raise ValueError(
  200. "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"
  201. f" {self.sequence_state_dim} and {self.sequence_state_dim}."
  202. )
  203. if self.pairwise_state_dim % self.pairwise_state_dim != 0:
  204. raise ValueError(
  205. "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"
  206. f" {self.pairwise_state_dim} and {self.pairwise_state_dim}."
  207. )
  208. sequence_num_heads = self.sequence_state_dim // self.sequence_head_width
  209. pairwise_num_heads = self.pairwise_state_dim // self.pairwise_head_width
  210. if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
  211. raise ValueError(
  212. "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"
  213. f" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}."
  214. )
  215. if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
  216. raise ValueError(
  217. "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"
  218. f" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}."
  219. )
  220. if self.pairwise_state_dim % 2 != 0:
  221. raise ValueError(f"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.")
  222. if self.dropout >= 0.4:
  223. raise ValueError(f"`dropout` should not be greater than 0.4, got {self.dropout}.")
  224. def to_dict(self):
  225. """
  226. Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
  227. Returns:
  228. `dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
  229. """
  230. output = asdict(self)
  231. output["structure_module"] = self.structure_module.to_dict()
  232. return output
  233. @dataclass
  234. class StructureModuleConfig:
  235. """
  236. Args:
  237. sequence_dim:
  238. Single representation channel dimension
  239. pairwise_dim:
  240. Pair representation channel dimension
  241. ipa_dim:
  242. IPA hidden channel dimension
  243. resnet_dim:
  244. Angle resnet (Alg. 23 lines 11-14) hidden channel dimension
  245. num_heads_ipa:
  246. Number of IPA heads
  247. num_qk_points:
  248. Number of query/key points to generate during IPA
  249. num_v_points:
  250. Number of value points to generate during IPA
  251. dropout_rate:
  252. Dropout rate used throughout the layer
  253. num_blocks:
  254. Number of structure module blocks
  255. num_transition_layers:
  256. Number of layers in the single representation transition (Alg. 23 lines 8-9)
  257. num_resnet_blocks:
  258. Number of blocks in the angle resnet
  259. num_angles:
  260. Number of angles to generate in the angle resnet
  261. trans_scale_factor:
  262. Scale of single representation transition hidden dimension
  263. epsilon:
  264. Small number used in angle resnet normalization
  265. inf:
  266. Large number used for attention masking
  267. """
  268. sequence_dim: int = 384
  269. pairwise_dim: int = 128
  270. ipa_dim: int = 16
  271. resnet_dim: int = 128
  272. num_heads_ipa: int = 12
  273. num_qk_points: int = 4
  274. num_v_points: int = 8
  275. dropout_rate: float = 0.1
  276. num_blocks: int = 8
  277. num_transition_layers: int = 1
  278. num_resnet_blocks: int = 2
  279. num_angles: int = 7
  280. trans_scale_factor: int = 10
  281. epsilon: float = 1e-8
  282. inf: float = 1e5
  283. def to_dict(self):
  284. return asdict(self)
  285. def get_default_vocab_list():
  286. return (
  287. "<cls>",
  288. "<pad>",
  289. "<eos>",
  290. "<unk>",
  291. "L",
  292. "A",
  293. "G",
  294. "V",
  295. "S",
  296. "E",
  297. "R",
  298. "T",
  299. "I",
  300. "D",
  301. "P",
  302. "K",
  303. "Q",
  304. "N",
  305. "F",
  306. "Y",
  307. "M",
  308. "H",
  309. "W",
  310. "C",
  311. "X",
  312. "B",
  313. "U",
  314. "Z",
  315. "O",
  316. ".",
  317. "-",
  318. "<null_1>",
  319. "<mask>",
  320. )
  321. __all__ = ["EsmConfig"]