

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 		a_       :



      """simple docstring"""







      def __init__(      self     :							List[Any]			,snake_case     :							Any			,snake_case     :							List[str]=3			,snake_case     :							str=32			,snake_case     :							Tuple=3			,snake_case     :							Dict=10			,snake_case     :							List[Any]=[10, 20, 30, 40]			,snake_case     :							List[Any]=[1, 1, 2, 1]			,snake_case     :							Any=True			,snake_case     :							Dict=True			,snake_case     :							Any="relu"			,snake_case     :							Union[str, Any]=3			,snake_case     :							List[str]=None			,):
           SCREAMING_SNAKE_CASE      						=parent
           SCREAMING_SNAKE_CASE      						=batch_size
           SCREAMING_SNAKE_CASE      						=image_size
           SCREAMING_SNAKE_CASE      						=num_channels
           SCREAMING_SNAKE_CASE      						=embeddings_size
           SCREAMING_SNAKE_CASE      						=hidden_sizes
           SCREAMING_SNAKE_CASE      						=depths
           SCREAMING_SNAKE_CASE      						=is_training
           SCREAMING_SNAKE_CASE      						=use_labels
           SCREAMING_SNAKE_CASE      						=hidden_act
           SCREAMING_SNAKE_CASE      						=num_labels
           SCREAMING_SNAKE_CASE      						=scope
           SCREAMING_SNAKE_CASE      						=len(__snake_case				)
      def        _lowerCAmelCase     (      self     :							Union[str, Any]				):
           SCREAMING_SNAKE_CASE      						=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

           SCREAMING_SNAKE_CASE      						=self.get_config()

           return config, pixel_values, labels
      def        _lowerCAmelCase     (      self     :							int				):
           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        _lowerCAmelCase     (      self     :							Optional[int]			,snake_case     :							Union[str, Any]			,snake_case     :							List[Any]			,snake_case     :							List[Any]				):
           SCREAMING_SNAKE_CASE      						=TFResNetModel(config=__snake_case				)
           SCREAMING_SNAKE_CASE      						=model(__snake_case				)
           # 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        _lowerCAmelCase     (      self     :							List[str]			,snake_case     :							Optional[int]			,snake_case     :							Union[str, Any]			,snake_case     :							str				):
           SCREAMING_SNAKE_CASE      						=self.num_labels
           SCREAMING_SNAKE_CASE      						=TFResNetForImageClassification(__snake_case				)
           SCREAMING_SNAKE_CASE      						=model(__snake_case			,labels=__snake_case				)
           self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_labels)				)


      def        _lowerCAmelCase     (      self     :							str				):
           SCREAMING_SNAKE_CASE      						=self.prepare_config_and_inputs()
           SCREAMING_SNAKE_CASE      						=config_and_inputs
           SCREAMING_SNAKE_CASE      						={'''pixel_values''': pixel_values}
           return config, inputs_dict







@require_tf
class 		a_       (							A__ ,			A__ ,			unittest.TestCase     ):



      """simple docstring"""







      __UpperCAmelCase					=      (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
      __UpperCAmelCase					=      (
          {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
          if is_tf_available()
          else {}
      )

      __UpperCAmelCase					=      False
      __UpperCAmelCase					=      False
      __UpperCAmelCase					=      False
      __UpperCAmelCase					=      False
      __UpperCAmelCase					=      False
      def        _lowerCAmelCase     (      self     :							Any				):
           SCREAMING_SNAKE_CASE      						=TFResNetModelTester(self				)
           SCREAMING_SNAKE_CASE      						=ConfigTester(self			,config_class=__snake_case			,has_text_modality=__snake_case				)
      def        _lowerCAmelCase     (      self     :							List[str]				):
           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        _lowerCAmelCase     (      self     :							Dict				):
           return
      @unittest.skip(reason='ResNet does not use inputs_embeds'				)
      def        _lowerCAmelCase     (      self     :							str				):
           pass
      @unittest.skip(reason='ResNet does not support input and output embeddings'				)
      def        _lowerCAmelCase     (      self     :							Dict				):
           pass
      def        _lowerCAmelCase     (      self     :							Optional[int]				):
           SCREAMING_SNAKE_CASE      						=self.model_tester.prepare_config_and_inputs_for_common()

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

                SCREAMING_SNAKE_CASE      						=['''pixel_values''']
                self.assertListEqual(arg_names[:1]			,__snake_case				)
      def        _lowerCAmelCase     (      self     :							Any				):
           SCREAMING_SNAKE_CASE      						=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__snake_case				)
      def        _lowerCAmelCase     (      self     :							Dict				):
           def check_hidden_states_output(snake_case     :							int			,snake_case     :							List[Any]			,snake_case     :							Optional[int]				):
                SCREAMING_SNAKE_CASE      						=model_class(__snake_case				)
                SCREAMING_SNAKE_CASE      						=model(**self._prepare_for_class(__snake_case			,__snake_case				)				)

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

                SCREAMING_SNAKE_CASE      						=self.model_tester.num_stages
                self.assertEqual(len(__snake_case				)			,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]			,)

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

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

                     check_hidden_states_output(__snake_case			,__snake_case			,__snake_case				)
      def        _lowerCAmelCase     (      self     :							Tuple				):
           SCREAMING_SNAKE_CASE      						=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__snake_case				)


      @slow
      def        _lowerCAmelCase     (      self     :							str				):
           for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                SCREAMING_SNAKE_CASE      						=TFResNetModel.from_pretrained(__snake_case				)
                self.assertIsNotNone(__snake_case				)







def 			snake_case__				(   ):





     """simple docstring"""







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



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



      """simple docstring"""







      @cached_property
      def        _lowerCAmelCase     (      self     :							str				):
           return (
               AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
               if is_vision_available()
               else None
           )


      @slow
      def        _lowerCAmelCase     (      self     :							Dict				):
           SCREAMING_SNAKE_CASE      						=TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

           SCREAMING_SNAKE_CASE      						=self.default_image_processor
           SCREAMING_SNAKE_CASE      						=prepare_img()
           SCREAMING_SNAKE_CASE      						=image_processor(images=__snake_case			,return_tensors='tf'				)

           # forward pass
           SCREAMING_SNAKE_CASE      						=model(**__snake_case				)

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

           SCREAMING_SNAKE_CASE      						=tf.constant([-11.1_069, -9.7_877, -8.3_777]				)

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






'''simple docstring'''






from manim import *

class 				SCREAMING_SNAKE_CASE(							A__			):







	"""simple docstring"""






	def      A	(						self			:     Union[str, Any]		)			->		List[str]:
								UpperCAmelCase :       Optional[Any] 							=		Rectangle(height=0.5		,			width=0.5		)
								UpperCAmelCase :       str 							=		Rectangle(height=0.46		,			width=0.46		).set_stroke(width=0		)

								UpperCAmelCase :       Tuple 							=		[mem.copy() for i in range(6		)]
								UpperCAmelCase :       Optional[int] 							=		[mem.copy() for i in range(6		)]
								UpperCAmelCase :       Dict 							=		VGroup(*__snake_case		).arrange(__snake_case		,			buff=0		)
								UpperCAmelCase :       Any 							=		VGroup(*__snake_case		).arrange(__snake_case		,			buff=0		)
								UpperCAmelCase :       Union[str, Any] 							=		VGroup(__snake_case		,			__snake_case		).arrange(__snake_case		,			buff=0		)
								UpperCAmelCase :       Optional[Any] 							=		Text('''CPU'''		,			font_size=24		)
								UpperCAmelCase :       Union[str, Any] 							=		Group(__snake_case		,			__snake_case		).arrange(__snake_case		,			buff=0.5		,			aligned_edge=__snake_case		)
								cpu.move_to([-2.5, -0.5, 0]		)
								self.add(__snake_case		)

								UpperCAmelCase :       Optional[Any] 							=		[mem.copy() for i in range(4		)]
								UpperCAmelCase :       Union[str, Any] 							=		VGroup(*__snake_case		).arrange(__snake_case		,			buff=0		)
								UpperCAmelCase :       List[str] 							=		Text('''GPU'''		,			font_size=24		)
								UpperCAmelCase :       Dict 							=		Group(__snake_case		,			__snake_case		).arrange(__snake_case		,			buff=0.5		,			aligned_edge=__snake_case		)
								gpu.move_to([-1, -1, 0]		)
								self.add(__snake_case		)

								UpperCAmelCase :       int 							=		[mem.copy() for i in range(6		)]
								UpperCAmelCase :       Union[str, Any] 							=		VGroup(*__snake_case		).arrange(__snake_case		,			buff=0		)

								UpperCAmelCase :       List[str] 							=		Text('''Model'''		,			font_size=24		)
								UpperCAmelCase :       Tuple 							=		Group(__snake_case		,			__snake_case		).arrange(__snake_case		,			buff=0.5		,			aligned_edge=__snake_case		)
								model.move_to([3, -1.0, 0]		)
								self.add(__snake_case		)

								UpperCAmelCase :       Any 							=		[]
								for i, rect in enumerate(__snake_case		):
															rect.set_stroke(__snake_case		)
															# target = fill.copy().set_fill(YELLOW, opacity=0.7)
															# target.move_to(rect)
															# self.add(target)

															UpperCAmelCase :       Dict 							=		Rectangle(height=0.46 / 4		,			width=0.46 / 3		).set_stroke(width=0.0		).set_fill(__snake_case		,			opacity=0.7		)

															if i == 0:
																						cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT		)		,			buff=0.02		,			direction=__snake_case		)
																						cpu_target.set_x(cpu_target.get_x() + 0.1		)
															elif i == 3:
																						cpu_target.next_to(cpu_targs[0]		,			direction=__snake_case		,			buff=0.0		)
															else:
																						cpu_target.next_to(cpu_targs[i - 1]		,			direction=__snake_case		,			buff=0.0		)
															self.add(__snake_case		)
															cpu_targs.append(__snake_case		)

								UpperCAmelCase :       int 							=		[mem.copy() for i in range(6		)]
								UpperCAmelCase :       int 							=		VGroup(*__snake_case		).arrange(__snake_case		,			buff=0		)

								UpperCAmelCase :       Any 							=		Text('''Loaded Checkpoint'''		,			font_size=24		)
								UpperCAmelCase :       Union[str, Any] 							=		Group(__snake_case		,			__snake_case		).arrange(__snake_case		,			aligned_edge=__snake_case		,			buff=0.4		)
								checkpoint.move_to([3, 0.5, 0]		)

								UpperCAmelCase :       Optional[int] 							=		Square(side_length=2.2		)
								key.move_to([-5, 2, 0]		)

								UpperCAmelCase :       str 							=		MarkupText(
								    F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model"""		,			font_size=18		,			)

								key_text.move_to([-5, 2.4, 0]		)

								self.add(__snake_case		,			__snake_case		)

								UpperCAmelCase :       Tuple 							=		MarkupText(
								    F"""<span fgcolor='{BLUE}'>●</span> Checkpoint"""		,			font_size=18		,			)

								blue_text.next_to(__snake_case		,			DOWN * 2.4		,			aligned_edge=key_text.get_left()		)

								UpperCAmelCase :       List[Any] 							=		MarkupText(
								    F"""Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>."""		,			font_size=24		,			)
								step_a.move_to([2, 2, 0]		)
								self.play(Write(__snake_case		)		,			Write(__snake_case		)		)

								self.play(Write(__snake_case		,			run_time=1		)		,			Create(__snake_case		,			run_time=1		)		)

								UpperCAmelCase :       Tuple 							=		[]
								UpperCAmelCase :       int 							=		[]
								for i, rect in enumerate(__snake_case		):
															UpperCAmelCase :       Any 							=		fill.copy().set_fill(__snake_case		,			opacity=0.7		)
															target.move_to(__snake_case		)
															first_animations.append(GrowFromCenter(__snake_case		,			run_time=1		)		)

															UpperCAmelCase :       List[str] 							=		target.copy()
															cpu_target.generate_target()
															if i < 5:
																						cpu_target.target.move_to(cpu_left_col_base[i + 1]		)
															else:
																						cpu_target.target.move_to(cpu_right_col_base[i - 5]		)
															second_animations.append(MoveToTarget(__snake_case		,			run_time=1.5		)		)

								self.play(*__snake_case		)
								self.play(*__snake_case		)
								self.wait()





