




from __future__ import annotations

import copy
import os
import tempfile
from importlib import import_module
from math import isnan

from transformers import is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import _tf_gpu_memory_limit, require_tf, slow

from ..test_modeling_tf_common import ids_tensor


if is_tf_available():
				import numpy as np
				import tensorflow as tf

				from transformers import (
				    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
				    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
				    TF_MODEL_FOR_MASKED_LM_MAPPING,
				    TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
				    TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
				    TF_MODEL_FOR_PRETRAINING_MAPPING,
				    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
				    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
				    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
				    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
				    TFSharedEmbeddings,
				)

				if _tf_gpu_memory_limit is not None:
								lowercase_		=							tf.config.list_physical_devices('''GPU''')
								for gpu in gpus:
												# Restrict TensorFlow to only allocate x GB of memory on the GPUs
												try:
																tf.config.set_logical_device_configuration(
																    gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)]
																)
																lowercase_		=							tf.config.list_logical_devices('''GPU''')
																print('''Logical GPUs''', logical_gpus)
												except RuntimeError as e:
																# Virtual devices must be set before GPUs have been initialized
																print(e)





@require_tf
class 		A__    :
	lowerCamelCase__		:			Tuple       =None
	lowerCamelCase__		:			int       =()
	lowerCamelCase__		:			Optional[int]       =()
	lowerCamelCase__		:			Union[str, Any]       =True
	lowerCamelCase__		:			Tuple       =True
	lowerCamelCase__		:			str       =True
	lowerCamelCase__		:			str       =False






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase=False						)				->       Union[str, Any]:




						"""simple docstring"""






						__magic_name__ :							str		       =							copy.deepcopy(UpperCamelCase_						)

						if model_class in get_values(UpperCamelCase_						):
											__magic_name__ :							Union[str, Any]		       =							{
											    k: tf.tile(tf.expand_dims(UpperCamelCase_    ,					1						)    ,					(1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)						)
											    if isinstance(UpperCamelCase_    ,					tf.Tensor						) and v.ndim > 0
											    else v
											    for k, v in inputs_dict.items()
											}

						if return_labels:
											if model_class in get_values(UpperCamelCase_						):
																__magic_name__ :							Tuple		       =							tf.ones(self.model_tester.batch_size    ,					dtype=tf.intaa						)
											elif model_class in get_values(UpperCamelCase_						):
																__magic_name__ :							List[Any]		       =							tf.zeros(self.model_tester.batch_size    ,					dtype=tf.intaa						)
																__magic_name__ :							Tuple		       =							tf.zeros(self.model_tester.batch_size    ,					dtype=tf.intaa						)
											elif model_class in [
											    *get_values(UpperCamelCase_						),
											    *get_values(UpperCamelCase_						),
											]:
																__magic_name__ :							Optional[Any]		       =							tf.zeros(self.model_tester.batch_size    ,					dtype=tf.intaa						)
											elif model_class in get_values(UpperCamelCase_						):
																__magic_name__ :							List[Any]		       =							tf.zeros(self.model_tester.batch_size    ,					dtype=tf.intaa						)
											elif model_class in [
											    *get_values(UpperCamelCase_						),
											    *get_values(UpperCamelCase_						),
											    *get_values(UpperCamelCase_						),
											    *get_values(UpperCamelCase_						),
											    *get_values(UpperCamelCase_						),
											]:
																__magic_name__ :							Union[str, Any]		       =							tf.zeros(
																    (self.model_tester.batch_size, self.model_tester.seq_length)    ,					dtype=tf.intaa						)
						return inputs_dict






	@slow
	def 			lowercase				(     self						)				->       List[str]:




						"""simple docstring"""






						__magic_name__       ,			__magic_name__ :							Dict		       =							self.model_tester.prepare_config_and_inputs_for_common()
						for model_class in self.all_model_classes[:2]:
											__magic_name__ :							List[Any]		       =							self._prepare_for_class(UpperCamelCase_    ,					UpperCamelCase_						)
											__magic_name__ :							List[str]		       =							model_class(UpperCamelCase_						)

											@tf.function
											def run_in_graph_mode():
																return model(UpperCamelCase_						)

											__magic_name__ :							str		       =							run_in_graph_mode()
											self.assertIsNotNone(UpperCamelCase_						)






	@slow
	def 			lowercase				(     self						)				->       Tuple:




						"""simple docstring"""






						__magic_name__       ,			__magic_name__ :							Optional[int]		       =							self.model_tester.prepare_config_and_inputs_for_common()
						for model_class in self.all_model_classes[:2]:
											__magic_name__ :							int		       =							self._prepare_for_class(UpperCamelCase_    ,					UpperCamelCase_						)
											__magic_name__ :							Optional[Any]		       =							model_class(UpperCamelCase_						)

											@tf.function(experimental_compile=UpperCamelCase_						)
											def run_in_graph_mode():
																return model(UpperCamelCase_						)

											__magic_name__ :							List[str]		       =							run_in_graph_mode()
											self.assertIsNotNone(UpperCamelCase_						)






	@slow
	def 			lowercase				(     self						)				->       Any:




						"""simple docstring"""






						__magic_name__       ,			__magic_name__ :							Union[str, Any]		       =							self.model_tester.prepare_config_and_inputs_for_common()
						for model_class in self.all_model_classes[:2]:
											__magic_name__ :							Tuple		       =							model_class(UpperCamelCase_						)
											if getattr(UpperCamelCase_    ,					'''hf_compute_loss'''    ,					UpperCamelCase_						):
																# Test that model correctly compute the loss with kwargs
																__magic_name__ :							Optional[Any]		       =							self._prepare_for_class(inputs_dict.copy()    ,					UpperCamelCase_    ,					return_labels=UpperCamelCase_						)
																# Is there a better way to remove these decoder inputs?
																__magic_name__ :							Optional[int]		       =							{
																    key: val
																    for key, val in prepared_for_class.items()
																    if key not in ('''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''decoder_input_ids''')
																}

																__magic_name__ :							List[Any]		       =							{
																    '''labels''',
																    '''label''',
																    '''label_ids''',
																    '''start_positions''',
																    '''start_position''',
																    '''end_positions''',
																    '''end_position''',
																    '''next_sentence_label''',
																}
																__magic_name__ :							Tuple		       =							possible_label_cols.intersection(set(UpperCamelCase_						)						)
																self.assertGreater(len(UpperCamelCase_						)    ,					0    ,					msg='''No matching label names found!'''						)
																__magic_name__ :							Optional[int]		       =							{key: val for key, val in prepared_for_class.items() if key in label_names}
																__magic_name__ :							List[Any]		       =							{key: val for key, val in prepared_for_class.items() if key not in label_names}
																self.assertGreater(len(UpperCamelCase_						)    ,					0						)

																# Make sure it works with XLA!
																model.compile(optimizer=tf.keras.optimizers.SGD(0.0						)    ,					jit_compile=UpperCamelCase_						)
																# Make sure the model fits without crashing regardless of where we pass the labels
																__magic_name__ :							Any		       =							model.fit(
																    UpperCamelCase_    ,					validation_data=UpperCamelCase_    ,					steps_per_epoch=1    ,					validation_steps=1    ,					shuffle=UpperCamelCase_    ,					verbose=0    ,					)
																__magic_name__ :							int		       =							history.history['''loss'''][0]
																self.assertTrue(not isnan(UpperCamelCase_						)						)
																__magic_name__ :							str		       =							history.history['''val_loss'''][0]
																self.assertTrue(not isnan(UpperCamelCase_						)						)

																# Now test it with separate labels, to make sure that path works in XLA too.
																__magic_name__ :							List[Any]		       =							model_class(UpperCamelCase_						)
																model.compile(optimizer=tf.keras.optimizers.SGD(0.0						)    ,					jit_compile=UpperCamelCase_						)
																__magic_name__ :							List[Any]		       =							model.fit(
																    UpperCamelCase_    ,					UpperCamelCase_    ,					validation_data=(inputs_minus_labels, labels)    ,					steps_per_epoch=1    ,					validation_steps=1    ,					shuffle=UpperCamelCase_    ,					verbose=0    ,					)

																__magic_name__ :							Any		       =							history.history['''loss'''][0]
																self.assertTrue(not isnan(UpperCamelCase_						)						)
																__magic_name__ :							Dict		       =							history.history['''val_loss'''][0]
																self.assertTrue(not isnan(UpperCamelCase_						)						)






	@slow
	def 			lowercase				(     self						)				->       List[str]:




						"""simple docstring"""






						__magic_name__       ,			__magic_name__ :							str		       =							self.model_tester.prepare_config_and_inputs_for_common()
						__magic_name__ :							Optional[int]		       =							True
						__magic_name__ :							List[str]		       =							True

						if hasattr(UpperCamelCase_    ,					'''use_cache'''						):
											__magic_name__ :							List[Any]		       =							True

						__magic_name__ :							str		       =							getattr(self.model_tester    ,					'''encoder_seq_length'''    ,					self.model_tester.seq_length						)
						__magic_name__ :							int		       =							getattr(self.model_tester    ,					'''key_length'''    ,					UpperCamelCase_						)

						for model_class in self.all_model_classes[:2]:
											__magic_name__ :							List[Any]		       =							self._prepare_for_class(UpperCamelCase_    ,					UpperCamelCase_						)
											__magic_name__ :							int		       =							model_class(UpperCamelCase_						)
											model.build()
											__magic_name__ :							Optional[Any]		       =							len(model(UpperCamelCase_						)						)

											for key in list(class_inputs_dict.keys()						):
																# Remove keys not in the serving signature, as the SavedModel will not be compiled to deal with them
																if key not in model.input_signature:
																					del class_inputs_dict[key]
																# Check it's a tensor, in case the inputs dict has some bools in it too
																elif isinstance(class_inputs_dict[key]    ,					tf.Tensor						) and class_inputs_dict[key].dtype.is_integer:
																					__magic_name__ :							int		       =							tf.cast(class_inputs_dict[key]    ,					tf.intaa						)

											if set(class_inputs_dict.keys()						) != set(model.input_signature.keys()						):
																continue  # Some models have inputs that the preparation functions don't create, we skip those

											with tempfile.TemporaryDirectory() as tmpdirname:
																model.save_pretrained(UpperCamelCase_    ,					saved_model=UpperCamelCase_						)
																__magic_name__ :							int		       =							os.path.join(UpperCamelCase_    ,					'''saved_model'''    ,					'''1'''						)
																__magic_name__ :							Optional[Any]		       =							tf.keras.models.load_model(UpperCamelCase_						)
																__magic_name__ :							Any		       =							model(UpperCamelCase_						)

																if self.is_encoder_decoder:
																					__magic_name__ :							str		       =							outputs['''encoder_hidden_states''']
																					__magic_name__ :							Optional[Any]		       =							outputs['''encoder_attentions''']
																else:
																					__magic_name__ :							str		       =							outputs['''hidden_states''']
																					__magic_name__ :							Optional[int]		       =							outputs['''attentions''']

																self.assertEqual(len(UpperCamelCase_						)    ,					UpperCamelCase_						)

																__magic_name__ :							Any		       =							getattr(
																    self.model_tester    ,					'''expected_num_hidden_layers'''    ,					self.model_tester.num_hidden_layers + 1						)

																self.assertEqual(len(UpperCamelCase_						)    ,					UpperCamelCase_						)
																self.assertListEqual(
																    list(output_hidden_states[0].shape[-2:]						)    ,					[self.model_tester.seq_length, self.model_tester.hidden_size]    ,					)

																self.assertEqual(len(UpperCamelCase_						)    ,					self.model_tester.num_hidden_layers						)
																self.assertListEqual(
																    list(output_attentions[0].shape[-3:]						)    ,					[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]    ,					)






	@slow
	def 			lowercase				(     self						)				->       Tuple:




						"""simple docstring"""






						tf.keras.mixed_precision.set_global_policy('''mixed_float16'''						)

						# try/finally block to ensure subsequent tests run in float32
						try:
											__magic_name__       ,			__magic_name__ :							str		       =							self.model_tester.prepare_config_and_inputs_for_common()
											for model_class in self.all_model_classes[:2]:
																__magic_name__ :							Any		       =							self._prepare_for_class(UpperCamelCase_    ,					UpperCamelCase_						)
																__magic_name__ :							Tuple		       =							model_class(UpperCamelCase_						)
																__magic_name__ :							int		       =							model(UpperCamelCase_						)

																self.assertIsNotNone(UpperCamelCase_						)
						finally:
											tf.keras.mixed_precision.set_global_policy('''float32'''						)






	@slow
	def 			lowercase				(     self						)				->       List[Any]:




						"""simple docstring"""






						__magic_name__       ,			__magic_name__ :							str		       =							self.model_tester.prepare_config_and_inputs_for_common()
						# head_mask and decoder_head_mask has different shapes than other input args
						if "head_mask" in inputs_dict:
											del inputs_dict["head_mask"]
						if "decoder_head_mask" in inputs_dict:
											del inputs_dict["decoder_head_mask"]
						if "cross_attn_head_mask" in inputs_dict:
											del inputs_dict["cross_attn_head_mask"]
						__magic_name__ :							Optional[int]		       =							{
						    module_member
						    for model_class in self.all_model_classes
						    for module in (import_module(model_class.__module__						),)
						    for module_member_name in dir(UpperCamelCase_						)
						    if module_member_name.endswith('''MainLayer'''						)
						    for module_member in (getattr(UpperCamelCase_    ,					UpperCamelCase_						),)
						    if isinstance(UpperCamelCase_    ,					UpperCamelCase_						)
						    and tf.keras.layers.Layer in module_member.__bases__
						    and getattr(UpperCamelCase_    ,					'''_keras_serializable'''    ,					UpperCamelCase_						)
						}

						for main_layer_class in tf_main_layer_classes:
											# T5MainLayer needs an embed_tokens parameter when called without the inputs_embeds parameter
											if "T5" in main_layer_class.__name__:
																# Take the same values than in TFT5ModelTester for this shared layer
																__magic_name__ :							Union[str, Any]		       =							TFSharedEmbeddings(self.model_tester.vocab_size    ,					self.model_tester.hidden_size    ,					name='''shared'''						)
																__magic_name__ :							Tuple		       =							False
																__magic_name__ :							str		       =							main_layer_class(UpperCamelCase_    ,					embed_tokens=UpperCamelCase_						)
											else:
																__magic_name__ :							Dict		       =							main_layer_class(UpperCamelCase_						)

											__magic_name__ :							Any		       =							{
											    name: tf.keras.Input(tensor.shape[1:]    ,					dtype=tensor.dtype						) for name, tensor in inputs_dict.items()
											}

											if hasattr(self.model_tester    ,					'''num_labels'''						):
																__magic_name__ :							List[str]		       =							self.model_tester.num_labels
											else:
																__magic_name__ :							Optional[int]		       =							2

											__magic_name__ :							List[Any]		       =							tf.data.Dataset.from_tensor_slices(
											    (inputs_dict, np.ones((self.model_tester.batch_size, self.model_tester.seq_length, num_labels, 1)						))						).batch(1						)

											__magic_name__ :							List[str]		       =							main_layer(UpperCamelCase_						)[0]
											__magic_name__ :							Optional[int]		       =							tf.keras.layers.Dense(UpperCamelCase_    ,					activation='''softmax'''    ,					name='''outputs'''						)(UpperCamelCase_						)
											__magic_name__ :							List[str]		       =							tf.keras.models.Model(inputs=UpperCamelCase_    ,					outputs=[outputs]						)

											model.compile(loss='''binary_crossentropy'''    ,					optimizer='''adam'''    ,					metrics=['''binary_accuracy''']						)
											model.fit(UpperCamelCase_    ,					epochs=1						)

											with tempfile.TemporaryDirectory() as tmpdirname:
																__magic_name__ :							Optional[int]		       =							os.path.join(UpperCamelCase_    ,					'''keras_model.h5'''						)
																model.save(UpperCamelCase_						)
																if "T5" in main_layer_class.__name__:
																					__magic_name__ :							List[Any]		       =							tf.keras.models.load_model(
																					    UpperCamelCase_    ,					custom_objects={
																					        main_layer_class.__name__: main_layer_class,
																					        '''TFSharedEmbeddings''': TFSharedEmbeddings,
																					    }    ,					)
																else:
																					__magic_name__ :							List[Any]		       =							tf.keras.models.load_model(
																					    UpperCamelCase_    ,					custom_objects={main_layer_class.__name__: main_layer_class}						)
																assert isinstance(UpperCamelCase_    ,					tf.keras.Model						)
																model(UpperCamelCase_						)






	@slow
	def 			lowercase				(     self						)				->       List[str]:




						"""simple docstring"""






						__magic_name__       ,			__magic_name__ :							Optional[Any]		       =							self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes[:2]:
											__magic_name__ :							Union[str, Any]		       =							model_class(UpperCamelCase_						)

											__magic_name__ :							int		       =							copy.deepcopy(UpperCamelCase_						)

											if not self.is_encoder_decoder:
																__magic_name__ :							List[str]		       =							inputs['''input_ids''']
																del inputs["input_ids"]
											else:
																__magic_name__ :							Optional[int]		       =							inputs['''input_ids''']
																__magic_name__ :							Tuple		       =							inputs.get('''decoder_input_ids'''    ,					UpperCamelCase_						)
																del inputs["input_ids"]
																inputs.pop('''decoder_input_ids'''    ,					UpperCamelCase_						)

											if not self.is_encoder_decoder:
																__magic_name__ :							Optional[Any]		       =							model.get_input_embeddings()(UpperCamelCase_						)
											else:
																__magic_name__ :							List[str]		       =							model.get_input_embeddings()(UpperCamelCase_						)
																__magic_name__ :							List[str]		       =							model.get_input_embeddings()(UpperCamelCase_						)

											__magic_name__ :							Any		       =							self._prepare_for_class(UpperCamelCase_    ,					UpperCamelCase_						)

											@tf.function
											def run_in_graph_mode():
																return model(UpperCamelCase_						)

											__magic_name__ :							int		       =							run_in_graph_mode()
											self.assertIsNotNone(UpperCamelCase_						)






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Dict:




						"""simple docstring"""






						__magic_name__ :							Dict		       =							[]
						if model.config.bos_token_id is not None:
											special_tokens.append(model.config.bos_token_id						)
						if model.config.pad_token_id is not None:
											special_tokens.append(model.config.pad_token_id						)
						if model.config.eos_token_id is not None:
											special_tokens.append(model.config.eos_token_id						)

						# create random bad tokens that are not special tokens
						__magic_name__ :							Optional[int]		       =							[]
						while len(UpperCamelCase_						) < num_bad_tokens:
											__magic_name__ :							int		       =							tf.squeeze(ids_tensor((1, 1)    ,					self.model_tester.vocab_size						)    ,					0						).numpy()[0]
											if token not in special_tokens:
																bad_tokens.append(UpperCamelCase_						)
						return bad_tokens






	def 			lowercase				(     self    ,					lowerCamelCase						)				->       List[str]:




						"""simple docstring"""






						for token_id in output_ids[0].numpy().tolist():
											self.assertGreaterEqual(UpperCamelCase_    ,					0						)
											self.assertLess(UpperCamelCase_    ,					self.model_tester.vocab_size						)






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Optional[int]:




						"""simple docstring"""






						for bad_word_ids in bad_words_ids:
											# for all slices in batch
											for generated_ids_slice in generated_ids:
																# for all word idx
																for i in range(len(UpperCamelCase_						)    ,					len(UpperCamelCase_						)						):
																					# if tokens match
																					if generated_ids_slice[i - len(UpperCamelCase_						) : i] == bad_word_ids:
																										return True
						return False









import inspect
import os
from argparse import ArgumentParser, Namespace
from importlib import import_module

import huggingface_hub
import numpy as np
from packaging import version

from .. import (
    FEATURE_EXTRACTOR_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoImageProcessor,
    AutoProcessor,
    AutoTokenizer,
    is_datasets_available,
    is_tf_available,
    is_torch_available,
)
from ..utils import TF2_WEIGHTS_INDEX_NAME, TF2_WEIGHTS_NAME, logging
from . import BaseTransformersCLICommand


if is_tf_available():
				import tensorflow as tf

				tf.config.experimental.enable_tensor_float_aa_execution(False)

if is_torch_available():
				import torch

if is_datasets_available():
				from datasets import load_dataset


lowercase_		=							5E-5  # larger error tolerance than in our internal tests, to avoid flaky user-facing errors







def 			lowerCAmelCase  (     UpperCAmelCase	)  ->Dict:






					"""simple docstring"""






					return PTtoTFCommand(
					    args.model_name,     args.local_dir,     args.max_error,     args.new_weights,     args.no_pr,     args.push,     args.extra_commit_description,     args.override_model_class,     )





class 		A__    (       __SCREAMING_SNAKE_CASE			):






	@staticmethod
	def 			lowercase				(     lowerCamelCase						)				->       Dict:




						"""simple docstring"""






						__magic_name__ :							Union[str, Any]		       =							parser.add_parser(
						    '''pt-to-tf'''    ,					help=(
						        '''CLI tool to run convert a transformers model from a PyTorch checkpoint to a TensorFlow checkpoint.'''
						        ''' Can also be used to validate existing weights without opening PRs, with --no-pr.'''
						    )    ,					)
						train_parser.add_argument(
						    '''--model-name'''    ,					type=lowerCamelCase    ,					required=lowerCamelCase    ,					help='''The model name, including owner/organization, as seen on the hub.'''    ,					)
						train_parser.add_argument(
						    '''--local-dir'''    ,					type=lowerCamelCase    ,					default=''''''    ,					help='''Optional local directory of the model repository. Defaults to /tmp/{model_name}'''    ,					)
						train_parser.add_argument(
						    '''--max-error'''    ,					type=lowerCamelCase    ,					default=lowerCamelCase    ,					help=(
						        F'''Maximum error tolerance. Defaults to {MAX_ERROR}. This flag should be avoided, use at your own risk.'''
						    )    ,					)
						train_parser.add_argument(
						    '''--new-weights'''    ,					action='''store_true'''    ,					help='''Optional flag to create new TensorFlow weights, even if they already exist.'''    ,					)
						train_parser.add_argument(
						    '''--no-pr'''    ,					action='''store_true'''    ,					help='''Optional flag to NOT open a PR with converted weights.'''						)
						train_parser.add_argument(
						    '''--push'''    ,					action='''store_true'''    ,					help='''Optional flag to push the weights directly to `main` (requires permissions)'''    ,					)
						train_parser.add_argument(
						    '''--extra-commit-description'''    ,					type=lowerCamelCase    ,					default=''''''    ,					help='''Optional additional commit description to use when opening a PR (e.g. to tag the owner).'''    ,					)
						train_parser.add_argument(
						    '''--override-model-class'''    ,					type=lowerCamelCase    ,					default=lowerCamelCase    ,					help='''If you think you know better than the auto-detector, you can specify the model class here. '''
						    '''Can be either an AutoModel class or a specific model class like BertForSequenceClassification.'''    ,					)
						train_parser.set_defaults(func=lowerCamelCase						)






	@staticmethod
	def 			lowercase				(     lowerCamelCase    ,					lowerCamelCase						)				->       str:




						"""simple docstring"""






						__magic_name__ :							Optional[int]		       =							set(pt_outputs.keys()						)
						__magic_name__ :							Tuple		       =							set(tf_outputs.keys()						)
						if pt_out_attrs != tf_out_attrs:
											raise ValueError(
											    F'''The model outputs have different attributes, aborting. (Pytorch: {pt_out_attrs}, TensorFlow:'''
											    F''' {tf_out_attrs})'''						)

						# 2. For each output attribute, computes the difference
						def _find_pt_tf_differences(lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase=""						):
											# If the current attribute is a tensor, it is a leaf and we make the comparison. Otherwise, we will dig in
											# recursivelly, keeping the name of the attribute.
											if isinstance(lowerCamelCase    ,					torch.Tensor						):
																__magic_name__ :							int		       =							np.max(np.abs(pt_out.numpy() - tf_out.numpy()						)						)
																__magic_name__ :							int		       =							tensor_difference
											else:
																__magic_name__ :							Union[str, Any]		       =							attr_name
																for i, pt_item in enumerate(lowerCamelCase						):
																					# If it is a named attribute, we keep the name. Otherwise, just its index.
																					if isinstance(lowerCamelCase    ,					lowerCamelCase						):
																										__magic_name__ :							Tuple		       =							root_name + pt_item
																										__magic_name__ :							Any		       =							tf_out[pt_item]
																										__magic_name__ :							Optional[Any]		       =							pt_out[pt_item]
																					else:
																										__magic_name__ :							Union[str, Any]		       =							root_name + F'''[{i}]'''
																										__magic_name__ :							Any		       =							tf_out[i]
																					__magic_name__ :							str		       =							_find_pt_tf_differences(lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase						)

											return differences

						return _find_pt_tf_differences(lowerCamelCase    ,					lowerCamelCase    ,					{}						)






	def __init__(     self    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase    ,					*lowerCamelCase    ,					)				->       str:




						"""simple docstring"""






						__magic_name__ :							Tuple		       =							logging.get_logger('''transformers-cli/pt_to_tf'''						)
						__magic_name__ :							Dict		       =							model_name
						__magic_name__ :							Optional[Any]		       =							local_dir if local_dir else os.path.join('''/tmp'''    ,					lowerCamelCase						)
						__magic_name__ :							str		       =							max_error
						__magic_name__ :							Any		       =							new_weights
						__magic_name__ :							Optional[Any]		       =							no_pr
						__magic_name__ :							Union[str, Any]		       =							push
						__magic_name__ :							Optional[Any]		       =							extra_commit_description
						__magic_name__ :							Optional[int]		       =							override_model_class






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Tuple:




						"""simple docstring"""






						def _get_audio_input():
											__magic_name__ :							int		       =							load_dataset('''hf-internal-testing/librispeech_asr_dummy'''    ,					'''clean'''    ,					split='''validation'''						)
											__magic_name__ :							Tuple		       =							ds.sort('''id'''						).select(range(2						)						)[:2]['''audio''']
											__magic_name__ :							Union[str, Any]		       =							[x['''array'''] for x in speech_samples]
											return raw_samples

						__magic_name__ :							Tuple		       =							type(pt_model.config						)
						if model_config_class in PROCESSOR_MAPPING:
											__magic_name__ :							Optional[int]		       =							AutoProcessor.from_pretrained(self._local_dir						)
											if model_config_class in TOKENIZER_MAPPING and processor.tokenizer.pad_token is None:
																__magic_name__ :							int		       =							processor.tokenizer.eos_token
						elif model_config_class in IMAGE_PROCESSOR_MAPPING:
											__magic_name__ :							List[str]		       =							AutoImageProcessor.from_pretrained(self._local_dir						)
						elif model_config_class in FEATURE_EXTRACTOR_MAPPING:
											__magic_name__ :							Dict		       =							AutoFeatureExtractor.from_pretrained(self._local_dir						)
						elif model_config_class in TOKENIZER_MAPPING:
											__magic_name__ :							str		       =							AutoTokenizer.from_pretrained(self._local_dir						)
											if processor.pad_token is None:
																__magic_name__ :							Union[str, Any]		       =							processor.eos_token
						else:
											raise ValueError(F'''Unknown data processing type (model config type: {model_config_class})'''						)

						__magic_name__ :							Optional[Any]		       =							set(inspect.signature(pt_model.forward						).parameters.keys()						)
						__magic_name__ :							Tuple		       =							{}
						if "input_ids" in model_forward_signature:
											processor_inputs.update(
											    {
											        '''text''': ['''Hi there!''', '''I am a batch with more than one row and different input lengths.'''],
											        '''padding''': True,
											        '''truncation''': True,
											    }						)
						if "pixel_values" in model_forward_signature:
											__magic_name__ :							List[str]		       =							load_dataset('''cifar10'''    ,					'''plain_text'''    ,					split='''test'''						)[:2]['''img''']
											processor_inputs.update({'''images''': sample_images}						)
						if "input_features" in model_forward_signature:
											__magic_name__ :							str		       =							inspect.signature(processor.feature_extractor						).parameters
											# Pad to the largest input length by default but take feature extractor default
											# padding value if it exists e.g. "max_length" and is not False or None
											if "padding" in feature_extractor_signature:
																__magic_name__ :							List[str]		       =							feature_extractor_signature['''padding'''].default
																if default_strategy is not False and default_strategy is not None:
																					__magic_name__ :							Optional[Any]		       =							default_strategy
																else:
																					__magic_name__ :							Tuple		       =							True
											else:
																__magic_name__ :							Tuple		       =							True
											processor_inputs.update({'''audio''': _get_audio_input(), '''padding''': padding_strategy}						)
						if "input_values" in model_forward_signature:  # Wav2Vec2 audio input
											processor_inputs.update({'''audio''': _get_audio_input(), '''padding''': True}						)
						__magic_name__ :							Tuple		       =							processor(**lowerCamelCase    ,					return_tensors='''pt'''						)
						__magic_name__ :							List[Any]		       =							processor(**lowerCamelCase    ,					return_tensors='''tf'''						)

						# Extra input requirements, in addition to the input modality
						if (
						    config.is_encoder_decoder
						    or (hasattr(lowerCamelCase    ,					'''encoder'''						) and hasattr(lowerCamelCase    ,					'''decoder'''						))
						    or "decoder_input_ids" in tf_dummy_inputs
						):
											__magic_name__ :							List[Any]		       =							np.asarray([[1], [1]]    ,					dtype=lowerCamelCase						) * (pt_model.config.decoder_start_token_id or 0)
											pt_input.update({'''decoder_input_ids''': torch.tensor(lowerCamelCase						)}						)
											tf_input.update({'''decoder_input_ids''': tf.convert_to_tensor(lowerCamelCase						)}						)

						return pt_input, tf_input






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




						"""simple docstring"""






						if version.parse(huggingface_hub.__version__						) < version.parse('''0.9.0'''						):
											raise ImportError(
											    '''The huggingface_hub version must be >= 0.9.0 to use this command. Please update your huggingface_hub'''
											    ''' installation.'''						)
						else:
											from huggingface_hub import Repository, create_commit
											from huggingface_hub._commit_api import CommitOperationAdd

						# Fetch remote data
						__magic_name__ :							int		       =							Repository(local_dir=self._local_dir    ,					clone_from=self._model_name						)

						# Load config and get the appropriate architecture -- the latter is needed to convert the head's weights
						__magic_name__ :							Optional[int]		       =							AutoConfig.from_pretrained(self._local_dir						)
						__magic_name__ :							int		       =							config.architectures
						if self._override_model_class is not None:
											if self._override_model_class.startswith('''TF'''						):
																__magic_name__ :							Dict		       =							[self._override_model_class[2:]]
											else:
																__magic_name__ :							Any		       =							[self._override_model_class]
											try:
																__magic_name__ :							List[Any]		       =							getattr(import_module('''transformers'''						)    ,					architectures[0]						)
											except AttributeError:
																raise ValueError(F'''Model class {self._override_model_class} not found in transformers.'''						)
											try:
																__magic_name__ :							Optional[Any]		       =							getattr(import_module('''transformers'''						)    ,					'''TF''' + architectures[0]						)
											except AttributeError:
																raise ValueError(F'''TF model class TF{self._override_model_class} not found in transformers.'''						)
						elif architectures is None:  # No architecture defined -- use auto classes
											__magic_name__ :							Union[str, Any]		       =							getattr(import_module('''transformers'''						)    ,					'''AutoModel'''						)
											__magic_name__ :							Union[str, Any]		       =							getattr(import_module('''transformers'''						)    ,					'''TFAutoModel'''						)
											self._logger.warning('''No detected architecture, using AutoModel/TFAutoModel'''						)
						else:  # Architecture defined -- use it
											if len(lowerCamelCase						) > 1:
																raise ValueError(F'''More than one architecture was found, aborting. (architectures = {architectures})'''						)
											self._logger.warning(F'''Detected architecture: {architectures[0]}'''						)
											__magic_name__ :							int		       =							getattr(import_module('''transformers'''						)    ,					architectures[0]						)
											try:
																__magic_name__ :							Optional[int]		       =							getattr(import_module('''transformers'''						)    ,					'''TF''' + architectures[0]						)
											except AttributeError:
																raise AttributeError(F'''The TensorFlow equivalent of {architectures[0]} doesn\'t exist in transformers.'''						)

        # Check the TF dummy inputs to see what keys we need in the forward pass
						__magic_name__ :							Dict		       =							tf_class.from_config(lowerCamelCase						)
						__magic_name__ :							Dict		       =							tf_from_pt_model.dummy_inputs

						del tf_from_pt_model  # Try to keep only one model in memory at a time

						# Load the model and get some basic inputs
						__magic_name__ :							List[str]		       =							pt_class.from_pretrained(self._local_dir						)
						pt_model.eval()

						__magic_name__       ,			__magic_name__ :							Any		       =							self.get_inputs(lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase						)

						with torch.no_grad():
											__magic_name__ :							str		       =							pt_model(**lowerCamelCase    ,					output_hidden_states=lowerCamelCase						)
						del pt_model  # will no longer be used, and may have a large memory footprint

						__magic_name__ :							str		       =							tf_class.from_pretrained(self._local_dir    ,					from_pt=lowerCamelCase						)
						__magic_name__ :							Optional[Any]		       =							tf_from_pt_model(**lowerCamelCase    ,					output_hidden_states=lowerCamelCase    ,					training=lowerCamelCase						)

						# Confirms that cross loading PT weights into TF worked.
						__magic_name__ :							Any		       =							self.find_pt_tf_differences(lowerCamelCase    ,					lowerCamelCase						)
						__magic_name__ :							Any		       =							{k: v for k, v in crossload_differences.items() if '''hidden''' not in k}
						__magic_name__ :							Union[str, Any]		       =							{k: v for k, v in crossload_differences.items() if '''hidden''' in k}
						if len(lowerCamelCase						) == 0 and architectures is not None:
											raise ValueError(
											    F'''Something went wrong -- the config file has architectures ({architectures}), but no model head'''
											    ''' output was found. All outputs start with \'hidden\''''						)
						__magic_name__ :							str		       =							max(output_differences.values()						) if output_differences else 0.0
						__magic_name__ :							Dict		       =							max(hidden_differences.values()						)
						if max_crossload_output_diff > self._max_error or max_crossload_hidden_diff > self._max_error:
											raise ValueError(
											    '''The cross-loaded TensorFlow model has different outputs, something went wrong!\n'''
											    + F'''\nList of maximum output differences above the threshold ({self._max_error}):\n'''
											    + '''\n'''.join([F'''{k}: {v:.3e}''' for k, v in output_differences.items() if v > self._max_error]						)
											    + F'''\n\nList of maximum hidden layer differences above the threshold ({self._max_error}):\n'''
											    + '''\n'''.join([F'''{k}: {v:.3e}''' for k, v in hidden_differences.items() if v > self._max_error]						)						)

						# Save the weights in a TF format (if needed) and confirms that the results are still good
						__magic_name__ :							Any		       =							os.path.join(self._local_dir    ,					lowerCamelCase						)
						__magic_name__ :							Tuple		       =							os.path.join(self._local_dir    ,					lowerCamelCase						)
						if (not os.path.exists(lowerCamelCase						) and not os.path.exists(lowerCamelCase						)) or self._new_weights:
											tf_from_pt_model.save_pretrained(self._local_dir						)
						del tf_from_pt_model  # will no longer be used, and may have a large memory footprint

						__magic_name__ :							Any		       =							tf_class.from_pretrained(self._local_dir						)
						__magic_name__ :							Optional[int]		       =							tf_model(**lowerCamelCase    ,					output_hidden_states=lowerCamelCase						)

						__magic_name__ :							Any		       =							self.find_pt_tf_differences(lowerCamelCase    ,					lowerCamelCase						)
						__magic_name__ :							Any		       =							{k: v for k, v in conversion_differences.items() if '''hidden''' not in k}
						__magic_name__ :							int		       =							{k: v for k, v in conversion_differences.items() if '''hidden''' in k}
						if len(lowerCamelCase						) == 0 and architectures is not None:
											raise ValueError(
											    F'''Something went wrong -- the config file has architectures ({architectures}), but no model head'''
											    ''' output was found. All outputs start with \'hidden\''''						)
						__magic_name__ :							str		       =							max(output_differences.values()						) if output_differences else 0.0
						__magic_name__ :							Optional[Any]		       =							max(hidden_differences.values()						)
						if max_conversion_output_diff > self._max_error or max_conversion_hidden_diff > self._max_error:
											raise ValueError(
											    '''The converted TensorFlow model has different outputs, something went wrong!\n'''
											    + F'''\nList of maximum output differences above the threshold ({self._max_error}):\n'''
											    + '''\n'''.join([F'''{k}: {v:.3e}''' for k, v in output_differences.items() if v > self._max_error]						)
											    + F'''\n\nList of maximum hidden layer differences above the threshold ({self._max_error}):\n'''
											    + '''\n'''.join([F'''{k}: {v:.3e}''' for k, v in hidden_differences.items() if v > self._max_error]						)						)

						__magic_name__ :							List[str]		       =							'''Update TF weights''' if self._new_weights else '''Add TF weights'''
						if self._push:
											repo.git_add(auto_lfs_track=lowerCamelCase						)
											repo.git_commit(lowerCamelCase						)
											repo.git_push(blocking=lowerCamelCase						)  # this prints a progress bar with the upload
											self._logger.warning(F'''TF weights pushed into {self._model_name}'''						)
						elif not self._no_pr:
											self._logger.warning('''Uploading the weights into a new PR...'''						)
											__magic_name__ :							Optional[int]		       =							(
											    '''Model converted by the [`transformers`\' `pt_to_tf`'''
											    ''' CLI](https://github.com/huggingface/transformers/blob/main/src/transformers/commands/pt_to_tf.py). '''
											    '''All converted model outputs and hidden layers were validated against its PyTorch counterpart.\n\n'''
											    F'''Maximum crossload output difference={max_crossload_output_diff:.3e}; '''
											    F'''Maximum crossload hidden layer difference={max_crossload_hidden_diff:.3e};\n'''
											    F'''Maximum conversion output difference={max_conversion_output_diff:.3e}; '''
											    F'''Maximum conversion hidden layer difference={max_conversion_hidden_diff:.3e};\n'''
											)
											if self._max_error > MAX_ERROR:
																commit_descrition += (
																    F'''\n\nCAUTION: The maximum admissible error was manually increased to {self._max_error}!'''
																)
											if self._extra_commit_description:
																commit_descrition += "\n\n" + self._extra_commit_description

											# sharded model -> adds all related files (index and .h5 shards)
											if os.path.exists(lowerCamelCase						):
																__magic_name__ :							str		       =							[
																    CommitOperationAdd(path_in_repo=lowerCamelCase    ,					path_or_fileobj=lowerCamelCase						)
																]
																for shard_path in tf.io.gfile.glob(self._local_dir + '''/tf_model-*.h5'''						):
																					operations += [
																					    CommitOperationAdd(path_in_repo=os.path.basename(lowerCamelCase						)    ,					path_or_fileobj=lowerCamelCase						)
																					]
											else:
																__magic_name__ :							Optional[int]		       =							[CommitOperationAdd(path_in_repo=lowerCamelCase    ,					path_or_fileobj=lowerCamelCase						)]

											__magic_name__ :							Dict		       =							create_commit(
											    repo_id=self._model_name    ,					operations=lowerCamelCase    ,					commit_message=lowerCamelCase    ,					commit_description=lowerCamelCase    ,					repo_type='''model'''    ,					create_pr=lowerCamelCase    ,					).pr_url
											self._logger.warning(F'''PR open in {hub_pr_url}'''						)



