import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import ASTForAudioClassification, ASTModel
    from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
        AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
    )


if is_torchaudio_available():
    import torchaudio

    from transformers import ASTFeatureExtractor



class  SCREAMING_SNAKE_CASE_ :
  '''simple docstring'''


  def __init__(				self    :					Tuple      ,	SCREAMING_SNAKE_CASE__    :					str      ,	SCREAMING_SNAKE_CASE__    :					List[str]=13      ,	SCREAMING_SNAKE_CASE__    :					Tuple=2      ,	SCREAMING_SNAKE_CASE__    :					Dict=24      ,	SCREAMING_SNAKE_CASE__    :					Optional[int]=16      ,	SCREAMING_SNAKE_CASE__    :					Optional[int]=True      ,	SCREAMING_SNAKE_CASE__    :					Union[str, Any]=True      ,	SCREAMING_SNAKE_CASE__    :					Optional[int]=32      ,	SCREAMING_SNAKE_CASE__    :					Dict=5      ,	SCREAMING_SNAKE_CASE__    :					Optional[Any]=4      ,	SCREAMING_SNAKE_CASE__    :					Union[str, Any]=37      ,	SCREAMING_SNAKE_CASE__    :					List[Any]="gelu"      ,	SCREAMING_SNAKE_CASE__    :					Any=0.1      ,	SCREAMING_SNAKE_CASE__    :					List[Any]=0.1      ,	SCREAMING_SNAKE_CASE__    :					List[Any]=10      ,	SCREAMING_SNAKE_CASE__    :					List[Any]=0.0_2      ,	SCREAMING_SNAKE_CASE__    :					Optional[int]=None      ,	SCREAMING_SNAKE_CASE__    :					int=2      ,	SCREAMING_SNAKE_CASE__    :					Tuple=2      ,	)    ->				int:
         A						:     List[Any]         =parent
         A						:     Any         =batch_size
         A						:     int         =patch_size
         A						:     Union[str, Any]         =max_length
         A						:     int         =num_mel_bins
         A						:     Optional[Any]         =is_training
         A						:     Optional[int]         =use_labels
         A						:     Optional[int]         =hidden_size
         A						:     Any         =num_hidden_layers
         A						:     Any         =num_attention_heads
         A						:     Optional[int]         =intermediate_size
         A						:     str         =hidden_act
         A						:     Optional[int]         =hidden_dropout_prob
         A						:     Dict         =attention_probs_dropout_prob
         A						:     Optional[int]         =type_sequence_label_size
         A						:     Any         =initializer_range
         A						:     List[str]         =scope
         A						:     str         =frequency_stride
         A						:     List[Any]         =time_stride

         # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
         A						:     int         =(self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
         A						:     Tuple         =(self.max_length - self.patch_size) // self.time_stride + 1
         A						:     str         =frequency_out_dimension * time_out_dimension
         A						:     int         =num_patches + 2







  def 		SCREAMING_SNAKE_CASE_		(				self    :					int     )    ->				List[Any]:
         A						:     Any         =floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]     )

         A						:     List[str]         =None
         if self.use_labels:
                A						:     Dict         =ids_tensor([self.batch_size]      ,	self.type_sequence_label_size     )

         A						:     Optional[int]         =self.get_config()

         return config, input_values, labels







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Dict     )    ->				Optional[int]:
         return ASTConfig(
             patch_size=self.patch_size      ,	max_length=self.max_length      ,	num_mel_bins=self.num_mel_bins      ,	hidden_size=self.hidden_size      ,	num_hidden_layers=self.num_hidden_layers      ,	num_attention_heads=self.num_attention_heads      ,	intermediate_size=self.intermediate_size      ,	hidden_act=self.hidden_act      ,	hidden_dropout_prob=self.hidden_dropout_prob      ,	attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,	is_decoder=SCREAMING_SNAKE_CASE__      ,	initializer_range=self.initializer_range      ,	frequency_stride=self.frequency_stride      ,	time_stride=self.time_stride      ,	)







  def 		SCREAMING_SNAKE_CASE_		(				self    :					str      ,	SCREAMING_SNAKE_CASE__    :					Tuple      ,	SCREAMING_SNAKE_CASE__    :					str      ,	SCREAMING_SNAKE_CASE__    :					Optional[int]     )    ->				str:
         A						:     List[str]         =ASTModel(config=SCREAMING_SNAKE_CASE__     )
         model.to(SCREAMING_SNAKE_CASE__     )
         model.eval()
         A						:     Dict         =model(SCREAMING_SNAKE_CASE__     )
         self.parent.assertEqual(result.last_hidden_state.shape      ,	(self.batch_size, self.seq_length, self.hidden_size)     )







  def 		SCREAMING_SNAKE_CASE_		(				self    :					List[Any]     )    ->				List[str]:
         A						:     str         =self.prepare_config_and_inputs()
         (
             (
             A
         )  ,  (
             A
         )  ,  (
             A
         )  ,  
         )						:     Any         =config_and_inputs
         A						:     Any         ={'input_values': input_values}
         return config, inputs_dict







@require_torch
class  SCREAMING_SNAKE_CASE_ (					lowerCAmelCase_   ,						lowerCAmelCase_   ,						unittest.TestCase			):
  '''simple docstring'''


  lowercase		:     Optional[Any]            =				(
      (
          ASTModel,
          ASTForAudioClassification,
      )
      if is_torch_available()
      else ()
  )
  lowercase		:     Dict            =				(
      {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
      if is_torch_available()
      else {}
  )
  lowercase		:     Optional[int]            =				False
  lowercase		:     int            =				False
  lowercase		:     Dict            =				False
  lowercase		:     List[Any]            =				False







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Dict      ,	SCREAMING_SNAKE_CASE__    :					Union[str, Any]      ,	SCREAMING_SNAKE_CASE__    :					Optional[Any]      ,	SCREAMING_SNAKE_CASE__    :					Union[str, Any]      ,	SCREAMING_SNAKE_CASE__    :					List[str]      ,	SCREAMING_SNAKE_CASE__    :					List[str]     )    ->				List[str]:
         if pipeline_test_casse_name == "AudioClassificationPipelineTests":
                return True

         return False







  def 		SCREAMING_SNAKE_CASE_		(				self    :					int     )    ->				Any:
         A						:     Optional[int]         =ASTModelTester(self     )
         A						:     Union[str, Any]         =ConfigTester(self      ,	config_class=SCREAMING_SNAKE_CASE__      ,	has_text_modality=SCREAMING_SNAKE_CASE__      ,	hidden_size=37     )







  def 		SCREAMING_SNAKE_CASE_		(				self    :					List[Any]     )    ->				Tuple:
         self.config_tester.run_common_tests()







  @unittest.skip(reason='AST does not use inputs_embeds'     )
  def 		SCREAMING_SNAKE_CASE_		(				self    :					str     )    ->				List[str]:
         pass







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Union[str, Any]     )    ->				int:
         A  ,  A						:     Optional[int]         =self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
                A						:     List[str]         =model_class(SCREAMING_SNAKE_CASE__     )
                self.assertIsInstance(model.get_input_embeddings()      ,	(nn.Module)     )
                A						:     Tuple         =model.get_output_embeddings()
                self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__      ,	nn.Linear     )     )







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Optional[Any]     )    ->				Optional[Any]:
         A  ,  A						:     Any         =self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
                A						:     Optional[Any]         =model_class(SCREAMING_SNAKE_CASE__     )
                A						:     Tuple         =inspect.signature(model.forward     )
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                A						:     Union[str, Any]         =[*signature.parameters.keys()]

                A						:     Union[str, Any]         =['input_values']
                self.assertListEqual(arg_names[:1]      ,	SCREAMING_SNAKE_CASE__     )







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Union[str, Any]     )    ->				Tuple:
         A						:     Dict         =self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__     )







  @slow
  def 		SCREAMING_SNAKE_CASE_		(				self    :					Any     )    ->				Tuple:
         for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                A						:     List[str]         =ASTModel.from_pretrained(SCREAMING_SNAKE_CASE__     )
                self.assertIsNotNone(SCREAMING_SNAKE_CASE__     )







def A__  (			)				->		Optional[int]:
       A						:     Tuple         =hf_hub_download(
           repo_id='nielsr/audio-spectogram-transformer-checkpoint',		filename='sample_audio.flac',		repo_type='dataset'					)

       A  ,  A						:     str         =torchaudio.load(lowercase					)

       return audio, sampling_rate



@require_torch
@require_torchaudio
class  SCREAMING_SNAKE_CASE_ (					unittest.TestCase			):
  '''simple docstring'''


  @cached_property
  def 		SCREAMING_SNAKE_CASE_		(				self    :					List[str]     )    ->				Union[str, Any]:
         return (
             ASTFeatureExtractor.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'     )
             if is_torchaudio_available()
             else None
         )







  @slow
  def 		SCREAMING_SNAKE_CASE_		(				self    :					str     )    ->				Dict:
         A						:     Dict         =self.default_feature_extractor
         A						:     int         =ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'     ).to(SCREAMING_SNAKE_CASE__     )

         A						:     Optional[Any]         =self.default_feature_extractor
         A  ,  A						:     Union[str, Any]         =prepare_audio()
         A						:     Optional[int]         =audio.squeeze().numpy()
         A						:     str         =feature_extractor(SCREAMING_SNAKE_CASE__      ,	sampling_rate=SCREAMING_SNAKE_CASE__      ,	return_tensors='pt'     ).to(SCREAMING_SNAKE_CASE__     )

         # forward pass
         with torch.no_grad():
                A						:     Optional[Any]         =model(**SCREAMING_SNAKE_CASE__     )

         # verify the logits
         A						:     Dict         =torch.Size((1, 5_27)     )
         self.assertEqual(outputs.logits.shape      ,	SCREAMING_SNAKE_CASE__     )

         A						:     Any         =torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]     ).to(SCREAMING_SNAKE_CASE__     )

         self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,	SCREAMING_SNAKE_CASE__      ,	atol=1e-4     )     )







import argparse
import json
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler


_lowercase							:      List[Any]      							=1_6
_lowercase							:      Union[str, Any]      							=3_2



def A__  (			lowercase:     Accelerator,		lowercase:     int = 16,		lowercase:     str = "bert-base-cased"					)				->		Optional[int]:
       A						:     List[Any]         =AutoTokenizer.from_pretrained(lowercase					)
       A						:     Any         =load_dataset('glue',		'mrpc'					)

       def tokenize_function(lowercase:     Any					):
              # max_length=None => use the model max length (it's actually the default)
              A						:     List[str]         =tokenizer(examples['sentence1'],		examples['sentence2'],		truncation=lowercase,		max_length=lowercase					)
              return outputs

       # Apply the method we just defined to all the examples in all the splits of the dataset
       A						:     Any         =datasets.map(
           lowercase,		batched=lowercase,		remove_columns=['idx', 'sentence1', 'sentence2'],		load_from_cache_file=lowercase					)

       # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
       # transformers library
       A						:     Dict         =tokenized_datasets.rename_column('label',		'labels'					)

       def collate_fn(lowercase:     Optional[int]					):
              # On TPU it's best to pad everything to the same length or training will be very slow.
              if accelerator.distributed_type == DistributedType.TPU:
                     return tokenizer.pad(lowercase,		padding='max_length',		max_length=128,		return_tensors='pt'					)
              return tokenizer.pad(lowercase,		padding='longest',		return_tensors='pt'					)

       # Instantiate dataloaders.
       A						:     Union[str, Any]         =DataLoader(
           tokenized_datasets['train'],		shuffle=lowercase,		collate_fn=lowercase,		batch_size=lowercase					)
       A						:     str         =DataLoader(
           tokenized_datasets['validation'],		shuffle=lowercase,		collate_fn=lowercase,		batch_size=lowercase					)

       return train_dataloader, eval_dataloader



def A__  (			lowercase:     Dict,		lowercase:     Optional[int],		lowercase:     Any,		lowercase:     str					)				->		Tuple:
       model.eval()
       A						:     Tuple         =0
       for step, batch in enumerate(lowercase					):
              # We could avoid this line since we set the accelerator with `device_placement=True`.
              batch.to(accelerator.device					)
              with torch.no_grad():
                     A						:     Tuple         =model(**lowercase					)
              A						:     Tuple         =outputs.logits.argmax(dim=-1					)
              # It is slightly faster to call this once, than multiple times
              A  ,  A						:     Union[str, Any]         =accelerator.gather(
                  (predictions, batch['labels'])					)  # If we are in a multiprocess environment, the last batch has duplicates
              if accelerator.use_distributed:
                     if step == len(lowercase					) - 1:
                            A						:     List[Any]         =predictions[: len(eval_dataloader.dataset					) - samples_seen]
                            A						:     Optional[int]         =references[: len(eval_dataloader.dataset					) - samples_seen]
                     else:
                            samples_seen += references.shape[0]
              metric.add_batch(
                  predictions=lowercase,		references=lowercase,		)

       A						:     Union[str, Any]         =metric.compute()
       return eval_metric["accuracy"]



def A__  (			lowercase:     Union[str, Any],		lowercase:     Dict					)				->		List[str]:
       # Initialize accelerator
       A						:     Optional[int]         =Accelerator()

       # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
       A						:     int         =config['lr']
       A						:     Optional[Any]         =int(config['num_epochs']					)
       A						:     Union[str, Any]         =int(config['seed']					)
       A						:     List[str]         =int(config['batch_size']					)
       A						:     Optional[Any]         =args.model_name_or_path

       set_seed(lowercase					)
       A  ,  A						:     str         =get_dataloaders(lowercase,		lowercase,		lowercase					)

       # Instantiate the model (we build the model here so that the seed also control new weights initialization)
       A						:     List[str]         =AutoModelForSequenceClassification.from_pretrained(lowercase,		return_dict=lowercase					)

       # Instantiate optimizer
       A						:     Any         =(
           AdamW
           if accelerator.state.deepspeed_plugin is None
           or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config
           else DummyOptim
       )
       A						:     List[str]         =optimizer_cls(params=model.parameters(),		lr=lowercase					)

       if accelerator.state.deepspeed_plugin is not None:
              A						:     Optional[int]         =accelerator.state.deepspeed_plugin.deepspeed_config[
                  'gradient_accumulation_steps'
              ]
       else:
              A						:     Dict         =1
       A						:     Union[str, Any]         =(len(lowercase					) * num_epochs) // gradient_accumulation_steps

       # Instantiate scheduler
       if (
           accelerator.state.deepspeed_plugin is None
           or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
       ):
              A						:     List[Any]         =get_linear_schedule_with_warmup(
                  optimizer=lowercase,		num_warmup_steps=0,		num_training_steps=lowercase,		)
       else:
              A						:     List[str]         =DummyScheduler(lowercase,		total_num_steps=lowercase,		warmup_num_steps=0					)

       # Prepare everything
       # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
       # prepare method.
       A  ,  A  ,  A  ,  A  ,  A						:     Optional[int]         =accelerator.prepare(
           lowercase,		lowercase,		lowercase,		lowercase,		lowercase					)

       # We need to keep track of how many total steps we have iterated over
       A						:     Tuple         =0
       # We also need to keep track of the stating epoch so files are named properly
       A						:     List[str]         =0
       A						:     Tuple         =evaluate.load('glue',		'mrpc'					)
       A						:     Optional[int]         =num_epochs

       if args.partial_train_epoch is not None:
              A						:     Dict         =args.partial_train_epoch

       if args.resume_from_checkpoint:
              accelerator.load_state(args.resume_from_checkpoint					)
              A						:     List[Any]         =args.resume_from_checkpoint.split('epoch_'					)[1]
              A						:     List[Any]         =''
              for char in epoch_string:
                     if char.isdigit():
                            state_epoch_num += char
                     else:
                            break
              A						:     Union[str, Any]         =int(lowercase					) + 1
              A						:     List[str]         =evaluation_loop(lowercase,		lowercase,		lowercase,		lowercase					)
              accelerator.print('resumed checkpoint performance:',		lowercase					)
              accelerator.print('resumed checkpoint\'s scheduler\'s lr:',		lr_scheduler.get_lr()[0]					)
              accelerator.print('resumed optimizers\'s lr:',		optimizer.param_groups[0]['lr']					)
              with open(os.path.join(args.output_dir,		F'state_{starting_epoch-1}.json'					),		'r'					) as f:
                     A						:     Union[str, Any]         =json.load(lowercase					)
                     assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed"
                     assert (
                         resumed_state["lr"] == lr_scheduler.get_lr()[0]
                     ), "Scheduler learning rate mismatch, loading from checkpoint failed"
                     assert (
                         resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"]
                     ), "Optimizer learning rate mismatch, loading from checkpoint failed"
                     assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed"
                     return

    # Now we train the model
       A						:     str         ={}
       for epoch in range(lowercase,		lowercase					):
              model.train()
              for step, batch in enumerate(lowercase					):
                     A						:     Tuple         =model(**lowercase					)
                     A						:     List[Any]         =outputs.loss
                     A						:     Any         =loss / gradient_accumulation_steps
                     accelerator.backward(lowercase					)
                     if step % gradient_accumulation_steps == 0:
                            optimizer.step()
                            lr_scheduler.step()
                            optimizer.zero_grad()

                     overall_step += 1
              A						:     Union[str, Any]         =F'epoch_{epoch}'
              A						:     Optional[Any]         =os.path.join(args.output_dir,		lowercase					)
              accelerator.save_state(lowercase					)
              A						:     Optional[Any]         =evaluation_loop(lowercase,		lowercase,		lowercase,		lowercase					)
              A						:     Dict         =accuracy
              A						:     Optional[Any]         =lr_scheduler.get_lr()[0]
              A						:     Any         =optimizer.param_groups[0]['lr']
              A						:     str         =epoch
              A						:     Dict         =overall_step
              accelerator.print(F'epoch {epoch}:',		lowercase					)

              accelerator.wait_for_everyone()
              if accelerator.is_main_process:
                     with open(os.path.join(args.output_dir,		F'state_{epoch}.json'					),		'w'					) as f:
                            json.dump(lowercase,		lowercase					)



def A__  (			)				->		Optional[int]:
       A						:     Optional[int]         =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.'					)
       parser.add_argument(
           '--model_name_or_path',		type=lowercase,		default='bert-base-cased',		help='Path to pretrained model or model identifier from huggingface.co/models.',		required=lowercase,		)
       parser.add_argument(
           '--output_dir',		type=lowercase,		default='.',		help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.',		)
       parser.add_argument(
           '--resume_from_checkpoint',		type=lowercase,		default=lowercase,		help='If the training should continue from a checkpoint folder.',		)
       parser.add_argument(
           '--partial_train_epoch',		type=lowercase,		default=lowercase,		help='If passed, the training will stop after this number of epochs.',		)
       parser.add_argument(
           '--num_epochs',		type=lowercase,		default=2,		help='Number of train epochs.',		)
       A						:     str         =parser.parse_args()
       A						:     Optional[int]         ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16}

       training_function(lowercase,		lowercase					)


if __name__ == "__main__":
    main()






