import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class 	__snake_case	( a__ ,  unittest.TestCase		):





      '''simple docstring'''






      _snake_case    		=       DiTPipeline
      _snake_case    		=       CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
      _snake_case    		=       PipelineTesterMixin.required_optional_params - {
          'latents',
          'num_images_per_prompt',
          'callback',
          'callback_steps',
      }
      _snake_case    		=       CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
      _snake_case    		=       False



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any])				->str:


          """simple docstring"""


          torch.manual_seed(0)
          _lowerCamelCase     :		List[str] 						=						TransformeraDModel(
              sample_size=16    ,  num_layers=2    ,  patch_size=4    ,  attention_head_dim=8    ,  num_attention_heads=2    ,  in_channels=4    ,  out_channels=8    ,  attention_bias=_A    ,  activation_fn="""gelu-approximate"""    ,  num_embeds_ada_norm=1000    ,  norm_type="""ada_norm_zero"""    ,  norm_elementwise_affine=_A    ,  )
          _lowerCamelCase     :		Union[str, Any] 						=						AutoencoderKL()
          _lowerCamelCase     :		Union[str, Any] 						=						DDIMScheduler()
          _lowerCamelCase     :		Tuple 						=						{'transformer': transformer.eval(), 'vae': vae.eval(), 'scheduler': scheduler}
          return components



      def 	_SCREAMING_SNAKE_CASE    (					self     :				int    ,  _UpperCamelCase     :				Any    ,  _UpperCamelCase     :				Union[str, Any]=0)				->List[Any]:


          """simple docstring"""


          if str(_A).startswith("""mps"""):
              _lowerCamelCase     :		Dict 						=						torch.manual_seed(_A)
          else:
              _lowerCamelCase     :		int 						=						torch.Generator(device=_A).manual_seed(_A)
          _lowerCamelCase     :		Tuple 						=						{
              'class_labels': [1],
              'generator': generator,
              'num_inference_steps': 2,
              'output_type': 'numpy',
          }
          return inputs



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[Any])				->Dict:


          """simple docstring"""


          _lowerCamelCase     :		List[str] 						=						'cpu'

          _lowerCamelCase     :		Optional[int] 						=						self.get_dummy_components()
          _lowerCamelCase     :		Optional[Any] 						=						self.pipeline_class(**_A)
          pipe.to(_A)
          pipe.set_progress_bar_config(disable=_A)

          _lowerCamelCase     :		Tuple 						=						self.get_dummy_inputs(_A)
          _lowerCamelCase     :		Dict 						=						pipe(**_A).images
          _lowerCamelCase     :		Optional[int] 						=						image[0, -3:, -3:, -1]

          self.assertEqual(image.shape    ,  (1, 16, 16, 3))
          _lowerCamelCase     :		List[str] 						=						np.array([0.2_9_4_6, 0.6_6_0_1, 0.4_3_2_9, 0.3_2_9_6, 0.4_1_4_4, 0.5_3_1_9, 0.7_2_7_3, 0.5_0_1_3, 0.4_4_5_7])
          _lowerCamelCase     :		int 						=						np.abs(image_slice.flatten() - expected_slice).max()
          self.assertLessEqual(_A    ,  1E-3)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any])				->Optional[Any]:


          """simple docstring"""


          self._test_inference_batch_single_identical(relax_max_difference=_A    ,  expected_max_diff=1E-3)




      @unittest.skipIf(
          torch_device != """cuda""" or not is_xformers_available()    ,  reason="""XFormers attention is only available with CUDA and `xformers` installed"""    ,  )
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Dict)				->Any:


          """simple docstring"""


          self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3)





@require_torch_gpu
@slow
class 	__snake_case	( unittest.TestCase		):





      '''simple docstring'''






      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[str])				->Any:


          """simple docstring"""


          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()



      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[Any])				->Tuple:


          """simple docstring"""


          _lowerCamelCase     :		Tuple 						=						torch.manual_seed(0)

          _lowerCamelCase     :		Any 						=						DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256""")
          pipe.to("""cuda""")

          _lowerCamelCase     :		List[Any] 						=						['vase', 'umbrella', 'white shark', 'white wolf']
          _lowerCamelCase     :		str 						=						pipe.get_label_ids(_A)

          _lowerCamelCase     :		Dict 						=						pipe(_A    ,  generator=_A    ,  num_inference_steps=40    ,  output_type="""np""").images

          for word, image in zip(_A    ,  _A):
              _lowerCamelCase     :		Any 						=						load_numpy(
                  F"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy""")
              assert np.abs((expected_image - image).max()) < 1E-2




      def 	_SCREAMING_SNAKE_CASE    (					self     :				str)				->Optional[Any]:


          """simple docstring"""


          _lowerCamelCase     :		Optional[int] 						=						DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512""")
          _lowerCamelCase     :		List[Any] 						=						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
          pipe.to("""cuda""")

          _lowerCamelCase     :		str 						=						['vase', 'umbrella']
          _lowerCamelCase     :		Any 						=						pipe.get_label_ids(_A)

          _lowerCamelCase     :		Optional[Any] 						=						torch.manual_seed(0)
          _lowerCamelCase     :		List[str] 						=						pipe(_A    ,  generator=_A    ,  num_inference_steps=25    ,  output_type="""np""").images

          for word, image in zip(_A    ,  _A):
              _lowerCamelCase     :		int 						=						load_numpy(
                  """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                  F"""/dit/{word}_512.npy""")

              assert np.abs((expected_image - image).max()) < 1E-1





from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


lowerCAmelCase			:							Any     =logging.get_logger(__name__)

lowerCAmelCase			:							List[Any]     ={
    "microsoft/swin-tiny-patch4-window7-224": (
        "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json"
    ),
    # See all Swin models at https://huggingface.co/models?filter=swin
}




class 	__snake_case	( __lowerCAmelCase ,  __lowerCAmelCase		):





      '''simple docstring'''






      _snake_case    		=       'swin'

      _snake_case    		=       {
          'num_attention_heads': 'num_heads',
          'num_hidden_layers': 'num_layers',
      }



      def __init__(					self     :				Optional[int]    ,  _UpperCamelCase     :				List[str]=224    ,  _UpperCamelCase     :				List[str]=4    ,  _UpperCamelCase     :				List[Any]=3    ,  _UpperCamelCase     :				Dict=96    ,  _UpperCamelCase     :				Any=[2, 2, 6, 2]    ,  _UpperCamelCase     :				Any=[3, 6, 12, 24]    ,  _UpperCamelCase     :				Tuple=7    ,  _UpperCamelCase     :				Tuple=4.0    ,  _UpperCamelCase     :				Dict=True    ,  _UpperCamelCase     :				Tuple=0.0    ,  _UpperCamelCase     :				Any=0.0    ,  _UpperCamelCase     :				Optional[int]=0.1    ,  _UpperCamelCase     :				Any="gelu"    ,  _UpperCamelCase     :				str=False    ,  _UpperCamelCase     :				str=0.0_2    ,  _UpperCamelCase     :				Dict=1E-5    ,  _UpperCamelCase     :				List[str]=32    ,  _UpperCamelCase     :				Optional[Any]=None    ,  _UpperCamelCase     :				List[Any]=None    ,  **_UpperCamelCase     :				List[Any]    ,  )				->Tuple:


          """simple docstring"""


          super().__init__(**_UpperCamelCase)

          _lowerCamelCase     :		List[str] 						=						image_size
          _lowerCamelCase     :		Tuple 						=						patch_size
          _lowerCamelCase     :		Dict 						=						num_channels
          _lowerCamelCase     :		Union[str, Any] 						=						embed_dim
          _lowerCamelCase     :		str 						=						depths
          _lowerCamelCase     :		str 						=						len(_UpperCamelCase)
          _lowerCamelCase     :		Optional[Any] 						=						num_heads
          _lowerCamelCase     :		Tuple 						=						window_size
          _lowerCamelCase     :		int 						=						mlp_ratio
          _lowerCamelCase     :		Optional[int] 						=						qkv_bias
          _lowerCamelCase     :		List[str] 						=						hidden_dropout_prob
          _lowerCamelCase     :		str 						=						attention_probs_dropout_prob
          _lowerCamelCase     :		Tuple 						=						drop_path_rate
          _lowerCamelCase     :		List[str] 						=						hidden_act
          _lowerCamelCase     :		Dict 						=						use_absolute_embeddings
          _lowerCamelCase     :		int 						=						layer_norm_eps
          _lowerCamelCase     :		str 						=						initializer_range
          _lowerCamelCase     :		Dict 						=						encoder_stride
          # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
          # this indicates the channel dimension after the last stage of the model
          _lowerCamelCase     :		int 						=						int(embed_dim * 2 ** (len(_UpperCamelCase) - 1))
          _lowerCamelCase     :		Dict 						=						["""stem"""] + [F"""stage{idx}""" for idx in range(1    ,  len(_UpperCamelCase) + 1)]
          _lowerCamelCase						,							_lowerCamelCase     :		List[str] 						=						get_aligned_output_features_output_indices(
              out_features=_UpperCamelCase    ,  out_indices=_UpperCamelCase    ,  stage_names=self.stage_names)





class 	__snake_case	( __lowerCAmelCase		):





      '''simple docstring'''






      _snake_case    		=       version.parse('1.11'		)



      @property
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->Mapping[str, Mapping[int, str]]:


          """simple docstring"""


          return OrderedDict(
              [
                  ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
              ])




      @property
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any])				->float:


          """simple docstring"""


          return 1E-4




