




import inspect
import os

import torch
from transformers import AutoModel
from transformers.testing_utils import mockenv_context
from transformers.trainer_utils import set_seed

import accelerate
from accelerate.accelerator import Accelerator
from accelerate.state import AcceleratorState
from accelerate.test_utils.testing import (
    AccelerateTestCase,
    TempDirTestCase,
    execute_subprocess_async,
    require_cuda,
    require_fsdp,
    require_multi_gpu,
    slow,
)
from accelerate.utils.constants import (
    FSDP_AUTO_WRAP_POLICY,
    FSDP_BACKWARD_PREFETCH,
    FSDP_SHARDING_STRATEGY,
    FSDP_STATE_DICT_TYPE,
)
from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin
from accelerate.utils.other import patch_environment


set_seed(4_2)

_lowerCAmelCase						:   Union[str, Any]		=   "bert-base-cased"
_lowerCAmelCase						:   Dict		=   "fp16"
_lowerCAmelCase						:   Dict		=   "bf16"
_lowerCAmelCase						:   List[Any]		=   [FPaa, BFaa]
@require_fsdp
@require_cuda
class 			_UpperCamelCase      (				lowerCAmelCase		):
      def 	UpperCAmelCase_						(			self   :Union[str, Any]      )     ->			List[str]:
       super().setUp()

       UpperCAmelCase__							 =						dict(
           ACCELERATE_USE_FSDP="true" ,      MASTER_ADDR="localhost" ,      MASTER_PORT="10999" ,      RANK="0" ,      LOCAL_RANK="0" ,      WORLD_SIZE="1" ,      )
      def 	UpperCAmelCase_						(			self   :Tuple      )     ->			Optional[int]:
       from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy

       for i, strategy in enumerate(lowerCamelCase      ):
        UpperCAmelCase__							 =						self.dist_env.copy()
        UpperCAmelCase__							 =						f'''{i + 1}'''
        UpperCAmelCase__							 =						strategy
        with mockenv_context(**lowerCamelCase      ):
         UpperCAmelCase__							 =						FullyShardedDataParallelPlugin()
         self.assertEqual(fsdp_plugin.sharding_strategy ,      ShardingStrategy(i + 1      )      )
      def 	UpperCAmelCase_						(			self   :Optional[Any]      )     ->			Union[str, Any]:
       from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch

       for i, prefetch_policy in enumerate(lowerCamelCase      ):
        UpperCAmelCase__							 =						self.dist_env.copy()
        UpperCAmelCase__							 =						prefetch_policy
        with mockenv_context(**lowerCamelCase      ):
         UpperCAmelCase__							 =						FullyShardedDataParallelPlugin()
         if prefetch_policy == "NO_PREFETCH":
          self.assertIsNone(fsdp_plugin.backward_prefetch      )
         else:
          self.assertEqual(fsdp_plugin.backward_prefetch ,      BackwardPrefetch(i + 1      )      )
      def 	UpperCAmelCase_						(			self   :List[str]      )     ->			Any:
       from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType

       for i, state_dict_type in enumerate(lowerCamelCase      ):
        UpperCAmelCase__							 =						self.dist_env.copy()
        UpperCAmelCase__							 =						state_dict_type
        with mockenv_context(**lowerCamelCase      ):
         UpperCAmelCase__							 =						FullyShardedDataParallelPlugin()
         self.assertEqual(fsdp_plugin.state_dict_type ,      StateDictType(i + 1      )      )
         if state_dict_type == "FULL_STATE_DICT":
          self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu      )
          self.assertTrue(fsdp_plugin.state_dict_config.ranka_only      )
      def 	UpperCAmelCase_						(			self   :Tuple      )     ->			Any:
       UpperCAmelCase__							 =						AutoModel.from_pretrained(lowerCamelCase      )
       for policy in FSDP_AUTO_WRAP_POLICY:
        UpperCAmelCase__							 =						self.dist_env.copy()
        UpperCAmelCase__							 =						policy
        if policy == "TRANSFORMER_BASED_WRAP":
         UpperCAmelCase__							 =						"BertLayer"
        elif policy == "SIZE_BASED_WRAP":
         UpperCAmelCase__							 =						"2000"
        with mockenv_context(**lowerCamelCase      ):
         UpperCAmelCase__							 =						FullyShardedDataParallelPlugin()
         fsdp_plugin.set_auto_wrap_policy(lowerCamelCase      )
         if policy == "NO_WRAP":
          self.assertIsNone(fsdp_plugin.auto_wrap_policy      )
         else:
          self.assertIsNotNone(fsdp_plugin.auto_wrap_policy      )

       UpperCAmelCase__							 =						self.dist_env.copy()
       UpperCAmelCase__							 =						"TRANSFORMER_BASED_WRAP"
       UpperCAmelCase__							 =						"T5Layer"
       with mockenv_context(**lowerCamelCase      ):
        UpperCAmelCase__							 =						FullyShardedDataParallelPlugin()
        with self.assertRaises(lowerCamelCase      ) as cm:
         fsdp_plugin.set_auto_wrap_policy(lowerCamelCase      )
        self.assertTrue("Could not find the transformer layer class to wrap in the model." in str(cm.exception      )      )

       UpperCAmelCase__							 =						self.dist_env.copy()
       UpperCAmelCase__							 =						"SIZE_BASED_WRAP"
       UpperCAmelCase__							 =						"0"
       with mockenv_context(**lowerCamelCase      ):
        UpperCAmelCase__							 =						FullyShardedDataParallelPlugin()
        fsdp_plugin.set_auto_wrap_policy(lowerCamelCase      )
        self.assertIsNone(fsdp_plugin.auto_wrap_policy      )
      def 	UpperCAmelCase_						(			self   :Optional[int]      )     ->			Tuple:
       from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
       from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler

       for mp_dtype in dtypes:
        UpperCAmelCase__							 =						self.dist_env.copy()
        UpperCAmelCase__							 =						mp_dtype
        with mockenv_context(**lowerCamelCase      ):
         UpperCAmelCase__							 =						Accelerator()
         if mp_dtype == "fp16":
          UpperCAmelCase__							 =						torch.floataa
         elif mp_dtype == "bf16":
          UpperCAmelCase__							 =						torch.bfloataa
         UpperCAmelCase__							 =						MixedPrecision(param_dtype=lowerCamelCase ,      reduce_dtype=lowerCamelCase ,      buffer_dtype=lowerCamelCase      )
         self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy ,      lowerCamelCase      )
         if mp_dtype == FPaa:
          self.assertTrue(isinstance(accelerator.scaler ,      lowerCamelCase      )      )
         elif mp_dtype == BFaa:
          self.assertIsNone(accelerator.scaler      )
         AcceleratorState._reset_state(lowerCamelCase      )







      def 	UpperCAmelCase_						(			self   :Tuple      )     ->			Optional[int]:
       from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload

       for flag in [True, False]:
        UpperCAmelCase__							 =						self.dist_env.copy()
        UpperCAmelCase__							 =						str(lowerCamelCase      ).lower()
        with mockenv_context(**lowerCamelCase      ):
         UpperCAmelCase__							 =						FullyShardedDataParallelPlugin()
         self.assertEqual(fsdp_plugin.cpu_offload ,      CPUOffload(offload_params=lowerCamelCase      )      )



@require_fsdp
@require_multi_gpu
@slow
class 			_UpperCamelCase      (				lowerCAmelCase		):
      def 	UpperCAmelCase_						(			self   :List[Any]      )     ->			str:
       super().setUp()
       UpperCAmelCase__							 =						0.82
       UpperCAmelCase__							 =						[
           "fsdp_shard_grad_op_transformer_based_wrap",
           "fsdp_full_shard_transformer_based_wrap",
       ]
       UpperCAmelCase__							 =						{
           "multi_gpu_fp16": 3200,
           "fsdp_shard_grad_op_transformer_based_wrap_fp16": 2000,
           "fsdp_full_shard_transformer_based_wrap_fp16": 1900,
           # Disabling below test as it overwhelms the RAM memory usage
           # on CI self-hosted runner leading to tests getting killed.
           # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500,  # fp16 was leading to indefinite hang
       }
       UpperCAmelCase__							 =						160
       UpperCAmelCase__							 =						160

       UpperCAmelCase__							 =						inspect.getfile(accelerate.test_utils      )
       UpperCAmelCase__							 =						os.path.sep.join(mod_file.split(os.path.sep      )[:-1] + ["scripts", "external_deps"]      )
      def 	UpperCAmelCase_						(			self   :List[Any]      )     ->			Dict:
       UpperCAmelCase__							 =						os.path.join(self.test_scripts_folder ,      "test_performance.py"      )
       UpperCAmelCase__							 =						["accelerate", "launch", "--num_processes=2", "--num_machines=1", "--machine_rank=0", "--use_fsdp"]
       for config in self.performance_configs:
        UpperCAmelCase__							 =						cmd.copy()
        for i, strategy in enumerate(lowerCamelCase      ):
         if strategy.lower() in config:
          cmd_config.append(f'''--fsdp_sharding_strategy={i+1}'''      )
          break

        if "fp32" in config:
         cmd_config.append("--mixed_precision=no"      )
        else:
         cmd_config.append("--mixed_precision=fp16"      )

        if "cpu_offload" in config:
         cmd_config.append("--fsdp_offload_params=True"      )

        for policy in FSDP_AUTO_WRAP_POLICY:
         if policy.lower() in config:
          cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}'''      )
          break

        if policy == "TRANSFORMER_BASED_WRAP":
         cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer"      )
        elif policy == "SIZE_BASED_WRAP":
         cmd_config.append("--fsdp_min_num_params=2000"      )

        cmd_config.extend(
            [
                self.test_file_path,
                f'''--output_dir={self.tmpdir}''',
                f'''--performance_lower_bound={self.performance_lower_bound}''',
            ]      )
        with patch_environment(omp_num_threads=1      ):
         execute_subprocess_async(lowerCamelCase ,      env=os.environ.copy()      )
      def 	UpperCAmelCase_						(			self   :Tuple      )     ->			Dict:
       UpperCAmelCase__							 =						os.path.join(self.test_scripts_folder ,      "test_checkpointing.py"      )
       UpperCAmelCase__							 =						[
           "accelerate",
           "launch",
           "--num_processes=2",
           "--num_machines=1",
           "--machine_rank=0",
           "--use_fsdp",
           "--mixed_precision=fp16",
           "--fsdp_transformer_layer_cls_to_wrap=BertLayer",
       ]

       for i, strategy in enumerate(lowerCamelCase      ):
        UpperCAmelCase__							 =						cmd.copy()
        cmd_config.append(f'''--fsdp_sharding_strategy={i+1}'''      )
        if strategy != "FULL_SHARD":
         continue
        UpperCAmelCase__							 =						len(lowerCamelCase      )
        for state_dict_type in FSDP_STATE_DICT_TYPE:
         UpperCAmelCase__							 =						cmd_config[:state_dict_config_index]
         cmd_config.append(f'''--fsdp_state_dict_type={state_dict_type}'''      )
         cmd_config.extend(
             [
                 self.test_file_path,
                 f'''--output_dir={self.tmpdir}''',
                 "--partial_train_epoch=1",
             ]      )
         with patch_environment(omp_num_threads=1      ):
          execute_subprocess_async(lowerCamelCase ,      env=os.environ.copy()      )

         UpperCAmelCase__							 =						cmd_config[:-1]
         UpperCAmelCase__							 =						os.path.join(self.tmpdir ,      "epoch_0"      )
         cmd_config.extend(
             [
                 f'''--resume_from_checkpoint={resume_from_checkpoint}''',
             ]      )
         with patch_environment(omp_num_threads=1      ):
          execute_subprocess_async(lowerCamelCase ,      env=os.environ.copy()      )







      def 	UpperCAmelCase_						(			self   :List[Any]      )     ->			Dict:
       UpperCAmelCase__							 =						os.path.join(self.test_scripts_folder ,      "test_peak_memory_usage.py"      )
       UpperCAmelCase__							 =						[
           "accelerate",
           "launch",
           "--num_processes=2",
           "--num_machines=1",
           "--machine_rank=0",
       ]
       for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items():
        UpperCAmelCase__							 =						cmd.copy()
        if "fp16" in spec:
         cmd_config.extend(["--mixed_precision=fp16"]      )
        else:
         cmd_config.extend(["--mixed_precision=no"]      )

        if "multi_gpu" in spec:
         continue
        else:
         cmd_config.extend(["--use_fsdp"]      )
         for i, strategy in enumerate(lowerCamelCase      ):
          if strategy.lower() in spec:
           cmd_config.append(f'''--fsdp_sharding_strategy={i+1}'''      )
           break

         if "cpu_offload" in spec:
          cmd_config.append("--fsdp_offload_params=True"      )

         for policy in FSDP_AUTO_WRAP_POLICY:
          if policy.lower() in spec:
           cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}'''      )
           break

         if policy == "TRANSFORMER_BASED_WRAP":
          cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer"      )
         elif policy == "SIZE_BASED_WRAP":
          cmd_config.append("--fsdp_min_num_params=2000"      )

        cmd_config.extend(
            [
                self.test_file_path,
                f'''--output_dir={self.tmpdir}''',
                f'''--peak_memory_upper_bound={peak_mem_upper_bound}''',
                f'''--n_train={self.n_train}''',
                f'''--n_val={self.n_val}''',
            ]      )
        with patch_environment(omp_num_threads=1      ):
         execute_subprocess_async(lowerCamelCase ,      env=os.environ.copy()      )











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      (				lowerCAmelCase		):
      # to overwrite at feature extractactor specific tests
      UpperCAmelCase_        =		None
      UpperCAmelCase_        =		None
      @property
      def 	UpperCAmelCase_						(			self   :int      )     ->			int:
       return self.feat_extract_tester.prepare_feat_extract_dict()
      def 	UpperCAmelCase_						(			self   :Any      )     ->			str:
       UpperCAmelCase__							 =						self.feature_extraction_class(**self.feat_extract_dict      )
       self.assertTrue(hasattr(lowerCamelCase ,      "feature_size"      )      )
       self.assertTrue(hasattr(lowerCamelCase ,      "sampling_rate"      )      )
       self.assertTrue(hasattr(lowerCamelCase ,      "padding_value"      )      )
      def 	UpperCAmelCase_						(			self   :str      )     ->			int:
       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common()
       UpperCAmelCase__							 =						self.feature_extraction_class(**self.feat_extract_dict      )
       UpperCAmelCase__							 =						feat_extract.model_input_names[0]

       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs}      )

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

       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common(equal_length=lowerCamelCase      )
       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs} ,      tensor_type="np"      )

       UpperCAmelCase__							 =						processed_features[input_name]

       if len(batch_features_input.shape      ) < 3:
        UpperCAmelCase__							 =						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 	UpperCAmelCase_						(			self   :Dict      )     ->			Union[str, Any]:
       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common(equal_length=lowerCamelCase      )
       UpperCAmelCase__							 =						self.feature_extraction_class(**self.feat_extract_dict      )
       UpperCAmelCase__							 =						feat_extract.model_input_names[0]

       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs} ,      tensor_type="pt"      )

       UpperCAmelCase__							 =						processed_features[input_name]

       if len(batch_features_input.shape      ) < 3:
        UpperCAmelCase__							 =						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 	UpperCAmelCase_						(			self   :Tuple      )     ->			Dict:
       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common(equal_length=lowerCamelCase      )
       UpperCAmelCase__							 =						self.feature_extraction_class(**self.feat_extract_dict      )
       UpperCAmelCase__							 =						feat_extract.model_input_names[0]

       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs} ,      tensor_type="tf"      )

       UpperCAmelCase__							 =						processed_features[input_name]

       if len(batch_features_input.shape      ) < 3:
        UpperCAmelCase__							 =						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 	UpperCAmelCase_						(			self   :int ,      lowerCamelCase   :int=False      )     ->			str:
       def _inputs_have_equal_length(lowerCamelCase   :Union[str, Any]      ):
        UpperCAmelCase__							 =						len(input[0]      )
        for input_slice in input[1:]:
         if len(lowerCamelCase      ) != length:
          return False
        return True

       def _inputs_are_equal(lowerCamelCase   :Dict ,      lowerCamelCase   :Optional[Any]      ):
        if len(lowerCamelCase      ) != len(lowerCamelCase      ):
         return False

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

       UpperCAmelCase__							 =						self.feature_extraction_class(**self.feat_extract_dict      )
       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common(numpify=lowerCamelCase      )
       UpperCAmelCase__							 =						feat_extract.model_input_names[0]

       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs}      )

       UpperCAmelCase__							 =						self.feat_extract_tester.seq_length_diff
       UpperCAmelCase__							 =						self.feat_extract_tester.max_seq_length + pad_diff
       UpperCAmelCase__							 =						self.feat_extract_tester.min_seq_length
       UpperCAmelCase__							 =						self.feat_extract_tester.batch_size
       UpperCAmelCase__							 =						self.feat_extract_tester.feature_size

       # test padding for List[int] + numpy
       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      padding=lowerCamelCase      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      padding="longest"      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[-1]      )      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      padding="longest" ,      return_tensors="np"      )
       UpperCAmelCase__							 =						input_a[input_name]

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

       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=lowerCamelCase ,      return_tensors="np"      )
       UpperCAmelCase__							 =						input_a[input_name]

       self.assertFalse(_inputs_have_equal_length(lowerCamelCase      )      )
       self.assertTrue(_inputs_have_equal_length(lowerCamelCase      )      )
       self.assertTrue(_inputs_have_equal_length(lowerCamelCase      )      )
       self.assertTrue(_inputs_are_equal(lowerCamelCase ,      lowerCamelCase      )      )
       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
       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      pad_to_multiple_of=10      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      padding="longest" ,      pad_to_multiple_of=10      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      pad_to_multiple_of=10 ,      max_length=lowerCamelCase      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      pad_to_multiple_of=10 ,      max_length=lowerCamelCase ,      return_tensors="np" ,      )
       UpperCAmelCase__							 =						input_a[input_name]

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

       UpperCAmelCase__							 =						pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10
       self.assertTrue(all(len(lowerCamelCase      ) == 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
       UpperCAmelCase__							 =						(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 	UpperCAmelCase_						(			self   :List[str] ,      lowerCamelCase   :int=False      )     ->			str:
       def _inputs_have_equal_length(lowerCamelCase   :Any      ):
        UpperCAmelCase__							 =						len(input[0]      )
        for input_slice in input[1:]:
         if len(lowerCamelCase      ) != length:
          return False
        return True

       def _inputs_are_equal(lowerCamelCase   :Optional[int] ,      lowerCamelCase   :str      ):
        if len(lowerCamelCase      ) != len(lowerCamelCase      ):
         return False

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

       UpperCAmelCase__							 =						self.feature_extraction_class(**self.feat_extract_dict      )
       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common(numpify=lowerCamelCase      )
       UpperCAmelCase__							 =						feat_extract.model_input_names[0]

       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs}      )

       # truncate to smallest
       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[0]      ) ,      truncation=lowerCamelCase      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[0]      )      )
       UpperCAmelCase__							 =						input_a[input_name]

       self.assertTrue(_inputs_have_equal_length(lowerCamelCase      )      )
       self.assertFalse(_inputs_have_equal_length(lowerCamelCase      )      )

       # truncate to smallest with np
       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[0]      ) ,      return_tensors="np" ,      truncation=lowerCamelCase ,      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[0]      ) ,      return_tensors="np"      )
       UpperCAmelCase__							 =						input_a[input_name]

       self.assertTrue(_inputs_have_equal_length(lowerCamelCase      )      )
       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(lowerCamelCase      )      )

       # truncate to middle
       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[1]      ) ,      truncation=lowerCamelCase ,      return_tensors="np" ,      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[1]      ) ,      truncation=lowerCamelCase      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[1]      ) ,      return_tensors="np"      )
       UpperCAmelCase__							 =						input_a[input_name]

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

       # 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(lowerCamelCase      )      )
       self.assertTrue(len(input_a[-1]      ) == len(speech_inputs[-1]      )      )

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

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

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

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

       # test truncation for `pad_to_multiple_of` for List[int] + numpy
       UpperCAmelCase__							 =						12
       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[0]      ) ,      pad_to_multiple_of=lowerCamelCase ,      truncation=lowerCamelCase ,      )
       UpperCAmelCase__							 =						input_a[input_name]

       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=len(speech_inputs[0]      ) ,      pad_to_multiple_of=lowerCamelCase ,      )
       UpperCAmelCase__							 =						input_a[input_name]

       # retrieve expected_length as multiple of pad_to_multiple_of
       UpperCAmelCase__							 =						len(speech_inputs[0]      )
       if expected_length % pad_to_multiple_of != 0:
        UpperCAmelCase__							 =						((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(lowerCamelCase      )      )
       self.assertFalse(_inputs_have_equal_length(lowerCamelCase      )      )
      def 	UpperCAmelCase_						(			self   :int      )     ->			List[str]:
       self._check_padding(numpify=lowerCamelCase      )
      def 	UpperCAmelCase_						(			self   :List[Any]      )     ->			int:
       self._check_padding(numpify=lowerCamelCase      )
      def 	UpperCAmelCase_						(			self   :str      )     ->			str:
       self._check_truncation(numpify=lowerCamelCase      )
      def 	UpperCAmelCase_						(			self   :Dict      )     ->			str:
       self._check_truncation(numpify=lowerCamelCase      )
      @require_torch
      def 	UpperCAmelCase_						(			self   :int      )     ->			Any:
       UpperCAmelCase__							 =						self.feature_extraction_class(**self.feat_extract_dict      )
       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common()
       UpperCAmelCase__							 =						feat_extract.model_input_names[0]

       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs}      )

       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      padding="longest" ,      return_tensors="np"      )[input_name]
       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      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 	UpperCAmelCase_						(			self   :List[Any]      )     ->			Optional[Any]:
       UpperCAmelCase__							 =						self.feature_extraction_class(**self.feat_extract_dict      )
       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common()
       UpperCAmelCase__							 =						feat_extract.model_input_names[0]

       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs}      )

       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      padding="longest" ,      return_tensors="np"      )[input_name]
       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      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 	UpperCAmelCase_						(			self   :List[str]      )     ->			str:
       UpperCAmelCase__							 =						self.feat_extract_dict
       UpperCAmelCase__							 =						True
       UpperCAmelCase__							 =						self.feature_extraction_class(**lowerCamelCase      )
       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common()
       UpperCAmelCase__							 =						[len(lowerCamelCase      ) for x in speech_inputs]
       UpperCAmelCase__							 =						feat_extract.model_input_names[0]

       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs}      )

       UpperCAmelCase__							 =						feat_extract.pad(lowerCamelCase ,      padding="longest" ,      return_tensors="np"      )
       self.assertIn("attention_mask" ,      lowerCamelCase      )
       self.assertListEqual(list(processed.attention_mask.shape      ) ,      list(processed[input_name].shape[:2]      )      )
       self.assertListEqual(processed.attention_mask.sum(-1      ).tolist() ,      lowerCamelCase      )







      def 	UpperCAmelCase_						(			self   :int      )     ->			int:
       UpperCAmelCase__							 =						self.feat_extract_dict
       UpperCAmelCase__							 =						True
       UpperCAmelCase__							 =						self.feature_extraction_class(**lowerCamelCase      )
       UpperCAmelCase__							 =						self.feat_extract_tester.prepare_inputs_for_common()
       UpperCAmelCase__							 =						[len(lowerCamelCase      ) for x in speech_inputs]
       UpperCAmelCase__							 =						feat_extract.model_input_names[0]

       UpperCAmelCase__							 =						BatchFeature({input_name: speech_inputs}      )
       UpperCAmelCase__							 =						min(lowerCamelCase      )

       UpperCAmelCase__							 =						feat_extract.pad(
           lowerCamelCase ,      padding="max_length" ,      max_length=lowerCamelCase ,      truncation=lowerCamelCase ,      return_tensors="np"      )
       self.assertIn("attention_mask" ,      lowerCamelCase      )
       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]      )





