






'''simple docstring'''

from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor




class      A     :






 """simple docstring"""





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

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

       UpperCamelCase_					: int            =				self.get_config()
       return config, pixel_values, labels
 def 	_UpperCAmelCase							(				self			):
       return RegNetConfig(
           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      ,  )
 def 	_UpperCAmelCase							(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			):
       UpperCamelCase_					: Optional[int]            =				TFRegNetModel(config=__lowerCAmelCase			)
       UpperCamelCase_					: Optional[Any]            =				model(__lowerCAmelCase      ,  training=__lowerCAmelCase			)
       # 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      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			):
       UpperCamelCase_					: Optional[Any]            =				self.num_labels
       UpperCamelCase_					: Any            =				TFRegNetForImageClassification(__lowerCAmelCase			)
       UpperCamelCase_					: str            =				model(__lowerCAmelCase      ,  labels=__lowerCAmelCase      ,  training=__lowerCAmelCase			)
       self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.num_labels)			)





 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: str            =				self.prepare_config_and_inputs()
       UpperCamelCase_     ,      UpperCamelCase_     ,      UpperCamelCase_					: Any            =				config_and_inputs
       UpperCamelCase_					: List[str]            =				{"""pixel_values""": pixel_values}
       return config, inputs_dict






@require_tf
class      A     (   SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, unittest.TestCase    ):






 """simple docstring"""





 __a      :    Dict			  =    (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
 __a      :    Optional[int]			  =    (
     {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
     if is_tf_available()
     else {}
 )

 __a      :    str			  =    False
 __a      :    str			  =    False
 __a      :    int			  =    False
 __a      :    str			  =    False
 __a      :    Tuple			  =    False
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: Union[str, Any]            =				TFRegNetModelTester(self			)
       UpperCamelCase_					: Optional[Any]            =				ConfigTester(self      ,  config_class=__lowerCAmelCase      ,  has_text_modality=__lowerCAmelCase			)
 def 	_UpperCAmelCase							(				self			):
       return
 @unittest.skip(reason="""RegNet does not use inputs_embeds"""			)
 def 	_UpperCAmelCase							(				self			):
       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."""      ,  )
 @slow
 def 	_UpperCAmelCase							(				self			):
       super().test_keras_fit()
 @unittest.skip(reason="""RegNet does not support input and output embeddings"""			)
 def 	_UpperCAmelCase							(				self			):
       pass
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_     ,      UpperCamelCase_					: int            =				self.model_tester.prepare_config_and_inputs_for_common()

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

             UpperCamelCase_					: str            =				["""pixel_values"""]
             self.assertListEqual(arg_names[:1]      ,  __lowerCAmelCase			)
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: List[Any]            =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCAmelCase			)
 def 	_UpperCAmelCase							(				self			):
       def check_hidden_states_output(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			):
             UpperCamelCase_					: List[Any]            =				model_class(__lowerCAmelCase			)
             UpperCamelCase_					: str            =				model(**self._prepare_for_class(__lowerCAmelCase      ,  __lowerCAmelCase			)      ,  training=__lowerCAmelCase			)

             UpperCamelCase_					: List[str]            =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             UpperCamelCase_					: Any            =				self.model_tester.num_stages
             self.assertEqual(len(__lowerCAmelCase			)      ,  expected_num_stages + 1			)

             # RegNet'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 // 2, self.model_tester.image_size // 2]      ,  )

       UpperCamelCase_     ,      UpperCamelCase_					: str            =				self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase_					: Union[str, Any]            =				["""basic""", """bottleneck"""]
       for model_class in self.all_model_classes:
             for layer_type in layers_type:
                   UpperCamelCase_					: Any            =				layer_type
                   UpperCamelCase_					: str            =				True
                   check_hidden_states_output(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			)

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

                   check_hidden_states_output(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			)
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_     ,      UpperCamelCase_					: str            =				self.model_tester.prepare_config_and_inputs_for_common()

       def check_equivalence(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase={}			):
             UpperCamelCase_					: Dict            =				model(__lowerCAmelCase      ,  return_dict=__lowerCAmelCase      ,  **__lowerCAmelCase			)
             UpperCamelCase_					: List[str]            =				model(__lowerCAmelCase      ,  return_dict=__lowerCAmelCase      ,  **__lowerCAmelCase			).to_tuple()

             def recursive_check(__lowerCAmelCase      ,  __lowerCAmelCase			):
                   if isinstance(__lowerCAmelCase      ,  (List, Tuple)			):
                         for tuple_iterable_value, dict_iterable_value in zip(__lowerCAmelCase      ,  __lowerCAmelCase			):
                               recursive_check(__lowerCAmelCase      ,  __lowerCAmelCase			)
                   elif tuple_object is None:
                         return
                   else:
                         self.assertTrue(
                             all(tf.equal(__lowerCAmelCase      ,  __lowerCAmelCase			)			)      ,  msg=(
                                 """Tuple and dict output are not equal. Difference:"""
                                 F" {tf.math.reduce_max(tf.abs(tuple_object - dict_object			)			)}"
                             )      ,  )

                   recursive_check(__lowerCAmelCase      ,  __lowerCAmelCase			)

       for model_class in self.all_model_classes:
             UpperCamelCase_					: Optional[Any]            =				model_class(__lowerCAmelCase			)

             UpperCamelCase_					: Any            =				self._prepare_for_class(__lowerCAmelCase      ,  __lowerCAmelCase			)
             UpperCamelCase_					: Optional[Any]            =				self._prepare_for_class(__lowerCAmelCase      ,  __lowerCAmelCase			)
             check_equivalence(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			)

             UpperCamelCase_					: List[Any]            =				self._prepare_for_class(__lowerCAmelCase      ,  __lowerCAmelCase      ,  return_labels=__lowerCAmelCase			)
             UpperCamelCase_					: str            =				self._prepare_for_class(__lowerCAmelCase      ,  __lowerCAmelCase      ,  return_labels=__lowerCAmelCase			)
             check_equivalence(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			)

             UpperCamelCase_					: str            =				self._prepare_for_class(__lowerCAmelCase      ,  __lowerCAmelCase			)
             UpperCamelCase_					: Any            =				self._prepare_for_class(__lowerCAmelCase      ,  __lowerCAmelCase			)
             check_equivalence(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  {"""output_hidden_states""": True}			)

             UpperCamelCase_					: Union[str, Any]            =				self._prepare_for_class(__lowerCAmelCase      ,  __lowerCAmelCase      ,  return_labels=__lowerCAmelCase			)
             UpperCamelCase_					: Tuple            =				self._prepare_for_class(__lowerCAmelCase      ,  __lowerCAmelCase      ,  return_labels=__lowerCAmelCase			)
             check_equivalence(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  {"""output_hidden_states""": True}			)
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: Tuple            =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase			)





 @slow
 def 	_UpperCAmelCase							(				self			):
       for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase_					: Any            =				TFRegNetModel.from_pretrained(__lowerCAmelCase			)
             self.assertIsNotNone(__lowerCAmelCase			)






def 				snake_case       (  )							->					Optional[Any]:





      """simple docstring"""

      UpperCamelCase_					: str            =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
      return image




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






 """simple docstring"""





 @cached_property
 def 	_UpperCAmelCase							(				self			):
       return (
           AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)
           if is_vision_available()
           else None
       )





 @slow
 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: str            =				TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)

       UpperCamelCase_					: List[str]            =				self.default_image_processor
       UpperCamelCase_					: Tuple            =				prepare_img()
       UpperCamelCase_					: Optional[Any]            =				image_processor(images=__lowerCAmelCase      ,  return_tensors="""tf"""			)

       # forward pass
       UpperCamelCase_					: Optional[int]            =				model(**__lowerCAmelCase      ,  training=__lowerCAmelCase			)

       # verify the logits
       UpperCamelCase_					: Optional[int]            =				tf.TensorShape((1, 10_00)			)
       self.assertEqual(outputs.logits.shape      ,  __lowerCAmelCase			)

       UpperCamelCase_					: Tuple            =				tf.constant([-0.41_80, -1.50_51, -3.48_36]			)

       tf.debugging.assert_near(outputs.logits[0, :3]      ,  __lowerCAmelCase      ,  atol=1E-4			)














'''simple docstring'''

import unittest

import numpy as np
import torch

from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()




class      A     (   unittest.TestCase    ):






 """simple docstring"""





 @property
 def 	_UpperCAmelCase							(				self			):
       torch.manual_seed(0			)
       UpperCamelCase_					: int            =				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""")      ,  )
       return model





 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: Union[str, Any]            =				self.dummy_uncond_unet
       UpperCamelCase_					: List[str]            =				PNDMScheduler()

       UpperCamelCase_					: Dict            =				PNDMPipeline(unet=__lowerCAmelCase      ,  scheduler=__lowerCAmelCase			)
       pndm.to(__lowerCAmelCase			)
       pndm.set_progress_bar_config(disable=__lowerCAmelCase			)

       UpperCamelCase_					: Union[str, Any]            =				torch.manual_seed(0			)
       UpperCamelCase_					: Optional[int]            =				pndm(generator=__lowerCAmelCase      ,  num_inference_steps=20      ,  output_type="""numpy"""			).images

       UpperCamelCase_					: Optional[int]            =				torch.manual_seed(0			)
       UpperCamelCase_					: Tuple            =				pndm(generator=__lowerCAmelCase      ,  num_inference_steps=20      ,  output_type="""numpy"""      ,  return_dict=__lowerCAmelCase			)[0]

       UpperCamelCase_					: Union[str, Any]            =				image[0, -3:, -3:, -1]
       UpperCamelCase_					: int            =				image_from_tuple[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       UpperCamelCase_					: Optional[int]            =				np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]			)

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






@slow
@require_torch
class      A     (   unittest.TestCase    ):






 """simple docstring"""





 def 	_UpperCAmelCase							(				self			):
       UpperCamelCase_					: Optional[Any]            =				"""google/ddpm-cifar10-32"""

       UpperCamelCase_					: List[str]            =				UNetaDModel.from_pretrained(__lowerCAmelCase			)
       UpperCamelCase_					: int            =				PNDMScheduler()

       UpperCamelCase_					: Any            =				PNDMPipeline(unet=__lowerCAmelCase      ,  scheduler=__lowerCAmelCase			)
       pndm.to(__lowerCAmelCase			)
       pndm.set_progress_bar_config(disable=__lowerCAmelCase			)
       UpperCamelCase_					: Optional[int]            =				torch.manual_seed(0			)
       UpperCamelCase_					: Optional[int]            =				pndm(generator=__lowerCAmelCase      ,  output_type="""numpy"""			).images

       UpperCamelCase_					: Tuple            =				image[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       UpperCamelCase_					: Union[str, Any]            =				np.array([0.15_64, 0.1_46_45, 0.14_06, 0.1_47_15, 0.1_24_25, 0.1_40_45, 0.1_31_15, 0.1_21_75, 0.1_25]			)

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






