






"""simple docstring"""

import tempfile
import unittest

import torch

from diffusers import UNetaDConditionModel
from diffusers.training_utils import EMAModel
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps, torch_device


enable_full_determinism()

class     A_				(   unittest.TestCase	):
				UpperCAmelCase__										=					'''hf-internal-testing/tiny-stable-diffusion-pipe'''
				UpperCAmelCase__										=					1
				UpperCAmelCase__										=					7_7
				UpperCAmelCase__										=					3_2
				UpperCAmelCase__										=					4
				UpperCAmelCase__										=					UpperCAmelCase__										=					6_4
				UpperCAmelCase__										=					torch.manual_seed(0	)







				def      _snake_case       (				self				:    Union[str, Any]    ,     __lowerCamelCase				:    int=0.9999						)					->       str:
										__magic_name__      =  UNetaDConditionModel.from_pretrained(self.model_id    ,     subfolder="unet"						)
										__magic_name__      =  unet.to(__lowerCamelCase						)
										__magic_name__      =  EMAModel(unet.parameters()    ,     decay=__lowerCamelCase    ,     model_cls=__lowerCamelCase    ,     model_config=unet.config						)
										return unet, ema_unet







				def      _snake_case       (				self				:    int						)					->       str:
										__magic_name__      =  torch.randn(
										    self.batch_size    ,     self.num_in_channels    ,     self.latent_height    ,     self.latent_width    ,     generator=self.generator						).to(__lowerCamelCase						)
										__magic_name__      =  torch.randint(0    ,     1_0_0_0    ,     size=(self.batch_size,)    ,     generator=self.generator						).to(__lowerCamelCase						)
										__magic_name__      =  torch.randn(
										    self.batch_size    ,     self.prompt_length    ,     self.text_encoder_hidden_dim    ,     generator=self.generator						).to(__lowerCamelCase						)
										return noisy_latents, timesteps, encoder_hidden_states







				def      _snake_case       (				self				:    Dict    ,     __lowerCamelCase				:    Optional[int]						)					->       Optional[Any]:
										__magic_name__      =  {}
										for k, param in unet.state_dict().items():
																__magic_name__      =  torch.randn_like(__lowerCamelCase						) + (param * torch.randn_like(__lowerCamelCase						))
																updated_state_dict.update({k: updated_param}						)
										unet.load_state_dict(__lowerCamelCase						)
										return unet







				def      _snake_case       (				self				:    Optional[int]						)					->       Optional[int]:
										__magic_name__   ,     __magic_name__      =  self.get_models()
										# Take the first (hypothetical) EMA step.
										ema_unet.step(unet.parameters()						)
										assert ema_unet.optimization_step == 1

										# Take two more.
										for _ in range(2						):
																ema_unet.step(unet.parameters()						)
										assert ema_unet.optimization_step == 3







				def      _snake_case       (				self				:    List[str]						)					->       List[Any]:
										__magic_name__   ,     __magic_name__      =  self.get_models()
										# Since the `unet` is not being updated (i.e., backprop'd)
										# there won't be any difference between the `params` of `unet`
										# and `ema_unet` even if we call `ema_unet.step(unet.parameters())`.
										ema_unet.step(unet.parameters()						)
										__magic_name__      =  list(unet.parameters()						)
										for s_param, param in zip(ema_unet.shadow_params    ,     __lowerCamelCase						):
																assert torch.allclose(__lowerCamelCase    ,     __lowerCamelCase						)

										# The above holds true even if we call `ema.step()` multiple times since
										# `unet` params are still not being updated.
										for _ in range(4						):
																ema_unet.step(unet.parameters()						)
										for s_param, param in zip(ema_unet.shadow_params    ,     __lowerCamelCase						):
																assert torch.allclose(__lowerCamelCase    ,     __lowerCamelCase						)







				def      _snake_case       (				self				:    List[str]						)					->       List[str]:
										__magic_name__   ,     __magic_name__      =  self.get_models()
										# Here we simulate the parameter updates for `unet`. Since there might
										# be some parameters which are initialized to zero we take extra care to
										# initialize their values to something non-zero before the multiplication.
										__magic_name__      =  self.simulate_backprop(__lowerCamelCase						)

										# Take the EMA step.
										ema_unet.step(unet_pseudo_updated_step_one.parameters()						)

										# Now the EMA'd parameters won't be equal to the original model parameters.
										__magic_name__      =  list(unet_pseudo_updated_step_one.parameters()						)
										for s_param, param in zip(ema_unet.shadow_params    ,     __lowerCamelCase						):
																assert ~torch.allclose(__lowerCamelCase    ,     __lowerCamelCase						)

										# Ensure this is the case when we take multiple EMA steps.
										for _ in range(4						):
																ema_unet.step(unet.parameters()						)
										for s_param, param in zip(ema_unet.shadow_params    ,     __lowerCamelCase						):
																assert ~torch.allclose(__lowerCamelCase    ,     __lowerCamelCase						)







				def      _snake_case       (				self				:    Optional[Any]						)					->       Tuple:
										# If we call EMA step after a backpropagation consecutively for two times,
										# the shadow params from those two steps should be different.
										__magic_name__   ,     __magic_name__      =  self.get_models()

										# First backprop + EMA
										__magic_name__      =  self.simulate_backprop(__lowerCamelCase						)
										ema_unet.step(unet_step_one.parameters()						)
										__magic_name__      =  ema_unet.shadow_params

										# Second backprop + EMA
										__magic_name__      =  self.simulate_backprop(__lowerCamelCase						)
										ema_unet.step(unet_step_two.parameters()						)
										__magic_name__      =  ema_unet.shadow_params

										for step_one, step_two in zip(__lowerCamelCase    ,     __lowerCamelCase						):
																assert ~torch.allclose(__lowerCamelCase    ,     __lowerCamelCase						)







				def      _snake_case       (				self				:    List[Any]						)					->       List[Any]:
										# If there's no decay even if there are backprops, EMA steps
										# won't take any effect i.e., the shadow params would remain the
										# same.
										__magic_name__   ,     __magic_name__      =  self.get_models(decay=0.0						)
										__magic_name__      =  self.simulate_backprop(__lowerCamelCase						)
										ema_unet.step(unet_step_one.parameters()						)
										__magic_name__      =  ema_unet.shadow_params

										__magic_name__      =  self.simulate_backprop(__lowerCamelCase						)
										ema_unet.step(unet_step_two.parameters()						)
										__magic_name__      =  ema_unet.shadow_params

										for step_one, step_two in zip(__lowerCamelCase    ,     __lowerCamelCase						):
																assert torch.allclose(__lowerCamelCase    ,     __lowerCamelCase						)







				@skip_mps
				def      _snake_case       (				self				:    int						)					->       str:
										__magic_name__   ,     __magic_name__      =  self.get_models()
										__magic_name__   ,     __magic_name__   ,     __magic_name__      =  self.get_dummy_inputs()

										with tempfile.TemporaryDirectory() as tmpdir:
																ema_unet.save_pretrained(__lowerCamelCase						)
																__magic_name__      =  UNetaDConditionModel.from_pretrained(__lowerCamelCase    ,     model_cls=__lowerCamelCase						)
																__magic_name__      =  loaded_unet.to(unet.device						)

										# Since no EMA step has been performed the outputs should match.
										__magic_name__      =  unet(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase						).sample
										__magic_name__      =  loaded_unet(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase						).sample

										assert torch.allclose(__lowerCamelCase    ,     __lowerCamelCase    ,     atol=1e-4						)











"""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     A_				:







				def __init__(				self				:    Optional[int]    ,     __lowerCamelCase				:    Tuple    ,     __lowerCamelCase				:    int=1_3    ,     __lowerCamelCase				:    Any=3_2    ,     __lowerCamelCase				:    Dict=3    ,     __lowerCamelCase				:    List[Any]=4    ,     __lowerCamelCase				:    Union[str, Any]=[1_0, 2_0, 3_0, 4_0]    ,     __lowerCamelCase				:    int=[2, 2, 3, 2]    ,     __lowerCamelCase				:    str=True    ,     __lowerCamelCase				:    List[str]=True    ,     __lowerCamelCase				:    List[Any]=3_7    ,     __lowerCamelCase				:    Optional[Any]="gelu"    ,     __lowerCamelCase				:    str=1_0    ,     __lowerCamelCase				:    int=0.02    ,     __lowerCamelCase				:    Optional[int]=3    ,     __lowerCamelCase				:    Any=None    ,     )					->       List[Any]:
										__magic_name__      =  parent
										__magic_name__      =  batch_size
										__magic_name__      =  image_size
										__magic_name__      =  num_channels
										__magic_name__      =  num_stages
										__magic_name__      =  hidden_sizes
										__magic_name__      =  depths
										__magic_name__      =  is_training
										__magic_name__      =  use_labels
										__magic_name__      =  intermediate_size
										__magic_name__      =  hidden_act
										__magic_name__      =  type_sequence_label_size
										__magic_name__      =  initializer_range
										__magic_name__      =  scope







				def      _snake_case       (				self				:    Optional[Any]						)					->       int:
										__magic_name__      =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

										__magic_name__      =  self.get_config()

										return config, pixel_values, labels







				def      _snake_case       (				self				:    Optional[int]						)					->       Union[str, Any]:
										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				:    List[Any]    ,     __lowerCamelCase				:    List[str]    ,     __lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Optional[Any]						)					->       List[str]:
										__magic_name__      =  TFConvNextModel(config=__lowerCamelCase						)
										__magic_name__      =  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 // 3_2, self.image_size // 3_2)    ,     )







				def      _snake_case       (				self				:    List[Any]    ,     __lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Tuple    ,     __lowerCamelCase				:    List[str]						)					->       int:
										__magic_name__      =  self.type_sequence_label_size
										__magic_name__      =  TFConvNextForImageClassification(__lowerCamelCase						)
										__magic_name__      =  model(__lowerCamelCase    ,     labels=__lowerCamelCase    ,     training=__lowerCamelCase						)
										self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.type_sequence_label_size)						)







				def      _snake_case       (				self				:    List[str]						)					->       str:
										__magic_name__      =  self.prepare_config_and_inputs()
										__magic_name__   ,     __magic_name__   ,     __magic_name__      =  config_and_inputs
										__magic_name__      =  {"pixel_values": pixel_values}
										return config, inputs_dict





@require_tf
class     A_				(   snake_case_       ,				snake_case_       ,				unittest.TestCase	):
				UpperCAmelCase__										=					(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
				UpperCAmelCase__										=					(
				    {'''feature-extraction''': TFConvNextModel, '''image-classification''': TFConvNextForImageClassification}
				    if is_tf_available()
				    else {}
				)

				UpperCAmelCase__										=					False
				UpperCAmelCase__										=					False
				UpperCAmelCase__										=					False
				UpperCAmelCase__										=					False
				UpperCAmelCase__										=					False







				def      _snake_case       (				self				:    str						)					->       str:
										__magic_name__      =  TFConvNextModelTester(self						)
										__magic_name__      =  ConfigTester(
										    self    ,     config_class=__lowerCamelCase    ,     has_text_modality=__lowerCamelCase    ,     hidden_size=3_7    ,     )







				@unittest.skip(reason="ConvNext does not use inputs_embeds"						)
				def      _snake_case       (				self				:    Dict						)					->       Dict:
										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[str]						)					->       Tuple:
										super().test_keras_fit()







				@unittest.skip(reason="ConvNext does not support input and output embeddings"						)
				def      _snake_case       (				self				:    str						)					->       Tuple:
										pass







				def      _snake_case       (				self				:    Union[str, Any]						)					->       Optional[int]:
										__magic_name__   ,     __magic_name__      =  self.model_tester.prepare_config_and_inputs_for_common()

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

																__magic_name__      =  ["pixel_values"]
																self.assertListEqual(arg_names[:1]    ,     __lowerCamelCase						)







				def      _snake_case       (				self				:    Dict						)					->       Optional[int]:
										__magic_name__      =  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				:    Optional[int]						)					->       Tuple:
										super().test_dataset_conversion()







				def      _snake_case       (				self				:    int						)					->       List[str]:
										def check_hidden_states_output(__lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Dict    ,     __lowerCamelCase				:    List[str]						):
																__magic_name__      =  model_class(__lowerCamelCase						)

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

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

										__magic_name__   ,     __magic_name__      =  self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																__magic_name__      =  True
																check_hidden_states_output(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase						)

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

																check_hidden_states_output(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase						)







				def      _snake_case       (				self				:    List[str]						)					->       Dict:
										__magic_name__   ,     __magic_name__      =  self.model_tester.prepare_config_and_inputs_for_common()

										def check_equivalence(__lowerCamelCase				:    Dict    ,     __lowerCamelCase				:    Any    ,     __lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Any={}						):
																__magic_name__      =  model(__lowerCamelCase    ,     return_dict=__lowerCamelCase    ,     **__lowerCamelCase						)
																__magic_name__      =  model(__lowerCamelCase    ,     return_dict=__lowerCamelCase    ,     **__lowerCamelCase						).to_tuple()

																def recursive_check(__lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Union[str, Any]						):
																						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:
																__magic_name__      =  model_class(__lowerCamelCase						)

																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase						)
																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase						)
																check_equivalence(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase						)

																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase    ,     return_labels=__lowerCamelCase						)
																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase    ,     return_labels=__lowerCamelCase						)
																check_equivalence(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase						)

																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase						)
																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase						)
																check_equivalence(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase    ,     {"output_hidden_states": True}						)

																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase    ,     return_labels=__lowerCamelCase						)
																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase    ,     return_labels=__lowerCamelCase						)
																check_equivalence(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase    ,     {"output_hidden_states": True}						)







				def      _snake_case       (				self				:    Union[str, Any]						)					->       Dict:
										__magic_name__      =  self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase						)







				@slow
				def      _snake_case       (				self				:    List[str]						)					->       Tuple:
										__magic_name__      =  TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"						)
										self.assertIsNotNone(__lowerCamelCase						)






def _lowerCAmelCase						(	):

						'''simple docstring'''






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


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







				@cached_property
				def      _snake_case       (				self				:    Tuple						)					->       Any:
										return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224"						) if is_vision_available() else None







				@slow
				def      _snake_case       (				self				:    Any						)					->       str:
										__magic_name__      =  TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"						)

										__magic_name__      =  self.default_image_processor
										__magic_name__      =  prepare_img()
										__magic_name__      =  image_processor(images=__lowerCamelCase    ,     return_tensors="tf"						)

										# forward pass
										__magic_name__      =  model(**__lowerCamelCase						)

										# verify the logits
										__magic_name__      =  tf.TensorShape((1, 1_0_0_0)						)
										self.assertEqual(outputs.logits.shape    ,     __lowerCamelCase						)

										__magic_name__      =  tf.constant([-0.0260, -0.4739, 0.1911]						)

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



