
'''simple docstring'''





import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
 from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor


class 	UpperCamelCase__					:






 def __init__(     self					:Optional[int]		,			_A					:Union[str, Any]		,			_A					:List[Any]=3		,			_A					:Optional[Any]=32		,			_A					:Any=3		,			_A					:str=10		,			_A					:List[str]=[10, 20, 30, 40]		,			_A					:Any=[1, 1, 2, 1]		,			_A					:Optional[Any]=True		,			_A					:Union[str, Any]=True		,			_A					:str="relu"		,			_A					:str=3		,			_A					:Optional[Any]=None		,			_A					:str=["stage2", "stage3", "stage4"]		,			_A					:List[str]=[2, 3, 4]		,			)			->     List[Any]:







       '''simple docstring'''



       __A    		=     parent
       __A    		=     batch_size
       __A    		=     image_size
       __A    		=     num_channels
       __A    		=     embeddings_size
       __A    		=     hidden_sizes
       __A    		=     depths
       __A    		=     is_training
       __A    		=     use_labels
       __A    		=     hidden_act
       __A    		=     num_labels
       __A    		=     scope
       __A    		=     len(_A     )
       __A    		=     out_features
       __A    		=     out_indices






 def 		lowercase_  (     self					:List[str]     )			->     int:







       '''simple docstring'''



       __A    		=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

       __A    		=     self.get_config()

       return config, pixel_values, labels






 def 		lowercase_  (     self					:Optional[int]     )			->     Optional[int]:







       '''simple docstring'''



       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		,			out_features=self.out_features		,			out_indices=self.out_indices		,			)






 def 		lowercase_  (     self					:Tuple		,			_A					:str		,			_A					:Dict		,			_A					:Tuple     )			->     Any:







       '''simple docstring'''



       __A    		=     ResNetModel(config=_A     )
       model.to(_A     )
       model.eval()
       __A    		=     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 		lowercase_  (     self					:Optional[int]		,			_A					:Union[str, Any]		,			_A					:Tuple		,			_A					:Any     )			->     Dict:







       '''simple docstring'''



       __A    		=     self.num_labels
       __A    		=     ResNetForImageClassification(_A     )
       model.to(_A     )
       model.eval()
       __A    		=     model(_A		,			labels=_A     )
       self.parent.assertEqual(result.logits.shape		,			(self.batch_size, self.num_labels)     )






 def 		lowercase_  (     self					:Any		,			_A					:Dict		,			_A					:Tuple		,			_A					:List[Any]     )			->     List[str]:







       '''simple docstring'''



       __A    		=     ResNetBackbone(config=_A     )
       model.to(_A     )
       model.eval()
       __A    		=     model(_A     )

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps     )		,			len(config.out_features     )     )
       self.parent.assertListEqual(list(result.feature_maps[0].shape     )		,			[self.batch_size, self.hidden_sizes[1], 4, 4]     )

       # verify channels
       self.parent.assertEqual(len(model.channels     )		,			len(config.out_features     )     )
       self.parent.assertListEqual(model.channels		,			config.hidden_sizes[1:]     )

       # verify backbone works with out_features=None
       __A    		=     None
       __A    		=     ResNetBackbone(config=_A     )
       model.to(_A     )
       model.eval()
       __A    		=     model(_A     )

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps     )		,			1     )
       self.parent.assertListEqual(list(result.feature_maps[0].shape     )		,			[self.batch_size, self.hidden_sizes[-1], 1, 1]     )

       # verify channels
       self.parent.assertEqual(len(model.channels     )		,			1     )
       self.parent.assertListEqual(model.channels		,			[config.hidden_sizes[-1]]     )






 def 		lowercase_  (     self					:Any     )			->     Tuple:







       '''simple docstring'''



       __A    		=     self.prepare_config_and_inputs()
       __A		, __A		, __A    		=     config_and_inputs
       __A    		=     {'pixel_values': pixel_values}
       return config, inputs_dict


@require_torch
class 	UpperCamelCase__					(      SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE ,       unittest.TestCase):
 UpperCAmelCase__      :      Any  			=   (
     (
         ResNetModel,
         ResNetForImageClassification,
         ResNetBackbone,
     )
     if is_torch_available()
     else ()
 )
 UpperCAmelCase__      :      Union[str, Any]  			=   (
     {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
     if is_torch_available()
     else {}
 )

 UpperCAmelCase__      :      Optional[int]  			=   True
 UpperCAmelCase__      :      Any  			=   False
 UpperCAmelCase__      :      List[str]  			=   False
 UpperCAmelCase__      :      str  			=   False
 UpperCAmelCase__      :      Optional[int]  			=   False






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







       '''simple docstring'''



       __A    		=     ResNetModelTester(self     )
       __A    		=     ConfigTester(self		,			config_class=_A		,			has_text_modality=_A     )






 def 		lowercase_  (     self					:List[Any]     )			->     Optional[int]:







       '''simple docstring'''



       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 		lowercase_  (     self					:Optional[Any]     )			->     Union[str, Any]:







       '''simple docstring'''



       return






 @unittest.skip(reason='ResNet does not use inputs_embeds'     )
 def 		lowercase_  (     self					:Union[str, Any]     )			->     Dict:







       '''simple docstring'''



       pass






 @unittest.skip(reason='ResNet does not support input and output embeddings'     )
 def 		lowercase_  (     self					:Union[str, Any]     )			->     Optional[int]:







       '''simple docstring'''



       pass






 def 		lowercase_  (     self					:str     )			->     str:







       '''simple docstring'''



       __A		, __A    		=     self.model_tester.prepare_config_and_inputs_for_common()

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

             __A    		=     ['pixel_values']
             self.assertListEqual(arg_names[:1]		,			_A     )






 def 		lowercase_  (     self					:Optional[int]     )			->     List[str]:







       '''simple docstring'''



       __A    		=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_A     )






 def 		lowercase_  (     self					:int     )			->     Any:







       '''simple docstring'''



       __A    		=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*_A     )






 def 		lowercase_  (     self					:Optional[int]     )			->     Any:







       '''simple docstring'''



       __A		, __A    		=     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             __A    		=     model_class(config=_A     )
             for name, module in model.named_modules():
                   if isinstance(_A		,			(nn.BatchNormad, nn.GroupNorm)     ):
                         self.assertTrue(
                             torch.all(module.weight == 1     )		,			msg=F'Parameter {name} of model {model_class} seems not properly initialized'		,			)
                         self.assertTrue(
                             torch.all(module.bias == 0     )		,			msg=F'Parameter {name} of model {model_class} seems not properly initialized'		,			)






 def 		lowercase_  (     self					:List[Any]     )			->     int:







       '''simple docstring'''



       def check_hidden_states_output(_A					:List[str]		,			_A					:Dict		,			_A					:List[str]     ):
             __A    		=     model_class(_A     )
             model.to(_A     )
             model.eval()

             with torch.no_grad():
                   __A    		=     model(**self._prepare_for_class(_A		,			_A     )     )

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

             __A    		=     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]		,			)

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

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

                   check_hidden_states_output(_A		,			_A		,			_A     )






 @unittest.skip(reason='ResNet does not use feedforward chunking'     )
 def 		lowercase_  (     self					:Dict     )			->     Dict:







       '''simple docstring'''



       pass






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







       '''simple docstring'''



       __A    		=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_A     )






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







       '''simple docstring'''



       for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __A    		=     ResNetModel.from_pretrained(_A     )
             self.assertIsNotNone(_A     )





def     snake_case							(						)->     Optional[int]:







      """simple docstring"""
      __A    		=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
      return image


@require_torch
@require_vision
class 	UpperCamelCase__					(      unittest.TestCase):






 @cached_property
 def 		lowercase_  (     self					:Any     )			->     Optional[int]:







       '''simple docstring'''



       return (
           AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
           if is_vision_available()
           else None
       )






 @slow
 def 		lowercase_  (     self					:Optional[int]     )			->     Any:







       '''simple docstring'''



       __A    		=     ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     ).to(_A     )

       __A    		=     self.default_image_processor
       __A    		=     prepare_img()
       __A    		=     image_processor(images=_A		,			return_tensors='pt'     ).to(_A     )

       # forward pass
       with torch.no_grad():
             __A    		=     model(**_A     )

       # verify the logits
       __A    		=     torch.Size((1, 1_000)     )
       self.assertEqual(outputs.logits.shape		,			_A     )

       __A    		=     torch.tensor([-11.1_069, -9.7_877, -8.3_777]     ).to(_A     )

       self.assertTrue(torch.allclose(outputs.logits[0, :3]		,			_A		,			atol=1E-4     )     )


@require_torch
class 	UpperCamelCase__					(      SCREAMING_SNAKE_CASE ,       unittest.TestCase):
 UpperCAmelCase__      :      Optional[Any]  			=   (ResNetBackbone,) if is_torch_available() else ()
 UpperCAmelCase__      :      List[str]  			=   False
 UpperCAmelCase__      :      Tuple  			=   ResNetConfig






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







       '''simple docstring'''



       __A    		=     ResNetModelTester(self     )








'''simple docstring'''





import unittest

import torch

from diffusers import DDIMScheduler, TextToVideoZeroPipeline
from diffusers.utils import load_pt, require_torch_gpu, slow

from ..test_pipelines_common import assert_mean_pixel_difference


@slow
@require_torch_gpu
class 	UpperCamelCase__					(      unittest.TestCase):






 def 		lowercase_  (     self					:Optional[int]     )			->     List[Any]:







       '''simple docstring'''



       __A    		=     'runwayml/stable-diffusion-v1-5'
       __A    		=     TextToVideoZeroPipeline.from_pretrained(_A		,			torch_dtype=torch.floataa     ).to('cuda'     )
       __A    		=     DDIMScheduler.from_config(pipe.scheduler.config     )
       __A    		=     torch.Generator(device='cuda'     ).manual_seed(0     )

       __A    		=     'A bear is playing a guitar on Times Square'
       __A    		=     pipe(prompt=_A		,			generator=_A     ).images

       __A    		=     load_pt(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text-to-video/A bear is playing a guitar on Times Square.pt'     )

       assert_mean_pixel_difference(_A		,			_A     )






