"""simple docstring"""







import collections
import inspect
import unittest

from transformers import DonutSwinConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

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 DonutSwinModel
       from transformers.models.donut.modeling_donut_swin import DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST






class 							__snake_case:


    '''simple docstring'''





    def __init__(  self					,       __lowerCamelCase					,       __lowerCamelCase=13					,       __lowerCamelCase=32					,       __lowerCamelCase=2					,       __lowerCamelCase=3					,       __lowerCamelCase=16					,       __lowerCamelCase=[1, 2, 1]					,       __lowerCamelCase=[2, 2, 4]					,       __lowerCamelCase=2					,       __lowerCamelCase=2.0					,       __lowerCamelCase=True					,       __lowerCamelCase=0.0					,       __lowerCamelCase=0.0					,       __lowerCamelCase=0.1					,       __lowerCamelCase="gelu"					,       __lowerCamelCase=False					,       __lowerCamelCase=True					,       __lowerCamelCase=0.02					,       __lowerCamelCase=1e-5					,       __lowerCamelCase=True					,       __lowerCamelCase=None					,       __lowerCamelCase=True					,       __lowerCamelCase=10					,       __lowerCamelCase=8					,       ):




         '''simple docstring'''



         __A					:					Dict								=		parent
         __A					:					List[str]								=		batch_size
         __A					:					List[Any]								=		image_size
         __A					:					Any								=		patch_size
         __A					:					Tuple								=		num_channels
         __A					:					List[Any]								=		embed_dim
         __A					:					Any								=		depths
         __A					:					str								=		num_heads
         __A					:					Tuple								=		window_size
         __A					:					Dict								=		mlp_ratio
         __A					:					str								=		qkv_bias
         __A					:					Optional[Any]								=		hidden_dropout_prob
         __A					:					List[Any]								=		attention_probs_dropout_prob
         __A					:					Optional[Any]								=		drop_path_rate
         __A					:					int								=		hidden_act
         __A					:					str								=		use_absolute_embeddings
         __A					:					Optional[int]								=		patch_norm
         __A					:					int								=		layer_norm_eps
         __A					:					Union[str, Any]								=		initializer_range
         __A					:					int								=		is_training
         __A					:					List[str]								=		scope
         __A					:					Dict								=		use_labels
         __A					:					str								=		type_sequence_label_size
         __A					:					List[str]								=		encoder_stride
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[int]								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

         __A					:					str								=		None
         if self.use_labels:
              __A					:					Optional[Any]								=		ids_tensor([self.batch_size]					,       self.type_sequence_label_size	)

         __A					:					Optional[int]								=		self.get_config()

         return config, pixel_values, labels
    def 						_a							(  self	):




         '''simple docstring'''



         return DonutSwinConfig(
             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					,       window_size=self.window_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					,       use_absolute_embeddings=self.use_absolute_embeddings					,       path_norm=self.patch_norm					,       layer_norm_eps=self.layer_norm_eps					,       initializer_range=self.initializer_range					,       encoder_stride=self.encoder_stride					,       )
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					Optional[int]								=		DonutSwinModel(config=__lowerCamelCase	)
         model.to(__lowerCamelCase	)
         model.eval()
         __A					:					Optional[int]								=		model(__lowerCamelCase	)

         __A					:					Optional[Any]								=		((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths	) - 1))
         __A					:					List[str]								=		int(config.embed_dim * 2 ** (len(config.depths	) - 1)	)

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

    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Any								=		self.prepare_config_and_inputs()
         (
             (
             __A
         )						,		(
             __A
         )						,		(
             __A
         )						,		
         )					:					Dict								=		config_and_inputs
         __A					:					int								=		{'pixel_values': pixel_values}
         return config, inputs_dict







@require_torch
class 							__snake_case(					A_				,	A_				,	unittest.TestCase	):


    '''simple docstring'''





    _UpperCAmelCase       =			(DonutSwinModel,) if is_torch_available() else ()
    _UpperCAmelCase       =			{"feature-extraction": DonutSwinModel} if is_torch_available() else {}
    _UpperCAmelCase       =			True

    _UpperCAmelCase       =			False
    _UpperCAmelCase       =			False
    _UpperCAmelCase       =			False
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					int								=		DonutSwinModelTester(self	)
         __A					:					Dict								=		ConfigTester(self					,       config_class=__lowerCamelCase					,       embed_dim=37	)
    def 						_a							(  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 						_a							(  self	):




         '''simple docstring'''



         return
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[Any]								=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         pass
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Optional[int]								=		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __A					:					Optional[int]								=		model_class(__lowerCamelCase	)
              self.assertIsInstance(model.get_input_embeddings()					,       (nn.Module)	)
              __A					:					int								=		model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(__lowerCamelCase					,       nn.Linear	)	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Union[str, Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

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

              __A					:					str								=		['pixel_values']
              self.assertListEqual(arg_names[:1]					,       __lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Optional[int]								=		self.model_tester.prepare_config_and_inputs_for_common()
         __A					:					int								=		True

         for model_class in self.all_model_classes:
              __A					:					Any								=		True
              __A					:					Union[str, Any]								=		False
              __A					:					Any								=		True
              __A					:					Optional[Any]								=		model_class(__lowerCamelCase	)
              model.to(__lowerCamelCase	)
              model.eval()
              with torch.no_grad():
                   __A					:					int								=		model(**self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase	)	)
              __A					:					Union[str, Any]								=		outputs.attentions
              __A					:					int								=		len(self.model_tester.depths	)
              self.assertEqual(len(__lowerCamelCase	)					,       __lowerCamelCase	)

              # check that output_attentions also work using config
              del inputs_dict["output_attentions"]
              __A					:					List[str]								=		True
              __A					:					int								=		config.window_size**2
              __A					:					Any								=		model_class(__lowerCamelCase	)
              model.to(__lowerCamelCase	)
              model.eval()
              with torch.no_grad():
                   __A					:					List[Any]								=		model(**self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase	)	)
              __A					:					List[Any]								=		outputs.attentions
              self.assertEqual(len(__lowerCamelCase	)					,       __lowerCamelCase	)

              self.assertListEqual(
                  list(attentions[0].shape[-3:]	)					,       [self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,       )
              __A					:					Optional[int]								=		len(__lowerCamelCase	)

              # Check attention is always last and order is fine
              __A					:					int								=		True
              __A					:					Optional[int]								=		True
              __A					:					str								=		model_class(__lowerCamelCase	)
              model.to(__lowerCamelCase	)
              model.eval()
              with torch.no_grad():
                   __A					:					Optional[Any]								=		model(**self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase	)	)

              if hasattr(self.model_tester					,       'num_hidden_states_types'	):
                   __A					:					List[Any]								=		self.model_tester.num_hidden_states_types
              else:
                   # also another +1 for reshaped_hidden_states
                   __A					:					Union[str, Any]								=		2
              self.assertEqual(out_len + added_hidden_states					,       len(__lowerCamelCase	)	)

              __A					:					int								=		outputs.attentions

              self.assertEqual(len(__lowerCamelCase	)					,       __lowerCamelCase	)

              self.assertListEqual(
                  list(self_attentions[0].shape[-3:]	)					,       [self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,       )
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					Optional[int]								=		model_class(__lowerCamelCase	)
         model.to(__lowerCamelCase	)
         model.eval()

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

         __A					:					str								=		outputs.hidden_states

         __A					:					Optional[Any]								=		getattr(
             self.model_tester					,       'expected_num_hidden_layers'					,       len(self.model_tester.depths	) + 1	)
         self.assertEqual(len(__lowerCamelCase	)					,       __lowerCamelCase	)

         # DonutSwin has a different seq_length
         __A					:					Tuple								=		(
             config.patch_size
             if isinstance(config.patch_size					,       collections.abc.Iterable	)
             else (config.patch_size, config.patch_size)
         )

         __A					:					Tuple								=		(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

         self.assertListEqual(
             list(hidden_states[0].shape[-2:]	)					,       [num_patches, self.model_tester.embed_dim]					,       )

         __A					:					List[Any]								=		outputs.reshaped_hidden_states
         self.assertEqual(len(__lowerCamelCase	)					,       __lowerCamelCase	)

         __A						,		__A						,		__A						,		__A					:					str								=		reshaped_hidden_states[0].shape
         __A					:					Optional[int]								=		(
             reshaped_hidden_states[0].view(__lowerCamelCase					,       __lowerCamelCase					,       height * width	).permute(0					,       2					,       1	)
         )
         self.assertListEqual(
             list(reshaped_hidden_states.shape[-2:]	)					,       [num_patches, self.model_tester.embed_dim]					,       )
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Union[str, Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

         __A					:					Optional[Any]								=		(
             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					:					Any								=		True
              self.check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              __A					:					Any								=		True

              self.check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Optional[Any]								=		self.model_tester.prepare_config_and_inputs_for_common()
         __A					:					int								=		3

         __A					:					Any								=		(
             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)
         )
         __A					:					List[Any]								=		(
             config.patch_size
             if isinstance(config.patch_size					,       collections.abc.Iterable	)
             else (config.patch_size, config.patch_size)
         )

         __A					:					Optional[Any]								=		image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
         __A					:					Dict								=		image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

         for model_class in self.all_model_classes:
              __A					:					List[str]								=		True
              self.check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       (padded_height, padded_width)	)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              __A					:					List[str]								=		True
              self.check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       (padded_height, padded_width)	)
    @slow
    def 						_a							(  self	):




         '''simple docstring'''



         for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __A					:					Any								=		DonutSwinModel.from_pretrained(__lowerCamelCase	)
              self.assertIsNotNone(__lowerCamelCase	)

    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Optional[int]								=		self.model_tester.prepare_config_and_inputs_for_common()

         __A					:					Tuple								=		_config_zero_init(__lowerCamelCase	)
         for model_class in self.all_model_classes:
              __A					:					List[Any]								=		model_class(config=__lowerCamelCase	)
              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'					,       )




"""simple docstring"""







import random
import unittest

import torch

from diffusers import IFImgaImgPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin






@skip_mps
class 							__snake_case(					A_				,	A_				,	unittest.TestCase	):


    '''simple docstring'''





    _UpperCAmelCase       =			IFImgaImgPipeline
    _UpperCAmelCase       =			TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"width", "height"}
    _UpperCAmelCase       =			TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
    _UpperCAmelCase       =			PipelineTesterMixin.required_optional_params - {"latents"}
    def 						_a							(  self	):




         '''simple docstring'''



         return self._get_dummy_components()
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase=0	):




         '''simple docstring'''



         if str(__lowerCamelCase	).startswith('mps'	):
              __A					:					Tuple								=		torch.manual_seed(__lowerCamelCase	)
         else:
              __A					:					int								=		torch.Generator(device=__lowerCamelCase	).manual_seed(__lowerCamelCase	)

         __A					:					str								=		floats_tensor((1, 3, 32, 32)					,       rng=random.Random(__lowerCamelCase	)	).to(__lowerCamelCase	)

         __A					:					str								=		{
             'prompt': 'A painting of a squirrel eating a burger',
             'image': image,
             'generator': generator,
             'num_inference_steps': 2,
             'output_type': 'numpy',
         }

         return inputs
    def 						_a							(  self	):




         '''simple docstring'''



         self._test_save_load_optional_components()
    @unittest.skipIf(
        torch_device != 'cuda' or not is_xformers_available()					,       reason='XFormers attention is only available with CUDA and `xformers` installed'					,       )
    def 						_a							(  self	):




         '''simple docstring'''



         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3	)
    @unittest.skipIf(torch_device != 'cuda'					,       reason='float16 requires CUDA'	)
    def 						_a							(  self	):




         '''simple docstring'''



         super().test_save_load_floataa(expected_max_diff=1e-1	)
    @unittest.skipIf(torch_device != 'cuda'					,       reason='float16 requires CUDA'	)
    def 						_a							(  self	):




         '''simple docstring'''



         super().test_floataa_inference(expected_max_diff=1e-1	)
    def 						_a							(  self	):




         '''simple docstring'''



         self._test_attention_slicing_forward_pass(expected_max_diff=1e-2	)
    def 						_a							(  self	):




         '''simple docstring'''



         self._test_save_load_local()

    def 						_a							(  self	):




         '''simple docstring'''



         self._test_inference_batch_single_identical(
             expected_max_diff=1e-2					,       )



