





from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
 from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor



class   lowercase_   :



      def __init__(      self				:    int      , A__				:    Union[str, Any]      , A__				:    int=3      , A__				:    Tuple=32      , A__				:    Optional[Any]=3      , A__				:    str=10      , A__				:    Tuple=[10, 20, 30, 40]      , A__				:    Any=[1, 1, 2, 1]      , A__				:    int=True      , A__				:    int=True      , A__				:    Union[str, Any]="relu"      , A__				:    List[str]=3      , A__				:    Optional[Any]=None      , )   ->					int:
        _snake_case						=							parent
        _snake_case						=							batch_size
        _snake_case						=							image_size
        _snake_case						=							num_channels
        _snake_case						=							embeddings_size
        _snake_case						=							hidden_sizes
        _snake_case						=							depths
        _snake_case						=							is_training
        _snake_case						=							use_labels
        _snake_case						=							hidden_act
        _snake_case						=							num_labels
        _snake_case						=							scope
        _snake_case						=							len(A__		)



      def 						UpperCamelCase_		(      self				:    List[str]		)   ->					str:
        _snake_case						=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

        _snake_case						=							None
        if self.use_labels:
          _snake_case						=							ids_tensor([self.batch_size]      , self.num_labels		)

        _snake_case						=							self.get_config()

        return config, pixel_values, labels



      def 						UpperCamelCase_		(      self				:    Optional[int]		)   ->					Dict:
        return ResNetConfig(
            num_channels=self.num_channels      , embeddings_size=self.embeddings_size      , hidden_sizes=self.hidden_sizes      , depths=self.depths      , hidden_act=self.hidden_act      , num_labels=self.num_labels      , image_size=self.image_size      , )



      def 						UpperCamelCase_		(      self				:    List[str]      , A__				:    int      , A__				:    str      , A__				:    Union[str, Any]		)   ->					Optional[Any]:
        _snake_case						=							TFResNetModel(config=A__		)
        _snake_case						=							model(A__		)
        # expected last hidden states: B, C, H // 32, W // 32
        self.parent.assertEqual(
            result.last_hidden_state.shape      , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)      , )



      def 						UpperCamelCase_		(      self				:    List[str]      , A__				:    Tuple      , A__				:    List[str]      , A__				:    Optional[int]		)   ->					int:
        _snake_case						=							self.num_labels
        _snake_case						=							TFResNetForImageClassification(A__		)
        _snake_case						=							model(A__      , labels=A__		)
        self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.num_labels)		)







      def 						UpperCamelCase_		(      self				:    str		)   ->					int:
        _snake_case						=							self.prepare_config_and_inputs()
        _snake_case,					_snake_case,					_snake_case						=							config_and_inputs
        _snake_case						=							{'''pixel_values''': pixel_values}
        return config, inputs_dict



@require_tf
class   lowercase_   (  __lowercase       ,							__lowercase       ,							unittest.TestCase					):
      UpperCamelCase_      :		Optional[int]										=    (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
      UpperCamelCase_      :		List[str]										=    (
          {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
          if is_tf_available()
          else {}
      )

      UpperCamelCase_      :		Dict										=    False
      UpperCamelCase_      :		List[str]										=    False
      UpperCamelCase_      :		Optional[int]										=    False
      UpperCamelCase_      :		Tuple										=    False
      UpperCamelCase_      :		Dict										=    False



      def 						UpperCamelCase_		(      self				:    List[str]		)   ->					List[Any]:
        _snake_case						=							TFResNetModelTester(self		)
        _snake_case						=							ConfigTester(self      , config_class=A__      , has_text_modality=A__		)



      def 						UpperCamelCase_		(      self				:    Optional[Any]		)   ->					int:
        self.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()



      def 						UpperCamelCase_		(      self				:    List[str]		)   ->					Any:
        return



      @unittest.skip(reason='''ResNet does not use inputs_embeds'''		)
      def 						UpperCamelCase_		(      self				:    List[Any]		)   ->					Dict:
        pass



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



      def 						UpperCamelCase_		(      self				:    Union[str, Any]		)   ->					Union[str, Any]:
        _snake_case,					_snake_case						=							self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          _snake_case						=							model_class(A__		)
          _snake_case						=							inspect.signature(model.call		)
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          _snake_case						=							[*signature.parameters.keys()]

          _snake_case						=							['''pixel_values''']
          self.assertListEqual(arg_names[:1]      , A__		)



      def 						UpperCamelCase_		(      self				:    Optional[Any]		)   ->					Any:
        _snake_case						=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A__		)



      def 						UpperCamelCase_		(      self				:    Optional[Any]		)   ->					Tuple:
        def check_hidden_states_output(A__				:    Optional[int]      , A__				:    Any      , A__				:    Optional[int]		):
          _snake_case						=							model_class(A__		)
          _snake_case						=							model(**self._prepare_for_class(A__      , A__		)		)

          _snake_case						=							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          _snake_case						=							self.model_tester.num_stages
          self.assertEqual(len(A__		)      , expected_num_stages + 1		)

          # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
          self.assertListEqual(
              list(hidden_states[0].shape[-2:]		)      , [self.model_tester.image_size // 4, self.model_tester.image_size // 4]      , )

        _snake_case,					_snake_case						=							self.model_tester.prepare_config_and_inputs_for_common()
        _snake_case						=							['''basic''', '''bottleneck''']
        for model_class in self.all_model_classes:
          for layer_type in layers_type:
            _snake_case						=							layer_type
            _snake_case						=							True
            check_hidden_states_output(A__      , A__      , A__		)

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            _snake_case						=							True

            check_hidden_states_output(A__      , A__      , A__		)



      def 						UpperCamelCase_		(      self				:    int		)   ->					Optional[Any]:
        _snake_case						=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*A__		)







      @slow
      def 						UpperCamelCase_		(      self				:    List[str]		)   ->					Dict:
        for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          _snake_case						=							TFResNetModel.from_pretrained(A__		)
          self.assertIsNotNone(A__		)



def 				snake_case_()							->     Tuple:



  """simple docstring"""






  _snake_case						=							Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
  return image



@require_tf
@require_vision
class   lowercase_   (  unittest.TestCase					):



      @cached_property
      def 						UpperCamelCase_		(      self				:    Tuple		)   ->					Optional[Any]:
        return (
            AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
            if is_vision_available()
            else None
        )







      @slow
      def 						UpperCamelCase_		(      self				:    Union[str, Any]		)   ->					Any:
        _snake_case						=							TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

        _snake_case						=							self.default_image_processor
        _snake_case						=							prepare_img()
        _snake_case						=							image_processor(images=A__      , return_tensors='''tf'''		)

        # forward pass
        _snake_case						=							model(**A__		)

        # verify the logits
        _snake_case						=							tf.TensorShape((1, 1000)		)
        self.assertEqual(outputs.logits.shape      , A__		)

        _snake_case						=							tf.constant([-11.1069, -9.7877, -8.3777]		)

        self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()      , A__      , atol=1e-4		)		)




import argparse

import torch

from ...utils import logging
from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert


logging.set_verbosity_info()



def 				snake_case_(_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase					)							->     Optional[Any]:



  """simple docstring"""






  _snake_case						=							AlbertConfig.from_json_file(_UpperCamelCase					)
  print(F"""Building PyTorch model from configuration: {config}"""					)
  _snake_case						=							AlbertForPreTraining(_UpperCamelCase					)

  # Load weights from tf checkpoint
  load_tf_weights_in_albert(_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase					)

  # Save pytorch-model
  print(F"""Save PyTorch model to {pytorch_dump_path}"""					)
  torch.save(model.state_dict()			,	_UpperCamelCase					)


if __name__ == "__main__":
 __A      		=     argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
 )
 parser.add_argument(
     '''--albert_config_file''',
     default=None,
     type=str,
     required=True,
     help=(
         '''The config json file corresponding to the pre-trained ALBERT model. \n'''
         '''This specifies the model architecture.'''
     ),
 )
 parser.add_argument(
     '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
 )
 __A      		=     parser.parse_args()
 convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)

