configuration_whisper.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. # coding=utf-8
  2. # Copyright 2022 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. """Whisper model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import TYPE_CHECKING, Any, Optional, Union
  19. from ...configuration_utils import PretrainedConfig
  20. from ...onnx import OnnxConfig, OnnxSeq2SeqConfigWithPast
  21. from ...utils import logging
  22. if TYPE_CHECKING:
  23. from ...feature_extraction_utils import FeatureExtractionMixin
  24. from ...tokenization_utils_base import PreTrainedTokenizerBase
  25. from ...utils import TensorType
  26. logger = logging.get_logger(__name__)
  27. # fmt: off
  28. NON_SPEECH_TOKENS = [
  29. 1, 2, 7, 8, 9, 10, 14, 25,
  30. 26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
  31. 63, 90, 91, 92, 93, 357, 366, 438, 532, 685,
  32. 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377,
  33. 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211,
  34. 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786,
  35. 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791,
  36. 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409,
  37. 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361
  38. ]
  39. NON_SPEECH_TOKENS_MULTI = [
  40. 1, 2, 7, 8, 9, 10, 14, 25,
  41. 26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
  42. 63, 90, 91, 92, 93, 359, 503, 522, 542, 873,
  43. 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627,
  44. 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647,
  45. 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793,
  46. 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675,
  47. 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865,
  48. 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362
  49. ]
  50. # fmt: on
  51. class WhisperConfig(PretrainedConfig):
  52. r"""
  53. This is the configuration class to store the configuration of a [`WhisperModel`]. It is used to instantiate a
  54. Whisper model according to the specified arguments, defining the model architecture. Instantiating a configuration
  55. with the defaults will yield a similar configuration to that of the Whisper
  56. [openai/whisper-tiny](https://huggingface.co/openai/whisper-tiny) architecture.
  57. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  58. documentation from [`PretrainedConfig`] for more information.
  59. Args:
  60. vocab_size (`int`, *optional*, defaults to 51865):
  61. Vocabulary size of the Whisper model. Defines the number of different tokens that can be represented by the
  62. `decoder_input_ids` passed when calling [`WhisperModel`]
  63. num_mel_bins (`int`, *optional*, defaults to 80):
  64. Number of mel features used per input features. Should correspond to the value used in the
  65. `WhisperProcessor` class.
  66. encoder_layers (`int`, *optional*, defaults to 4):
  67. Number of encoder layers.
  68. decoder_layers (`int`, *optional*, defaults to 4):
  69. Number of decoder layers.
  70. encoder_attention_heads (`int`, *optional*, defaults to 6):
  71. Number of attention heads for each attention layer in the Transformer encoder.
  72. decoder_attention_heads (`int`, *optional*, defaults to 6):
  73. Number of attention heads for each attention layer in the Transformer decoder.
  74. encoder_ffn_dim (`int`, *optional*, defaults to 1536):
  75. Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
  76. decoder_ffn_dim (`int`, *optional*, defaults to 1536):
  77. Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
  78. encoder_layerdrop (`float`, *optional*, defaults to 0.0):
  79. The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
  80. for more details.
  81. decoder_layerdrop (`float`, *optional*, defaults to 0.0):
  82. The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
  83. for more details.
  84. decoder_start_token_id (`int`, *optional*, defaults to 50257):
  85. Corresponds to the "<|startoftranscript|>" token, which is automatically used when no `decoder_input_ids`
  86. are provided to the `generate` function. It is used to guide the model`s generation process depending on
  87. the task.
  88. use_cache (`bool`, *optional*, defaults to `True`):
  89. Whether or not the model should return the last key/values attentions (not used by all models).
  90. is_encoder_decoder (`bool`, *optional*, defaults to `True`):
  91. Whether the model is used as an encoder/decoder or not.
  92. activation_function (`str`, *optional*, defaults to `"gelu"`):
  93. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  94. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  95. d_model (`int`, *optional*, defaults to 384):
  96. Dimensionality of the layers.
  97. dropout (`float`, *optional*, defaults to 0.1):
  98. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  99. attention_dropout (`float`, *optional*, defaults to 0.0):
  100. The dropout ratio for the attention probabilities.
  101. activation_dropout (`float`, *optional*, defaults to 0.0):
  102. The dropout ratio for activations inside the fully connected layer.
  103. init_std (`float`, *optional*, defaults to 0.02):
  104. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  105. scale_embedding (`bool`, *optional*, defaults to False):
  106. Scale embeddings by diving by sqrt(d_model).
  107. max_source_positions (`int`, *optional*, defaults to 1500):
  108. The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
  109. max_target_positions (`int`, *optional*, defaults to 448):
  110. The maximum sequence length that this model might ever be used with. Typically set this to something large
  111. just in case (e.g., 512 or 1024 or 2048).
  112. pad_token_id (`int`, *optional*, defaults to 50256):
  113. Padding token id.
  114. bos_token_id (`int`, *optional*, defaults to 50256):
  115. Begin of stream token id.
  116. eos_token_id (`int`, *optional*, defaults to 50256):
  117. End of stream token id.
  118. suppress_tokens (`list[int]`, *optional*):
  119. A list containing the non-speech tokens that will be used by the logit processor in the `generate`
  120. function. NON_SPEECH_TOKENS and NON_SPEECH_TOKENS_MULTI each correspond to the `english-only` and the
  121. `multilingual` model.
  122. begin_suppress_tokens (`list[int]`, *optional*, defaults to `[220,50256]`):
  123. A list containing tokens that will be suppressed at the beginning of the sampling process. Initialized as
  124. the token for `" "` (`blank_token_id`) and the `eos_token_id`
  125. use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
  126. Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
  127. instance of [`WhisperForAudioClassification`].
  128. classifier_proj_size (`int`, *optional*, defaults to 256):
  129. Dimensionality of the projection before token mean-pooling for classification. Only relevant when using an
  130. instance of [`WhisperForAudioClassification`].
  131. apply_spec_augment (`bool`, *optional*, defaults to `False`):
  132. Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
  133. [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
  134. Recognition](https://huggingface.co/papers/1904.08779).
  135. mask_time_prob (`float`, *optional*, defaults to 0.05):
  136. Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
  137. procedure generates `mask_time_prob*len(time_axis)/mask_time_length` independent masks over the axis. If
  138. reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
  139. masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
  140. actual percentage of masked vectors. This is only relevant if `apply_spec_augment == True`.
  141. mask_time_length (`int`, *optional*, defaults to 10):
  142. Length of vector span along the time axis.
  143. mask_time_min_masks (`int`, *optional*, defaults to 2),:
  144. The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
  145. irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
  146. mask_time_min_masks''
  147. mask_feature_prob (`float`, *optional*, defaults to 0.0):
  148. Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
  149. masking procedure generates `mask_feature_prob*len(feature_axis)/mask_time_length` independent masks over
  150. the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
  151. span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
  152. may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
  153. True`.
  154. mask_feature_length (`int`, *optional*, defaults to 10):
  155. Length of vector span along the feature axis.
  156. mask_feature_min_masks (`int`, *optional*, defaults to 0),:
  157. The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
  158. step, irrespectively of `mask_feature_prob`. Only relevant if
  159. `mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks`.
  160. median_filter_width (`int`, *optional*, defaults to 7):
  161. Width of the median filter used to smoothen to cross-attention outputs when computing token timestamps.
  162. Should be an odd number.
  163. Example:
  164. ```python
  165. >>> from transformers import WhisperConfig, WhisperModel
  166. >>> # Initializing a Whisper tiny style configuration
  167. >>> configuration = WhisperConfig()
  168. >>> # Initializing a model (with random weights) from the tiny style configuration
  169. >>> model = WhisperModel(configuration)
  170. >>> # Accessing the model configuration
  171. >>> configuration = model.config
  172. ```"""
  173. model_type = "whisper"
  174. keys_to_ignore_at_inference = ["past_key_values"]
  175. attribute_map = {
  176. "num_key_value_heads": "encoder_attention_heads",
  177. "num_attention_heads": "encoder_attention_heads",
  178. "hidden_size": "d_model",
  179. }
  180. def __init__(
  181. self,
  182. vocab_size=51865,
  183. num_mel_bins=80,
  184. encoder_layers=4,
  185. encoder_attention_heads=6,
  186. decoder_layers=4,
  187. decoder_attention_heads=6,
  188. decoder_ffn_dim=1536,
  189. encoder_ffn_dim=1536,
  190. encoder_layerdrop=0.0,
  191. decoder_layerdrop=0.0,
  192. decoder_start_token_id=50257,
  193. use_cache=True,
  194. is_encoder_decoder=True,
  195. activation_function="gelu",
  196. d_model=384,
  197. dropout=0.0,
  198. attention_dropout=0.0,
  199. activation_dropout=0.0,
  200. init_std=0.02,
  201. scale_embedding=False,
  202. max_source_positions=1500,
  203. max_target_positions=448,
  204. pad_token_id=50256,
  205. bos_token_id=50256,
  206. eos_token_id=50256,
  207. suppress_tokens=None,
  208. begin_suppress_tokens=[220, 50256],
  209. use_weighted_layer_sum=False,
  210. classifier_proj_size=256,
  211. apply_spec_augment=False,
  212. mask_time_prob=0.05,
  213. mask_time_length=10,
  214. mask_time_min_masks=2,
  215. mask_feature_prob=0.0,
  216. mask_feature_length=10,
  217. mask_feature_min_masks=0,
  218. median_filter_width=7,
  219. **kwargs,
  220. ):
  221. self.vocab_size = vocab_size
  222. self.num_mel_bins = num_mel_bins
  223. self.d_model = d_model
  224. self.encoder_layers = encoder_layers
  225. self.encoder_attention_heads = encoder_attention_heads
  226. self.decoder_layers = decoder_layers
  227. self.decoder_attention_heads = decoder_attention_heads
  228. self.decoder_ffn_dim = decoder_ffn_dim
  229. self.encoder_ffn_dim = encoder_ffn_dim
  230. self.dropout = dropout
  231. self.attention_dropout = attention_dropout
  232. self.activation_dropout = activation_dropout
  233. self.activation_function = activation_function
  234. self.init_std = init_std
  235. self.encoder_layerdrop = encoder_layerdrop
  236. self.decoder_layerdrop = decoder_layerdrop
  237. self.use_cache = use_cache
  238. self.num_hidden_layers = encoder_layers
  239. self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
  240. self.max_source_positions = max_source_positions
  241. self.max_target_positions = max_target_positions
  242. # Audio Classification-specific parameters. Feel free to ignore for other classes.
  243. self.classifier_proj_size = classifier_proj_size
  244. self.use_weighted_layer_sum = use_weighted_layer_sum
  245. # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
  246. self.apply_spec_augment = apply_spec_augment
  247. self.mask_time_prob = mask_time_prob
  248. self.mask_time_length = mask_time_length
  249. self.mask_time_min_masks = mask_time_min_masks
  250. self.mask_feature_prob = mask_feature_prob
  251. self.mask_feature_length = mask_feature_length
  252. self.mask_feature_min_masks = mask_feature_min_masks
  253. self.median_filter_width = median_filter_width
  254. super().__init__(
  255. pad_token_id=pad_token_id,
  256. bos_token_id=bos_token_id,
  257. eos_token_id=eos_token_id,
  258. is_encoder_decoder=is_encoder_decoder,
  259. decoder_start_token_id=decoder_start_token_id,
  260. suppress_tokens=suppress_tokens,
  261. begin_suppress_tokens=begin_suppress_tokens,
  262. **kwargs,
  263. )
  264. class WhisperOnnxConfig(OnnxSeq2SeqConfigWithPast):
  265. @property
  266. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  267. common_inputs = OrderedDict(
  268. [
  269. ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}),
  270. ]
  271. )
  272. if self.use_past:
  273. common_inputs["decoder_input_ids"] = {0: "batch"}
  274. else:
  275. common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
  276. if self.use_past:
  277. self.fill_with_past_key_values_(common_inputs, direction="inputs")
  278. return common_inputs
  279. def generate_dummy_inputs(
  280. self,
  281. preprocessor: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"],
  282. batch_size: int = -1,
  283. seq_length: int = -1,
  284. is_pair: bool = False,
  285. framework: Optional["TensorType"] = None,
  286. sampling_rate: int = 22050,
  287. time_duration: float = 5.0,
  288. frequency: int = 220,
  289. ) -> Mapping[str, Any]:
  290. dummy_inputs = OrderedDict()
  291. encoder_inputs = OnnxConfig.generate_dummy_inputs(
  292. self,
  293. preprocessor=preprocessor.feature_extractor,
  294. batch_size=batch_size,
  295. framework=framework,
  296. sampling_rate=sampling_rate,
  297. time_duration=time_duration,
  298. frequency=frequency,
  299. )
  300. encoder_sequence_length = encoder_inputs["input_features"].shape[2]
  301. seq_length = encoder_sequence_length // 2 if self.use_past else seq_length
  302. decoder_inputs = super().generate_dummy_inputs(
  303. preprocessor.tokenizer, batch_size, seq_length, is_pair, framework
  304. )
  305. dummy_inputs["input_features"] = encoder_inputs.pop("input_features")
  306. dummy_inputs["decoder_input_ids"] = decoder_inputs.pop("decoder_input_ids")
  307. if "past_key_values" in decoder_inputs:
  308. dummy_inputs["past_key_values"] = decoder_inputs.pop("past_key_values")
  309. return dummy_inputs
  310. @property
  311. def atol_for_validation(self) -> float:
  312. return 1e-3
  313. __all__ = ["WhisperConfig", "WhisperOnnxConfig"]