feature_extraction_sequence_utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # Copyright 2021 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Sequence feature extraction class for common feature extractors to preprocess sequences.
  16. """
  17. import numpy as np
  18. from .audio_utils import is_valid_audio, load_audio
  19. from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
  20. from .utils import PaddingStrategy, TensorType, is_torch_tensor, logging, to_numpy
  21. logger = logging.get_logger(__name__)
  22. class SequenceFeatureExtractor(FeatureExtractionMixin):
  23. """
  24. This is a general feature extraction class for speech recognition.
  25. Args:
  26. feature_size (`int`):
  27. The feature dimension of the extracted features.
  28. sampling_rate (`int`):
  29. The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
  30. padding_value (`float`):
  31. The value that is used to fill the padding values / vectors.
  32. """
  33. def __init__(self, feature_size: int, sampling_rate: int, padding_value: float, **kwargs):
  34. self.feature_size = feature_size
  35. self.sampling_rate = sampling_rate
  36. self.padding_value = padding_value
  37. self.padding_side = kwargs.pop("padding_side", "right")
  38. self.return_attention_mask = kwargs.pop("return_attention_mask", True)
  39. super().__init__(**kwargs)
  40. def pad(
  41. self,
  42. processed_features: BatchFeature
  43. | list[BatchFeature]
  44. | dict[str, BatchFeature]
  45. | dict[str, list[BatchFeature]]
  46. | list[dict[str, BatchFeature]],
  47. padding: bool | str | PaddingStrategy = True,
  48. max_length: int | None = None,
  49. truncation: bool = False,
  50. pad_to_multiple_of: int | None = None,
  51. return_attention_mask: bool | None = None,
  52. return_tensors: str | TensorType | None = None,
  53. ) -> BatchFeature:
  54. """
  55. Pad input values / input vectors or a batch of input values / input vectors up to predefined length or to the
  56. max sequence length in the batch.
  57. Padding side (left/right) padding values are defined at the feature extractor level (with `self.padding_side`,
  58. `self.padding_value`)
  59. <Tip>
  60. If the `processed_features` passed are dictionary of numpy arrays or PyTorch tensors the
  61. result will use the same type unless you provide a different tensor type with `return_tensors`. In the case of
  62. PyTorch tensors, you will lose the specific device of your tensors however.
  63. </Tip>
  64. Args:
  65. processed_features ([`BatchFeature`], list of [`BatchFeature`], `dict[str, list[float]]`, `dict[str, list[list[float]]` or `list[dict[str, list[float]]]`):
  66. Processed inputs. Can represent one input ([`BatchFeature`] or `dict[str, list[float]]`) or a batch of
  67. input values / vectors (list of [`BatchFeature`], *dict[str, list[list[float]]]* or *list[dict[str,
  68. list[float]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
  69. collate function.
  70. Instead of `list[float]` you can have tensors (numpy arrays or PyTorch tensors),
  71. see the note above for the return type.
  72. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
  73. Select a strategy to pad the returned sequences (according to the model's padding side and padding
  74. index) among:
  75. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  76. sequence if provided).
  77. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  78. acceptable input length for the model if that argument is not provided.
  79. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  80. lengths).
  81. max_length (`int`, *optional*):
  82. Maximum length of the returned list and optionally padding length (see above).
  83. truncation (`bool`):
  84. Activates truncation to cut input sequences longer than `max_length` to `max_length`.
  85. pad_to_multiple_of (`int`, *optional*):
  86. If set will pad the sequence to a multiple of the provided value.
  87. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
  88. `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
  89. return_attention_mask (`bool`, *optional*):
  90. Whether to return the attention mask. If left to the default, will return the attention mask according
  91. to the specific feature_extractor's default.
  92. [What are attention masks?](../glossary#attention-mask)
  93. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  94. If set, will return tensors instead of list of python integers. Acceptable values are:
  95. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  96. - `'np'`: Return Numpy `np.ndarray` objects.
  97. """
  98. # If we have a list of dicts, let's convert it in a dict of lists
  99. # We do this to allow using this method as a collate_fn function in PyTorch Dataloader
  100. if isinstance(processed_features, (list, tuple)) and isinstance(processed_features[0], (dict, BatchFeature)):
  101. # Call .keys() explicitly for compatibility with TensorDict and other Mapping subclasses
  102. processed_features = {
  103. key: [example[key] for example in processed_features] for key in processed_features[0].keys()
  104. }
  105. # The model's main input name, usually `input_values`, has be passed for padding
  106. if self.model_input_names[0] not in processed_features:
  107. raise ValueError(
  108. "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`"
  109. f" to this method that includes {self.model_input_names[0]}, but you provided"
  110. f" {list(processed_features.keys())}"
  111. )
  112. required_input = processed_features[self.model_input_names[0]]
  113. return_attention_mask = (
  114. return_attention_mask if return_attention_mask is not None else self.return_attention_mask
  115. )
  116. if len(required_input) == 0:
  117. if return_attention_mask:
  118. processed_features["attention_mask"] = []
  119. return processed_features
  120. # If we have PyTorch tensors or lists as inputs, we cast them as Numpy arrays
  121. # and rebuild them afterwards if no return_tensors is specified
  122. # Note that we lose the specific device the tensor may be on for PyTorch
  123. first_element = required_input[0]
  124. if isinstance(first_element, (list, tuple)):
  125. # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
  126. index = 0
  127. while len(required_input[index]) == 0:
  128. index += 1
  129. if index < len(required_input):
  130. first_element = required_input[index][0]
  131. if return_tensors is None:
  132. if is_torch_tensor(first_element):
  133. return_tensors = "pt"
  134. elif isinstance(first_element, (int, float, list, tuple, np.ndarray)):
  135. return_tensors = "np"
  136. else:
  137. raise ValueError(
  138. f"type of {first_element} unknown: {type(first_element)}. "
  139. "Should be one of a python, numpy, or pytorch object."
  140. )
  141. for key, value in processed_features.items():
  142. if isinstance(value[0], (int, float)):
  143. processed_features[key] = to_numpy(value)
  144. else:
  145. processed_features[key] = [to_numpy(v) for v in value]
  146. # Convert padding_strategy in PaddingStrategy
  147. padding_strategy = self._get_padding_strategies(padding=padding, max_length=max_length)
  148. required_input = processed_features[self.model_input_names[0]]
  149. batch_size = len(required_input)
  150. if not all(len(v) == batch_size for v in processed_features.values()):
  151. raise ValueError("Some items in the output dictionary have a different batch size than others.")
  152. truncated_inputs = []
  153. for i in range(batch_size):
  154. inputs = {k: v[i] for k, v in processed_features.items()}
  155. # truncation
  156. inputs_slice = self._truncate(
  157. inputs,
  158. max_length=max_length,
  159. pad_to_multiple_of=pad_to_multiple_of,
  160. truncation=truncation,
  161. )
  162. truncated_inputs.append(inputs_slice)
  163. if padding_strategy == PaddingStrategy.LONGEST:
  164. # make sure that `max_length` cannot be longer than the longest truncated length
  165. max_length = max(len(input_slice[self.model_input_names[0]]) for input_slice in truncated_inputs)
  166. padding_strategy = PaddingStrategy.MAX_LENGTH
  167. batch_outputs = {}
  168. for i in range(batch_size):
  169. # padding
  170. outputs = self._pad(
  171. truncated_inputs[i],
  172. max_length=max_length,
  173. padding_strategy=padding_strategy,
  174. pad_to_multiple_of=pad_to_multiple_of,
  175. return_attention_mask=return_attention_mask,
  176. )
  177. for key, value in outputs.items():
  178. if key not in batch_outputs:
  179. batch_outputs[key] = []
  180. if value.dtype is np.dtype(np.float64):
  181. value = value.astype(np.float32)
  182. batch_outputs[key].append(value)
  183. return BatchFeature(batch_outputs, tensor_type=return_tensors)
  184. def _pad(
  185. self,
  186. processed_features: dict[str, np.ndarray] | BatchFeature,
  187. max_length: int | None = None,
  188. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  189. pad_to_multiple_of: int | None = None,
  190. return_attention_mask: bool | None = None,
  191. ) -> dict:
  192. """
  193. Pad inputs (on left/right and up to predefined length or max length in the batch)
  194. Args:
  195. processed_features (`Union[dict[str, np.ndarray], BatchFeature]`):
  196. Dictionary of input values (`np.ndarray[float]`) / input vectors (`list[np.ndarray[float]]`) or batch
  197. of inputs values (`list[np.ndarray[int]]`) / input vectors (`list[np.ndarray[int]]`)
  198. max_length (`int`, *optional*):
  199. Maximum length of the returned list and optionally padding length (see below)
  200. padding_strategy (`PaddingStrategy`, *optional*, default to `PaddingStrategy.DO_NOT_PAD`):
  201. PaddingStrategy to use for padding.
  202. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  203. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  204. - PaddingStrategy.DO_NOT_PAD: Do not pad
  205. The feature_extractor padding sides are defined in self.padding_side:
  206. - 'left': pads on the left of the sequences
  207. - 'right': pads on the right of the sequences
  208. pad_to_multiple_of (`int`, *optional*):
  209. Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to
  210. enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs
  211. which benefit from having sequence lengths be a multiple of 128.
  212. return_attention_mask (`bool`, *optional*):
  213. Set to False to avoid returning attention mask (default: set to model specifics)
  214. """
  215. required_input = processed_features[self.model_input_names[0]]
  216. if padding_strategy == PaddingStrategy.LONGEST:
  217. max_length = len(required_input)
  218. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  219. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  220. needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) < max_length
  221. if return_attention_mask and "attention_mask" not in processed_features:
  222. processed_features["attention_mask"] = np.ones(len(required_input), dtype=np.int32)
  223. if needs_to_be_padded:
  224. difference = max_length - len(required_input)
  225. if self.padding_side == "right":
  226. if return_attention_mask:
  227. processed_features["attention_mask"] = np.pad(
  228. processed_features["attention_mask"], (0, difference)
  229. )
  230. padding_shape = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
  231. processed_features[self.model_input_names[0]] = np.pad(
  232. required_input, padding_shape, "constant", constant_values=self.padding_value
  233. )
  234. elif self.padding_side == "left":
  235. if return_attention_mask:
  236. processed_features["attention_mask"] = np.pad(
  237. processed_features["attention_mask"], (difference, 0)
  238. )
  239. padding_shape = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
  240. processed_features[self.model_input_names[0]] = np.pad(
  241. required_input, padding_shape, "constant", constant_values=self.padding_value
  242. )
  243. else:
  244. raise ValueError("Invalid padding strategy:" + str(self.padding_side))
  245. return processed_features
  246. def _truncate(
  247. self,
  248. processed_features: dict[str, np.ndarray] | BatchFeature,
  249. max_length: int | None = None,
  250. pad_to_multiple_of: int | None = None,
  251. truncation: bool | None = None,
  252. ):
  253. """
  254. Truncate inputs to predefined length or max length in the batch
  255. Args:
  256. processed_features(`Union[dict[str, np.ndarray], BatchFeature]`):
  257. Dictionary of input values (`np.ndarray[float]`) / input vectors (`list[np.ndarray[float]]`) or batch
  258. of inputs values (`list[np.ndarray[int]]`) / input vectors (`list[np.ndarray[int]]`)
  259. max_length (`int`, *optional*):
  260. maximum length of the returned list and optionally padding length (see below)
  261. pad_to_multiple_of (`int`, *optional*) :
  262. Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to
  263. enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs
  264. which benefit from having sequence lengths be a multiple of 128.
  265. truncation (`bool`, *optional*):
  266. Activates truncation to cut input sequences longer than `max_length` to `max_length`.
  267. """
  268. if not truncation:
  269. return processed_features
  270. elif truncation and max_length is None:
  271. raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined.")
  272. required_input = processed_features[self.model_input_names[0]]
  273. # find `max_length` that fits `pad_to_multiple_of`
  274. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  275. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  276. needs_to_be_truncated = len(required_input) > max_length
  277. if needs_to_be_truncated:
  278. processed_features[self.model_input_names[0]] = processed_features[self.model_input_names[0]][:max_length]
  279. if "attention_mask" in processed_features:
  280. processed_features["attention_mask"] = processed_features["attention_mask"][:max_length]
  281. return processed_features
  282. def _get_padding_strategies(self, padding=False, max_length=None):
  283. """
  284. Find the correct padding strategy
  285. """
  286. # Get padding strategy
  287. if padding is not False:
  288. if padding is True:
  289. padding_strategy = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch
  290. elif not isinstance(padding, PaddingStrategy):
  291. padding_strategy = PaddingStrategy(padding)
  292. elif isinstance(padding, PaddingStrategy):
  293. padding_strategy = padding
  294. else:
  295. padding_strategy = PaddingStrategy.DO_NOT_PAD
  296. # Set max length if needed
  297. if max_length is None:
  298. if padding_strategy == PaddingStrategy.MAX_LENGTH:
  299. raise ValueError(
  300. f"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined"
  301. )
  302. # Test if we have a padding value
  303. if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
  304. raise ValueError(
  305. "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use"
  306. " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`."
  307. )
  308. return padding_strategy
  309. def fetch_audio(self, audio_url_or_urls: str | list[str] | list[list[str]]):
  310. """
  311. Convert a single or a list of urls into the corresponding `np.ndarray` objects.
  312. If a single url is passed, the return value will be a single object. If a list is passed a list of objects is
  313. returned.
  314. """
  315. if isinstance(audio_url_or_urls, list):
  316. return [self.fetch_audio(x) for x in audio_url_or_urls]
  317. elif isinstance(audio_url_or_urls, str):
  318. return load_audio(audio_url_or_urls)
  319. elif is_valid_audio(audio_url_or_urls):
  320. return audio_url_or_urls
  321. else:
  322. raise TypeError(f"only a single or a list of entries is supported but got type={type(audio_url_or_urls)}")