
'''simple docstring'''



from __future__ import annotations

import unittest

from transformers import FunnelConfig, is_tf_available
from transformers.testing_utils import require_tf

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers import (
         TFFunnelBaseModel,
         TFFunnelForMaskedLM,
         TFFunnelForMultipleChoice,
         TFFunnelForPreTraining,
         TFFunnelForQuestionAnswering,
         TFFunnelForSequenceClassification,
         TFFunnelForTokenClassification,
         TFFunnelModel,
     )

class    _a				:





       """simple docstring"""




       def __init__(							self       ,							A__       ,							A__=13       ,							A__=7       ,							A__=True       ,							A__=True       ,							A__=True       ,							A__=True       ,							A__=99       ,							A__=[1, 1, 2]       ,							A__=1       ,							A__=32       ,							A__=4       ,							A__=8       ,							A__=37       ,							A__="gelu_new"       ,							A__=0.1       ,							A__=0.1       ,							A__=0.0       ,							A__=5_12       ,							A__=3       ,							A__=0.02       ,							A__=3       ,							A__=4       ,							A__=None       ,							A__=False       ,							)    ->			Dict:
          _SCREAMING_SNAKE_CASE      =				parent
          _SCREAMING_SNAKE_CASE      =				batch_size
          _SCREAMING_SNAKE_CASE      =				seq_length
          _SCREAMING_SNAKE_CASE      =				is_training
          _SCREAMING_SNAKE_CASE      =				use_input_mask
          _SCREAMING_SNAKE_CASE      =				use_token_type_ids
          _SCREAMING_SNAKE_CASE      =				use_labels
          _SCREAMING_SNAKE_CASE      =				vocab_size
          _SCREAMING_SNAKE_CASE      =				block_sizes
          _SCREAMING_SNAKE_CASE      =				num_decoder_layers
          _SCREAMING_SNAKE_CASE      =				d_model
          _SCREAMING_SNAKE_CASE      =				n_head
          _SCREAMING_SNAKE_CASE      =				d_head
          _SCREAMING_SNAKE_CASE      =				d_inner
          _SCREAMING_SNAKE_CASE      =				hidden_act
          _SCREAMING_SNAKE_CASE      =				hidden_dropout
          _SCREAMING_SNAKE_CASE      =				attention_dropout
          _SCREAMING_SNAKE_CASE      =				activation_dropout
          _SCREAMING_SNAKE_CASE      =				max_position_embeddings
          _SCREAMING_SNAKE_CASE      =				type_vocab_size
          _SCREAMING_SNAKE_CASE      =				2
          _SCREAMING_SNAKE_CASE      =				num_labels
          _SCREAMING_SNAKE_CASE      =				num_choices
          _SCREAMING_SNAKE_CASE      =				scope
          _SCREAMING_SNAKE_CASE      =				initializer_std

          # Used in the tests to check the size of the first attention layer
          _SCREAMING_SNAKE_CASE      =				n_head
          # Used in the tests to check the size of the first hidden state
          _SCREAMING_SNAKE_CASE      =				self.d_model
          # Used in the tests to check the number of output hidden states/attentions
          _SCREAMING_SNAKE_CASE      =				sum(self.block_sizes      ) + (0 if base else self.num_decoder_layers)
          # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
          # the last hidden state of the first block (which is the first hidden state of the decoder).
          if not base:
             _SCREAMING_SNAKE_CASE      =				self.num_hidden_layers + 2






       def        UpperCamelCase				(							self      )    ->			int:
          _SCREAMING_SNAKE_CASE      =				ids_tensor([self.batch_size, self.seq_length]       ,							self.vocab_size      )

          _SCREAMING_SNAKE_CASE      =				None
          if self.use_input_mask:
             _SCREAMING_SNAKE_CASE      =				random_attention_mask([self.batch_size, self.seq_length]      )

          _SCREAMING_SNAKE_CASE      =				None
          if self.use_token_type_ids:
             _SCREAMING_SNAKE_CASE      =				ids_tensor([self.batch_size, self.seq_length]       ,							self.type_vocab_size      )

          _SCREAMING_SNAKE_CASE      =				None
          _SCREAMING_SNAKE_CASE      =				None
          _SCREAMING_SNAKE_CASE      =				None
          if self.use_labels:
             _SCREAMING_SNAKE_CASE      =				ids_tensor([self.batch_size]       ,							self.type_sequence_label_size      )
             _SCREAMING_SNAKE_CASE      =				ids_tensor([self.batch_size, self.seq_length]       ,							self.num_labels      )
             _SCREAMING_SNAKE_CASE      =				ids_tensor([self.batch_size]       ,							self.num_choices      )

          _SCREAMING_SNAKE_CASE      =				FunnelConfig(
              vocab_size=self.vocab_size       ,							block_sizes=self.block_sizes       ,							num_decoder_layers=self.num_decoder_layers       ,							d_model=self.d_model       ,							n_head=self.n_head       ,							d_head=self.d_head       ,							d_inner=self.d_inner       ,							hidden_act=self.hidden_act       ,							hidden_dropout=self.hidden_dropout       ,							attention_dropout=self.attention_dropout       ,							activation_dropout=self.activation_dropout       ,							max_position_embeddings=self.max_position_embeddings       ,							type_vocab_size=self.type_vocab_size       ,							initializer_std=self.initializer_std       ,							)

          return (
              config,
              input_ids,
              token_type_ids,
              input_mask,
              sequence_labels,
              token_labels,
              choice_labels,
          )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							)    ->			List[str]:
          _SCREAMING_SNAKE_CASE      =				TFFunnelModel(config=A__      )
          _SCREAMING_SNAKE_CASE      =				{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
          _SCREAMING_SNAKE_CASE      =				model(A__      )

          _SCREAMING_SNAKE_CASE      =				[input_ids, input_mask]
          _SCREAMING_SNAKE_CASE      =				model(A__      )

          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, self.seq_length, self.d_model)      )

          _SCREAMING_SNAKE_CASE      =				False
          _SCREAMING_SNAKE_CASE      =				TFFunnelModel(config=A__      )
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, self.seq_length, self.d_model)      )

          _SCREAMING_SNAKE_CASE      =				False
          _SCREAMING_SNAKE_CASE      =				TFFunnelModel(config=A__      )
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, self.seq_length, self.d_model)      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							)    ->			Optional[int]:
          _SCREAMING_SNAKE_CASE      =				TFFunnelBaseModel(config=A__      )
          _SCREAMING_SNAKE_CASE      =				{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
          _SCREAMING_SNAKE_CASE      =				model(A__      )

          _SCREAMING_SNAKE_CASE      =				[input_ids, input_mask]
          _SCREAMING_SNAKE_CASE      =				model(A__      )

          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, 2, self.d_model)      )

          _SCREAMING_SNAKE_CASE      =				False
          _SCREAMING_SNAKE_CASE      =				TFFunnelBaseModel(config=A__      )
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, 3, self.d_model)      )

          _SCREAMING_SNAKE_CASE      =				False
          _SCREAMING_SNAKE_CASE      =				TFFunnelBaseModel(config=A__      )
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, 2, self.d_model)      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							)    ->			Optional[Any]:
          _SCREAMING_SNAKE_CASE      =				TFFunnelForPreTraining(config=A__      )
          _SCREAMING_SNAKE_CASE      =				{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.seq_length)      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							)    ->			Optional[Any]:
          _SCREAMING_SNAKE_CASE      =				TFFunnelForMaskedLM(config=A__      )
          _SCREAMING_SNAKE_CASE      =				{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.seq_length, self.vocab_size)      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							)    ->			Tuple:
          _SCREAMING_SNAKE_CASE      =				self.num_labels
          _SCREAMING_SNAKE_CASE      =				TFFunnelForSequenceClassification(config=A__      )
          _SCREAMING_SNAKE_CASE      =				{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.num_labels)      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							)    ->			Dict:
          _SCREAMING_SNAKE_CASE      =				self.num_choices
          _SCREAMING_SNAKE_CASE      =				TFFunnelForMultipleChoice(config=A__      )
          _SCREAMING_SNAKE_CASE      =				tf.tile(tf.expand_dims(A__       ,							1      )       ,							(1, self.num_choices, 1)      )
          _SCREAMING_SNAKE_CASE      =				tf.tile(tf.expand_dims(A__       ,							1      )       ,							(1, self.num_choices, 1)      )
          _SCREAMING_SNAKE_CASE      =				tf.tile(tf.expand_dims(A__       ,							1      )       ,							(1, self.num_choices, 1)      )
          _SCREAMING_SNAKE_CASE      =				{
              """input_ids""": multiple_choice_inputs_ids,
              """attention_mask""": multiple_choice_input_mask,
              """token_type_ids""": multiple_choice_token_type_ids,
          }
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.num_choices)      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							)    ->			List[Any]:
          _SCREAMING_SNAKE_CASE      =				self.num_labels
          _SCREAMING_SNAKE_CASE      =				TFFunnelForTokenClassification(config=A__      )
          _SCREAMING_SNAKE_CASE      =				{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.seq_length, self.num_labels)      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							A__       ,							)    ->			Dict:
          _SCREAMING_SNAKE_CASE      =				TFFunnelForQuestionAnswering(config=A__      )
          _SCREAMING_SNAKE_CASE      =				{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
          _SCREAMING_SNAKE_CASE      =				model(A__      )
          self.parent.assertEqual(result.start_logits.shape       ,							(self.batch_size, self.seq_length)      )
          self.parent.assertEqual(result.end_logits.shape       ,							(self.batch_size, self.seq_length)      )






       def        UpperCamelCase				(							self      )    ->			Optional[Any]:
          _SCREAMING_SNAKE_CASE      =				self.prepare_config_and_inputs()
          (
              (
              _SCREAMING_SNAKE_CASE							
          ) ,							(
              _SCREAMING_SNAKE_CASE							
          ) ,							(
              _SCREAMING_SNAKE_CASE							
          ) ,							(
              _SCREAMING_SNAKE_CASE							
          ) ,							(
              _SCREAMING_SNAKE_CASE							
          ) ,							(
              _SCREAMING_SNAKE_CASE							
          ) ,							(
              _SCREAMING_SNAKE_CASE							
          ) ,														
          )      =				config_and_inputs
          _SCREAMING_SNAKE_CASE      =				{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
          return config, inputs_dict






@require_tf
class    _a				(_lowerCamelCase  ,					_lowerCamelCase  ,					unittest.TestCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE      =		(
           (
               TFFunnelModel,
               TFFunnelForMaskedLM,
               TFFunnelForPreTraining,
               TFFunnelForQuestionAnswering,
               TFFunnelForTokenClassification,
           )
           if is_tf_available()
           else ()
       )
       SCREAMING_SNAKE_CASE      =		(
           {
               'feature-extraction': (TFFunnelBaseModel, TFFunnelModel),
               'fill-mask': TFFunnelForMaskedLM,
               'question-answering': TFFunnelForQuestionAnswering,
               'text-classification': TFFunnelForSequenceClassification,
               'token-classification': TFFunnelForTokenClassification,
               'zero-shot': TFFunnelForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       SCREAMING_SNAKE_CASE      =		False
       SCREAMING_SNAKE_CASE      =		False






       def        UpperCamelCase				(							self      )    ->			int:
          _SCREAMING_SNAKE_CASE      =				TFFunnelModelTester(self      )
          _SCREAMING_SNAKE_CASE      =				ConfigTester(self       ,							config_class=A__      )






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






       def        UpperCamelCase				(							self      )    ->			Optional[int]:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*A__      )






       def        UpperCamelCase				(							self      )    ->			int:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_pretraining(*A__      )






       def        UpperCamelCase				(							self      )    ->			Union[str, Any]:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_lm(*A__      )






       def        UpperCamelCase				(							self      )    ->			str:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_token_classification(*A__      )






       def        UpperCamelCase				(							self      )    ->			Optional[int]:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_question_answering(*A__      )






@require_tf
class    _a				(_lowerCamelCase  ,					unittest.TestCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE      =		(
           (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
       )
       SCREAMING_SNAKE_CASE      =		False
       SCREAMING_SNAKE_CASE      =		False






       def        UpperCamelCase				(							self      )    ->			Optional[int]:
          _SCREAMING_SNAKE_CASE      =				TFFunnelModelTester(self       ,							base=A__      )
          _SCREAMING_SNAKE_CASE      =				ConfigTester(self       ,							config_class=A__      )






       def        UpperCamelCase				(							self      )    ->			str:
          self.config_tester.run_common_tests()






       def        UpperCamelCase				(							self      )    ->			List[Any]:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_base_model(*A__      )






       def        UpperCamelCase				(							self      )    ->			Union[str, Any]:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_sequence_classification(*A__      )






       def        UpperCamelCase				(							self      )    ->			Tuple:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_multiple_choice(*A__      )








'''simple docstring'''



import argparse

import torch
from torch import nn

from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     Any:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				[
       """encoder.version""",
       """decoder.version""",
       """model.encoder.version""",
       """model.decoder.version""",
       """decoder.output_projection.weight""",
       """_float_tensor""",
       """encoder.embed_positions._float_tensor""",
       """decoder.embed_positions._float_tensor""",
   ]
   for k in ignore_keys:
      state_dict.pop(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						)
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     str:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				emb.weight.shape
   _SCREAMING_SNAKE_CASE      =				nn.Linear(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      bias=SCREAMING_SNAKE_CASE_						)
   _SCREAMING_SNAKE_CASE      =				emb.weight.data
   return lin_layer
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     List[Any]:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				torch.load(SCREAMING_SNAKE_CASE_    ,      map_location="""cpu"""						)
   _SCREAMING_SNAKE_CASE      =				mam_aaa["""args"""] or mam_aaa["""cfg"""]["""model"""]
   _SCREAMING_SNAKE_CASE      =				mam_aaa["""model"""]
   remove_ignore_keys_(SCREAMING_SNAKE_CASE_						)
   _SCREAMING_SNAKE_CASE      =				state_dict["""encoder.embed_tokens.weight"""].shape[0]

   _SCREAMING_SNAKE_CASE      =				MaMaaaConfig(
       vocab_size=SCREAMING_SNAKE_CASE_    ,      max_position_embeddings=10_24    ,      encoder_layers=args.encoder_layers    ,      decoder_layers=args.decoder_layers    ,      encoder_attention_heads=args.encoder_attention_heads    ,      decoder_attention_heads=args.decoder_attention_heads    ,      encoder_ffn_dim=args.encoder_ffn_embed_dim    ,      decoder_ffn_dim=args.decoder_ffn_embed_dim    ,      d_model=args.encoder_embed_dim    ,      encoder_layerdrop=args.encoder_layerdrop    ,      decoder_layerdrop=args.decoder_layerdrop    ,      dropout=args.dropout    ,      attention_dropout=args.attention_dropout    ,      activation_dropout=args.activation_dropout    ,      activation_function="""relu"""    ,      )

   _SCREAMING_SNAKE_CASE      =				state_dict["""decoder.embed_tokens.weight"""]
   _SCREAMING_SNAKE_CASE      =				MaMaaaForConditionalGeneration(SCREAMING_SNAKE_CASE_						)
   model.model.load_state_dict(SCREAMING_SNAKE_CASE_    ,      strict=SCREAMING_SNAKE_CASE_						)
   _SCREAMING_SNAKE_CASE      =				make_linear_from_emb(model.model.shared						)

   return model


if __name__ == "__main__":
     UpperCamelCase__      :		Dict       							=  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.")
     UpperCamelCase__      :		List[str]       							=  parser.parse_args()
     UpperCamelCase__      :		Any       							=  convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß)
     model.save_pretrained(args.pytorch_dump_folder_path)






