


import argparse

import fairseq
import torch
from torch import nn

from transformers import (
    MBartaaTokenizer,
    MBartConfig,
    MBartForCausalLM,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    logging,
)


logging.set_verbosity_info()
A			:						Union[str, Any]        =  logging.get_logger(__name__)

A			:						List[str]        =  {
    'post_extract_proj': 'feature_projection.projection',
    'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv',
    'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
    'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
    'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
    'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
    'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
    'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
    'fc2': 'encoder.layers.*.feed_forward.output_dense',
    'final_layer_norm': 'encoder.layers.*.final_layer_norm',
    'encoder.layer_norm': 'encoder.layer_norm',
    'w2v_model.layer_norm': 'feature_projection.layer_norm',
    'quantizer.weight_proj': 'quantizer.weight_proj',
    'quantizer.vars': 'quantizer.codevectors',
    'project_q': 'project_q',
    'final_proj': 'project_hid',
    'w2v_encoder.proj': 'lm_head',
    'mask_emb': 'masked_spec_embed',
}
A			:						List[Any]        =  [
    'lm_head',
    'quantizer.weight_proj',
    'quantizer.codevectors',
    'project_q',
    'project_hid',
]






def 					UpperCamelCase   (      __magic_name__	:				List[str]       ,       __magic_name__	:				List[str]       ,       __magic_name__	:				int       ,       __magic_name__	:				List[str]       ,       __magic_name__	:				Tuple	)  ->    int:
		"""simple docstring"""




		for attribute in key.split("""."""	):
				lowercase__	     =						getattr(lowerCamelCase_       ,       lowerCamelCase_	)

		if weight_type is not None:
				lowercase__	     =						getattr(lowerCamelCase_       ,       lowerCamelCase_	).shape
		else:
				lowercase__	     =						hf_pointer.shape

		assert hf_shape == value.shape, (
		    f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
		    f''' {value.shape} for {full_name}'''
		)

		if weight_type == "weight":
				lowercase__	     =						value
		elif weight_type == "weight_g":
				lowercase__	     =						value
		elif weight_type == "weight_v":
				lowercase__	     =						value
		elif weight_type == "bias":
				lowercase__	     =						value
		else:
				lowercase__	     =						value

		logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'''	)






def 					UpperCamelCase   (      __magic_name__	:				str       ,       __magic_name__	:				Union[str, Any]	)  ->    Union[str, Any]:
		"""simple docstring"""




		lowercase__	     =						[]
		lowercase__	     =						fairseq_model.state_dict()

		lowercase__	     =						hf_model.feature_extractor
		lowercase__	     =						hf_model.adapter

		for name, value in fairseq_dict.items():
				lowercase__	     =						False
				if "conv_layers" in name:
						load_conv_layer(
						    lowerCamelCase_       ,       lowerCamelCase_       ,       lowerCamelCase_       ,       lowerCamelCase_       ,       hf_model.config.feat_extract_norm == """group"""       ,       )
						lowercase__	     =						True
				elif any(x in name for x in ["""adaptor""", """w2v_encoder.proj.""", """w2v_proj_ln."""]	):
						load_adapter(lowerCamelCase_       ,       lowerCamelCase_       ,       lowerCamelCase_       ,       lowerCamelCase_	)
						lowercase__	     =						True
				else:
						for key, mapped_key in MAPPING.items():
								if key in name or key.split("""w2v_model."""	)[-1] == name.split("""."""	)[0]:
										lowercase__	     =						True
										if "*" in mapped_key:
												lowercase__	     =						name.split(lowerCamelCase_	)[0].split("""."""	)[-2]
												lowercase__	     =						mapped_key.replace("""*"""       ,       lowerCamelCase_	)
										if "weight_g" in name:
												lowercase__	     =						"weight_g"
										elif "weight_v" in name:
												lowercase__	     =						"weight_v"
										elif "bias" in name:
												lowercase__	     =						"bias"
										elif "weight" in name:
												lowercase__	     =						"weight"
										else:
												lowercase__	     =						None
										set_recursively(lowerCamelCase_       ,       lowerCamelCase_       ,       lowerCamelCase_       ,       lowerCamelCase_       ,       lowerCamelCase_	)
								continue
				if not is_used:
						unused_weights.append(lowerCamelCase_	)

		logger.warning(f'''Unused weights: {unused_weights}'''	)






def 					UpperCamelCase   (      __magic_name__	:				Optional[int]       ,       __magic_name__	:				Dict       ,       __magic_name__	:				Optional[int]       ,       __magic_name__	:				List[str]       ,       __magic_name__	:				Optional[Any]	)  ->    Union[str, Any]:
		"""simple docstring"""




		lowercase__	     =						full_name.split("""conv_layers."""	)[-1]
		lowercase__	     =						name.split("""."""	)
		lowercase__	     =						int(items[0]	)
		lowercase__	     =						int(items[1]	)

		if type_id == 0:
				if "bias" in name:
						assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
						    f'''{full_name} has size {value.shape}, but'''
						    f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
						)
						lowercase__	     =						value
						logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''	)
				elif "weight" in name:
						assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
						    f'''{full_name} has size {value.shape}, but'''
						    f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
						)
						lowercase__	     =						value
						logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''	)
		elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
				if "bias" in name:
						assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
						    f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
						    " found."
						)
						lowercase__	     =						value
						logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''	)
				elif "weight" in name:
						assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
						    f'''{full_name} has size {value.shape}, but'''
						    f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
						)
						lowercase__	     =						value
						logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''	)
		else:
				unused_weights.append(lowerCamelCase_	)






def 					UpperCamelCase   (      __magic_name__	:				List[Any]       ,       __magic_name__	:				int       ,       __magic_name__	:				str       ,       __magic_name__	:				int	)  ->    Tuple:
		"""simple docstring"""




		lowercase__	     =						full_name.split("""adaptor."""	)[-1]
		lowercase__	     =						name.split("""."""	)

		if items[1].isdigit():
				lowercase__	     =						int(items[1]	)
		else:
				lowercase__	     =						None

		if "adaptor" not in full_name:
				if "proj_ln" in full_name:
						# has to be layer norm
						if "bias" in name:
								assert (
								    value.shape == adapter.proj_layer_norm.bias.data.shape
								), f'''{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found.'''
								lowercase__	     =						value
								logger.info(f'''Adapter proj layer norm bias was initialized from {full_name}.'''	)
						if "weight" in name:
								assert (
								    value.shape == adapter.proj_layer_norm.weight.data.shape
								), f'''{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found.'''
								lowercase__	     =						value
				else:
						# has to be projection layer
						if "bias" in name:
								assert (
								    value.shape == adapter.proj.bias.data.shape
								), f'''{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found.'''
								lowercase__	     =						value
								logger.info(f'''Adapter proj layer bias was initialized from {full_name}.'''	)
						if "weight" in name:
								assert (
								    value.shape == adapter.proj.weight.data.shape
								), f'''{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found.'''
								lowercase__	     =						value
								logger.info(f'''Adapter proj layer weight was initialized from {full_name}.'''	)
		elif isinstance(lowerCamelCase_       ,       lowerCamelCase_	):
				if "bias" in name:
						assert (
						    value.shape == adapter.layers[layer_id].conv.bias.data.shape
						), f'''{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found.'''
						lowercase__	     =						value
						logger.info(f'''Adapter layer {layer_id} bias was initialized from {full_name}.'''	)
				elif "weight" in name:
						assert (
						    value.shape == adapter.layers[layer_id].conv.weight.data.shape
						), f'''{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found.'''
						lowercase__	     =						value
						logger.info(f'''Adapter layer {layer_id} bias was initialized from {full_name}.'''	)
		else:
				unused_weights.append(lowerCamelCase_	)






def 					UpperCamelCase   (      __magic_name__	:				Union[str, Any]	)  ->    str:
		"""simple docstring"""




		lowercase__	     =						emb.weight.shape
		lowercase__	     =						nn.Linear(lowerCamelCase_       ,       lowerCamelCase_       ,       bias=lowerCamelCase_	)
		lowercase__	     =						emb.weight.data
		return lin_layer






@torch.no_grad()
def 					UpperCamelCase   (      __magic_name__	:				Tuple       ,       __magic_name__	:				Union[str, Any]       ,       __magic_name__	:				Dict       ,       __magic_name__	:				Optional[Any]       ,       __magic_name__	:				Any       ,       __magic_name__	:				str       ,       __magic_name__	:				List[Any]       ,       __magic_name__	:				List[Any]       ,       __magic_name__	:				str       ,       __magic_name__	:				List[str]       ,       __magic_name__	:				Tuple       ,       )  ->    List[str]:
		"""simple docstring"""




		lowercase__	     =						WavaVecaConfig.from_pretrained(
		    lowerCamelCase_       ,       add_adapter=lowerCamelCase_       ,       adapter_stride=lowerCamelCase_       ,       adapter_kernel_size=lowerCamelCase_       ,       use_auth_token=lowerCamelCase_       ,       output_hidden_size=lowerCamelCase_       ,       )
		lowercase__	     =						MBartConfig.from_pretrained(lowerCamelCase_	)

		# load model
		lowercase__	     =						fairseq.checkpoint_utils.load_model_ensemble_and_task(
		    [checkpoint_path]       ,       arg_overrides={
		        """config_yaml""": config_yaml_path,
		        """data""": """/""".join(dict_path.split("""/"""	)[:-1]	),
		        """w2v_path""": checkpoint_path,
		        """load_pretrained_decoder_from""": None,
		    }       ,       )
		lowercase__	     =						model[0].eval()

		# load feature extractor
		lowercase__	     =						WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase_       ,       use_auth_token=lowerCamelCase_	)

		# set weights for wav2vec2 encoder
		lowercase__	     =						WavaVecaModel(lowerCamelCase_	)

		recursively_load_weights_wavaveca(model.encoder       ,       lowerCamelCase_	)

		# load decoder weights
		lowercase__	     =						MBartForCausalLM(lowerCamelCase_	)
		lowercase__	     =						hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()       ,       strict=lowerCamelCase_	)
		logger.warning(f'''The following keys are missing when loading the decoder weights: {missing_keys}'''	)
		logger.warning(f'''The following keys are unexpected when loading the decoder weights: {unexpected_keys}'''	)

		lowercase__	     =						SpeechEncoderDecoderModel(encoder=lowerCamelCase_       ,       decoder=lowerCamelCase_	)
		lowercase__	     =						False

		lowercase__	     =						MBartaaTokenizer(lowerCamelCase_	)
		tokenizer.save_pretrained(lowerCamelCase_	)

		lowercase__	     =						hf_wavavec.config.to_dict()
		lowercase__	     =						tokenizer.pad_token_id
		lowercase__	     =						tokenizer.bos_token_id
		lowercase__	     =						tokenizer.eos_token_id
		lowercase__	     =						"mbart50"
		lowercase__	     =						"wav2vec2"

		lowercase__	     =						tokenizer.eos_token_id
		lowercase__	     =						25_0004
		lowercase__	     =						tokenizer.eos_token_id

		lowercase__	     =						SpeechEncoderDecoderConfig.from_dict(lowerCamelCase_	)

		hf_wavavec.save_pretrained(lowerCamelCase_	)
		feature_extractor.save_pretrained(lowerCamelCase_	)


if __name__ == "__main__":
	A			:						int        =  argparse.ArgumentParser()
	parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
	parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
	parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model')
	parser.add_argument('--config_yaml_path', default=None, type=str, help='Path to yaml file of fine-tuned model')
	parser.add_argument(
	    '--encoder_config_path',
	    default='facebook/wav2vec2-xls-r-1b',
	    type=str,
	    help='Path to hf encoder wav2vec2 checkpoint config',
	)
	parser.add_argument(
	    '--decoder_config_path',
	    default='facebook/mbart-large-50-one-to-many-mmt',
	    type=str,
	    help='Path to hf decoder checkpoint config',
	)
	parser.add_argument('--add_adapter', default=True, type=bool, help='whethere to add model adapter layers')
	parser.add_argument('--adapter_stride', default=2, type=int, help='stride of adapter layers')
	parser.add_argument('--adapter_kernel_size', default=3, type=int, help='kernel size of adapter layers')
	parser.add_argument('--encoder_output_dim', default=1_0_2_4, type=int, help='encoder output dim')
	parser.add_argument('--start_token_id', default=2_5_0_0_0_4, type=int, help='`decoder_start_token_id` of model config')

	A			:						Optional[Any]        =  parser.parse_args()
	convert_wavaveca_checkpoint(
	    args.checkpoint_path,
	    args.pytorch_dump_folder_path,
	    args.dict_path,
	    args.config_yaml_path,
	    encoder_config_path=args.encoder_config_path,
	    decoder_config_path=args.decoder_config_path,
	    add_adapter=args.add_adapter,
	    adapter_kernel_size=args.adapter_kernel_size,
	    adapter_stride=args.adapter_stride,
	    decoder_start_token_id=args.start_token_id,
	    encoder_output_dim=args.encoder_output_dim,
	)



'''simple docstring'''

import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
         OpenAIGPTConfig,
         OpenAIGPTDoubleHeadsModel,
         OpenAIGPTForSequenceClassification,
         OpenAIGPTLMHeadModel,
         OpenAIGPTModel,
     )




class    lowerCAmelCase       :


 def __init__(    self  : str			,							a__  : Union[str, Any]			,							a__  : Union[str, Any]=13			,							a__  : Union[str, Any]=7			,							a__  : Any=True			,							a__  : str=True			,							a__  : Optional[Any]=True			,							a__  : Any=99			,							a__  : Dict=32			,							a__  : Tuple=5			,							a__  : List[Any]=4			,							a__  : List[Any]=37			,							a__  : List[str]="gelu"			,							a__  : Dict=0.1			,							a__  : str=0.1			,							a__  : str=512			,							a__  : List[str]=16			,							a__  : Dict=2			,							a__  : Union[str, Any]=0.02			,							a__  : Dict=3			,							a__  : List[Any]=4			,							a__  : Optional[int]=None			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   List[Any]     		=	parent
  lowerCAmelCase__     :   Optional[Any]     		=	batch_size
  lowerCAmelCase__     :   Optional[int]     		=	seq_length
  lowerCAmelCase__     :   int     		=	is_training
  lowerCAmelCase__     :   int     		=	use_token_type_ids
  lowerCAmelCase__     :   List[Any]     		=	use_labels
  lowerCAmelCase__     :   int     		=	vocab_size
  lowerCAmelCase__     :   Dict     		=	hidden_size
  lowerCAmelCase__     :   Tuple     		=	num_hidden_layers
  lowerCAmelCase__     :   Tuple     		=	num_attention_heads
  lowerCAmelCase__     :   Any     		=	intermediate_size
  lowerCAmelCase__     :   Optional[int]     		=	hidden_act
  lowerCAmelCase__     :   Optional[int]     		=	hidden_dropout_prob
  lowerCAmelCase__     :   Optional[Any]     		=	attention_probs_dropout_prob
  lowerCAmelCase__     :   Tuple     		=	max_position_embeddings
  lowerCAmelCase__     :   str     		=	type_vocab_size
  lowerCAmelCase__     :   List[Any]     		=	type_sequence_label_size
  lowerCAmelCase__     :   List[str]     		=	initializer_range
  lowerCAmelCase__     :   Tuple     		=	num_labels
  lowerCAmelCase__     :   Optional[Any]     		=	num_choices
  lowerCAmelCase__     :   int     		=	scope
  lowerCAmelCase__     :   List[str]     		=	self.vocab_size - 1


 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.vocab_size    )

  lowerCAmelCase__     :   Dict     		=	None
  if self.use_token_type_ids:
   lowerCAmelCase__     :   List[str]     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.type_vocab_size    )

  lowerCAmelCase__     :   List[str]     		=	None
  lowerCAmelCase__     :   Tuple     		=	None
  lowerCAmelCase__     :   Optional[int]     		=	None
  if self.use_labels:
   lowerCAmelCase__     :   int     		=	ids_tensor([self.batch_size]			,							self.type_sequence_label_size    )
   lowerCAmelCase__     :   Any     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.num_labels    )
   lowerCAmelCase__     :   Optional[Any]     		=	ids_tensor([self.batch_size]			,							self.num_choices    )

  lowerCAmelCase__     :   Any     		=	OpenAIGPTConfig(
      vocab_size=self.vocab_size			,							n_embd=self.hidden_size			,							n_layer=self.num_hidden_layers			,							n_head=self.num_attention_heads			,							n_positions=self.max_position_embeddings			,							pad_token_id=self.pad_token_id			,							)

  lowerCAmelCase__     :   Optional[Any]     		=	ids_tensor([self.num_hidden_layers, self.num_attention_heads]			,							2    )

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


 def    _A	(    self  : Dict			,							a__  : Any			,							a__  : Any			,							a__  : int			,							a__  : str			,							*a__  : Optional[Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	OpenAIGPTModel(config=a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Optional[Any]     		=	model(a__			,							token_type_ids=a__			,							head_mask=a__    )
  lowerCAmelCase__     :   Optional[int]     		=	model(a__			,							token_type_ids=a__    )
  lowerCAmelCase__     :   Any     		=	model(a__    )

  self.parent.assertEqual(result.last_hidden_state.shape			,							(self.batch_size, self.seq_length, self.hidden_size)    )


 def    _A	(    self  : Optional[int]			,							a__  : List[Any]			,							a__  : int			,							a__  : Dict			,							a__  : Any			,							*a__  : Any    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	OpenAIGPTLMHeadModel(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Dict     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )


 def    _A	(    self  : List[str]			,							a__  : str			,							a__  : Dict			,							a__  : Union[str, Any]			,							a__  : int			,							*a__  : Dict    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	OpenAIGPTDoubleHeadsModel(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Optional[Any]     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )


 def    _A	(    self  : Any			,							a__  : Any			,							a__  : Union[str, Any]			,							a__  : Optional[int]			,							a__  : Any			,							*a__  : List[str]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[Any]     		=	self.num_labels
  lowerCAmelCase__     :   Union[str, Any]     		=	OpenAIGPTForSequenceClassification(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   List[str]     		=	ids_tensor([self.batch_size]			,							self.type_sequence_label_size    )
  lowerCAmelCase__     :   Tuple     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)    )


 def    _A	(    self  : Optional[int]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	self.prepare_config_and_inputs()
  (
      (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     
  )     :   Union[str, Any]     		=	config_and_inputs
  lowerCAmelCase__     :   str     		=	{
      "input_ids": input_ids,
      "token_type_ids": token_type_ids,
      "head_mask": head_mask,
  }

  return config, inputs_dict




@require_torch
class    lowerCAmelCase       (     UpperCamelCase_    ,  UpperCamelCase_    ,  UpperCamelCase_    ,  unittest.TestCase  ):
 A_				:				str	=			(
     (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
     if is_torch_available()
     else ()
 )
 A_				:				Any	=			(
     (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
 )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
 A_				:				int	=			(
     {
         """feature-extraction""": OpenAIGPTModel,
         """text-classification""": OpenAIGPTForSequenceClassification,
         """text-generation""": OpenAIGPTLMHeadModel,
         """zero-shot""": OpenAIGPTForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )


 def    _A	(    self  : List[Any]			,							a__  : Optional[Any]			,							a__  : Optional[int]			,							a__  : Optional[Any]			,							a__  : List[Any]			,							a__  : int    ):
  '''simple docstring'''

  if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
   # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
   # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
   # tiny config could not be created.
   return True

  return False


 def    _A	(    self  : Dict			,							a__  : Optional[int]			,							a__  : List[Any]			,							a__  : List[Any]=False    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	super()._prepare_for_class(a__			,							a__			,							return_labels=a__    )

  if return_labels:
   if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
    lowerCAmelCase__     :   Tuple     		=	torch.zeros(
        (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)			,							dtype=torch.long			,							device=a__			,							)
    lowerCAmelCase__     :   Union[str, Any]     		=	inputs_dict["labels"]
    lowerCAmelCase__     :   int     		=	inputs_dict["labels"]
    lowerCAmelCase__     :   Optional[int]     		=	torch.zeros(
        (self.model_tester.batch_size, self.model_tester.num_choices)			,							dtype=torch.long			,							device=a__			,							)
    lowerCAmelCase__     :   List[str]     		=	torch.zeros(
        self.model_tester.batch_size			,							dtype=torch.long			,							device=a__    )
  return inputs_dict


 def    _A	(    self  : str    ):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	OpenAIGPTModelTester(self    )
  lowerCAmelCase__     :   Any     		=	ConfigTester(self			,							config_class=a__			,							n_embd=37    )


 def    _A	(    self  : List[str]    ):
  '''simple docstring'''

  self.config_tester.run_common_tests()


 def    _A	(    self  : Optional[int]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Dict     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_openai_gpt_model(*a__    )


 def    _A	(    self  : Union[str, Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_lm_head_model(*a__    )


 def    _A	(    self  : int    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_double_lm_head_model(*a__    )


 def    _A	(    self  : str    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Union[str, Any]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a__    )


 @slow
 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   lowerCAmelCase__     :   Any     		=	OpenAIGPTModel.from_pretrained(a__    )
   self.assertIsNotNone(a__    )




@require_torch
class    lowerCAmelCase       (     unittest.TestCase  ):


 @slow
 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   int     		=	OpenAIGPTLMHeadModel.from_pretrained("openai-gpt"    )
  model.to(a__    )
  lowerCAmelCase__     :   Union[str, Any]     		=	torch.tensor([[481, 4735, 544]]			,							dtype=torch.long			,							device=a__    )  # the president is
  lowerCAmelCase__     :   Optional[int]     		=	[
      481,
      4735,
      544,
      246,
      963,
      870,
      762,
      239,
      244,
      4_0477,
      244,
      249,
      719,
      881,
      487,
      544,
      240,
      244,
      603,
      481,
  ]  # the president is a very good man. " \n " i\'m sure he is, " said the

  lowerCAmelCase__     :   Optional[int]     		=	model.generate(a__			,							do_sample=a__    )
  self.assertListEqual(output_ids[0].tolist()			,							a__    )





