'''simple docstring'''




import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
 import bitsandbytes as bnb

from copy import deepcopy


_A								=   logging.getLogger(__name__)

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_ = None  ,       SCREAMING_SNAKE_CASE_ = None  ,       SCREAMING_SNAKE_CASE_ = None  ,       SCREAMING_SNAKE_CASE_ = None  ,       SCREAMING_SNAKE_CASE_ = None  ,       SCREAMING_SNAKE_CASE_ = False  ,       ):
     lowercase_					:       Union[str, Any]     				=					bnb_quantization_config.load_in_abit
     lowercase_					:       List[str]     				=					bnb_quantization_config.load_in_abit

     if load_in_abit and not is_abit_bnb_available():
          raise ImportError(
              'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'
              ' make sure you have the latest version of `bitsandbytes` installed.'							)
     if load_in_abit and not is_abit_bnb_available():
          raise ValueError(
              'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'
              'make sure you have the latest version of `bitsandbytes` installed.'							)

     lowercase_					:       Optional[Any]     				=					[]
     # custom device map
     if isinstance(lowerCamelCase__  ,       lowerCamelCase__							) and len(device_map.keys()							) > 1:
          lowercase_					:       str     				=					[key for key, value in device_map.items() if value in ["disk", "cpu"]]

     # We keep some modules such as the lm_head in their original dtype for numerical stability reasons
     if bnb_quantization_config.skip_modules is None:
          lowercase_					:       Union[str, Any]     				=					get_keys_to_not_convert(lowerCamelCase__							)

     # add cpu modules to skip modules only for 4-bit modules
     if load_in_abit:
          bnb_quantization_config.skip_modules.extend(lowerCamelCase__							)
     lowercase_					:       List[str]     				=					bnb_quantization_config.skip_modules

     # We add the modules we want to keep in full precision
     if bnb_quantization_config.keep_in_fpaa_modules is None:
          lowercase_					:       List[str]     				=					[]
     lowercase_					:       Optional[Any]     				=					bnb_quantization_config.keep_in_fpaa_modules
     modules_to_not_convert.extend(lowerCamelCase__							)

     # compatibility with peft
     lowercase_					:       List[str]     				=					load_in_abit
     lowercase_					:       Optional[int]     				=					load_in_abit

     lowercase_					:       Optional[int]     				=					get_parameter_device(lowerCamelCase__							)
     if model_device.type != "meta":
          # quantization of an already loaded model
          logger.warning(
              'It is not recommended to quantize a loaded model. '
              'The model should be instantiated under the `init_empty_weights` context manager.'							)
          lowercase_					:       Tuple     				=					replace_with_bnb_layers(lowerCamelCase__  ,       lowerCamelCase__  ,       modules_to_not_convert=lowerCamelCase__							)
          # convert param to the right dtype
          lowercase_					:       Dict     				=					bnb_quantization_config.torch_dtype
          for name, param in model.state_dict().items():
               if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules							):
                    param.to(torch.floataa							)
                    if param.dtype != torch.floataa:
                         lowercase_					:       List[Any]     				=					name.replace('.weight'  ,       ''							).replace('.bias'  ,       ''							)
                         lowercase_					:       Union[str, Any]     				=					getattr(lowerCamelCase__  ,       lowerCamelCase__  ,       lowerCamelCase__							)
                         if param is not None:
                              param.to(torch.floataa							)
               elif torch.is_floating_point(lowerCamelCase__							):
                    param.to(lowerCamelCase__							)
          if model_device.type == "cuda":
               # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
               model.cuda(torch.cuda.current_device()							)
               torch.cuda.empty_cache()
          elif torch.cuda.is_available():
               model.to(torch.cuda.current_device()							)
          else:
               raise RuntimeError('No GPU found. A GPU is needed for quantization.'							)
          logger.info(
              f'''The model device type is {model_device.type}. However, cuda is needed for quantization.'''
              'We move the model to cuda.'							)
          return model

     elif weights_location is None:
          raise RuntimeError(
              f'''`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} '''							)

     else:
          with init_empty_weights():
               lowercase_					:       int     				=					replace_with_bnb_layers(
                   lowerCamelCase__  ,       lowerCamelCase__  ,       modules_to_not_convert=lowerCamelCase__							)

          lowercase_					:       Any     				=					get_quantized_model_device_map(
              lowerCamelCase__  ,       lowerCamelCase__  ,       lowerCamelCase__  ,       max_memory=lowerCamelCase__  ,       no_split_module_classes=lowerCamelCase__  ,       )
          if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
               lowercase_					:       Dict     				=					True

          lowercase_					:       Tuple     				=					any(x in list(device_map.values()							) for x in ['cpu', 'disk']							)

          load_checkpoint_in_model(
              lowerCamelCase__  ,       lowerCamelCase__  ,       lowerCamelCase__  ,       dtype=bnb_quantization_config.torch_dtype  ,       offload_folder=lowerCamelCase__  ,       offload_state_dict=lowerCamelCase__  ,       keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules  ,       offload_abit_bnb=load_in_abit and offload  ,       )
          return dispatch_model(lowerCamelCase__  ,       device_map=lowerCamelCase__  ,       offload_dir=lowerCamelCase__							)

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_=None  ,       SCREAMING_SNAKE_CASE_=None  ,       SCREAMING_SNAKE_CASE_=None							):


     if device_map is None:
          if torch.cuda.is_available():
               lowercase_					:       Tuple     				=					{"": torch.cuda.current_device()}
          else:
               raise RuntimeError('No GPU found. A GPU is needed for quantization.'							)
          logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.'							)

     if isinstance(lowerCamelCase__  ,       lowerCamelCase__							):
          if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
               raise ValueError(
                   'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '
                   '\'sequential\'.'							)

          lowercase_					:       List[Any]     				=					{}
          special_dtypes.update(
              {
                  name: bnb_quantization_config.torch_dtype
                  for name, _ in model.named_parameters()
                  if any(m in name for m in bnb_quantization_config.skip_modules							)
              }							)
          special_dtypes.update(
              {
                  name: torch.floataa
                  for name, _ in model.named_parameters()
                  if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules							)
              }							)

          lowercase_					:       Optional[Any]     				=					{}
          lowercase_					:       Union[str, Any]     				=					special_dtypes
          lowercase_					:       Tuple     				=					no_split_module_classes
          lowercase_					:       Optional[Any]     				=					bnb_quantization_config.target_dtype

          # get max_memory for each device.
          if device_map != "sequential":
               lowercase_					:       Any     				=					get_balanced_memory(
                   lowerCamelCase__  ,       low_zero=(device_map == 'balanced_low_0')  ,       max_memory=lowerCamelCase__  ,       **lowerCamelCase__  ,       )

          lowercase_					:       List[str]     				=					max_memory
          lowercase_					:       str     				=					infer_auto_device_map(lowerCamelCase__  ,       **lowerCamelCase__							)

     if isinstance(lowerCamelCase__  ,       lowerCamelCase__							):
          # check if don't have any quantized module on the cpu
          lowercase_					:       Optional[Any]     				=					bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

          lowercase_					:       Dict     				=					{
              key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
          }
          for device in ["cpu", "disk"]:
               if device in device_map_without_some_modules.values():
                    if bnb_quantization_config.load_in_abit:
                         raise ValueError(
                             '\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        '							)
                    else:
                         logger.info(
                             'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit'							)
          del device_map_without_some_modules
     return device_map

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_=None  ,       SCREAMING_SNAKE_CASE_=None							):


     if modules_to_not_convert is None:
          lowercase_					:       int     				=					[]

     lowercase_					:       str     				=					_replace_with_bnb_layers(
         lowerCamelCase__  ,       lowerCamelCase__  ,       lowerCamelCase__  ,       lowerCamelCase__							)
     if not has_been_replaced:
          logger.warning(
              'You are loading your model in 8bit or 4bit but no linear modules were found in your model.'
              ' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'
              ' Please double check your model architecture, or submit an issue on github if you think this is'
              ' a bug.'							)
     return model

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_=None  ,       SCREAMING_SNAKE_CASE_=None  ,       ):
     lowercase_					:       Tuple     				=					False
     for name, module in model.named_children():
          if current_key_name is None:
               lowercase_					:       List[Any]     				=					[]
          current_key_name.append(lowerCamelCase__							)
          if isinstance(lowerCamelCase__  ,       nn.Linear							) and name not in modules_to_not_convert:
               # Check if the current key is not in the `modules_to_not_convert`
               lowercase_					:       Optional[Any]     				=					".".join(lowerCamelCase__							)
               lowercase_					:       Optional[int]     				=					True
               for key in modules_to_not_convert:
                    if (
                        (key in current_key_name_str) and (key + "." in current_key_name_str)
                    ) or key == current_key_name_str:
                         lowercase_					:       Optional[int]     				=					False
                         break
               if proceed:
                    # Load bnb module with empty weight and replace ``nn.Linear` module
                    if bnb_quantization_config.load_in_abit:
                         lowercase_					:       Any     				=					bnb.nn.LinearabitLt(
                             module.in_features  ,       module.out_features  ,       module.bias is not None  ,       has_fpaa_weights=lowerCamelCase__  ,       threshold=bnb_quantization_config.llm_inta_threshold  ,       )
                    elif bnb_quantization_config.load_in_abit:
                         lowercase_					:       Union[str, Any]     				=					bnb.nn.Linearabit(
                             module.in_features  ,       module.out_features  ,       module.bias is not None  ,       bnb_quantization_config.bnb_abit_compute_dtype  ,       compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant  ,       quant_type=bnb_quantization_config.bnb_abit_quant_type  ,       )
                    else:
                         raise ValueError('load_in_8bit and load_in_4bit can\'t be both False'							)
                    lowercase_					:       Union[str, Any]     				=					module.weight.data
                    if module.bias is not None:
                         lowercase_					:       Optional[int]     				=					module.bias.data
                    bnb_module.requires_grad_(lowerCamelCase__							)
                    setattr(lowerCamelCase__  ,       lowerCamelCase__  ,       lowerCamelCase__							)
                    lowercase_					:       Tuple     				=					True
          if len(list(module.children()							)							) > 0:
               lowercase_					:       List[str]     				=					_replace_with_bnb_layers(
                   lowerCamelCase__  ,       lowerCamelCase__  ,       lowerCamelCase__  ,       lowerCamelCase__							)
               lowercase_					:       List[Any]     				=					has_been_replaced | _has_been_replaced
          # Remove the last key for recursion
          current_key_name.pop(-1							)
     return model, has_been_replaced

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):


     with init_empty_weights():
          lowercase_					:       List[Any]     				=					deepcopy(lowerCamelCase__							)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

     lowercase_					:       Optional[int]     				=					find_tied_parameters(lowerCamelCase__							)
     # For compatibility with Accelerate < 0.18
     if isinstance(lowerCamelCase__  ,       lowerCamelCase__							):
          lowercase_					:       Optional[int]     				=					sum(list(tied_params.values()							)  ,       []							) + list(tied_params.keys()							)
     else:
          lowercase_					:       Dict     				=					sum(lowerCamelCase__  ,       []							)
     lowercase_					:       int     				=					len(lowerCamelCase__							) > 0

     # Check if it is a base model
     lowercase_					:       Tuple     				=					False
     if hasattr(lowerCamelCase__  ,       'base_model_prefix'							):
          lowercase_					:       int     				=					not hasattr(lowerCamelCase__  ,       model.base_model_prefix							)

     # Ignore this for base models (BertModel, GPT2Model, etc.)
     if (not has_tied_params) and is_base_model:
          return []

     # otherwise they have an attached head
     lowercase_					:       List[str]     				=					list(model.named_children()							)
     lowercase_					:       Dict     				=					[list_modules[-1][0]]

     # add last module together with tied weights
     lowercase_					:       Optional[int]     				=					set(lowerCamelCase__							) - set(lowerCamelCase__							)
     lowercase_					:       Dict     				=					list(set(lowerCamelCase__							)							) + list(lowerCamelCase__							)

     # remove ".weight" from the keys
     lowercase_					:       int     				=					[".weight", ".bias"]
     lowercase_					:       int     				=					[]
     for name in list_untouched:
          for name_to_remove in names_to_remove:
               if name_to_remove in name:
                    lowercase_					:       Tuple     				=					name.replace(lowerCamelCase__  ,       ''							)
          filtered_module_names.append(lowerCamelCase__							)

     return filtered_module_names

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):


     for m in model.modules():
          if isinstance(lowerCamelCase__  ,       bnb.nn.Linearabit							):
               return True
     return False

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     return next(parameter.parameters()							).device






def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):


     if fpaa_statistics is None:
          set_module_tensor_to_device(lowerCamelCase__  ,       lowerCamelCase__  ,       0  ,       dtype=lowerCamelCase__  ,       value=lowerCamelCase__							)
          lowercase_					:       Any     				=					param_name
          lowercase_					:       Dict     				=					model
          if "." in tensor_name:
               lowercase_					:       Any     				=					tensor_name.split('.'							)
               for split in splits[:-1]:
                    lowercase_					:       Optional[int]     				=					getattr(lowerCamelCase__  ,       lowerCamelCase__							)
                    if new_module is None:
                         raise ValueError(f'''{module} has no attribute {split}.'''							)
                    lowercase_					:       List[Any]     				=					new_module
               lowercase_					:       str     				=					splits[-1]
          # offload weights
          lowercase_					:       Any     				=					False
          offload_weight(module._parameters[tensor_name]  ,       lowerCamelCase__  ,       lowerCamelCase__  ,       index=lowerCamelCase__							)
          if hasattr(module._parameters[tensor_name]  ,       'SCB'							):
               offload_weight(
                   module._parameters[tensor_name].SCB  ,       param_name.replace('weight'  ,       'SCB'							)  ,       lowerCamelCase__  ,       index=lowerCamelCase__  ,       )
     else:
          offload_weight(lowerCamelCase__  ,       lowerCamelCase__  ,       lowerCamelCase__  ,       index=lowerCamelCase__							)
          offload_weight(lowerCamelCase__  ,       param_name.replace('weight'  ,       'SCB'							)  ,       lowerCamelCase__  ,       index=lowerCamelCase__							)

     set_module_tensor_to_device(lowerCamelCase__  ,       lowerCamelCase__  ,       'meta'  ,       dtype=lowerCamelCase__  ,       value=torch.empty(*param.size()							)							)





'''simple docstring'''




import numpy as np

from transformers import BatchFeature
from transformers.testing_utils import require_tf, require_torch

from .test_feature_extraction_common import FeatureExtractionSavingTestMixin


class       UpperCAmelCase__  (       _snake_case			):






   """simple docstring"""
   # to overwrite at feature extractactor specific tests
   A							:       List[str]     =    None
   A							:       Tuple     =    None
   @property
   def 		_lowerCamelCase (self				)    ->     Any:
        return self.feat_extract_tester.prepare_feat_extract_dict()
   def 		_lowerCamelCase (self				)    ->     str:
        lowercase_					:       Dict     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        self.assertTrue(hasattr(_a       ,				'feature_size'				)				)
        self.assertTrue(hasattr(_a       ,				'sampling_rate'				)				)
        self.assertTrue(hasattr(_a       ,				'padding_value'				)				)
   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_					:       List[str]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       Union[str, Any]     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       Union[str, Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       Union[str, Any]     				=					BatchFeature({input_name: speech_inputs}				)

        self.assertTrue(all(len(_a				) == len(_a				) for x, y in zip(_a       ,				processed_features[input_name]				)				)				)

        lowercase_					:       Optional[int]     				=					self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a				)
        lowercase_					:       Tuple     				=					BatchFeature({input_name: speech_inputs}       ,				tensor_type='np'				)

        lowercase_					:       Dict     				=					processed_features[input_name]

        if len(batch_features_input.shape				) < 3:
             lowercase_					:       Optional[Any]     				=					batch_features_input[:, :, None]

        self.assertTrue(
            batch_features_input.shape
            == (self.feat_extract_tester.batch_size, len(speech_inputs[0]				), self.feat_extract_tester.feature_size)				)
   @require_torch
   def 		_lowerCamelCase (self				)    ->     Tuple:
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a				)
        lowercase_					:       Any     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       int     				=					feat_extract.model_input_names[0]

        lowercase_					:       Union[str, Any]     				=					BatchFeature({input_name: speech_inputs}       ,				tensor_type='pt'				)

        lowercase_					:       Tuple     				=					processed_features[input_name]

        if len(batch_features_input.shape				) < 3:
             lowercase_					:       List[str]     				=					batch_features_input[:, :, None]

        self.assertTrue(
            batch_features_input.shape
            == (self.feat_extract_tester.batch_size, len(speech_inputs[0]				), self.feat_extract_tester.feature_size)				)
   @require_tf
   def 		_lowerCamelCase (self				)    ->     Union[str, Any]:
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a				)
        lowercase_					:       int     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       Dict     				=					feat_extract.model_input_names[0]

        lowercase_					:       List[Any]     				=					BatchFeature({input_name: speech_inputs}       ,				tensor_type='tf'				)

        lowercase_					:       int     				=					processed_features[input_name]

        if len(batch_features_input.shape				) < 3:
             lowercase_					:       Union[str, Any]     				=					batch_features_input[:, :, None]

        self.assertTrue(
            batch_features_input.shape
            == (self.feat_extract_tester.batch_size, len(speech_inputs[0]				), self.feat_extract_tester.feature_size)				)
   def 		_lowerCamelCase (self       ,				_a=False				)    ->     Union[str, Any]:
        def _inputs_have_equal_length(_a				):
             lowercase_					:       Optional[Any]     				=					len(input[0]				)
             for input_slice in input[1:]:
                  if len(_a				) != length:
                       return False
             return True

        def _inputs_are_equal(_a       ,				_a				):
             if len(_a				) != len(_a				):
                  return False

             for input_slice_a, input_slice_a in zip(_a       ,				_a				):
                  if not np.allclose(np.asarray(_a				)       ,				np.asarray(_a				)       ,				atol=1e-3				):
                       return False
             return True

        lowercase_					:       int     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       str     				=					self.feat_extract_tester.prepare_inputs_for_common(numpify=_a				)
        lowercase_					:       Union[str, Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       Union[str, Any]     				=					BatchFeature({input_name: speech_inputs}				)

        lowercase_					:       Optional[Any]     				=					self.feat_extract_tester.seq_length_diff
        lowercase_					:       Union[str, Any]     				=					self.feat_extract_tester.max_seq_length + pad_diff
        lowercase_					:       str     				=					self.feat_extract_tester.min_seq_length
        lowercase_					:       Optional[Any]     				=					self.feat_extract_tester.batch_size
        lowercase_					:       Any     				=					self.feat_extract_tester.feature_size

        # test padding for List[int] + numpy
        lowercase_					:       List[str]     				=					feat_extract.pad(_a       ,				padding=_a				)
        lowercase_					:       Any     				=					input_a[input_name]

        lowercase_					:       str     				=					feat_extract.pad(_a       ,				padding='longest'				)
        lowercase_					:       List[str]     				=					input_a[input_name]

        lowercase_					:       Dict     				=					feat_extract.pad(_a       ,				padding='max_length'       ,				max_length=len(speech_inputs[-1]				)				)
        lowercase_					:       Any     				=					input_a[input_name]

        lowercase_					:       Any     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='np'				)
        lowercase_					:       str     				=					input_a[input_name]

        # max_length parameter has to be provided when setting `padding="max_length"`
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				padding='max_length'				)[input_name]

        lowercase_					:       Union[str, Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=_a       ,				return_tensors='np'				)
        lowercase_					:       Any     				=					input_a[input_name]

        self.assertFalse(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_are_equal(_a       ,				_a				)				)
        self.assertTrue(len(input_a[0]				) == pad_min_length				)
        self.assertTrue(len(input_a[1]				) == pad_min_length + pad_diff				)
        self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0]				))				)
        self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length)				)

        if feature_size > 1:
             self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size				)

        # test padding for `pad_to_multiple_of` for List[int] + numpy
        lowercase_					:       Tuple     				=					feat_extract.pad(_a       ,				pad_to_multiple_of=10				)
        lowercase_					:       Dict     				=					input_a[input_name]

        lowercase_					:       int     				=					feat_extract.pad(_a       ,				padding='longest'       ,				pad_to_multiple_of=10				)
        lowercase_					:       Union[str, Any]     				=					input_a[input_name]

        lowercase_					:       Optional[int]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				pad_to_multiple_of=10       ,				max_length=_a				)
        lowercase_					:       Tuple     				=					input_a[input_name]

        lowercase_					:       Optional[int]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				pad_to_multiple_of=10       ,				max_length=_a       ,				return_tensors='np'       ,				)
        lowercase_					:       Union[str, Any]     				=					input_a[input_name]

        self.assertTrue(all(len(_a				) % 10 == 0 for x in input_a				)				)
        self.assertTrue(_inputs_are_equal(_a       ,				_a				)				)

        lowercase_					:       str     				=					pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10
        self.assertTrue(all(len(_a				) == expected_mult_pad_length for x in input_a				)				)
        self.assertEqual(input_a.shape[:2]       ,				(batch_size, expected_mult_pad_length)				)

        if feature_size > 1:
             self.assertTrue(input_a.shape[2] == feature_size				)

        # Check padding value is correct
        lowercase_					:       Optional[int]     				=					(np.ones(self.feat_extract_tester.feature_size				) * feat_extract.padding_value).sum()
        self.assertTrue(
            abs(np.asarray(input_a[0]				)[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)				)
            < 1e-3				)
        self.assertTrue(
            abs(
                np.asarray(input_a[1]				)[pad_min_length + pad_diff :].sum()
                - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff)				)
            < 1e-3				)
        self.assertTrue(
            abs(
                np.asarray(input_a[2]				)[pad_min_length + 2 * pad_diff :].sum()
                - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff)				)
            < 1e-3				)
        self.assertTrue(
            abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)				) < 1e-3				)
        self.assertTrue(
            abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length)				)
            < 1e-3				)
   def 		_lowerCamelCase (self       ,				_a=False				)    ->     Union[str, Any]:
        def _inputs_have_equal_length(_a				):
             lowercase_					:       str     				=					len(input[0]				)
             for input_slice in input[1:]:
                  if len(_a				) != length:
                       return False
             return True

        def _inputs_are_equal(_a       ,				_a				):
             if len(_a				) != len(_a				):
                  return False

             for input_slice_a, input_slice_a in zip(_a       ,				_a				):
                  if not np.allclose(np.asarray(_a				)       ,				np.asarray(_a				)       ,				atol=1e-3				):
                       return False
             return True

        lowercase_					:       Any     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common(numpify=_a				)
        lowercase_					:       List[str]     				=					feat_extract.model_input_names[0]

        lowercase_					:       str     				=					BatchFeature({input_name: speech_inputs}				)

        # truncate to smallest
        lowercase_					:       Union[str, Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				truncation=_a				)
        lowercase_					:       List[str]     				=					input_a[input_name]

        lowercase_					:       Optional[int]     				=					feat_extract.pad(_a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)				)
        lowercase_					:       Union[str, Any]     				=					input_a[input_name]

        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertFalse(_inputs_have_equal_length(_a				)				)

        # truncate to smallest with np
        lowercase_					:       List[str]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				return_tensors='np'       ,				truncation=_a       ,				)
        lowercase_					:       List[str]     				=					input_a[input_name]

        lowercase_					:       List[Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				return_tensors='np'				)
        lowercase_					:       List[Any]     				=					input_a[input_name]

        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(input_a.shape[1] == len(speech_inputs[0]				)				)

        # since truncation forces padding to be smaller than longest input
        # function can't return `np.ndarray`, but has to return list
        self.assertFalse(_inputs_have_equal_length(_a				)				)

        # truncate to middle
        lowercase_					:       int     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[1]				)       ,				truncation=_a       ,				return_tensors='np'       ,				)
        lowercase_					:       Union[str, Any]     				=					input_a[input_name]

        lowercase_					:       str     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[1]				)       ,				truncation=_a				)
        lowercase_					:       int     				=					input_a[input_name]

        lowercase_					:       Dict     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[1]				)       ,				return_tensors='np'				)
        lowercase_					:       Optional[int]     				=					input_a[input_name]

        self.assertTrue(input_a.shape[1] == len(speech_inputs[1]				)				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_are_equal(_a       ,				_a				)				)

        # since truncation forces padding to be smaller than longest input
        # function can't return `np.ndarray`, but has to return list
        self.assertFalse(_inputs_have_equal_length(_a				)				)
        self.assertTrue(len(input_a[-1]				) == len(speech_inputs[-1]				)				)

        # padding has to be max_length when setting `truncation=True`
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				truncation=_a				)[input_name]

        # padding has to be max_length when setting `truncation=True`
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				padding='longest'       ,				truncation=_a				)[input_name]

        # padding has to be max_length when setting `truncation=True`
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				padding='longest'       ,				truncation=_a				)[input_name]

        # max_length parameter has to be provided when setting `truncation=True` and padding="max_length"
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				padding='max_length'       ,				truncation=_a				)[input_name]

        # test truncation for `pad_to_multiple_of` for List[int] + numpy
        lowercase_					:       str     				=					12
        lowercase_					:       List[Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				pad_to_multiple_of=_a       ,				truncation=_a       ,				)
        lowercase_					:       Any     				=					input_a[input_name]

        lowercase_					:       List[Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				pad_to_multiple_of=_a       ,				)
        lowercase_					:       str     				=					input_a[input_name]

        # retrieve expected_length as multiple of pad_to_multiple_of
        lowercase_					:       Dict     				=					len(speech_inputs[0]				)
        if expected_length % pad_to_multiple_of != 0:
             lowercase_					:       List[Any]     				=					((len(speech_inputs[0]				) // pad_to_multiple_of) + 1) * pad_to_multiple_of

        self.assertTrue(len(input_a[0]				) == expected_length				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertFalse(_inputs_have_equal_length(_a				)				)
   def 		_lowerCamelCase (self				)    ->     str:
        self._check_padding(numpify=_a				)
   def 		_lowerCamelCase (self				)    ->     Optional[int]:
        self._check_padding(numpify=_a				)
   def 		_lowerCamelCase (self				)    ->     Any:
        self._check_truncation(numpify=_a				)
   def 		_lowerCamelCase (self				)    ->     Any:
        self._check_truncation(numpify=_a				)
   @require_torch
   def 		_lowerCamelCase (self				)    ->     int:
        lowercase_					:       Tuple     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       Optional[Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       Dict     				=					BatchFeature({input_name: speech_inputs}				)

        lowercase_					:       Tuple     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='np'				)[input_name]
        lowercase_					:       List[Any]     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='pt'				)[input_name]

        self.assertTrue(abs(input_np.astype(np.floataa				).sum() - input_pt.numpy().astype(np.floataa				).sum()				) < 1e-2				)
   @require_tf
   def 		_lowerCamelCase (self				)    ->     List[Any]:
        lowercase_					:       Any     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       Optional[int]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       List[Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       Tuple     				=					BatchFeature({input_name: speech_inputs}				)

        lowercase_					:       List[Any]     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='np'				)[input_name]
        lowercase_					:       Optional[int]     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='tf'				)[input_name]

        self.assertTrue(abs(input_np.astype(np.floataa				).sum() - input_tf.numpy().astype(np.floataa				).sum()				) < 1e-2				)
   def 		_lowerCamelCase (self				)    ->     List[str]:
        lowercase_					:       Any     				=					self.feat_extract_dict
        lowercase_					:       List[Any]     				=					True
        lowercase_					:       Tuple     				=					self.feature_extraction_class(**_a				)
        lowercase_					:       Optional[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       str     				=					[len(_a				) for x in speech_inputs]
        lowercase_					:       Union[str, Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       List[Any]     				=					BatchFeature({input_name: speech_inputs}				)

        lowercase_					:       str     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='np'				)
        self.assertIn('attention_mask'       ,				_a				)
        self.assertListEqual(list(processed.attention_mask.shape				)       ,				list(processed[input_name].shape[:2]				)				)
        self.assertListEqual(processed.attention_mask.sum(-1				).tolist()       ,				_a				)





   def 		_lowerCamelCase (self				)    ->     List[Any]:
        lowercase_					:       Union[str, Any]     				=					self.feat_extract_dict
        lowercase_					:       List[Any]     				=					True
        lowercase_					:       List[Any]     				=					self.feature_extraction_class(**_a				)
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       Optional[int]     				=					[len(_a				) for x in speech_inputs]
        lowercase_					:       int     				=					feat_extract.model_input_names[0]

        lowercase_					:       Tuple     				=					BatchFeature({input_name: speech_inputs}				)
        lowercase_					:       Optional[Any]     				=					min(_a				)

        lowercase_					:       int     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=_a       ,				truncation=_a       ,				return_tensors='np'				)
        self.assertIn('attention_mask'       ,				_a				)
        self.assertListEqual(
            list(processed_pad.attention_mask.shape				)       ,				[processed_pad[input_name].shape[0], max_length]				)
        self.assertListEqual(
            processed_pad.attention_mask[:, :max_length].sum(-1				).tolist()       ,				[max_length for x in speech_inputs]				)




