



'''simple docstring'''





from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
   import tensorflow as tf

   from transformers import TFCvtForImageClassification, TFCvtModel
   from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor






class    lowerCamelCase_       (							snake_case_	):
  """simple docstring"""




  def 		_lowercase	(					self :      Tuple  )   ->   Any:
    __lowerCamelCase			:			int       			=					self.config_class(**self.inputs_dict  )
    self.parent.assertTrue(hasattr(_a     ,      'embed_dim'  )  )
    self.parent.assertTrue(hasattr(_a     ,      'num_heads'  )  )






class    lowerCamelCase_       :
  """simple docstring"""




  def __init__(					self :      Dict     ,      _a :      Optional[Any]     ,      _a :      Optional[Any]=13     ,      _a :      List[str]=64     ,      _a :      Optional[Any]=3     ,      _a :      int=[16, 48, 96]     ,      _a :      Optional[int]=[1, 3, 6]     ,      _a :      Any=[1, 2, 10]     ,      _a :      Optional[Any]=[7, 3, 3]     ,      _a :      Dict=[4, 2, 2]     ,      _a :      int=[2, 1, 1]     ,      _a :      str=[2, 2, 2]     ,      _a :      Dict=[False, False, True]     ,      _a :      List[Any]=[0.0, 0.0, 0.0]     ,      _a :      Tuple=0.02     ,      _a :      Optional[int]=1e-12     ,      _a :      int=True     ,      _a :      Union[str, Any]=True     ,      _a :      Optional[int]=2     ,      )   ->   List[Any]:
    __lowerCamelCase			:			Optional[Any]       			=					parent
    __lowerCamelCase			:			List[str]       			=					batch_size
    __lowerCamelCase			:			List[str]       			=					image_size
    __lowerCamelCase			:			Union[str, Any]       			=					patch_sizes
    __lowerCamelCase			:			List[Any]       			=					patch_stride
    __lowerCamelCase			:			int       			=					patch_padding
    __lowerCamelCase			:			List[str]       			=					is_training
    __lowerCamelCase			:			int       			=					use_labels
    __lowerCamelCase			:			Dict       			=					num_labels
    __lowerCamelCase			:			Dict       			=					num_channels
    __lowerCamelCase			:			List[str]       			=					embed_dim
    __lowerCamelCase			:			Any       			=					num_heads
    __lowerCamelCase			:			Optional[int]       			=					stride_kv
    __lowerCamelCase			:			Dict       			=					depth
    __lowerCamelCase			:			Optional[int]       			=					cls_token
    __lowerCamelCase			:			Optional[Any]       			=					attention_drop_rate
    __lowerCamelCase			:			Optional[Any]       			=					initializer_range
    __lowerCamelCase			:			Union[str, Any]       			=					layer_norm_eps




  def 		_lowercase	(					self :      Tuple  )   ->   Dict:
    __lowerCamelCase			:			Any       			=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

    __lowerCamelCase			:			Optional[Any]       			=					None
    if self.use_labels:
      # create a random int32 tensor of given shape
      __lowerCamelCase			:			Tuple       			=					ids_tensor([self.batch_size]     ,      self.num_labels  )

    __lowerCamelCase			:			List[str]       			=					self.get_config()
    return config, pixel_values, labels




  def 		_lowercase	(					self :      Tuple  )   ->   Dict:
    return CvtConfig(
        image_size=self.image_size     ,      num_labels=self.num_labels     ,      num_channels=self.num_channels     ,      embed_dim=self.embed_dim     ,      num_heads=self.num_heads     ,      patch_sizes=self.patch_sizes     ,      patch_padding=self.patch_padding     ,      patch_stride=self.patch_stride     ,      stride_kv=self.stride_kv     ,      depth=self.depth     ,      cls_token=self.cls_token     ,      attention_drop_rate=self.attention_drop_rate     ,      initializer_range=self.initializer_range     ,      )




  def 		_lowercase	(					self :      Any     ,      _a :      Union[str, Any]     ,      _a :      Any     ,      _a :      Optional[int]  )   ->   int:
    __lowerCamelCase			:			List[Any]       			=					TFCvtModel(config=_a  )
    __lowerCamelCase			:			Tuple       			=					model(_a     ,      training=_a  )
    __lowerCamelCase			:			List[Any]       			=					(self.image_size, self.image_size)
    __lowerCamelCase			,__lowerCamelCase			:			Optional[Any]       			=					image_size[0], image_size[1]
    for i in range(len(self.depth  )  ):
      __lowerCamelCase			:			Union[str, Any]       			=					floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1  )
      __lowerCamelCase			:			Tuple       			=					floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1  )
    self.parent.assertEqual(result.last_hidden_state.shape     ,      (self.batch_size, self.embed_dim[-1], height, width)  )




  def 		_lowercase	(					self :      Union[str, Any]     ,      _a :      Optional[int]     ,      _a :      List[str]     ,      _a :      List[str]  )   ->   Dict:
    __lowerCamelCase			:			Tuple       			=					self.num_labels
    __lowerCamelCase			:			Optional[int]       			=					TFCvtForImageClassification(_a  )
    __lowerCamelCase			:			int       			=					model(_a     ,      labels=_a     ,      training=_a  )
    self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.num_labels)  )




  def 		_lowercase	(					self :      Tuple  )   ->   Tuple:
    __lowerCamelCase			:			Dict       			=					self.prepare_config_and_inputs()
    __lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			:			List[Any]       			=					config_and_inputs
    __lowerCamelCase			:			str       			=					{'pixel_values': pixel_values}
    return config, inputs_dict






@require_tf
class    lowerCamelCase_       (							snake_case_  ,  snake_case_  ,  unittest.TestCase	):
  """simple docstring"""




  a_				   =(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
  a_				   =(
      {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
      if is_tf_available()
      else {}
  )
  a_				   =False
  a_				   =False
  a_				   =False
  a_				   =False
  a_				   =False




  def 		_lowercase	(					self :      str  )   ->   Optional[int]:
    __lowerCamelCase			:			Dict       			=					TFCvtModelTester(self  )
    __lowerCamelCase			:			Any       			=					TFCvtConfigTester(self     ,      config_class=_a     ,      has_text_modality=_a     ,      hidden_size=37  )




  def 		_lowercase	(					self :      str  )   ->   Optional[int]:
    self.config_tester.create_and_test_config_common_properties()
    self.config_tester.create_and_test_config_to_json_string()
    self.config_tester.create_and_test_config_to_json_file()
    self.config_tester.create_and_test_config_from_and_save_pretrained()
    self.config_tester.create_and_test_config_with_num_labels()
    self.config_tester.check_config_can_be_init_without_params()
    self.config_tester.check_config_arguments_init()




  @unittest.skip(reason='Cvt does not output attentions'  )
  def 		_lowercase	(					self :      List[Any]  )   ->   Dict:
    pass




  @unittest.skip(reason='Cvt does not use inputs_embeds'  )
  def 		_lowercase	(					self :      Optional[Any]  )   ->   List[str]:
    pass




  @unittest.skip(reason='Cvt does not support input and output embeddings'  )
  def 		_lowercase	(					self :      List[str]  )   ->   Optional[int]:
    pass




  @unittest.skipIf(
      not is_tf_available() or len(tf.config.list_physical_devices('GPU'  )  ) == 0     ,      reason='TF does not support backprop for grouped convolutions on CPU.'     ,      )
  def 		_lowercase	(					self :      Dict  )   ->   Dict:
    super().test_dataset_conversion()




  @unittest.skipIf(
      not is_tf_available() or len(tf.config.list_physical_devices('GPU'  )  ) == 0     ,      reason='TF does not support backprop for grouped convolutions on CPU.'     ,      )
  @slow
  def 		_lowercase	(					self :      Tuple  )   ->   Dict:
    super().test_keras_fit()




  @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8'  )
  def 		_lowercase	(					self :      str  )   ->   List[str]:
    __lowerCamelCase			:			Any       			=					tf.keras.mixed_precision.Policy('mixed_float16'  )
    tf.keras.mixed_precision.set_global_policy(_a  )
    super().test_keras_fit()
    tf.keras.mixed_precision.set_global_policy('float32'  )




  def 		_lowercase	(					self :      Dict  )   ->   Optional[int]:
    __lowerCamelCase			,__lowerCamelCase			:			Tuple       			=					self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      __lowerCamelCase			:			str       			=					model_class(_a  )
      __lowerCamelCase			:			Tuple       			=					inspect.signature(model.call  )
      # signature.parameters is an OrderedDict => so arg_names order is deterministic
      __lowerCamelCase			:			Optional[int]       			=					[*signature.parameters.keys()]

      __lowerCamelCase			:			Dict       			=					['pixel_values']
      self.assertListEqual(arg_names[:1]     ,      _a  )




  def 		_lowercase	(					self :      Optional[Any]  )   ->   Optional[Any]:
    def check_hidden_states_output(_a :      Dict     ,      _a :      Optional[Any]     ,      _a :      Dict  ):
      __lowerCamelCase			:			List[str]       			=					model_class(_a  )

      __lowerCamelCase			:			Any       			=					model(**self._prepare_for_class(_a     ,      _a  )  )
      __lowerCamelCase			:			int       			=					outputs.hidden_states

      __lowerCamelCase			:			int       			=					len(self.model_tester.depth  )
      self.assertEqual(len(_a  )     ,      _a  )

      # verify the first hidden states (first block)
      self.assertListEqual(
          list(hidden_states[0].shape[-3:]  )     ,      [
              self.model_tester.embed_dim[0],
              self.model_tester.image_size // 4,
              self.model_tester.image_size // 4,
          ]     ,      )

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

    for model_class in self.all_model_classes:
      __lowerCamelCase			:			Dict       			=					True
      check_hidden_states_output(_a     ,      _a     ,      _a  )

      # check that output_hidden_states also work using config
      del inputs_dict["output_hidden_states"]
      __lowerCamelCase			:			Optional[Any]       			=					True

      check_hidden_states_output(_a     ,      _a     ,      _a  )




  def 		_lowercase	(					self :      Any  )   ->   List[Any]:
    __lowerCamelCase			:			str       			=					self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*_a  )




  def 		_lowercase	(					self :      Union[str, Any]  )   ->   List[str]:
    __lowerCamelCase			:			Any       			=					self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*_a  )




  @slow
  def 		_lowercase	(					self :      Tuple  )   ->   int:
    for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __lowerCamelCase			:			Any       			=					TFCvtModel.from_pretrained(_a  )
      self.assertIsNotNone(_a  )




def 			a_	(				) -> Union[str, Any]:
  __lowerCamelCase			:			str       			=					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
  return image






@require_tf
@require_vision
class    lowerCamelCase_       (							unittest.TestCase	):
  """simple docstring"""




  @cached_property
  def 		_lowercase	(					self :      str  )   ->   Any:
    return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )




  @slow
  def 		_lowercase	(					self :      Dict  )   ->   Dict:
    __lowerCamelCase			:			int       			=					TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

    __lowerCamelCase			:			Optional[int]       			=					self.default_image_processor
    __lowerCamelCase			:			Optional[int]       			=					prepare_img()
    __lowerCamelCase			:			Optional[int]       			=					image_processor(images=_a     ,      return_tensors='tf'  )

    # forward pass
    __lowerCamelCase			:			List[str]       			=					model(**_a  )

    # verify the logits
    __lowerCamelCase			:			Any       			=					tf.TensorShape((1, 1000)  )
    self.assertEqual(outputs.logits.shape     ,      _a  )

    __lowerCamelCase			:			Optional[Any]       			=					tf.constant([0.9285, 0.9015, -0.3150]  )
    self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()     ,      _a     ,      atol=1e-4  )  )














import argparse
import collections

import torch
from flax import traverse_util
from tax import checkpoints

from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration
from transformers.utils import logging


logging.set_verbosity_info()





def 		__UpperCAmelCase     (	a_				,	a_				,	a_				,	a_="attention"):
							snake_case_           =				params[f'''{prefix}/layers_{i}/{layer_name}/key/kernel''']
							snake_case_           =				params[f'''{prefix}/layers_{i}/{layer_name}/out/kernel''']
							snake_case_           =				params[f'''{prefix}/layers_{i}/{layer_name}/query/kernel''']
							snake_case_           =				params[f'''{prefix}/layers_{i}/{layer_name}/value/kernel''']
							return k, o, q, v





def 		__UpperCAmelCase     (	a_				,	a_				,	a_				,	a_=False):
							if split_mlp_wi:
														snake_case_           =				params[f'''{prefix}/layers_{i}/mlp/wi_0/kernel''']
														snake_case_           =				params[f'''{prefix}/layers_{i}/mlp/wi_1/kernel''']
														snake_case_           =				(wi_a, wi_a)
							else:
														snake_case_           =				params[f'''{prefix}/layers_{i}/mlp/wi/kernel''']

							snake_case_           =				params[f'''{prefix}/layers_{i}/mlp/wo/kernel''']
							return wi, wo





def 		__UpperCAmelCase     (	a_				,	a_				,	a_				,	a_):
							return params[f'''{prefix}/layers_{i}/{layer_name}/scale''']





def 		__UpperCAmelCase     (	a_				,	*, a_				,	a_):
							snake_case_           =				traverse_util.flatten_dict(variables['target'])
							snake_case_           =				{'/'.join(a_): v for k, v in old.items()}

							# v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi
							snake_case_           =				'encoder/layers_0/mlp/wi_0/kernel' in old
							print('Split MLP:'				,	a_)

							snake_case_           =				collections.OrderedDict()

							# Shared embeddings.
							snake_case_           =				old['token_embedder/embedding']

							# Encoder.
							for i in range(a_):
														# Block i, layer 0 (Self Attention).
														snake_case_           =				tax_layer_norm_lookup(a_				,	a_				,	'encoder'				,	'pre_attention_layer_norm')
														snake_case_     ,						snake_case_     ,						snake_case_     ,						snake_case_           =				tax_attention_lookup(a_				,	a_				,	'encoder'				,	'attention')
														snake_case_           =				layer_norm
														snake_case_           =				k.T
														snake_case_           =				o.T
														snake_case_           =				q.T
														snake_case_           =				v.T

														# Block i, layer 1 (MLP).
														snake_case_           =				tax_layer_norm_lookup(a_				,	a_				,	'encoder'				,	'pre_mlp_layer_norm')
														snake_case_     ,						snake_case_           =				tax_mlp_lookup(a_				,	a_				,	'encoder'				,	a_)
														snake_case_           =				layer_norm
														if split_mlp_wi:
																					snake_case_           =				wi[0].T
																					snake_case_           =				wi[1].T
														else:
																					snake_case_           =				wi.T
														snake_case_           =				wo.T

							snake_case_           =				old[
							    'encoder/relpos_bias/rel_embedding'
							].T
							snake_case_           =				old['encoder/encoder_norm/scale']

							if not is_encoder_only:
														# Decoder.
														for i in range(a_):
																					# Block i, layer 0 (Self Attention).
																					snake_case_           =				tax_layer_norm_lookup(a_				,	a_				,	'decoder'				,	'pre_self_attention_layer_norm')
																					snake_case_     ,						snake_case_     ,						snake_case_     ,						snake_case_           =				tax_attention_lookup(a_				,	a_				,	'decoder'				,	'self_attention')
																					snake_case_           =				layer_norm
																					snake_case_           =				k.T
																					snake_case_           =				o.T
																					snake_case_           =				q.T
																					snake_case_           =				v.T

																					# Block i, layer 1 (Cross Attention).
																					snake_case_           =				tax_layer_norm_lookup(a_				,	a_				,	'decoder'				,	'pre_cross_attention_layer_norm')
																					snake_case_     ,						snake_case_     ,						snake_case_     ,						snake_case_           =				tax_attention_lookup(a_				,	a_				,	'decoder'				,	'encoder_decoder_attention')
																					snake_case_           =				layer_norm
																					snake_case_           =				k.T
																					snake_case_           =				o.T
																					snake_case_           =				q.T
																					snake_case_           =				v.T

																					# Block i, layer 2 (MLP).
																					snake_case_           =				tax_layer_norm_lookup(a_				,	a_				,	'decoder'				,	'pre_mlp_layer_norm')
																					snake_case_     ,						snake_case_           =				tax_mlp_lookup(a_				,	a_				,	'decoder'				,	a_)
																					snake_case_           =				layer_norm
																					if split_mlp_wi:
																												snake_case_           =				wi[0].T
																												snake_case_           =				wi[1].T
																					else:
																												snake_case_           =				wi.T
																					snake_case_           =				wo.T

														snake_case_           =				old['decoder/decoder_norm/scale']
														snake_case_           =				old[
														    'decoder/relpos_bias/rel_embedding'
														].T

														# LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)
														if "decoder/logits_dense/kernel" in old:
																					snake_case_           =				old['decoder/logits_dense/kernel'].T

							return new





def 		__UpperCAmelCase     (	a_				,	a_):
							snake_case_           =				collections.OrderedDict([(k, torch.from_numpy(v.copy())) for (k, v) in converted_params.items()])

							# Add what is missing.
							if "encoder.embed_tokens.weight" not in state_dict:
														snake_case_           =				state_dict['shared.weight']

							if not is_encoder_only:
														if "decoder.embed_tokens.weight" not in state_dict:
																					snake_case_           =				state_dict['shared.weight']

														if "lm_head.weight" not in state_dict:  # For old 1.0 models.
																					print('Using shared word embeddings as lm_head.')
																					snake_case_           =				state_dict['shared.weight']

							return state_dict





def 		__UpperCAmelCase     (	a_				,	a_				,	a_				,	a_):
							snake_case_           =				checkpoints.load_tax_checkpoint(a_)
							snake_case_           =				convert_tax_to_pytorch(a_				,	num_layers=config.num_layers				,	is_encoder_only=a_)
							snake_case_           =				make_state_dict(a_				,	a_)
							model.load_state_dict(a_				,	strict=a_)





def 		__UpperCAmelCase     (	a_				,	a_				,	a_				,	a_ = False):
							snake_case_           =				TaConfig.from_json_file(a_)
							print(f'''Building PyTorch model from configuration: {config}''')
							# Non-v1.1 checkpoints could also use T5Model, but this works for all.
							# The v1.0 checkpoints will simply have an LM head that is the word embeddings.
							if is_encoder_only:
														snake_case_           =				TaEncoderModel(a_)
							else:
														snake_case_           =				TaForConditionalGeneration(a_)

							# Load weights from tf checkpoint
							load_tax_weights_in_ta(a_				,	a_				,	a_				,	a_)

							# Save pytorch-model
							print(f'''Save PyTorch model to {pytorch_dump_path}''')
							model.save_pretrained(a_)

							# Verify that we can load the checkpoint.
							model.from_pretrained(a_)
							print('Done')


if __name__ == "__main__":
	lowercase    				=   argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.")
	# Required parameters
	parser.add_argument(
	    "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint."
	)
	parser.add_argument(
	    "--config_file",
	    default=None,
	    type=str,
	    required=True,
	    help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.",
	)
	parser.add_argument(
	    "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
	)
	parser.add_argument(
	    "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False
	)
	lowercase    				=   parser.parse_args()
	convert_tax_checkpoint_to_pytorch(
	    args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only
	)





