



"""simple docstring"""
import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
  import torch

  from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin
class 							_UpperCAmelCase							:





     '''simple docstring'''



     def __init__(					self       ,	A       ,	A=None       ,	A=None       ,	A=None       ,	A="resnet50"       ,	A=3       ,	A=3_2       ,	A=3       ,	A=True       ,	A=True       ,	)							->					List[str]:
         _UpperCAmelCase							:  Optional[Any]											=    parent
         _UpperCAmelCase							:  Union[str, Any]											=    out_indices if out_indices is not None else [4]
         _UpperCAmelCase							:  Dict											=    stage_names
         _UpperCAmelCase							:  List[str]											=    out_features
         _UpperCAmelCase							:  List[str]											=    backbone
         _UpperCAmelCase							:  str											=    batch_size
         _UpperCAmelCase							:  Optional[int]											=    image_size
         _UpperCAmelCase							:  Dict											=    num_channels
         _UpperCAmelCase							:  List[Any]											=    use_pretrained_backbone
         _UpperCAmelCase							:  List[Any]											=    is_training





     def  __lowerCAmelCase	(					self		)							->					Optional[int]:
         _UpperCAmelCase							:  Any											=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)
         _UpperCAmelCase							:  Tuple											=    self.get_config()

         return config, pixel_values





     def  __lowerCAmelCase	(					self		)							->					str:
         return TimmBackboneConfig(
             image_size=self.image_size       ,	num_channels=self.num_channels       ,	out_features=self.out_features       ,	out_indices=self.out_indices       ,	stage_names=self.stage_names       ,	use_pretrained_backbone=self.use_pretrained_backbone       ,	backbone=self.backbone       ,	)





     def  __lowerCAmelCase	(					self       ,	A       ,	A		)							->					Dict:
         _UpperCAmelCase							:  Optional[int]											=    TimmBackbone(config=A		)
         model.to(A		)
         model.eval()
         with torch.no_grad():
             _UpperCAmelCase							:  int											=    model(A		)
         self.parent.assertEqual(
             result.feature_map[-1].shape       ,	(self.batch_size, model.channels[-1], 1_4, 1_4)       ,	)





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



@require_torch
@require_timm
class 							_UpperCAmelCase							( a		,a		,a		,unittest.TestCase      ):





     '''simple docstring'''



     a__									=(TimmBackbone,) if is_torch_available() else ()
     a__									={'''feature-extraction''': TimmBackbone} if is_torch_available() else {}
     a__									=False
     a__									=False
     a__									=False
     a__									=False





     def  __lowerCAmelCase	(					self		)							->					Dict:
         _UpperCAmelCase							:  Any											=    TimmBackboneModelTester(self		)
         _UpperCAmelCase							:  Optional[Any]											=    ConfigTester(self       ,	config_class=A       ,	has_text_modality=A		)





     def  __lowerCAmelCase	(					self		)							->					Dict:
         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		)							->					List[str]:
         _UpperCAmelCase							:  str											=    '''resnet18'''
         _UpperCAmelCase							:  int											=    '''microsoft/resnet-18'''

         _UpperCAmelCase							:  List[str]											=    AutoBackbone.from_pretrained(A       ,	use_timm_backbone=A		)
         _UpperCAmelCase							:  int											=    AutoBackbone.from_pretrained(A		)

         self.assertEqual(len(timm_model.out_features		)       ,	len(transformers_model.out_features		)		)
         self.assertEqual(len(timm_model.stage_names		)       ,	len(transformers_model.stage_names		)		)
         self.assertEqual(timm_model.channels       ,	transformers_model.channels		)
         # Out indices are set to the last layer by default. For timm models, we don't know
         # the number of layers in advance, so we set it to (-1,), whereas for transformers
         # models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
         self.assertEqual(timm_model.out_indices       ,	(-1,)		)
         self.assertEqual(transformers_model.out_indices       ,	[len(timm_model.stage_names		) - 1]		)

         _UpperCAmelCase							:  Any											=    AutoBackbone.from_pretrained(A       ,	use_timm_backbone=A       ,	out_indices=[1, 2, 3]		)
         _UpperCAmelCase							:  Any											=    AutoBackbone.from_pretrained(A       ,	out_indices=[1, 2, 3]		)

         self.assertEqual(timm_model.out_indices       ,	transformers_model.out_indices		)
         self.assertEqual(len(timm_model.out_features		)       ,	len(transformers_model.out_features		)		)
         self.assertEqual(timm_model.channels       ,	transformers_model.channels		)





     @unittest.skip('''TimmBackbone doesn\'t support feed forward chunking'''		)
     def  __lowerCAmelCase	(					self		)							->					List[Any]:
         pass





     @unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute'''		)
     def  __lowerCAmelCase	(					self		)							->					Any:
         pass





     @unittest.skip('''TimmBackbone initialization is managed on the timm side'''		)
     def  __lowerCAmelCase	(					self		)							->					List[str]:
         pass





     @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''		)
     def  __lowerCAmelCase	(					self		)							->					Tuple:
         pass





     @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''		)
     def  __lowerCAmelCase	(					self		)							->					Optional[Any]:
         pass





     @unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint'''		)
     def  __lowerCAmelCase	(					self		)							->					int:
         pass





     @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''		)
     def  __lowerCAmelCase	(					self		)							->					Optional[Any]:
         pass





     @unittest.skip('''model weights aren\'t tied in TimmBackbone.'''		)
     def  __lowerCAmelCase	(					self		)							->					Union[str, Any]:
         pass





     @unittest.skip('''model weights aren\'t tied in TimmBackbone.'''		)
     def  __lowerCAmelCase	(					self		)							->					Dict:
         pass





     @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''		)
     def  __lowerCAmelCase	(					self		)							->					Dict:
         pass





     @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''		)
     def  __lowerCAmelCase	(					self		)							->					List[str]:
         pass





     @unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.'''		)
     def  __lowerCAmelCase	(					self		)							->					List[Any]:
         pass





     @unittest.skip('''TimmBackbone doesn\'t support output_attentions.'''		)
     def  __lowerCAmelCase	(					self		)							->					List[str]:
         pass





     @unittest.skip('''Safetensors is not supported by timm.'''		)
     def  __lowerCAmelCase	(					self		)							->					Union[str, Any]:
         pass





     @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''		)
     def  __lowerCAmelCase	(					self		)							->					int:
         pass





     def  __lowerCAmelCase	(					self		)							->					Any:
         _UpperCAmelCase							,				_UpperCAmelCase							:  Optional[Any]											=    self.model_tester.prepare_config_and_inputs_for_common()

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

             _UpperCAmelCase							:  Optional[int]											=    ['''pixel_values''']
             self.assertListEqual(arg_names[:1]       ,	A		)





     def  __lowerCAmelCase	(					self		)							->					Dict:
         _UpperCAmelCase							,				_UpperCAmelCase							:  Tuple											=    self.model_tester.prepare_config_and_inputs_for_common()
         _UpperCAmelCase							:  Optional[int]											=    True
         _UpperCAmelCase							:  Dict											=    self.has_attentions

         # no need to test all models as different heads yield the same functionality
         _UpperCAmelCase							:  Dict											=    self.all_model_classes[0]
         _UpperCAmelCase							:  List[Any]											=    model_class(A		)
         model.to(A		)

         _UpperCAmelCase							:  str											=    self._prepare_for_class(A       ,	A		)
         _UpperCAmelCase							:  str											=    model(**A		)
         _UpperCAmelCase							:  Optional[int]											=    outputs[0][-1]

         # Encoder-/Decoder-only models
         _UpperCAmelCase							:  Any											=    outputs.hidden_states[0]
         hidden_states.retain_grad()

         if self.has_attentions:
             _UpperCAmelCase							:  str											=    outputs.attentions[0]
             attentions.retain_grad()

         output.flatten()[0].backward(retain_graph=A		)

         self.assertIsNotNone(hidden_states.grad		)

         if self.has_attentions:
             self.assertIsNotNone(attentions.grad		)





     def  __lowerCAmelCase	(					self		)							->					Any:
         _UpperCAmelCase							,				_UpperCAmelCase							:  Dict											=    self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             _UpperCAmelCase							:  Dict											=    model_class(A		)
             model.to(A		)
             model.eval()
             _UpperCAmelCase							:  str											=    model(**A		)

             self.assertEqual(len(result.feature_maps		)       ,	len(config.out_indices		)		)
             self.assertEqual(len(model.channels		)       ,	len(config.out_indices		)		)

             # Check output of last stage is taken if out_features=None, out_indices=None
             _UpperCAmelCase							:  int											=    copy.deepcopy(A		)
             _UpperCAmelCase							:  List[str]											=    None
             _UpperCAmelCase							:  Optional[Any]											=    model_class(A		)
             model.to(A		)
             model.eval()
             _UpperCAmelCase							:  Union[str, Any]											=    model(**A		)

             self.assertEqual(len(result.feature_maps		)       ,	1		)
             self.assertEqual(len(model.channels		)       ,	1		)

             # Check backbone can be initialized with fresh weights
             _UpperCAmelCase							:  Optional[Any]											=    copy.deepcopy(A		)
             _UpperCAmelCase							:  Dict											=    False
             _UpperCAmelCase							:  List[Any]											=    model_class(A		)
             model.to(A		)
             model.eval()
             _UpperCAmelCase							:  Optional[Any]											=    model(**A		)







"""simple docstring"""
import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


_lowerCAmelCase    :Optional[Any]     =					False
class 							_UpperCAmelCase							( unittest.TestCase      ):





     '''simple docstring'''



     pass



@nightly
@require_torch_gpu
class 							_UpperCAmelCase							( unittest.TestCase      ):





     '''simple docstring'''



     def  __lowerCAmelCase	(					self		)							->					List[Any]:
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()





     def  __lowerCAmelCase	(					self		)							->					Dict:
         _UpperCAmelCase							:  Tuple											=    VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion'''       ,	torch_dtype=torch.floataa		)
         pipe.to(A		)
         pipe.set_progress_bar_config(disable=A		)

         _UpperCAmelCase							:  List[str]											=    load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''		)

         _UpperCAmelCase							:  Optional[Any]											=    torch.manual_seed(0		)
         _UpperCAmelCase							:  List[Any]											=    pipe.dual_guided(
             prompt='''first prompt'''       ,	image=A       ,	text_to_image_strength=0.75       ,	generator=A       ,	guidance_scale=7.5       ,	num_inference_steps=2       ,	output_type='''numpy'''       ,	).images

         with tempfile.TemporaryDirectory() as tmpdirname:
             pipe.save_pretrained(A		)
             _UpperCAmelCase							:  int											=    VersatileDiffusionPipeline.from_pretrained(A       ,	torch_dtype=torch.floataa		)
         pipe.to(A		)
         pipe.set_progress_bar_config(disable=A		)

         _UpperCAmelCase							:  int											=    generator.manual_seed(0		)
         _UpperCAmelCase							:  Union[str, Any]											=    pipe.dual_guided(
             prompt='''first prompt'''       ,	image=A       ,	text_to_image_strength=0.75       ,	generator=A       ,	guidance_scale=7.5       ,	num_inference_steps=2       ,	output_type='''numpy'''       ,	).images

         assert np.abs(image - new_image		).sum() < 1E-5, "Models don't have the same forward pass"





     def  __lowerCAmelCase	(					self		)							->					List[str]:
         _UpperCAmelCase							:  List[Any]											=    VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion'''       ,	torch_dtype=torch.floataa		)
         pipe.to(A		)
         pipe.set_progress_bar_config(disable=A		)

         _UpperCAmelCase							:  int											=    '''cyberpunk 2077'''
         _UpperCAmelCase							:  Optional[int]											=    load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''		)
         _UpperCAmelCase							:  str											=    torch.manual_seed(0		)
         _UpperCAmelCase							:  Optional[Any]											=    pipe.dual_guided(
             prompt=A       ,	image=A       ,	text_to_image_strength=0.75       ,	generator=A       ,	guidance_scale=7.5       ,	num_inference_steps=5_0       ,	output_type='''numpy'''       ,	).images

         _UpperCAmelCase							:  Union[str, Any]											=    image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _UpperCAmelCase							:  List[Any]											=    np.array([0.1_448, 0.1_619, 0.1_741, 0.1_086, 0.1_147, 0.1_128, 0.1_199, 0.1_165, 0.1_001]		)

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

         _UpperCAmelCase							:  Dict											=    '''A painting of a squirrel eating a burger '''
         _UpperCAmelCase							:  Tuple											=    torch.manual_seed(0		)
         _UpperCAmelCase							:  Optional[Any]											=    pipe.text_to_image(
             prompt=A       ,	generator=A       ,	guidance_scale=7.5       ,	num_inference_steps=5_0       ,	output_type='''numpy'''		).images

         _UpperCAmelCase							:  Tuple											=    image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _UpperCAmelCase							:  int											=    np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778]		)

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

         _UpperCAmelCase							:  int											=    pipe.image_variation(A       ,	generator=A       ,	output_type='''numpy'''		).images

         _UpperCAmelCase							:  Optional[int]											=    image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _UpperCAmelCase							:  List[str]											=    np.array([0.3_076, 0.3_123, 0.3_284, 0.3_782, 0.3_770, 0.3_894, 0.4_297, 0.4_331, 0.4_456]		)

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


