




'''simple docstring'''
from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
  from PIL import Image

  from transformers import ConvNextImageProcessor






class        SCREAMING_SNAKE_CASE:

       def __init__(    self					,		lowerCamelCase__					,		lowerCamelCase__=13					,		lowerCamelCase__=32					,		lowerCamelCase__=3					,		lowerCamelCase__=4					,		lowerCamelCase__=[10, 20, 30, 40]					,		lowerCamelCase__=[2, 2, 3, 2]					,		lowerCamelCase__=True					,		lowerCamelCase__=True					,		lowerCamelCase__=37					,		lowerCamelCase__="gelu"					,		lowerCamelCase__=10					,		lowerCamelCase__=0.02					,		lowerCamelCase__=3					,		lowerCamelCase__=None					,		)    ->					Optional[int]:

           """simple docstring"""



           __lowercase							=						parent
           __lowercase							=						batch_size
           __lowercase							=						image_size
           __lowercase							=						num_channels
           __lowercase							=						num_stages
           __lowercase							=						hidden_sizes
           __lowercase							=						depths
           __lowercase							=						is_training
           __lowercase							=						use_labels
           __lowercase							=						intermediate_size
           __lowercase							=						hidden_act
           __lowercase							=						type_sequence_label_size
           __lowercase							=						initializer_range
           __lowercase							=						scope

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

           """simple docstring"""



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

           __lowercase							=						None
           if self.use_labels:
               __lowercase							=						ids_tensor([self.batch_size]					,		self.type_sequence_label_size     )

           __lowercase							=						self.get_config()

           return config, pixel_values, labels

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

           """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=lowerCamelCase__					,		initializer_range=self.initializer_range					,		)

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						TFConvNextModel(config=lowerCamelCase__     )
           __lowercase							=						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     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						self.type_sequence_label_size
           __lowercase							=						TFConvNextForImageClassification(lowerCamelCase__     )
           __lowercase							=						model(lowerCamelCase__					,		labels=lowerCamelCase__					,		training=lowerCamelCase__     )
           self.parent.assertEqual(result.logits.shape					,		(self.batch_size, self.type_sequence_label_size)     )




       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           __lowercase							=						self.prepare_config_and_inputs()
           __lowercase				,__lowercase				,__lowercase							=						config_and_inputs
           __lowercase							=						{"""pixel_values""": pixel_values}
           return config, inputs_dict






@require_tf
class        SCREAMING_SNAKE_CASE(				__A   ,      __A   ,      unittest.TestCase     ):
       snake_case_ :     Optional[int]    =					(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
       snake_case_ :     str    =					(
           {"""feature-extraction""": TFConvNextModel, """image-classification""": TFConvNextForImageClassification}
           if is_tf_available()
           else {}
       )

       snake_case_ :     Optional[Any]    =					False
       snake_case_ :     Union[str, Any]    =					False
       snake_case_ :     int    =					False
       snake_case_ :     Optional[int]    =					False
       snake_case_ :     Union[str, Any]    =					False

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           __lowercase							=						TFConvNextModelTester(self     )
           __lowercase							=						ConfigTester(
               self					,		config_class=lowerCamelCase__					,		has_text_modality=lowerCamelCase__					,		hidden_size=37					,		)

       @unittest.skip(reason="""ConvNext does not use inputs_embeds"""     )
       def     snake_case__			(    self     )    ->					Union[str, Any]:

           """simple docstring"""



           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     snake_case__			(    self     )    ->					List[Any]:

           """simple docstring"""



           super().test_keras_fit()

       @unittest.skip(reason="""ConvNext does not support input and output embeddings"""     )
       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           pass

       def     snake_case__			(    self     )    ->					Dict:

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

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

               __lowercase							=						["""pixel_values"""]
               self.assertListEqual(arg_names[:1]					,		lowerCamelCase__     )

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

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase__     )

       @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."""					,		)
       def     snake_case__			(    self     )    ->					List[Any]:

           """simple docstring"""



           super().test_dataset_conversion()

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           def check_hidden_states_output(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     ):
               __lowercase							=						model_class(lowerCamelCase__     )

               __lowercase							=						model(**self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__     )     )
               __lowercase							=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               __lowercase							=						True
               check_hidden_states_output(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )

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

               check_hidden_states_output(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					Dict:

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

           def check_equivalence(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__={}     ):
               __lowercase							=						model(lowerCamelCase__					,		return_dict=lowerCamelCase__					,		**lowerCamelCase__     )
               __lowercase							=						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:
               __lowercase							=						model_class(lowerCamelCase__     )

               __lowercase							=						self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__     )
               __lowercase							=						self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__     )
               check_equivalence(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__					,		return_labels=lowerCamelCase__     )
               __lowercase							=						self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__					,		return_labels=lowerCamelCase__     )
               check_equivalence(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__     )
               __lowercase							=						self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__     )
               check_equivalence(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		{"""output_hidden_states""": True}     )

               __lowercase							=						self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__					,		return_labels=lowerCamelCase__     )
               __lowercase							=						self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__					,		return_labels=lowerCamelCase__     )
               check_equivalence(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		{"""output_hidden_states""": True}     )

       def     snake_case__			(    self     )    ->					Optional[Any]:

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__     )




       @slow
       def     snake_case__			(    self     )    ->					List[Any]:

           """simple docstring"""



           __lowercase							=						TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""     )
           self.assertIsNotNone(lowerCamelCase__     )

def 				snake_case_  (   ):



    """simple docstring"""




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






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

       @cached_property
       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""     ) if is_vision_available() else None




       @slow
       def     snake_case__			(    self     )    ->					Dict:

           """simple docstring"""



           __lowercase							=						TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""     )

           __lowercase							=						self.default_image_processor
           __lowercase							=						prepare_img()
           __lowercase							=						image_processor(images=lowerCamelCase__					,		return_tensors="""tf"""     )

           # forward pass
           __lowercase							=						model(**lowerCamelCase__     )

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

           __lowercase							=						tf.constant([-0.02_60, -0.47_39, 0.19_11]     )

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










'''simple docstring'''
import torch

from diffusers import HeunDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest






class        SCREAMING_SNAKE_CASE(				__A     ):
       snake_case_ :     Any    =					(HeunDiscreteScheduler,)
       snake_case_ :     Any    =					10

       def     snake_case__			(    self					,		**lowerCamelCase__     )    ->					int:

           """simple docstring"""



           __lowercase							=						{
               """num_train_timesteps""": 1100,
               """beta_start""": 0.00_01,
               """beta_end""": 0.02,
               """beta_schedule""": """linear""",
           }

           config.update(**lowerCamelCase__     )
           return config

       def     snake_case__			(    self     )    ->					Optional[Any]:

           """simple docstring"""



           for timesteps in [10, 50, 100, 1000]:
               self.check_over_configs(num_train_timesteps=lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					Dict:

           """simple docstring"""



           for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01]					,		[0.00_02, 0.0_02, 0.02]     ):
               self.check_over_configs(beta_start=lowerCamelCase__					,		beta_end=lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           for schedule in ["linear", "scaled_linear", "exp"]:
               self.check_over_configs(beta_schedule=lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           for clip_sample_range in [1.0, 2.0, 3.0]:
               self.check_over_configs(clip_sample_range=lowerCamelCase__					,		clip_sample=lowerCamelCase__     )

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

           """simple docstring"""



           for prediction_type in ["epsilon", "v_prediction", "sample"]:
               self.check_over_configs(prediction_type=lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           __lowercase							=						self.scheduler_classes[0]
           __lowercase							=						self.get_scheduler_config()
           __lowercase							=						scheduler_class(**lowerCamelCase__     )

           scheduler.set_timesteps(self.num_inference_steps     )

           __lowercase							=						self.dummy_model()
           __lowercase							=						self.dummy_sample_deter * scheduler.init_noise_sigma
           __lowercase							=						sample.to(lowerCamelCase__     )

           for i, t in enumerate(scheduler.timesteps     ):
               __lowercase							=						scheduler.scale_model_input(lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						model(lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						scheduler.step(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )
               __lowercase							=						output.prev_sample

           __lowercase							=						torch.sum(torch.abs(lowerCamelCase__     )     )
           __lowercase							=						torch.mean(torch.abs(lowerCamelCase__     )     )

           if torch_device in ["cpu", "mps"]:
               assert abs(result_sum.item() - 0.12_33     ) < 1E-2
               assert abs(result_mean.item() - 0.00_02     ) < 1E-3
           else:
               # CUDA
               assert abs(result_sum.item() - 0.12_33     ) < 1E-2
               assert abs(result_mean.item() - 0.00_02     ) < 1E-3

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           __lowercase							=						self.scheduler_classes[0]
           __lowercase							=						self.get_scheduler_config(prediction_type="""v_prediction"""     )
           __lowercase							=						scheduler_class(**lowerCamelCase__     )

           scheduler.set_timesteps(self.num_inference_steps     )

           __lowercase							=						self.dummy_model()
           __lowercase							=						self.dummy_sample_deter * scheduler.init_noise_sigma
           __lowercase							=						sample.to(lowerCamelCase__     )

           for i, t in enumerate(scheduler.timesteps     ):
               __lowercase							=						scheduler.scale_model_input(lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						model(lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						scheduler.step(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )
               __lowercase							=						output.prev_sample

           __lowercase							=						torch.sum(torch.abs(lowerCamelCase__     )     )
           __lowercase							=						torch.mean(torch.abs(lowerCamelCase__     )     )

           if torch_device in ["cpu", "mps"]:
               assert abs(result_sum.item() - 4.6_9_3_4E-0_7     ) < 1E-2
               assert abs(result_mean.item() - 6.1_1_1_2E-1_0     ) < 1E-3
           else:
               # CUDA
               assert abs(result_sum.item() - 4.6_9_3_4_2_8_6_5_0_1_7_0_9_7_2E-0_7     ) < 1E-2
               assert abs(result_mean.item() - 0.00_02     ) < 1E-3

       def     snake_case__			(    self     )    ->					Dict:

           """simple docstring"""



           __lowercase							=						self.scheduler_classes[0]
           __lowercase							=						self.get_scheduler_config()
           __lowercase							=						scheduler_class(**lowerCamelCase__     )

           scheduler.set_timesteps(self.num_inference_steps					,		device=lowerCamelCase__     )

           __lowercase							=						self.dummy_model()
           __lowercase							=						self.dummy_sample_deter.to(lowerCamelCase__     ) * scheduler.init_noise_sigma

           for t in scheduler.timesteps:
               __lowercase							=						scheduler.scale_model_input(lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						model(lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						scheduler.step(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )
               __lowercase							=						output.prev_sample

           __lowercase							=						torch.sum(torch.abs(lowerCamelCase__     )     )
           __lowercase							=						torch.mean(torch.abs(lowerCamelCase__     )     )

           if str(lowerCamelCase__     ).startswith("""cpu"""     ):
               # The following sum varies between 148 and 156 on mps. Why?
               assert abs(result_sum.item() - 0.12_33     ) < 1E-2
               assert abs(result_mean.item() - 0.00_02     ) < 1E-3
           elif str(lowerCamelCase__     ).startswith("""mps"""     ):
               # Larger tolerance on mps
               assert abs(result_mean.item() - 0.00_02     ) < 1E-2
           else:
               # CUDA
               assert abs(result_sum.item() - 0.12_33     ) < 1E-2
               assert abs(result_mean.item() - 0.00_02     ) < 1E-3




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

           """simple docstring"""



           __lowercase							=						self.scheduler_classes[0]
           __lowercase							=						self.get_scheduler_config()
           __lowercase							=						scheduler_class(**lowerCamelCase__					,		use_karras_sigmas=lowerCamelCase__     )

           scheduler.set_timesteps(self.num_inference_steps					,		device=lowerCamelCase__     )

           __lowercase							=						self.dummy_model()
           __lowercase							=						self.dummy_sample_deter.to(lowerCamelCase__     ) * scheduler.init_noise_sigma
           __lowercase							=						sample.to(lowerCamelCase__     )

           for t in scheduler.timesteps:
               __lowercase							=						scheduler.scale_model_input(lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						model(lowerCamelCase__					,		lowerCamelCase__     )

               __lowercase							=						scheduler.step(lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )
               __lowercase							=						output.prev_sample

           __lowercase							=						torch.sum(torch.abs(lowerCamelCase__     )     )
           __lowercase							=						torch.mean(torch.abs(lowerCamelCase__     )     )

           assert abs(result_sum.item() - 0.0_00_15     ) < 1E-2
           assert abs(result_mean.item() - 1.9_8_6_9_5_5_4_5_3_5_0_3_4_6_9_5E-0_7     ) < 1E-2




