configuration_blenderbot.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. # coding=utf-8
  2. # Copyright 2021 The Facebook, Inc. 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. """Blenderbot model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import Any, Optional
  19. from ... import PreTrainedTokenizer
  20. from ...configuration_utils import PretrainedConfig
  21. from ...file_utils import TensorType, is_torch_available
  22. from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeq2SeqConfigWithPast
  23. from ...onnx.utils import compute_effective_axis_dimension
  24. from ...utils import logging
  25. logger = logging.get_logger(__name__)
  26. class BlenderbotConfig(PretrainedConfig):
  27. r"""
  28. This is the configuration class to store the configuration of a [`BlenderbotModel`]. It is used to instantiate an
  29. Blenderbot model according to the specified arguments, defining the model architecture. Instantiating a
  30. configuration with the defaults will yield a similar configuration to that of the Blenderbot
  31. [facebook/blenderbot-3B](https://huggingface.co/facebook/blenderbot-3B) architecture.
  32. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  33. documentation from [`PretrainedConfig`] for more information.
  34. Args:
  35. vocab_size (`int`, *optional*, defaults to 50265):
  36. Vocabulary size of the Blenderbot model. Defines the number of different tokens that can be represented by
  37. the `inputs_ids` passed when calling [`BlenderbotModel`] or [`TFBlenderbotModel`].
  38. d_model (`int`, *optional*, defaults to 1024):
  39. Dimensionality of the layers and the pooler layer.
  40. encoder_layers (`int`, *optional*, defaults to 12):
  41. Number of encoder layers.
  42. decoder_layers (`int`, *optional*, defaults to 12):
  43. Number of decoder layers.
  44. encoder_attention_heads (`int`, *optional*, defaults to 16):
  45. Number of attention heads for each attention layer in the Transformer encoder.
  46. decoder_attention_heads (`int`, *optional*, defaults to 16):
  47. Number of attention heads for each attention layer in the Transformer decoder.
  48. decoder_ffn_dim (`int`, *optional*, defaults to 4096):
  49. Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
  50. encoder_ffn_dim (`int`, *optional*, defaults to 4096):
  51. Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
  52. activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
  53. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  54. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  55. dropout (`float`, *optional*, defaults to 0.1):
  56. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  57. attention_dropout (`float`, *optional*, defaults to 0.0):
  58. The dropout ratio for the attention probabilities.
  59. activation_dropout (`float`, *optional*, defaults to 0.0):
  60. The dropout ratio for activations inside the fully connected layer.
  61. max_position_embeddings (`int`, *optional*, defaults to 128):
  62. The maximum sequence length that this model might ever be used with. Typically set this to something large
  63. just in case (e.g., 512 or 1024 or 2048).
  64. init_std (`float`, *optional*, defaults to 0.02):
  65. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  66. encoder_layerdrop (`float`, *optional*, defaults to 0.0):
  67. The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
  68. for more details.
  69. decoder_layerdrop (`float`, *optional*, defaults to 0.0):
  70. The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
  71. for more details.
  72. scale_embedding (`bool`, *optional*, defaults to `False`):
  73. Scale embeddings by diving by sqrt(d_model).
  74. use_cache (`bool`, *optional*, defaults to `True`):
  75. Whether or not the model should return the last key/values attentions (not used by all models)
  76. forced_eos_token_id (`int`, *optional*, defaults to 2):
  77. The id of the token to force as the last generated token when `max_length` is reached. Usually set to
  78. `eos_token_id`.
  79. Example:
  80. ```python
  81. >>> from transformers import BlenderbotConfig, BlenderbotModel
  82. >>> # Initializing a Blenderbot facebook/blenderbot-3B style configuration
  83. >>> configuration = BlenderbotConfig()
  84. >>> # Initializing a model (with random weights) from the facebook/blenderbot-3B style configuration
  85. >>> model = BlenderbotModel(configuration)
  86. >>> # Accessing the model configuration
  87. >>> configuration = model.config
  88. ```"""
  89. model_type = "blenderbot"
  90. keys_to_ignore_at_inference = ["past_key_values"]
  91. attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
  92. def __init__(
  93. self,
  94. vocab_size=8008,
  95. max_position_embeddings=128,
  96. encoder_layers=2,
  97. encoder_ffn_dim=10240,
  98. encoder_attention_heads=32,
  99. decoder_layers=24,
  100. decoder_ffn_dim=10240,
  101. decoder_attention_heads=32,
  102. encoder_layerdrop=0.0,
  103. decoder_layerdrop=0.0,
  104. use_cache=True,
  105. is_encoder_decoder=True,
  106. activation_function="gelu",
  107. d_model=2560,
  108. dropout=0.1,
  109. attention_dropout=0.0,
  110. activation_dropout=0.0,
  111. init_std=0.02,
  112. decoder_start_token_id=1,
  113. scale_embedding=False,
  114. pad_token_id=0,
  115. bos_token_id=1,
  116. eos_token_id=2,
  117. encoder_no_repeat_ngram_size=3,
  118. forced_eos_token_id=2,
  119. **kwargs,
  120. ):
  121. self.vocab_size = vocab_size
  122. self.max_position_embeddings = max_position_embeddings
  123. self.d_model = d_model
  124. self.encoder_ffn_dim = encoder_ffn_dim
  125. self.encoder_layers = encoder_layers
  126. self.encoder_attention_heads = encoder_attention_heads
  127. self.decoder_ffn_dim = decoder_ffn_dim
  128. self.decoder_layers = decoder_layers
  129. self.decoder_attention_heads = decoder_attention_heads
  130. self.dropout = dropout
  131. self.attention_dropout = attention_dropout
  132. self.activation_dropout = activation_dropout
  133. self.activation_function = activation_function
  134. self.init_std = init_std
  135. self.encoder_layerdrop = encoder_layerdrop
  136. self.decoder_layerdrop = decoder_layerdrop
  137. self.use_cache = use_cache
  138. self.num_hidden_layers = encoder_layers
  139. self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
  140. super().__init__(
  141. pad_token_id=pad_token_id,
  142. bos_token_id=bos_token_id,
  143. eos_token_id=eos_token_id,
  144. is_encoder_decoder=is_encoder_decoder,
  145. decoder_start_token_id=decoder_start_token_id,
  146. encoder_no_repeat_ngram_size=encoder_no_repeat_ngram_size,
  147. forced_eos_token_id=forced_eos_token_id,
  148. **kwargs,
  149. )
  150. class BlenderbotOnnxConfig(OnnxSeq2SeqConfigWithPast):
  151. @property
  152. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  153. if self.task in ["default", "seq2seq-lm"]:
  154. common_inputs = OrderedDict(
  155. [
  156. ("input_ids", {0: "batch", 1: "encoder_sequence"}),
  157. ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
  158. ]
  159. )
  160. if self.use_past:
  161. common_inputs["decoder_input_ids"] = {0: "batch"}
  162. common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
  163. else:
  164. common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
  165. common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
  166. if self.use_past:
  167. self.fill_with_past_key_values_(common_inputs, direction="inputs")
  168. elif self.task == "causal-lm":
  169. common_inputs = OrderedDict(
  170. [
  171. ("input_ids", {0: "batch", 1: "encoder_sequence"}),
  172. ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
  173. ]
  174. )
  175. if self.use_past:
  176. _, num_decoder_layers = self.num_layers
  177. for i in range(num_decoder_layers):
  178. common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
  179. common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
  180. else:
  181. common_inputs = OrderedDict(
  182. [
  183. ("input_ids", {0: "batch", 1: "encoder_sequence"}),
  184. ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
  185. ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
  186. ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
  187. ]
  188. )
  189. return common_inputs
  190. @property
  191. # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
  192. def outputs(self) -> Mapping[str, Mapping[int, str]]:
  193. if self.task in ["default", "seq2seq-lm"]:
  194. common_outputs = super().outputs
  195. else:
  196. common_outputs = super(OnnxConfigWithPast, self).outputs
  197. if self.use_past:
  198. num_encoder_layers, _ = self.num_layers
  199. for i in range(num_encoder_layers):
  200. common_outputs[f"present.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
  201. common_outputs[f"present.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
  202. return common_outputs
  203. def _generate_dummy_inputs_for_default_and_seq2seq_lm(
  204. self,
  205. tokenizer: PreTrainedTokenizer,
  206. batch_size: int = -1,
  207. seq_length: int = -1,
  208. is_pair: bool = False,
  209. framework: Optional[TensorType] = None,
  210. ) -> Mapping[str, Any]:
  211. encoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
  212. tokenizer, batch_size, seq_length, is_pair, framework
  213. )
  214. # Generate decoder inputs
  215. decoder_seq_length = seq_length if not self.use_past else 1
  216. decoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
  217. tokenizer, batch_size, decoder_seq_length, is_pair, framework
  218. )
  219. decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
  220. common_inputs = dict(**encoder_inputs, **decoder_inputs)
  221. if self.use_past:
  222. if not is_torch_available():
  223. raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
  224. else:
  225. import torch
  226. batch, encoder_seq_length = common_inputs["input_ids"].shape
  227. decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
  228. num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
  229. encoder_shape = (
  230. batch,
  231. num_encoder_attention_heads,
  232. encoder_seq_length,
  233. self._config.hidden_size // num_encoder_attention_heads,
  234. )
  235. decoder_past_length = decoder_seq_length
  236. decoder_shape = (
  237. batch,
  238. num_decoder_attention_heads,
  239. decoder_past_length,
  240. self._config.hidden_size // num_decoder_attention_heads,
  241. )
  242. common_inputs["decoder_attention_mask"] = torch.cat(
  243. [common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
  244. )
  245. common_inputs["past_key_values"] = []
  246. _, num_decoder_layers = self.num_layers
  247. for _ in range(num_decoder_layers):
  248. common_inputs["past_key_values"].append(
  249. (
  250. torch.zeros(decoder_shape),
  251. torch.zeros(decoder_shape),
  252. torch.zeros(encoder_shape),
  253. torch.zeros(encoder_shape),
  254. )
  255. )
  256. return common_inputs
  257. def _generate_dummy_inputs_for_causal_lm(
  258. self,
  259. tokenizer: PreTrainedTokenizer,
  260. batch_size: int = -1,
  261. seq_length: int = -1,
  262. is_pair: bool = False,
  263. framework: Optional[TensorType] = None,
  264. ) -> Mapping[str, Any]:
  265. common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
  266. tokenizer, batch_size, seq_length, is_pair, framework
  267. )
  268. if self.use_past:
  269. if not is_torch_available():
  270. raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
  271. else:
  272. import torch
  273. batch, seqlen = common_inputs["input_ids"].shape
  274. past_key_values_length = seqlen
  275. _, num_decoder_layers = self.num_layers
  276. num_encoder_attention_heads, _ = self.num_attention_heads
  277. past_shape = (
  278. batch,
  279. num_encoder_attention_heads,
  280. past_key_values_length,
  281. self._config.hidden_size // num_encoder_attention_heads,
  282. )
  283. mask_dtype = common_inputs["attention_mask"].dtype
  284. common_inputs["attention_mask"] = torch.cat(
  285. [common_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
  286. )
  287. common_inputs["past_key_values"] = [
  288. (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(num_decoder_layers)
  289. ]
  290. return common_inputs
  291. # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig._generate_dummy_inputs_for_sequence_classification_and_question_answering
  292. def _generate_dummy_inputs_for_sequence_classification_and_question_answering(
  293. self,
  294. tokenizer: PreTrainedTokenizer,
  295. batch_size: int = -1,
  296. seq_length: int = -1,
  297. is_pair: bool = False,
  298. framework: Optional[TensorType] = None,
  299. ) -> Mapping[str, Any]:
  300. # Copied from OnnxConfig.generate_dummy_inputs
  301. # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
  302. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
  303. batch_size = compute_effective_axis_dimension(
  304. batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
  305. )
  306. # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
  307. token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
  308. seq_length = compute_effective_axis_dimension(
  309. seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
  310. )
  311. # Generate dummy inputs according to compute batch and sequence
  312. dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
  313. common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
  314. return common_inputs
  315. # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.generate_dummy_inputs
  316. def generate_dummy_inputs(
  317. self,
  318. tokenizer: PreTrainedTokenizer,
  319. batch_size: int = -1,
  320. seq_length: int = -1,
  321. is_pair: bool = False,
  322. framework: Optional[TensorType] = None,
  323. ) -> Mapping[str, Any]:
  324. if self.task in ["default", "seq2seq-lm"]:
  325. common_inputs = self._generate_dummy_inputs_for_default_and_seq2seq_lm(
  326. tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
  327. )
  328. elif self.task == "causal-lm":
  329. common_inputs = self._generate_dummy_inputs_for_causal_lm(
  330. tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
  331. )
  332. else:
  333. common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
  334. tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
  335. )
  336. return common_inputs
  337. # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig._flatten_past_key_values_
  338. def _flatten_past_key_values_(self, flattened_output, name, idx, t):
  339. if self.task in ["default", "seq2seq-lm"]:
  340. flattened_output = super()._flatten_past_key_values_(flattened_output, name, idx, t)
  341. else:
  342. flattened_output = super(OnnxSeq2SeqConfigWithPast, self)._flatten_past_key_values_(
  343. flattened_output, name, idx, t
  344. )
  345. def fill_with_past_key_values_(self, inputs_or_outputs: Mapping[str, Mapping[int, str]], direction: str):
  346. if direction not in ["inputs", "outputs"]:
  347. raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given')
  348. name = "past_key_values" if direction == "inputs" else "present"
  349. _, num_decoder_layers = self.num_layers
  350. encoder_sequence = "past_encoder_sequence"
  351. decoder_sequence = "past_decoder_sequence" if direction == "inputs" else "past_decoder_sequence + sequence"
  352. for i in range(num_decoder_layers):
  353. inputs_or_outputs[f"{name}.{i}.decoder.key"] = {0: "batch", 2: decoder_sequence}
  354. inputs_or_outputs[f"{name}.{i}.decoder.value"] = {0: "batch", 2: decoder_sequence}
  355. inputs_or_outputs[f"{name}.{i}.encoder.key"] = {0: "batch", 2: encoder_sequence}
  356. inputs_or_outputs[f"{name}.{i}.encoder.value"] = {0: "batch", 2: encoder_sequence}
  357. __all__ = ["BlenderbotConfig", "BlenderbotOnnxConfig"]