



"""simple docstring"""







import unittest

from datasets import load_dataset

from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow







@is_pipeline_test
@require_torch
class       UpperCamelCase__   (	unittest.TestCase  ):




      """simple docstring"""




      @require_torch
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        lowerCAmelCase_   :				Optional[int]								= pipeline(
            task='zero-shot-audio-classification'    ,			model='hf-internal-testing/tiny-clap-htsat-unfused'       )
        lowerCAmelCase_   :				Optional[int]								= load_dataset('ashraq/esc50'       )
        lowerCAmelCase_   :				str								= dataset['train']['audio'][-1]['array']
        lowerCAmelCase_   :				Optional[int]								= audio_classifier(UpperCamelCase__    ,			candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']       )
        self.assertEqual(
            nested_simplify(UpperCamelCase__       )    ,			[{'score': 0.5_01, 'label': 'Sound of a dog'}, {'score': 0.4_99, 'label': 'Sound of vaccum cleaner'}]    ,			)



      @unittest.skip('No models are available in TF'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        pass



      @slow
      @require_torch
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        lowerCAmelCase_   :				Optional[int]								= pipeline(
            task='zero-shot-audio-classification'    ,			model='laion/clap-htsat-unfused'    ,			)
        # This is an audio of a dog
        lowerCAmelCase_   :				List[Any]								= load_dataset('ashraq/esc50'       )
        lowerCAmelCase_   :				List[Any]								= dataset['train']['audio'][-1]['array']
        lowerCAmelCase_   :				List[Any]								= audio_classifier(UpperCamelCase__    ,			candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']       )

        self.assertEqual(
            nested_simplify(UpperCamelCase__       )    ,			[
                {'score': 0.9_99, 'label': 'Sound of a dog'},
                {'score': 0.0_01, 'label': 'Sound of vaccum cleaner'},
            ]    ,			)

        lowerCAmelCase_   :				Optional[Any]								= audio_classifier([audio] * 5    ,			candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']       )
        self.assertEqual(
            nested_simplify(UpperCamelCase__       )    ,			[
                [
                    {'score': 0.9_99, 'label': 'Sound of a dog'},
                    {'score': 0.0_01, 'label': 'Sound of vaccum cleaner'},
                ],
            ]
            * 5    ,			)
        lowerCAmelCase_   :				Optional[int]								= audio_classifier(
            [audio] * 5    ,			candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']    ,			batch_size=5       )
        self.assertEqual(
            nested_simplify(UpperCamelCase__       )    ,			[
                [
                    {'score': 0.9_99, 'label': 'Sound of a dog'},
                    {'score': 0.0_01, 'label': 'Sound of vaccum cleaner'},
                ],
            ]
            * 5    ,			)





      @unittest.skip('No models are available in TF'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        pass











import argparse
from argparse import Namespace

import torch
from torch import nn

from transformers import XGLMConfig, XGLMForCausalLM





def __UpperCamelCase			(       _A  ):
						lowerCAmelCase_      			=  [
						    '''decoder.version''',
						    '''decoder.output_projection.weight''',
						    '''_float_tensor''',
						    '''decoder.embed_positions._float_tensor''',
						]
						for k in ignore_keys:
												state_dict.pop(_A ,  _A  )





def __UpperCamelCase			(       _A  ):
						lowerCAmelCase_			,					lowerCAmelCase_      			=  emb.weight.shape
						lowerCAmelCase_      			=  nn.Linear(_A ,  _A ,  bias=_A  )
						lowerCAmelCase_      			=  emb.weight.data
						return lin_layer





def __UpperCamelCase			(       _A  ):
						lowerCAmelCase_      			=  torch.load(_A ,  map_location='''cpu'''  )
						lowerCAmelCase_      			=  Namespace(**checkpoint['''cfg''']['''model''']  )
						lowerCAmelCase_      			=  checkpoint['''model''']
						remove_ignore_keys_(_A  )
						lowerCAmelCase_      			=  state_dict['''decoder.embed_tokens.weight'''].shape[0]

						lowerCAmelCase_      			=  {key.replace('''decoder''' ,  '''model'''  ): val for key, val in state_dict.items()}

						lowerCAmelCase_      			=  XGLMConfig(
						    vocab_size=_A ,  max_position_embeddings=args.max_target_positions ,  num_layers=args.decoder_layers ,  attention_heads=args.decoder_attention_heads ,  ffn_dim=args.decoder_ffn_embed_dim ,  d_model=args.decoder_embed_dim ,  layerdrop=args.decoder_layerdrop ,  dropout=args.dropout ,  attention_dropout=args.attention_dropout ,  activation_dropout=args.activation_dropout ,  activation_function='''gelu''' ,  scale_embedding=not args.no_scale_embedding ,  tie_word_embeddings=args.share_decoder_input_output_embed ,  )

						lowerCAmelCase_      			=  XGLMForCausalLM(_A  )
						lowerCAmelCase_      			=  model.load_state_dict(_A ,  strict=_A  )
						print(_A  )
						lowerCAmelCase_      			=  make_linear_from_emb(model.model.embed_tokens  )

						return model


if __name__ == "__main__":
						_A     =			argparse.ArgumentParser()
						# Required parameters
						parser.add_argument('''fairseq_path''', type=str, help='''path to a model.pt on local filesystem.''')
						parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
						_A     =			parser.parse_args()
						_A     =			convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path)
						model.save_pretrained(args.pytorch_dump_folder_path)




