





"""simple docstring"""





import inspect
import unittest

from transformers import ConvNextConfig
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 transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
  from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor






class 					_lowerCAmelCase   :
       """simple docstring"""




       def __init__(    self    , __UpperCAmelCase    , __UpperCAmelCase=1_3    , __UpperCAmelCase=3_2    , __UpperCAmelCase=3    , __UpperCAmelCase=4    , __UpperCAmelCase=[1_0, 2_0, 3_0, 4_0]    , __UpperCAmelCase=[2, 2, 3, 2]    , __UpperCAmelCase=True    , __UpperCAmelCase=True    , __UpperCAmelCase=3_7    , __UpperCAmelCase="gelu"    , __UpperCAmelCase=1_0    , __UpperCAmelCase=0.02    , __UpperCAmelCase=["stage2", "stage3", "stage4"]    , __UpperCAmelCase=[2, 3, 4]    , __UpperCAmelCase=None    , ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[int]											=							parent
         lowerCAmelCase__			:Any											=							batch_size
         lowerCAmelCase__			:List[Any]											=							image_size
         lowerCAmelCase__			:Optional[Any]											=							num_channels
         lowerCAmelCase__			:List[Any]											=							num_stages
         lowerCAmelCase__			:int											=							hidden_sizes
         lowerCAmelCase__			:Any											=							depths
         lowerCAmelCase__			:Any											=							is_training
         lowerCAmelCase__			:List[Any]											=							use_labels
         lowerCAmelCase__			:Optional[int]											=							intermediate_size
         lowerCAmelCase__			:Tuple											=							hidden_act
         lowerCAmelCase__			:Dict											=							num_labels
         lowerCAmelCase__			:Dict											=							initializer_range
         lowerCAmelCase__			:List[Any]											=							out_features
         lowerCAmelCase__			:Union[str, Any]											=							out_indices
         lowerCAmelCase__			:Dict											=							scope






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[int]											=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

         lowerCAmelCase__			:List[Any]											=							None
         if self.use_labels:
           lowerCAmelCase__			:Optional[Any]											=							ids_tensor([self.batch_size]    , self.num_labels      )

         lowerCAmelCase__			:str											=							self.get_config()
         return config, pixel_values, labels






       def      snake_case						(    self      ):



         '''simple docstring'''

         return ConvNextConfig(
             num_channels=self.num_channels    , hidden_sizes=self.hidden_sizes    , depths=self.depths    , num_stages=self.num_stages    , hidden_act=self.hidden_act    , is_decoder=_SCREAMING_SNAKE_CASE    , initializer_range=self.initializer_range    , out_features=self.out_features    , out_indices=self.out_indices    , num_labels=self.num_labels    , )






       def      snake_case						(    self    , __UpperCAmelCase    , __UpperCAmelCase    , __UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[int]											=							ConvNextModel(config=_SCREAMING_SNAKE_CASE      )
         model.to(_SCREAMING_SNAKE_CASE      )
         model.eval()
         lowerCAmelCase__			:Dict											=							model(_SCREAMING_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 // 3_2, self.image_size // 3_2)    , )






       def      snake_case						(    self    , __UpperCAmelCase    , __UpperCAmelCase    , __UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:Any											=							ConvNextForImageClassification(_SCREAMING_SNAKE_CASE      )
         model.to(_SCREAMING_SNAKE_CASE      )
         model.eval()
         lowerCAmelCase__			:Tuple											=							model(_SCREAMING_SNAKE_CASE    , labels=_SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.num_labels)      )






       def      snake_case						(    self    , __UpperCAmelCase    , __UpperCAmelCase    , __UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:int											=							ConvNextBackbone(config=_SCREAMING_SNAKE_CASE      )
         model.to(_SCREAMING_SNAKE_CASE      )
         model.eval()
         lowerCAmelCase__			:Optional[int]											=							model(_SCREAMING_SNAKE_CASE      )

         # verify hidden states
         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
         lowerCAmelCase__			:Union[str, Any]											=							None
         lowerCAmelCase__			:List[Any]											=							ConvNextBackbone(config=_SCREAMING_SNAKE_CASE      )
         model.to(_SCREAMING_SNAKE_CASE      )
         model.eval()
         lowerCAmelCase__			:Union[str, Any]											=							model(_SCREAMING_SNAKE_CASE      )

         # 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      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[Any]											=							self.prepare_config_and_inputs()
         lowerCAmelCase__			:Tuple											=							config_and_inputs
         lowerCAmelCase__			:Union[str, Any]											=							{'''pixel_values''': pixel_values}
         return config, inputs_dict






@require_torch
class 					_lowerCAmelCase   (     a  ,   a  ,   unittest.TestCase       ):
       """simple docstring"""




       __magic_name__     :Tuple		  =					(
           (
               ConvNextModel,
               ConvNextForImageClassification,
               ConvNextBackbone,
           )
           if is_torch_available()
           else ()
       )
       __magic_name__     :Optional[int]		  =					(
           {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
           if is_torch_available()
           else {}
       )

       __magic_name__     :str		  =					True
       __magic_name__     :Union[str, Any]		  =					False
       __magic_name__     :Optional[int]		  =					False
       __magic_name__     :Dict		  =					False
       __magic_name__     :List[str]		  =					False






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[Any]											=							ConvNextModelTester(self      )
         lowerCAmelCase__			:List[str]											=							ConfigTester(self    , config_class=_SCREAMING_SNAKE_CASE    , has_text_modality=_SCREAMING_SNAKE_CASE    , hidden_size=3_7      )






       def      snake_case						(    self      ):



         '''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      snake_case						(    self      ):



         '''simple docstring'''

         return






       @unittest.skip(reason='ConvNext does not use inputs_embeds'      )
       def      snake_case						(    self      ):



         '''simple docstring'''

         pass






       @unittest.skip(reason='ConvNext does not support input and output embeddings'      )
       def      snake_case						(    self      ):



         '''simple docstring'''

         pass






       @unittest.skip(reason='ConvNext does not use feedforward chunking'      )
       def      snake_case						(    self      ):



         '''simple docstring'''

         pass






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Tuple											=							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           lowerCAmelCase__			:Optional[int]											=							model_class(_SCREAMING_SNAKE_CASE      )
           lowerCAmelCase__			:Dict											=							inspect.signature(model.forward      )
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           lowerCAmelCase__			:List[Any]											=							[*signature.parameters.keys()]

           lowerCAmelCase__			:Any											=							['''pixel_values''']
           self.assertListEqual(arg_names[:1]    , _SCREAMING_SNAKE_CASE      )






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[int]											=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE      )






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Union[str, Any]											=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE      )






       def      snake_case						(    self      ):



         '''simple docstring'''

         def check_hidden_states_output(__UpperCAmelCase    , __UpperCAmelCase    , __UpperCAmelCase      ):
           lowerCAmelCase__			:List[Any]											=							model_class(_SCREAMING_SNAKE_CASE      )
           model.to(_SCREAMING_SNAKE_CASE      )
           model.eval()

           with torch.no_grad():
             lowerCAmelCase__			:Tuple											=							model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE    , _SCREAMING_SNAKE_CASE      )      )

           lowerCAmelCase__			:int											=							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           lowerCAmelCase__			:List[Any]											=							self.model_tester.num_stages
           self.assertEqual(len(_SCREAMING_SNAKE_CASE      )    , expected_num_stages + 1      )

           # ConvNext'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]    , )

         lowerCAmelCase__			:int											=							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           lowerCAmelCase__			:Union[str, Any]											=							True
           check_hidden_states_output(_SCREAMING_SNAKE_CASE    , _SCREAMING_SNAKE_CASE    , _SCREAMING_SNAKE_CASE      )

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           lowerCAmelCase__			:Dict											=							True

           check_hidden_states_output(_SCREAMING_SNAKE_CASE    , _SCREAMING_SNAKE_CASE    , _SCREAMING_SNAKE_CASE      )






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Union[str, Any]											=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE      )






       @slow
       def      snake_case						(    self      ):



         '''simple docstring'''

         for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowerCAmelCase__			:List[Any]											=							ConvNextModel.from_pretrained(_SCREAMING_SNAKE_CASE      )
           self.assertIsNotNone(_SCREAMING_SNAKE_CASE      )






def  __A   ()					->Union[str, Any]:





  """simple docstring"""


  lowerCAmelCase__			:Union[str, Any]											=							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
  return image






@require_torch
@require_vision
class 					_lowerCAmelCase   (     unittest.TestCase       ):
       """simple docstring"""




       @cached_property
       def      snake_case						(    self      ):



         '''simple docstring'''

         return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'      ) if is_vision_available() else None






       @slow
       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Union[str, Any]											=							ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'      ).to(_SCREAMING_SNAKE_CASE      )

         lowerCAmelCase__			:Union[str, Any]											=							self.default_image_processor
         lowerCAmelCase__			:Union[str, Any]											=							prepare_img()
         lowerCAmelCase__			:Any											=							image_processor(images=_SCREAMING_SNAKE_CASE    , return_tensors='pt'      ).to(_SCREAMING_SNAKE_CASE      )

         # forward pass
         with torch.no_grad():
           lowerCAmelCase__			:int											=							model(**_SCREAMING_SNAKE_CASE      )

         # verify the logits
         lowerCAmelCase__			:Union[str, Any]											=							torch.Size((1, 1_0_0_0)      )
         self.assertEqual(outputs.logits.shape    , _SCREAMING_SNAKE_CASE      )

         lowerCAmelCase__			:int											=							torch.tensor([-0.02_60, -0.47_39, 0.19_11]      ).to(_SCREAMING_SNAKE_CASE      )

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






@require_torch
class 					_lowerCAmelCase   (     unittest.TestCase  ,   a       ):
       """simple docstring"""




       __magic_name__     :Union[str, Any]		  =					(ConvNextBackbone,) if is_torch_available() else ()
       __magic_name__     :Optional[int]		  =					ConvNextConfig

       __magic_name__     :Optional[int]		  =					False






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:List[Any]											=							ConvNextModelTester(self      )




import unittest

import numpy as np
import torch

from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class   _lowerCamelCase (					UpperCamelCase					,							unittest.TestCase			):




       """simple docstring"""
       snake_case      =    DDIMPipeline
       snake_case      =    UNCONDITIONAL_IMAGE_GENERATION_PARAMS
       snake_case      =    PipelineTesterMixin.required_optional_params - {
           "num_images_per_prompt",
           "latents",
           "callback",
           "callback_steps",
       }
       snake_case      =    UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
       snake_case      =    False



       def        _snake_case       (      self		)->List[str]:




         '''simple docstring'''





         torch.manual_seed(0		)
         A_      :				List[str]		     =					UNetaDModel(
             block_out_channels=(32, 64)				,       layers_per_block=2				,       sample_size=32				,       in_channels=3				,       out_channels=3				,       down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')				,       up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')				,       )
         A_      :				Optional[Any]		     =					DDIMScheduler()
         A_      :				str		     =					{'''unet''': unet, '''scheduler''': scheduler}
         return components



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE=0		)->Optional[Any]:




         '''simple docstring'''





         if str(_SCREAMING_SNAKE_CASE		).startswith('''mps'''		):
           A_      :				Any		     =					torch.manual_seed(_SCREAMING_SNAKE_CASE		)
         else:
           A_      :				Optional[int]		     =					torch.Generator(device=_SCREAMING_SNAKE_CASE		).manual_seed(_SCREAMING_SNAKE_CASE		)
         A_      :				Any		     =					{
             '''batch_size''': 1,
             '''generator''': generator,
             '''num_inference_steps''': 2,
             '''output_type''': '''numpy''',
         }
         return inputs



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




         '''simple docstring'''





         A_      :				Optional[int]		     =					'''cpu'''

         A_      :				Dict		     =					self.get_dummy_components()
         A_      :				str		     =					self.pipeline_class(**_SCREAMING_SNAKE_CASE		)
         pipe.to(_SCREAMING_SNAKE_CASE		)
         pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

         A_      :				str		     =					self.get_dummy_inputs(_SCREAMING_SNAKE_CASE		)
         A_      :				Any		     =					pipe(**_SCREAMING_SNAKE_CASE		).images
         A_      :				int		     =					image[0, -3:, -3:, -1]

         self.assertEqual(image.shape				,       (1, 32, 32, 3)		)
         A_      :				List[Any]		     =					np.array(
             [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04]		)
         A_      :				str		     =					np.abs(image_slice.flatten() - expected_slice		).max()
         self.assertLessEqual(_SCREAMING_SNAKE_CASE				,       1e-3		)



       def        _snake_case       (      self		)->Union[str, Any]:




         '''simple docstring'''





         super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3		)



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




         '''simple docstring'''





         super().test_save_load_local(expected_max_difference=3e-3		)



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




         '''simple docstring'''





         super().test_save_load_optional_components(expected_max_difference=3e-3		)







       def        _snake_case       (      self		)->Any:




         '''simple docstring'''





         super().test_inference_batch_single_identical(expected_max_diff=3e-3		)






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




       """simple docstring"""



       def        _snake_case       (      self		)->Union[str, Any]:




         '''simple docstring'''





         A_      :				int		     =					'''google/ddpm-cifar10-32'''

         A_      :				Tuple		     =					UNetaDModel.from_pretrained(_SCREAMING_SNAKE_CASE		)
         A_      :				str		     =					DDIMScheduler()

         A_      :				str		     =					DDIMPipeline(unet=_SCREAMING_SNAKE_CASE				,       scheduler=_SCREAMING_SNAKE_CASE		)
         ddim.to(_SCREAMING_SNAKE_CASE		)
         ddim.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

         A_      :				Optional[int]		     =					torch.manual_seed(0		)
         A_      :				Any		     =					ddim(generator=_SCREAMING_SNAKE_CASE				,       eta=0.0				,       output_type='''numpy'''		).images

         A_      :				Any		     =					image[0, -3:, -3:, -1]

         assert image.shape == (1, 32, 32, 3)
         A_      :				Any		     =					np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3]		)

         assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-2







       def        _snake_case       (      self		)->List[str]:




         '''simple docstring'''





         A_      :				Tuple		     =					'''google/ddpm-ema-bedroom-256'''

         A_      :				int		     =					UNetaDModel.from_pretrained(_SCREAMING_SNAKE_CASE		)
         A_      :				Any		     =					DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE		)

         A_      :				Optional[Any]		     =					DDIMPipeline(unet=_SCREAMING_SNAKE_CASE				,       scheduler=_SCREAMING_SNAKE_CASE		)
         ddpm.to(_SCREAMING_SNAKE_CASE		)
         ddpm.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

         A_      :				Dict		     =					torch.manual_seed(0		)
         A_      :				List[str]		     =					ddpm(generator=_SCREAMING_SNAKE_CASE				,       output_type='''numpy'''		).images

         A_      :				Any		     =					image[0, -3:, -3:, -1]

         assert image.shape == (1, 256, 256, 3)
         A_      :				Tuple		     =					np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9]		)

         assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-2




