






import collections
import inspect
import unittest

from transformers import NatConfig
from transformers.testing_utils import require_natten, 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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import NatBackbone, NatForImageClassification, NatModel
				from transformers.models.nat.modeling_nat import NAT_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:      Tuple						,   __A:      Dict						,   __A:      Optional[Any]=13						,   __A:      Optional[Any]=64						,   __A:      int=4						,   __A:      Union[str, Any]=3						,   __A:      int=16						,   __A:      Union[str, Any]=[1, 2, 1]						,   __A:      Union[str, Any]=[2, 4, 8]						,   __A:      str=3						,   __A:      List[Any]=2.0						,   __A:      Any=True						,   __A:      List[str]=0.0						,   __A:      Optional[int]=0.0						,   __A:      Dict=0.1						,   __A:      Any="gelu"						,   __A:      int=True						,   __A:      Union[str, Any]=0.02						,   __A:      List[Any]=1e-5						,   __A:      str=True						,   __A:      Optional[int]=None						,   __A:      List[str]=True						,   __A:      Any=10						,   __A:      Any=["stage1", "stage2"]						,   __A:      List[str]=[1, 2]						,   )			-> Optional[Any]:
												_A									=       parent
												_A									=       batch_size
												_A									=       image_size
												_A									=       patch_size
												_A									=       num_channels
												_A									=       embed_dim
												_A									=       depths
												_A									=       num_heads
												_A									=       kernel_size
												_A									=       mlp_ratio
												_A									=       qkv_bias
												_A									=       hidden_dropout_prob
												_A									=       attention_probs_dropout_prob
												_A									=       drop_path_rate
												_A									=       hidden_act
												_A									=       patch_norm
												_A									=       layer_norm_eps
												_A									=       initializer_range
												_A									=       is_training
												_A									=       scope
												_A									=       use_labels
												_A									=       num_labels
												_A									=       out_features
												_A									=       out_indices

							def 					__A       (     self:      Optional[Any]      )			-> Any:
												_A									=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

												_A									=       None
												if self.use_labels:
																	_A									=       ids_tensor([self.batch_size]						,   self.num_labels      )

												_A									=       self.get_config()

												return config, pixel_values, labels

							def 					__A       (     self:      int      )			-> Any:
												return NatConfig(
												    num_labels=self.num_labels						,   image_size=self.image_size						,   patch_size=self.patch_size						,   num_channels=self.num_channels						,   embed_dim=self.embed_dim						,   depths=self.depths						,   num_heads=self.num_heads						,   kernel_size=self.kernel_size						,   mlp_ratio=self.mlp_ratio						,   qkv_bias=self.qkv_bias						,   hidden_dropout_prob=self.hidden_dropout_prob						,   attention_probs_dropout_prob=self.attention_probs_dropout_prob						,   drop_path_rate=self.drop_path_rate						,   hidden_act=self.hidden_act						,   patch_norm=self.patch_norm						,   layer_norm_eps=self.layer_norm_eps						,   initializer_range=self.initializer_range						,   out_features=self.out_features						,   out_indices=self.out_indices						,   )

							def 					__A       (     self:      str						,   __A:      Tuple						,   __A:      Tuple						,   __A:      int      )			-> int:
												_A									=       NatModel(config=__A      )
												model.to(__A      )
												model.eval()
												_A									=       model(__A      )

												_A									=       _A									=       (config.image_size // config.patch_size) // (2 ** (len(config.depths      ) - 1))
												_A									=       int(config.embed_dim * 2 ** (len(config.depths      ) - 1)      )

												self.parent.assertEqual(
												    result.last_hidden_state.shape						,   (self.batch_size, expected_height, expected_width, expected_dim)      )

							def 					__A       (     self:      str						,   __A:      Tuple						,   __A:      Optional[int]						,   __A:      List[Any]      )			-> str:
												_A									=       NatForImageClassification(__A      )
												model.to(__A      )
												model.eval()
												_A									=       model(__A						,   labels=__A      )
												self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.num_labels)      )

												# test greyscale images
												_A									=       1
												_A									=       NatForImageClassification(__A      )
												model.to(__A      )
												model.eval()

												_A									=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
												_A									=       model(__A      )
												self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.num_labels)      )

							def 					__A       (     self:      List[str]						,   __A:      str						,   __A:      Any						,   __A:      str      )			-> int:
												_A									=       NatBackbone(config=__A      )
												model.to(__A      )
												model.eval()
												_A									=       model(__A      )

												# 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, model.channels[0], 16, 16]      )

												# verify channels
												self.parent.assertEqual(len(model.channels      )						,   len(config.out_features      )      )

												# verify backbone works with out_features=None
												_A									=       None
												_A									=       NatBackbone(config=__A      )
												model.to(__A      )
												model.eval()
												_A									=       model(__A      )

												# verify feature maps
												self.parent.assertEqual(len(result.feature_maps      )						,   1      )
												self.parent.assertListEqual(list(result.feature_maps[0].shape      )						,   [self.batch_size, model.channels[-1], 4, 4]      )

												# verify channels
												self.parent.assertEqual(len(model.channels      )						,   1      )



							def 					__A       (     self:      Optional[Any]      )			-> int:
												_A									=       self.prepare_config_and_inputs()
												_A							,_A							,_A									=       config_and_inputs
												_A									=       {'''pixel_values''': pixel_values}
												return config, inputs_dict





@require_natten
@require_torch
class   SCREAMING_SNAKE_CASE (       snake_case     ,		snake_case     ,		unittest.TestCase    ):





							"""simple docstring"""

							A_       =    (
							    (
							        NatModel,
							        NatForImageClassification,
							        NatBackbone,
							    )
							    if is_torch_available()
							    else ()
							)
							A_       =    (
							    {"feature-extraction": NatModel, "image-classification": NatForImageClassification}
							    if is_torch_available()
							    else {}
							)
							A_       =    False

							A_       =    False
							A_       =    False
							A_       =    False
							A_       =    False

							def 					__A       (     self:      Union[str, Any]      )			-> Any:
												_A									=       NatModelTester(self      )
												_A									=       ConfigTester(self						,   config_class=__A						,   embed_dim=37      )

							def 					__A       (     self:      Optional[int]      )			-> Optional[Any]:
												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 					__A       (     self:      List[Any]      )			-> List[Any]:
												return

							def 					__A       (     self:      str      )			-> Union[str, Any]:
												_A									=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__A      )

							def 					__A       (     self:      List[str]      )			-> Tuple:
												_A									=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__A      )

							def 					__A       (     self:      Tuple      )			-> Dict:
												_A									=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_backbone(*__A      )

							@unittest.skip(reason='''Nat does not use inputs_embeds'''      )
							def 					__A       (     self:      Optional[int]      )			-> Dict:
												pass

							@unittest.skip(reason='''Nat does not use feedforward chunking'''      )
							def 					__A       (     self:      Optional[Any]      )			-> Union[str, Any]:
												pass

							def 					__A       (     self:      Dict      )			-> Union[str, Any]:
												_A							,_A									=       self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_A									=       model_class(__A      )
																	self.assertIsInstance(model.get_input_embeddings()						,   (nn.Module)      )
																	_A									=       model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(__A						,   nn.Linear      )      )

							def 					__A       (     self:      Dict      )			-> int:
												_A							,_A									=       self.model_tester.prepare_config_and_inputs_for_common()

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

																	_A									=       ['''pixel_values''']
																	self.assertListEqual(arg_names[:1]						,   __A      )

							def 					__A       (     self:      Union[str, Any]      )			-> int:
												self.skipTest('''Nat\'s attention operation is handled entirely by NATTEN.'''      )

							def 					__A       (     self:      int						,   __A:      Union[str, Any]						,   __A:      Optional[int]						,   __A:      Tuple						,   __A:      Any      )			-> Any:
												_A									=       model_class(__A      )
												model.to(__A      )
												model.eval()

												with torch.no_grad():
																	_A									=       model(**self._prepare_for_class(__A						,   __A      )      )

												_A									=       outputs.hidden_states

												_A									=       getattr(
												    self.model_tester						,   '''expected_num_hidden_layers'''						,   len(self.model_tester.depths      ) + 1      )
												self.assertEqual(len(__A      )						,   __A      )

												# Nat has a different seq_length
												_A									=       (
												    config.patch_size
												    if isinstance(config.patch_size						,   collections.abc.Iterable      )
												    else (config.patch_size, config.patch_size)
												)

												_A									=       image_size[0] // patch_size[0]
												_A									=       image_size[1] // patch_size[1]

												self.assertListEqual(
												    list(hidden_states[0].shape[-3:]      )						,   [height, width, self.model_tester.embed_dim]						,   )

												if model_class.__name__ != "NatBackbone":
																	_A									=       outputs.reshaped_hidden_states
																	self.assertEqual(len(__A      )						,   __A      )

																	_A							,_A							,_A							,_A									=       reshaped_hidden_states[0].shape
																	_A									=       (
																	    reshaped_hidden_states[0].view(__A						,   __A						,   __A						,   __A      ).permute(0						,   2						,   3						,   1      )
																	)
																	self.assertListEqual(
																	    list(reshaped_hidden_states.shape[-3:]      )						,   [height, width, self.model_tester.embed_dim]						,   )

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

												_A									=       (
												    self.model_tester.image_size
												    if isinstance(self.model_tester.image_size						,   collections.abc.Iterable      )
												    else (self.model_tester.image_size, self.model_tester.image_size)
												)

												for model_class in self.all_model_classes:
																	_A									=       True
																	self.check_hidden_states_output(__A						,   __A						,   __A						,   __A      )

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

																	self.check_hidden_states_output(__A						,   __A						,   __A						,   __A      )

							@slow
							def 					__A       (     self:      Union[str, Any]      )			-> List[str]:
												for model_name in NAT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_A									=       NatModel.from_pretrained(__A      )
																	self.assertIsNotNone(__A      )



							def 					__A       (     self:      List[str]      )			-> List[str]:
												_A							,_A									=       self.model_tester.prepare_config_and_inputs_for_common()

												_A									=       _config_zero_init(__A      )
												for model_class in self.all_model_classes:
																	_A									=       model_class(config=__A      )
																	for name, param in model.named_parameters():
																						if "embeddings" not in name and param.requires_grad:
																											self.assertIn(
																											    ((param.data.mean() * 1e9).round() / 1e9).item()						,   [0.0, 1.0]						,   msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""						,   )





@require_natten
@require_vision
@require_torch
class   SCREAMING_SNAKE_CASE (       unittest.TestCase    ):





							"""simple docstring"""

							@cached_property
							def 					__A       (     self:      int      )			-> str:
												return AutoImageProcessor.from_pretrained('''shi-labs/nat-mini-in1k-224'''      ) if is_vision_available() else None



							@slow
							def 					__A       (     self:      str      )			-> str:
												_A									=       NatForImageClassification.from_pretrained('''shi-labs/nat-mini-in1k-224'''      ).to(__A      )
												_A									=       self.default_image_processor

												_A									=       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
												_A									=       image_processor(images=__A						,   return_tensors='''pt'''      ).to(__A      )

												# forward pass
												with torch.no_grad():
																	_A									=       model(**__A      )

												# verify the logits
												_A									=       torch.Size((1, 10_00)      )
												self.assertEqual(outputs.logits.shape						,   __A      )
												_A									=       torch.tensor([0.3_805, -0.8_676, -0.3_912]      ).to(__A      )
												self.assertTrue(torch.allclose(outputs.logits[0, :3]						,   __A						,   atol=1e-4      )      )





@require_torch
@require_natten
class   SCREAMING_SNAKE_CASE (       unittest.TestCase     ,		snake_case    ):





							"""simple docstring"""

							A_       =    (NatBackbone,) if is_torch_available() else ()
							A_       =    NatConfig

							def 					__A       (     self:      Dict      )			-> str:
												_A									=       NatModelTester(self      )











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   SCREAMING_SNAKE_CASE (       unittest.TestCase    ):





							"""simple docstring"""

							A_       =    "hf-internal-testing/tiny-stable-diffusion-pipe"
							A_       =    1
							A_       =    77
							A_       =    32
							A_       =    4
							A_       =    A_       =    64
							A_       =    torch.manual_seed(0    )

							def 					__A       (     self:      List[Any]						,   __A:      List[Any]=0.9_999      )			-> Dict:
												_A									=       UNetaDConditionModel.from_pretrained(self.model_id						,   subfolder='''unet'''      )
												_A									=       unet.to(__A      )
												_A									=       EMAModel(unet.parameters()						,   decay=__A						,   model_cls=__A						,   model_config=unet.config      )
												return unet, ema_unet

							def 					__A       (     self:      Tuple      )			-> Union[str, Any]:
												_A									=       torch.randn(
												    self.batch_size						,   self.num_in_channels						,   self.latent_height						,   self.latent_width						,   generator=self.generator      ).to(__A      )
												_A									=       torch.randint(0						,   10_00						,   size=(self.batch_size,)						,   generator=self.generator      ).to(__A      )
												_A									=       torch.randn(
												    self.batch_size						,   self.prompt_length						,   self.text_encoder_hidden_dim						,   generator=self.generator      ).to(__A      )
												return noisy_latents, timesteps, encoder_hidden_states

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

							def 					__A       (     self:      Any      )			-> Any:
												_A							,_A									=       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 					__A       (     self:      Union[str, Any]      )			-> str:
												_A							,_A									=       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()      )
												_A									=       list(unet.parameters()      )
												for s_param, param in zip(ema_unet.shadow_params						,   __A      ):
																	assert torch.allclose(__A						,   __A      )

												# 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						,   __A      ):
																	assert torch.allclose(__A						,   __A      )

							def 					__A       (     self:      Tuple      )			-> List[str]:
												_A							,_A									=       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.
												_A									=       self.simulate_backprop(__A      )

												# 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.
												_A									=       list(unet_pseudo_updated_step_one.parameters()      )
												for s_param, param in zip(ema_unet.shadow_params						,   __A      ):
																	assert ~torch.allclose(__A						,   __A      )

												# 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						,   __A      ):
																	assert ~torch.allclose(__A						,   __A      )

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

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

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

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

							def 					__A       (     self:      int      )			-> 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.
												_A							,_A									=       self.get_models(decay=0.0      )
												_A									=       self.simulate_backprop(__A      )
												ema_unet.step(unet_step_one.parameters()      )
												_A									=       ema_unet.shadow_params

												_A									=       self.simulate_backprop(__A      )
												ema_unet.step(unet_step_two.parameters()      )
												_A									=       ema_unet.shadow_params

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



							@skip_mps
							def 					__A       (     self:      Optional[Any]      )			-> List[str]:
												_A							,_A									=       self.get_models()
												_A							,_A							,_A									=       self.get_dummy_inputs()

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

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

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



