






"""simple docstring"""







import argparse
import shutil
import time
from json import JSONDecodeError
from logging import getLogger
from pathlib import Path
from typing import Dict, List

import torch
from torch.utils.data import DataLoader
from tqdm import tqdm

from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from utils import (
    SeqaSeqDataset,
    calculate_bleu,
    calculate_rouge,
    chunks,
    lmap,
    load_json,
    parse_numeric_n_bool_cl_kwargs,
    save_json,
    use_task_specific_params,
    write_txt_file,
)


lowerCAmelCase_	:    Optional[Any]            =      getLogger(__name__)






def       _lowerCAmelCase       (      lowerCAmelCase	,      lowerCAmelCase	,      lowerCAmelCase	,      lowerCAmelCase = 8	,      lowerCAmelCase = 1024	,      lowerCAmelCase="val"	,      lowerCAmelCase=None	,      lowerCAmelCase=False	,      lowerCAmelCase="summarization"	,      lowerCAmelCase=None	,      lowerCAmelCase=1	,      lowerCAmelCase = None	,      lowerCAmelCase=""	,      **lowerCAmelCase	,      ):







       '''simple docstring'''
       UpperCAmelCase	    =			str(lowerCAmelCase		)
       assert local_rank is not None
       torch.distributed.init_process_group(backend="""nccl"""	,      rank=lowerCAmelCase		)

       UpperCAmelCase	    =			Path(lowerCAmelCase		)
       UpperCAmelCase	    =			save_dir.joinpath(F'''rank_{local_rank}_output.json'''		)
       torch.cuda.set_device(lowerCAmelCase		)
       UpperCAmelCase	    =			AutoModelForSeqaSeqLM.from_pretrained(lowerCAmelCase		).cuda()
       if fpaa:
              UpperCAmelCase	    =			model.half()
       # determine if we need to increase num_beams
       use_task_specific_params(lowerCAmelCase	,      lowerCAmelCase		)  # update config with task specific params
       UpperCAmelCase	    =			generate_kwargs.pop("""num_beams"""	,      model.config.num_beams		)  # AttributeError risk?
       if num_return_sequences > num_beams:
              UpperCAmelCase	    =			num_return_sequences

       UpperCAmelCase	    =			AutoTokenizer.from_pretrained(lowerCAmelCase		)
       logger.info(F'''Inferred tokenizer type: {tokenizer.__class__}'''		)  # if this is wrong, check config.model_type.

       if max_source_length is None:
              UpperCAmelCase	    =			tokenizer.model_max_length
       if prefix is None:
              UpperCAmelCase	    =			prefix or getattr(model.config	,      """prefix"""	,      """"""		) or """"""
       UpperCAmelCase	    =			SeqaSeqDataset(
           lowerCAmelCase	,      lowerCAmelCase	,      lowerCAmelCase	,      max_target_length=1024	,      type_path=lowerCAmelCase	,      n_obs=lowerCAmelCase	,      prefix=lowerCAmelCase	,      **lowerCAmelCase	,      )
       # I set shuffle=True for a more accurate progress bar.
       # If all the longest samples are first, the prog bar estimate is too high at the beginning.
       UpperCAmelCase	    =			ds.make_sortish_sampler(lowerCAmelCase	,      distributed=lowerCAmelCase	,      add_extra_examples=lowerCAmelCase	,      shuffle=lowerCAmelCase		)
       UpperCAmelCase	    =			DataLoader(lowerCAmelCase	,      sampler=lowerCAmelCase	,      batch_size=lowerCAmelCase	,      collate_fn=ds.collate_fn		)
       UpperCAmelCase	    =			[]
       for batch in tqdm(lowerCAmelCase		):
              UpperCAmelCase	    =			model.generate(
                  input_ids=batch["""input_ids"""].to(model.device		)	,      attention_mask=batch["""attention_mask"""].to(model.device		)	,      num_return_sequences=lowerCAmelCase	,      num_beams=lowerCAmelCase	,      **lowerCAmelCase	,      )
              UpperCAmelCase	    =			tokenizer.batch_decode(lowerCAmelCase	,      skip_special_tokens=lowerCAmelCase	,      clean_up_tokenization_spaces=lowerCAmelCase		)
              UpperCAmelCase	    =			batch["""ids"""]
              if num_return_sequences > 1:
                     UpperCAmelCase	    =			chunks(lowerCAmelCase	,      lowerCAmelCase		)  # batch size chunks, each of size num_return_seq
              for i, pred in enumerate(lowerCAmelCase		):
                     results.append({"""pred""": pred, """id""": ids[i].item()}		)
       save_json(lowerCAmelCase	,      lowerCAmelCase		)
       return results, sampler.num_replicas






def       _lowerCAmelCase       (      ):







       '''simple docstring'''
       UpperCAmelCase	    =			argparse.ArgumentParser(
           epilog="""Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate"""		)
       parser.add_argument("""--data_dir"""	,      type=lowerCAmelCase	,      help="""like cnn_dm/test.source"""		)
       parser.add_argument(
           """--model_name"""	,      type=lowerCAmelCase	,      help="""like facebook/bart-large-cnn,t5-base, etc."""	,      default="""sshleifer/distilbart-xsum-12-3"""	,      )
       parser.add_argument("""--save_dir"""	,      type=lowerCAmelCase	,      help="""where to save"""	,      default="""tmp_gen"""		)
       parser.add_argument("""--max_source_length"""	,      type=lowerCAmelCase	,      default=lowerCAmelCase		)
       parser.add_argument(
           """--type_path"""	,      type=lowerCAmelCase	,      default="""test"""	,      help="""which subset to evaluate typically train/val/test"""		)
       parser.add_argument("""--task"""	,      type=lowerCAmelCase	,      default="""summarization"""	,      help="""used for task_specific_params + metrics"""		)
       parser.add_argument("""--bs"""	,      type=lowerCAmelCase	,      default=8	,      required=lowerCAmelCase	,      help="""batch size"""		)
       parser.add_argument(
           """--local_rank"""	,      type=lowerCAmelCase	,      default=-1	,      required=lowerCAmelCase	,      help="""should be passed by distributed.launch"""		)

       parser.add_argument(
           """--n_obs"""	,      type=lowerCAmelCase	,      default=lowerCAmelCase	,      required=lowerCAmelCase	,      help="""How many observations. Defaults to all."""		)
       parser.add_argument(
           """--num_return_sequences"""	,      type=lowerCAmelCase	,      default=1	,      required=lowerCAmelCase	,      help="""How many sequences to return"""		)
       parser.add_argument(
           """--sync_timeout"""	,      type=lowerCAmelCase	,      default=600	,      required=lowerCAmelCase	,      help="""How long should master process wait for other processes to finish."""	,      )
       parser.add_argument("""--src_lang"""	,      type=lowerCAmelCase	,      default=lowerCAmelCase	,      required=lowerCAmelCase		)
       parser.add_argument("""--tgt_lang"""	,      type=lowerCAmelCase	,      default=lowerCAmelCase	,      required=lowerCAmelCase		)
       parser.add_argument(
           """--prefix"""	,      type=lowerCAmelCase	,      required=lowerCAmelCase	,      default=lowerCAmelCase	,      help="""will be added to the begininng of src examples"""		)
       parser.add_argument("""--fp16"""	,      action="""store_true"""		)
       parser.add_argument("""--debug"""	,      action="""store_true"""		)
       UpperCAmelCase	    =			time.time()
       UpperCAmelCase    ,       UpperCAmelCase	    =			parser.parse_known_args()
       UpperCAmelCase	    =			parse_numeric_n_bool_cl_kwargs(lowerCAmelCase		)
       if generate_kwargs and args.local_rank <= 0:
              print(F'''parsed the following generate kwargs: {generate_kwargs}'''		)
       UpperCAmelCase	    =			Path(args.save_dir + """_tmp"""		)
       Path(lowerCAmelCase		).mkdir(exist_ok=lowerCAmelCase		)  # this handles locking.
       UpperCAmelCase	    =			list(json_save_dir.glob("""rank_*.json"""		)		)
       if intermediate_files:
              raise ValueError(F'''Found files at {json_save_dir} please move or remove them.'''		)
              # In theory, a node could finish and save before another node hits this. If this happens, we can address later.
       UpperCAmelCase	    =			{}
       if args.src_lang is not None:
              UpperCAmelCase	    =			args.src_lang
       if args.tgt_lang is not None:
              UpperCAmelCase	    =			args.tgt_lang

       Path(args.save_dir		).mkdir(exist_ok=lowerCAmelCase		)
       UpperCAmelCase    ,       UpperCAmelCase	    =			eval_data_dir(
           args.data_dir	,      lowerCAmelCase	,      args.model_name	,      type_path=args.type_path	,      bs=args.bs	,      fpaa=args.fpaa	,      task=args.task	,      local_rank=args.local_rank	,      n_obs=args.n_obs	,      max_source_length=args.max_source_length	,      num_return_sequences=args.num_return_sequences	,      prefix=args.prefix	,      dataset_kwargs=lowerCAmelCase	,      **lowerCAmelCase	,      )

       if args.local_rank <= 0:
              UpperCAmelCase	    =			Path(args.save_dir		)
              save_dir.mkdir(exist_ok=lowerCAmelCase		)
              UpperCAmelCase	    =			gather_results_from_each_node(lowerCAmelCase	,      lowerCAmelCase	,      args.sync_timeout		)
              UpperCAmelCase	    =			combine_partial_results(lowerCAmelCase		)
              if args.num_return_sequences > 1:
                     UpperCAmelCase	    =			save_dir.joinpath("""pseudolabel_results.json"""		)
                     print(F'''Saving aggregated results at {save_path}, intermediate in {json_save_dir}/'''		)
                     save_json(lowerCAmelCase	,      lowerCAmelCase		)
                     return
              UpperCAmelCase	    =			Path(args.data_dir		).joinpath(args.type_path + """.target"""		)
              with open(lowerCAmelCase		) as f:
                     UpperCAmelCase	    =			[x.rstrip() for x in f.readlines()][: len(lowerCAmelCase		)]

              # Calculate metrics, save metrics,  and save _generations.txt
              UpperCAmelCase	    =			"""translation""" in args.task
              UpperCAmelCase	    =			calculate_bleu if calc_bleu else calculate_rouge
              UpperCAmelCase	    =			"""bleu""" if calc_bleu else """rouge"""
              UpperCAmelCase	    =			score_fn(lowerCAmelCase	,      lowerCAmelCase		)
              UpperCAmelCase	    =			len(lowerCAmelCase		)
              UpperCAmelCase	    =			time.time() - start_time
              UpperCAmelCase	    =			round(runtime / metrics["""n_obs"""]	,      4		)
              UpperCAmelCase	    =			num_replicas
              # TODO(@stas00): add whatever metadata to metrics
              UpperCAmelCase	    =			save_dir.joinpath(F'''{args.type_path}_{metric_name}.json'''		)
              save_json(lowerCAmelCase	,      lowerCAmelCase	,      indent=lowerCAmelCase		)
              print(lowerCAmelCase		)
              write_txt_file(lowerCAmelCase	,      save_dir.joinpath(F'''{args.type_path}_generations.txt'''		)		)
              if args.debug:
                     write_txt_file(lowerCAmelCase	,      save_dir.joinpath(F'''{args.type_path}.target'''		)		)
              else:
                     shutil.rmtree(lowerCAmelCase		)






def       _lowerCAmelCase       (      lowerCAmelCase		):







       '''simple docstring'''
       UpperCAmelCase	    =			[]
       for partial_result in partial_results:
              records.extend(lowerCAmelCase		)
       UpperCAmelCase	    =			sorted(lowerCAmelCase	,      key=lambda lowerCAmelCase		: x["id"]		)
       UpperCAmelCase	    =			[x["""pred"""] for x in records]
       return preds






def       _lowerCAmelCase       (      lowerCAmelCase	,      lowerCAmelCase	,      lowerCAmelCase		):







       '''simple docstring'''
       UpperCAmelCase	    =			time.time()
       logger.info("""waiting for all nodes to finish"""		)
       UpperCAmelCase	    =			None
       while (time.time() - start_wait) < timeout:
              UpperCAmelCase	    =			list(save_dir.glob("""rank_*.json"""		)		)
              if len(lowerCAmelCase		) < num_replicas:
                     continue
              try:
                     # make sure all json files are fully saved
                     UpperCAmelCase	    =			lmap(lowerCAmelCase	,      lowerCAmelCase		)
                     return json_data
              except JSONDecodeError:
                     continue
       else:
              raise TimeoutError("""Rank 0 gave up on waiting for other processes"""		)
       # Unreachable


if __name__ == "__main__":
 # Usage for MT:
 run_generate()







"""simple docstring"""







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   UpperCamelCase_ :



  def __init__(      self ,		snake_case__ ,		snake_case__=13 ,		snake_case__=2 ,		snake_case__=24 ,		snake_case__=16 ,		snake_case__=True ,		snake_case__=True ,		snake_case__=32 ,		snake_case__=5 ,		snake_case__=4 ,		snake_case__=37 ,		snake_case__="gelu" ,		snake_case__=0.1 ,		snake_case__=0.1 ,		snake_case__=10 ,		snake_case__=0.02 ,		snake_case__=None ,		snake_case__=2 ,		snake_case__=2 ,		)			->			List[Any]:



         """simple docstring"""





         UpperCAmelCase	    =			parent
         UpperCAmelCase	    =			batch_size
         UpperCAmelCase	    =			patch_size
         UpperCAmelCase	    =			max_length
         UpperCAmelCase	    =			num_mel_bins
         UpperCAmelCase	    =			is_training
         UpperCAmelCase	    =			use_labels
         UpperCAmelCase	    =			hidden_size
         UpperCAmelCase	    =			num_hidden_layers
         UpperCAmelCase	    =			num_attention_heads
         UpperCAmelCase	    =			intermediate_size
         UpperCAmelCase	    =			hidden_act
         UpperCAmelCase	    =			hidden_dropout_prob
         UpperCAmelCase	    =			attention_probs_dropout_prob
         UpperCAmelCase	    =			type_sequence_label_size
         UpperCAmelCase	    =			initializer_range
         UpperCAmelCase	    =			scope
         UpperCAmelCase	    =			frequency_stride
         UpperCAmelCase	    =			time_stride

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



  def 		UpperCamelCase_				(      self				)			->			Optional[Any]:



         """simple docstring"""





         UpperCAmelCase	    =			floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]				)

         UpperCAmelCase	    =			None
         if self.use_labels:
                UpperCAmelCase	    =			ids_tensor([self.batch_size] ,		self.type_sequence_label_size				)

         UpperCAmelCase	    =			self.get_config()

         return config, input_values, labels



  def 		UpperCamelCase_				(      self				)			->			int:



         """simple docstring"""





         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=snake_case__ ,		initializer_range=self.initializer_range ,		frequency_stride=self.frequency_stride ,		time_stride=self.time_stride ,		)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__				)			->			List[Any]:



         """simple docstring"""





         UpperCAmelCase	    =			ASTModel(config=snake_case__				)
         model.to(snake_case__				)
         model.eval()
         UpperCAmelCase	    =			model(snake_case__				)
         self.parent.assertEqual(result.last_hidden_state.shape ,		(self.batch_size, self.seq_length, self.hidden_size)				)



  def 		UpperCamelCase_				(      self				)			->			Optional[Any]:



         """simple docstring"""





         UpperCAmelCase	    =			self.prepare_config_and_inputs()
         (
             (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       (
             UpperCAmelCase
         )    ,       
         )	    =			config_and_inputs
         UpperCAmelCase	    =			{"""input_values""": input_values}
         return config, inputs_dict





@require_torch
class   UpperCamelCase_ (       a_   ,					a_   ,					unittest.TestCase  ):
  _A       :					Any				=	(
      (
          ASTModel,
          ASTForAudioClassification,
      )
      if is_torch_available()
      else ()
  )
  _A       :					Union[str, Any]				=	(
      {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
      if is_torch_available()
      else {}
  )
  _A       :					Any				=	False
  _A       :					Dict				=	False
  _A       :					Optional[Any]				=	False
  _A       :					List[str]				=	False



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__				)			->			Dict:



         """simple docstring"""





         if pipeline_test_casse_name == "AudioClassificationPipelineTests":
                return True

         return False



  def 		UpperCamelCase_				(      self				)			->			List[Any]:



         """simple docstring"""





         UpperCAmelCase	    =			ASTModelTester(self				)
         UpperCAmelCase	    =			ConfigTester(self ,		config_class=snake_case__ ,		has_text_modality=snake_case__ ,		hidden_size=37				)



  def 		UpperCamelCase_				(      self				)			->			Tuple:



         """simple docstring"""





         self.config_tester.run_common_tests()



  @unittest.skip(reason="""AST does not use inputs_embeds"""				)
  def 		UpperCamelCase_				(      self				)			->			Tuple:



         """simple docstring"""





         pass



  def 		UpperCamelCase_				(      self				)			->			Dict:



         """simple docstring"""





         UpperCAmelCase    ,       UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
                UpperCAmelCase	    =			model_class(snake_case__				)
                self.assertIsInstance(model.get_input_embeddings() ,		(nn.Module)				)
                UpperCAmelCase	    =			model.get_output_embeddings()
                self.assertTrue(x is None or isinstance(snake_case__ ,		nn.Linear				)				)



  def 		UpperCamelCase_				(      self				)			->			List[Any]:



         """simple docstring"""





         UpperCAmelCase    ,       UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
                UpperCAmelCase	    =			model_class(snake_case__				)
                UpperCAmelCase	    =			inspect.signature(model.forward				)
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                UpperCAmelCase	    =			[*signature.parameters.keys()]

                UpperCAmelCase	    =			["""input_values"""]
                self.assertListEqual(arg_names[:1] ,		snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			List[str]:



         """simple docstring"""





         UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*snake_case__				)



  @slow
  def 		UpperCamelCase_				(      self				)			->			Union[str, Any]:



         """simple docstring"""





         for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase	    =			ASTModel.from_pretrained(snake_case__				)
                self.assertIsNotNone(snake_case__				)






def       _lowerCAmelCase       (      ):







       '''simple docstring'''
       UpperCAmelCase	    =			hf_hub_download(
           repo_id="""nielsr/audio-spectogram-transformer-checkpoint"""	,      filename="""sample_audio.flac"""	,      repo_type="""dataset"""		)

       UpperCAmelCase    ,       UpperCAmelCase	    =			torchaudio.load(lowerCAmelCase		)

       return audio, sampling_rate





@require_torch
@require_torchaudio
class   UpperCamelCase_ (       unittest.TestCase  ):



  @cached_property
  def 		UpperCamelCase_				(      self				)			->			int:



         """simple docstring"""





         return (
             ASTFeatureExtractor.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""				)
             if is_torchaudio_available()
             else None
         )



  @slow
  def 		UpperCamelCase_				(      self				)			->			Optional[int]:



         """simple docstring"""





         UpperCAmelCase	    =			self.default_feature_extractor
         UpperCAmelCase	    =			ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""				).to(snake_case__				)

         UpperCAmelCase	    =			self.default_feature_extractor
         UpperCAmelCase    ,       UpperCAmelCase	    =			prepare_audio()
         UpperCAmelCase	    =			audio.squeeze().numpy()
         UpperCAmelCase	    =			feature_extractor(snake_case__ ,		sampling_rate=snake_case__ ,		return_tensors="""pt"""				).to(snake_case__				)

         # forward pass
         with torch.no_grad():
                UpperCAmelCase	    =			model(**snake_case__				)

         # verify the logits
         UpperCAmelCase	    =			torch.Size((1, 5_27)				)
         self.assertEqual(outputs.logits.shape ,		snake_case__				)

         UpperCAmelCase	    =			torch.tensor([-0.8_760, -7.0_042, -8.6_602]				).to(snake_case__				)

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