




"""simple docstring"""




import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
					from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor






class 					__magic_name__							:






				'''simple docstring'''





				def __init__( self	,				_a	,				_a=13	,				_a=32	,				_a=3	,				_a=4	,				_a=[10, 20, 30, 40]	,				_a=[2, 2, 3, 2]	,				_a=True	,				_a=True	,				_a=37	,				_a="gelu"	,				_a=10	,				_a=0.02	,				_a=["stage2", "stage3", "stage4"]	,				_a=[2, 3, 4]	,				_a=None	,				):





							"""simple docstring"""
							lowerCamelCase       =      parent
							lowerCamelCase       =      batch_size
							lowerCamelCase       =      image_size
							lowerCamelCase       =      num_channels
							lowerCamelCase       =      num_stages
							lowerCamelCase       =      hidden_sizes
							lowerCamelCase       =      depths
							lowerCamelCase       =      is_training
							lowerCamelCase       =      use_labels
							lowerCamelCase       =      intermediate_size
							lowerCamelCase       =      hidden_act
							lowerCamelCase       =      num_labels
							lowerCamelCase       =      initializer_range
							lowerCamelCase       =      out_features
							lowerCamelCase       =      out_indices
							lowerCamelCase       =      scope





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							lowerCamelCase       =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

							lowerCamelCase       =      self.get_config()

							return config, pixel_values, labels





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							return ConvNextVaConfig(
							    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=_a	,				initializer_range=self.initializer_range	,				out_features=self.out_features	,				out_indices=self.out_indices	,				num_labels=self.num_labels	,				)





				def      _lowerCAmelCase       ( self	,				_a	,				_a	,				_a				):





							"""simple docstring"""
							lowerCamelCase       =      ConvNextVaModel(config=_a				)
							model.to(_a				)
							model.eval()
							lowerCamelCase       =      model(_a				)
							# 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	,				_a	,				_a	,				_a				):





							"""simple docstring"""
							lowerCamelCase       =      ConvNextVaForImageClassification(_a				)
							model.to(_a				)
							model.eval()
							lowerCamelCase       =      model(_a	,				labels=_a				)
							self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.num_labels)				)





				def      _lowerCAmelCase       ( self	,				_a	,				_a	,				_a				):





							"""simple docstring"""
							lowerCamelCase       =      ConvNextVaBackbone(config=_a				)
							model.to(_a				)
							model.eval()
							lowerCamelCase       =      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, self.hidden_sizes[1], 4, 4]				)

							# verify channels
							self.parent.assertEqual(len(model.channels				)	,				len(config.out_features				)				)
							self.parent.assertListEqual(model.channels	,				config.hidden_sizes[1:]				)

							# verify backbone works with out_features=None
							lowerCamelCase       =      None
							lowerCamelCase       =      ConvNextVaBackbone(config=_a				)
							model.to(_a				)
							model.eval()
							lowerCamelCase       =      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, self.hidden_sizes[-1], 1, 1]				)

							# verify channels
							self.parent.assertEqual(len(model.channels				)	,				1				)
							self.parent.assertListEqual(model.channels	,				[config.hidden_sizes[-1]]				)





				def      _lowerCAmelCase       ( self				):





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





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							lowerCamelCase       =      self.prepare_config_and_inputs()
							lowerCamelCase   ,     lowerCamelCase   ,     lowerCamelCase       =      config_and_inputs
							lowerCamelCase       =      {"""pixel_values""": pixel_values, """labels""": labels}
							return config, inputs_dict






@require_torch
class 					__magic_name__							( UpperCAmelCase__		,      UpperCAmelCase__		,      unittest.TestCase       ):






				'''simple docstring'''
				__UpperCamelCase    						=		(
				    (
				        ConvNextVaModel,
				        ConvNextVaForImageClassification,
				        ConvNextVaBackbone,
				    )
				    if is_torch_available()
				    else ()
				)
				__UpperCamelCase    						=		(
				    {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
				    if is_torch_available()
				    else {}
				)

				__UpperCamelCase    						=		False
				__UpperCamelCase    						=		False
				__UpperCamelCase    						=		False
				__UpperCamelCase    						=		False
				__UpperCamelCase    						=		False





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							lowerCamelCase       =      ConvNextVaModelTester(self				)
							lowerCamelCase       =      ConfigTester(self	,				config_class=_a	,				has_text_modality=_a	,				hidden_size=37				)





				def      _lowerCAmelCase       ( self				):





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





							"""simple docstring"""
							return





				@unittest.skip(reason="""ConvNextV2 does not use inputs_embeds"""				)
				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							pass





				@unittest.skip(reason="""ConvNextV2 does not support input and output embeddings"""				)
				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							pass





				@unittest.skip(reason="""ConvNextV2 does not use feedforward chunking"""				)
				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							pass





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							if not self.model_tester.is_training:
										return

							for model_class in self.all_model_classes:
										lowerCamelCase   ,     lowerCamelCase       =      self.model_tester.prepare_config_and_inputs_with_labels()
										lowerCamelCase       =      True

										if model_class.__name__ in [
										    *get_values(_a				),
										    *get_values(_a				),
										]:
													continue

										lowerCamelCase       =      model_class(_a				)
										model.to(_a				)
										model.train()
										lowerCamelCase       =      self._prepare_for_class(_a	,				_a	,				return_labels=_a				)
										lowerCamelCase       =      model(**_a				).loss
										loss.backward()





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							if not self.model_tester.is_training:
										return

							for model_class in self.all_model_classes:
										lowerCamelCase   ,     lowerCamelCase       =      self.model_tester.prepare_config_and_inputs_with_labels()
										lowerCamelCase       =      False
										lowerCamelCase       =      True

										if (
										    model_class.__name__
										    in [*get_values(_a				), *get_values(_a				)]
										    or not model_class.supports_gradient_checkpointing
										):
													continue

										lowerCamelCase       =      model_class(_a				)
										model.to(_a				)
										model.gradient_checkpointing_enable()
										model.train()
										lowerCamelCase       =      self._prepare_for_class(_a	,				_a	,				return_labels=_a				)
										lowerCamelCase       =      model(**_a				).loss
										loss.backward()





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							lowerCamelCase   ,     lowerCamelCase       =      self.model_tester.prepare_config_and_inputs_for_common()

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

										lowerCamelCase       =      ["""pixel_values"""]
										self.assertListEqual(arg_names[:1]	,				_a				)





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							lowerCamelCase       =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_a				)





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							def check_hidden_states_output(_a	,				_a	,				_a				):
										lowerCamelCase       =      model_class(_a				)
										model.to(_a				)
										model.eval()

										with torch.no_grad():
													lowerCamelCase       =      model(**self._prepare_for_class(_a	,				_a				)				)

										lowerCamelCase       =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

										lowerCamelCase       =      self.model_tester.num_stages
										self.assertEqual(len(_a				)	,				expected_num_stages + 1				)

										# ConvNextV2'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]	,				)

							lowerCamelCase   ,     lowerCamelCase       =      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										lowerCamelCase       =      True
										check_hidden_states_output(_a	,				_a	,				_a				)

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

										check_hidden_states_output(_a	,				_a	,				_a				)





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							lowerCamelCase       =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_a				)





				@slow
				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowerCamelCase       =      ConvNextVaModel.from_pretrained(_a				)
										self.assertIsNotNone(_a				)




def 					a__				(       )		->      List[Any]:
			lowerCamelCase       =      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""       )
			return image






@require_torch
@require_vision
class 					__magic_name__							( unittest.TestCase       ):






				'''simple docstring'''





				@cached_property
				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224"""				) if is_vision_available() else None





				@slow
				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							lowerCamelCase       =      ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224"""				).to(_a				)

							lowerCamelCase       =      self.default_image_processor
							lowerCamelCase       =      prepare_img()
							lowerCamelCase       =      preprocessor(images=_a	,				return_tensors="""pt"""				).to(_a				)

							# forward pass
							with torch.no_grad():
										lowerCamelCase       =      model(**_a				)

							# verify the logits
							lowerCamelCase       =      torch.Size((1, 1_000)				)
							self.assertEqual(outputs.logits.shape	,				_a				)

							lowerCamelCase       =      torch.tensor([0.9_996, 0.1_966, -0.4_386]				).to(_a				)
							self.assertTrue(torch.allclose(outputs.logits[0, :3]	,				_a	,				atol=1e-4				)				)









"""simple docstring"""




import unittest

import numpy as np
import torch

from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()






class 					__magic_name__							( unittest.TestCase       ):






				'''simple docstring'''





				@property
				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							torch.manual_seed(0				)
							lowerCamelCase       =      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      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							lowerCamelCase       =      self.dummy_uncond_unet
							lowerCamelCase       =      ScoreSdeVeScheduler()

							lowerCamelCase       =      ScoreSdeVePipeline(unet=_a	,				scheduler=_a				)
							sde_ve.to(_a				)
							sde_ve.set_progress_bar_config(disable=_a				)

							lowerCamelCase       =      torch.manual_seed(0				)
							lowerCamelCase       =      sde_ve(num_inference_steps=2	,				output_type="""numpy"""	,				generator=_a				).images

							lowerCamelCase       =      torch.manual_seed(0				)
							lowerCamelCase       =      sde_ve(num_inference_steps=2	,				output_type="""numpy"""	,				generator=_a	,				return_dict=_a				)[
							    0
							]

							lowerCamelCase       =      image[0, -3:, -3:, -1]
							lowerCamelCase       =      image_from_tuple[0, -3:, -3:, -1]

							assert image.shape == (1, 32, 32, 3)
							lowerCamelCase       =      np.array([0.0, 1.0, 0.0, 0.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 					__magic_name__							( unittest.TestCase       ):






				'''simple docstring'''





				def      _lowerCAmelCase       ( self				):





							"""simple docstring"""
							lowerCamelCase       =      """google/ncsnpp-church-256"""
							lowerCamelCase       =      UNetaDModel.from_pretrained(_a				)

							lowerCamelCase       =      ScoreSdeVeScheduler.from_pretrained(_a				)

							lowerCamelCase       =      ScoreSdeVePipeline(unet=_a	,				scheduler=_a				)
							sde_ve.to(_a				)
							sde_ve.set_progress_bar_config(disable=_a				)

							lowerCamelCase       =      torch.manual_seed(0				)
							lowerCamelCase       =      sde_ve(num_inference_steps=10	,				output_type="""numpy"""	,				generator=_a				).images

							lowerCamelCase       =      image[0, -3:, -3:, -1]

							assert image.shape == (1, 256, 256, 3)

							lowerCamelCase       =      np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0]				)

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



