






"""simple docstring"""
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   SCREAMING_SNAKE_CASE	:





	"""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  ,  ):
		A_		:    Optional[Any]						     = parent
		A_		:    Tuple						     = batch_size
		A_		:    int						     = image_size
		A_		:    List[str]						     = num_channels
		A_		:    Optional[int]						     = embeddings_size
		A_		:    List[Any]						     = hidden_sizes
		A_		:    Union[str, Any]						     = depths
		A_		:    Dict						     = is_training
		A_		:    Any						     = use_labels
		A_		:    Optional[int]						     = hidden_act
		A_		:    int						     = num_labels
		A_		:    Optional[int]						     = scope
		A_		:    int						     = len(lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		A_		:    Any						     = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

		A_		:    int						     = self.get_config()

		return config, pixel_values, labels





	def  lowerCamelCase(self				):
		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  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				):
		A_		:    str						     = TFResNetModel(config=lowerCAmelCase_				)
		A_		:    Union[str, Any]						     = model(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  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				):
		A_		:    List[str]						     = self.num_labels
		A_		:    int						     = TFResNetForImageClassification(lowerCAmelCase_				)
		A_		:    List[str]						     = model(lowerCAmelCase_  ,  labels=lowerCAmelCase_				)
		self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.num_labels)				)





	def  lowerCamelCase(self				):
		A_		:    Optional[int]						     = self.prepare_config_and_inputs()
		A_     ,  A_     ,  A_		:    str						     = config_and_inputs
		A_		:    Union[str, Any]						     = {"""pixel_values""": pixel_values}
		return config, inputs_dict






@require_tf
class   SCREAMING_SNAKE_CASE	(					_SCREAMING_SNAKE_CASE							,							_SCREAMING_SNAKE_CASE							,							unittest.TestCase    ):





	"""simple docstring"""




	_A							:					Any 			=					(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
	_A							:					Dict 			=					(
	    {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	_A							:					int 			=					False
	_A							:					Optional[Any] 			=					False
	_A							:					str 			=					False
	_A							:					List[Any] 			=					False
	_A							:					Tuple 			=					False





	def  lowerCamelCase(self				):
		A_		:    List[Any]						     = TFResNetModelTester(self				)
		A_		:    Union[str, Any]						     = ConfigTester(self  ,  config_class=lowerCAmelCase_  ,  has_text_modality=lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		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				):
		return





	@unittest.skip(reason="""ResNet does not use inputs_embeds"""				)
	def  lowerCamelCase(self				):
		pass





	@unittest.skip(reason="""ResNet does not support input and output embeddings"""				)
	def  lowerCamelCase(self				):
		pass





	def  lowerCamelCase(self				):
		A_     ,  A_		:    Optional[Any]						     = self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			A_		:    Optional[Any]						     = model_class(lowerCAmelCase_				)
			A_		:    Union[str, Any]						     = inspect.signature(model.call				)
			# signature.parameters is an OrderedDict => so arg_names order is deterministic
			A_		:    Any						     = [*signature.parameters.keys()]

			A_		:    Tuple						     = ["""pixel_values"""]
			self.assertListEqual(arg_names[:1]  ,  lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		A_		:    List[Any]						     = self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		def check_hidden_states_output(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				):
			A_		:    int						     = model_class(lowerCAmelCase_				)
			A_		:    Any						     = model(**self._prepare_for_class(lowerCAmelCase_  ,  lowerCAmelCase_				)				)

			A_		:    Any						     = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

			A_		:    Tuple						     = self.model_tester.num_stages
			self.assertEqual(len(lowerCAmelCase_				)  ,  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_		:    Optional[Any]						     = self.model_tester.prepare_config_and_inputs_for_common()
		A_		:    List[str]						     = ["""basic""", """bottleneck"""]
		for model_class in self.all_model_classes:
			for layer_type in layers_type:
				A_		:    List[str]						     = layer_type
				A_		:    List[Any]						     = True
				check_hidden_states_output(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				)

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

				check_hidden_states_output(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		A_		:    str						     = self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_				)





	@slow
	def  lowerCamelCase(self				):
		for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			A_		:    Tuple						     = TFResNetModel.from_pretrained(lowerCAmelCase_				)
			self.assertIsNotNone(lowerCAmelCase_				)






def       __UpperCamelCase						(		):
	A_		:    Union[str, Any]						     = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""       )
	return image




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





	"""simple docstring"""




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





	@slow
	def  lowerCamelCase(self				):
		A_		:    Union[str, Any]						     = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

		A_		:    Dict						     = self.default_image_processor
		A_		:    List[Any]						     = prepare_img()
		A_		:    List[Any]						     = image_processor(images=lowerCAmelCase_  ,  return_tensors="""tf"""				)

		# forward pass
		A_		:    Union[str, Any]						     = model(**lowerCAmelCase_				)

		# verify the logits
		A_		:    List[str]						     = tf.TensorShape((1, 1000)				)
		self.assertEqual(outputs.logits.shape  ,  lowerCAmelCase_				)

		A_		:    str						     = tf.constant([-11.1069, -9.7877, -8.3777]				)

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









"""simple docstring"""
import tempfile

import torch

from diffusers import (
    DEISMultistepScheduler,
    DPMSolverMultistepScheduler,
    DPMSolverSinglestepScheduler,
    UniPCMultistepScheduler,
)

from .test_schedulers import SchedulerCommonTest



class   SCREAMING_SNAKE_CASE	(					_SCREAMING_SNAKE_CASE    ):





	"""simple docstring"""




	_A							:					Optional[int] 			=					(UniPCMultistepScheduler,)
	_A							:					Optional[Any] 			=					(("""num_inference_steps""", 25),)





	def  lowerCamelCase(self  ,  **lowerCAmelCase_				):
		A_		:    str						     = {
		    """num_train_timesteps""": 1000,
		    """beta_start""": 0.0001,
		    """beta_end""": 0.02,
		    """beta_schedule""": """linear""",
		    """solver_order""": 2,
		    """solver_type""": """bh2""",
		}

		config.update(**lowerCAmelCase_				)
		return config





	def  lowerCamelCase(self  ,  lowerCAmelCase_=0  ,  **lowerCAmelCase_				):
		A_		:    Tuple						     = dict(self.forward_default_kwargs				)
		A_		:    Any						     = kwargs.pop("""num_inference_steps"""  ,  lowerCAmelCase_				)
		A_		:    str						     = self.dummy_sample
		A_		:    Dict						     = 0.1 * sample
		A_		:    int						     = [residual + 0.2, residual + 0.15, residual + 0.10]

		for scheduler_class in self.scheduler_classes:
			A_		:    List[Any]						     = self.get_scheduler_config(**lowerCAmelCase_				)
			A_		:    Dict						     = scheduler_class(**lowerCAmelCase_				)
			scheduler.set_timesteps(lowerCAmelCase_				)
			# copy over dummy past residuals
			A_		:    Tuple						     = dummy_past_residuals[: scheduler.config.solver_order]

			with tempfile.TemporaryDirectory() as tmpdirname:
				scheduler.save_config(lowerCAmelCase_				)
				A_		:    Any						     = scheduler_class.from_pretrained(lowerCAmelCase_				)
				new_scheduler.set_timesteps(lowerCAmelCase_				)
				# copy over dummy past residuals
				A_		:    Any						     = dummy_past_residuals[: new_scheduler.config.solver_order]

			A_     ,  A_		:    Optional[int]						     = sample, sample
			for t in range(lowerCAmelCase_  ,  time_step + scheduler.config.solver_order + 1				):
				A_		:    Any						     = scheduler.step(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				).prev_sample
				A_		:    Dict						     = new_scheduler.step(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				).prev_sample

				assert torch.sum(torch.abs(output - new_output				)				) < 1e-5, "Scheduler outputs are not identical"





	def  lowerCamelCase(self  ,  lowerCAmelCase_=0  ,  **lowerCAmelCase_				):
		A_		:    Optional[int]						     = dict(self.forward_default_kwargs				)
		A_		:    int						     = kwargs.pop("""num_inference_steps"""  ,  lowerCAmelCase_				)
		A_		:    Optional[Any]						     = self.dummy_sample
		A_		:    List[Any]						     = 0.1 * sample
		A_		:    List[Any]						     = [residual + 0.2, residual + 0.15, residual + 0.10]

		for scheduler_class in self.scheduler_classes:
			A_		:    Dict						     = self.get_scheduler_config()
			A_		:    str						     = scheduler_class(**lowerCAmelCase_				)
			scheduler.set_timesteps(lowerCAmelCase_				)

			# copy over dummy past residuals (must be after setting timesteps)
			A_		:    Union[str, Any]						     = dummy_past_residuals[: scheduler.config.solver_order]

			with tempfile.TemporaryDirectory() as tmpdirname:
				scheduler.save_config(lowerCAmelCase_				)
				A_		:    Tuple						     = scheduler_class.from_pretrained(lowerCAmelCase_				)
				# copy over dummy past residuals
				new_scheduler.set_timesteps(lowerCAmelCase_				)

				# copy over dummy past residual (must be after setting timesteps)
				A_		:    Optional[int]						     = dummy_past_residuals[: new_scheduler.config.solver_order]

			A_		:    Tuple						     = scheduler.step(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				).prev_sample
			A_		:    str						     = new_scheduler.step(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				).prev_sample

			assert torch.sum(torch.abs(output - new_output				)				) < 1e-5, "Scheduler outputs are not identical"





	def  lowerCamelCase(self  ,  lowerCAmelCase_=None  ,  **lowerCAmelCase_				):
		if scheduler is None:
			A_		:    int						     = self.scheduler_classes[0]
			A_		:    List[str]						     = self.get_scheduler_config(**lowerCAmelCase_				)
			A_		:    Any						     = scheduler_class(**lowerCAmelCase_				)

		A_		:    int						     = self.scheduler_classes[0]
		A_		:    str						     = self.get_scheduler_config(**lowerCAmelCase_				)
		A_		:    Union[str, Any]						     = scheduler_class(**lowerCAmelCase_				)

		A_		:    Optional[int]						     = 10
		A_		:    Optional[Any]						     = self.dummy_model()
		A_		:    Optional[Any]						     = self.dummy_sample_deter
		scheduler.set_timesteps(lowerCAmelCase_				)

		for i, t in enumerate(scheduler.timesteps				):
			A_		:    Optional[int]						     = model(lowerCAmelCase_  ,  lowerCAmelCase_				)
			A_		:    Optional[int]						     = scheduler.step(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				).prev_sample

		return sample





	def  lowerCamelCase(self				):
		A_		:    Any						     = dict(self.forward_default_kwargs				)

		A_		:    Any						     = kwargs.pop("""num_inference_steps"""  ,  lowerCAmelCase_				)

		for scheduler_class in self.scheduler_classes:
			A_		:    Dict						     = self.get_scheduler_config()
			A_		:    List[Any]						     = scheduler_class(**lowerCAmelCase_				)

			A_		:    int						     = self.dummy_sample
			A_		:    str						     = 0.1 * sample

			if num_inference_steps is not None and hasattr(lowerCAmelCase_  ,  """set_timesteps"""				):
				scheduler.set_timesteps(lowerCAmelCase_				)
			elif num_inference_steps is not None and not hasattr(lowerCAmelCase_  ,  """set_timesteps"""				):
				A_		:    Tuple						     = num_inference_steps

			# copy over dummy past residuals (must be done after set_timesteps)
			A_		:    List[Any]						     = [residual + 0.2, residual + 0.15, residual + 0.10]
			A_		:    Dict						     = dummy_past_residuals[: scheduler.config.solver_order]

			A_		:    str						     = scheduler.timesteps[5]
			A_		:    Any						     = scheduler.timesteps[6]

			A_		:    Tuple						     = scheduler.step(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				).prev_sample
			A_		:    Dict						     = scheduler.step(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				).prev_sample

			self.assertEqual(output_a.shape  ,  sample.shape				)
			self.assertEqual(output_a.shape  ,  output_a.shape				)





	def  lowerCamelCase(self				):
		# make sure that iterating over schedulers with same config names gives same results
		# for defaults
		A_		:    Tuple						     = UniPCMultistepScheduler(**self.get_scheduler_config()				)
		A_		:    List[str]						     = self.full_loop(scheduler=lowerCAmelCase_				)
		A_		:    int						     = torch.mean(torch.abs(lowerCAmelCase_				)				)

		assert abs(result_mean.item() - 0.2464				) < 1e-3

		A_		:    List[str]						     = DPMSolverSinglestepScheduler.from_config(scheduler.config				)
		A_		:    List[str]						     = DEISMultistepScheduler.from_config(scheduler.config				)
		A_		:    Optional[int]						     = DPMSolverMultistepScheduler.from_config(scheduler.config				)
		A_		:    str						     = UniPCMultistepScheduler.from_config(scheduler.config				)

		A_		:    Dict						     = self.full_loop(scheduler=lowerCAmelCase_				)
		A_		:    List[Any]						     = torch.mean(torch.abs(lowerCAmelCase_				)				)

		assert abs(result_mean.item() - 0.2464				) < 1e-3





	def  lowerCamelCase(self				):
		for timesteps in [25, 50, 100, 999, 1000]:
			self.check_over_configs(num_train_timesteps=lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		self.check_over_configs(thresholding=lowerCAmelCase_				)
		for order in [1, 2, 3]:
			for solver_type in ["bh1", "bh2"]:
				for threshold in [0.5, 1.0, 2.0]:
					for prediction_type in ["epsilon", "sample"]:
						self.check_over_configs(
						    thresholding=lowerCAmelCase_  ,  prediction_type=lowerCAmelCase_  ,  sample_max_value=lowerCAmelCase_  ,  solver_order=lowerCAmelCase_  ,  solver_type=lowerCAmelCase_  ,  )





	def  lowerCamelCase(self				):
		for prediction_type in ["epsilon", "v_prediction"]:
			self.check_over_configs(prediction_type=lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		for solver_type in ["bh1", "bh2"]:
			for order in [1, 2, 3]:
				for prediction_type in ["epsilon", "sample"]:
					self.check_over_configs(
					    solver_order=lowerCAmelCase_  ,  solver_type=lowerCAmelCase_  ,  prediction_type=lowerCAmelCase_  ,  )
					A_		:    Union[str, Any]						     = self.full_loop(
					    solver_order=lowerCAmelCase_  ,  solver_type=lowerCAmelCase_  ,  prediction_type=lowerCAmelCase_  ,  )
					assert not torch.isnan(lowerCAmelCase_				).any(), "Samples have nan numbers"





	def  lowerCamelCase(self				):
		self.check_over_configs(lower_order_final=lowerCAmelCase_				)
		self.check_over_configs(lower_order_final=lowerCAmelCase_				)





	def  lowerCamelCase(self				):
		for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]:
			self.check_over_forward(num_inference_steps=lowerCAmelCase_  ,  time_step=0				)





	def  lowerCamelCase(self				):
		A_		:    Optional[int]						     = self.full_loop()
		A_		:    Optional[int]						     = torch.mean(torch.abs(lowerCAmelCase_				)				)

		assert abs(result_mean.item() - 0.2464				) < 1e-3





	def  lowerCamelCase(self				):
		A_		:    str						     = self.full_loop(prediction_type="""v_prediction"""				)
		A_		:    Optional[Any]						     = torch.mean(torch.abs(lowerCAmelCase_				)				)

		assert abs(result_mean.item() - 0.1014				) < 1e-3





	def  lowerCamelCase(self				):
		A_		:    List[str]						     = self.scheduler_classes[0]
		A_		:    str						     = self.get_scheduler_config(thresholding=lowerCAmelCase_  ,  dynamic_thresholding_ratio=0				)
		A_		:    Union[str, Any]						     = scheduler_class(**lowerCAmelCase_				)

		A_		:    Any						     = 10
		A_		:    int						     = self.dummy_model()
		A_		:    Optional[Any]						     = self.dummy_sample_deter.half()
		scheduler.set_timesteps(lowerCAmelCase_				)

		for i, t in enumerate(scheduler.timesteps				):
			A_		:    Dict						     = model(lowerCAmelCase_  ,  lowerCAmelCase_				)
			A_		:    Tuple						     = scheduler.step(lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_				).prev_sample

		assert sample.dtype == torch.floataa





	def  lowerCamelCase(self  ,  **lowerCAmelCase_				):
		for scheduler_class in self.scheduler_classes:
			A_		:    Tuple						     = self.get_scheduler_config(**lowerCAmelCase_				)
			A_		:    int						     = scheduler_class(**lowerCAmelCase_				)

			scheduler.set_timesteps(scheduler.config.num_train_timesteps				)
			assert len(scheduler.timesteps.unique()				) == scheduler.num_inference_steps

