
"""simple docstring"""






import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu




class 				lowercase__(				unittest.TestCase   ):
	'''simple docstring'''

	def   __lowerCAmelCase (						self    :str					)							->			List[str]:







			'''simple docstring'''




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





	@property
	def   __lowerCAmelCase (						self    :Optional[Any]					)							->			str:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[Any]				= 1
			SCREAMING_SNAKE_CASE       :     Any				= 3
			SCREAMING_SNAKE_CASE       :     Optional[int]				= (32, 32)

			SCREAMING_SNAKE_CASE       :     Optional[int]				= floats_tensor((batch_size, num_channels) + sizes		, rng=random.Random(0					)					).to(lowerCamelCase_					)
			return image





	@property
	def   __lowerCAmelCase (						self    :Union[str, Any]					)							->			Dict:







			'''simple docstring'''




			torch.manual_seed(0					)
			SCREAMING_SNAKE_CASE       :     str				= UNetaDConditionModel(
			    block_out_channels=(32, 64)		, layers_per_block=2		, sample_size=32		, in_channels=4		, out_channels=4		, down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')		, up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')		, cross_attention_dim=32		, )
			return model





	@property
	def   __lowerCAmelCase (						self    :Tuple					)							->			Union[str, Any]:







			'''simple docstring'''




			torch.manual_seed(0					)
			SCREAMING_SNAKE_CASE       :     Any				= AutoencoderKL(
			    block_out_channels=[32, 64]		, in_channels=3		, out_channels=3		, down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']		, up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']		, latent_channels=4		, )
			return model





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







			'''simple docstring'''




			torch.manual_seed(0					)
			SCREAMING_SNAKE_CASE       :     Any				= CLIPTextConfig(
			    bos_token_id=0		, eos_token_id=2		, hidden_size=32		, intermediate_size=37		, layer_norm_eps=1E-05		, num_attention_heads=4		, num_hidden_layers=5		, pad_token_id=1		, vocab_size=10_00		, )
			return CLIPTextModel(lowerCamelCase_					)





	@property
	def   __lowerCAmelCase (						self    :Optional[Any]					)							->			str:







			'''simple docstring'''




			def extract(*lowerCamelCase_    :Union[str, Any]		, **lowerCamelCase_    :List[str]					):




					class 				lowercase__:
						'''simple docstring'''

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







								'''simple docstring'''




								SCREAMING_SNAKE_CASE       :     Any				= torch.ones([0]					)







						def   __lowerCAmelCase (						self    :Any		, lowerCamelCase_    :Tuple					)							->			int:







								'''simple docstring'''




								self.pixel_values.to(lowerCamelCase_					)
								return self





					return Out()

			return extract





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Any				= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
			SCREAMING_SNAKE_CASE       :     Any				= self.dummy_cond_unet
			SCREAMING_SNAKE_CASE       :     int				= DDIMScheduler(
			    beta_start=0.0_0_0_8_5		, beta_end=0.0_1_2		, beta_schedule='''scaled_linear'''		, clip_sample=lowerCamelCase_		, set_alpha_to_one=lowerCamelCase_		, )

			SCREAMING_SNAKE_CASE       :     Optional[int]				= self.dummy_vae
			SCREAMING_SNAKE_CASE       :     Optional[int]				= self.dummy_text_encoder
			SCREAMING_SNAKE_CASE       :     str				= CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''					)

			# make sure here that pndm scheduler skips prk
			SCREAMING_SNAKE_CASE       :     List[str]				= StableDiffusionPipeline(
			    unet=lowerCamelCase_		, scheduler=lowerCamelCase_		, vae=lowerCamelCase_		, text_encoder=lowerCamelCase_		, tokenizer=lowerCamelCase_		, safety_checker=lowerCamelCase_		, feature_extractor=self.dummy_extractor		, )
			SCREAMING_SNAKE_CASE       :     str				= sd_pipe.to(lowerCamelCase_					)
			sd_pipe.set_progress_bar_config(disable=lowerCamelCase_					)

			SCREAMING_SNAKE_CASE       :     Optional[int]				= '''A painting of a squirrel eating a burger'''

			SCREAMING_SNAKE_CASE       :     Tuple				= torch.Generator(device=lowerCamelCase_					).manual_seed(0					)
			SCREAMING_SNAKE_CASE       :     List[Any]				= sd_pipe([prompt]		, generator=lowerCamelCase_		, guidance_scale=6.0		, num_inference_steps=2		, output_type='''np'''					)
			SCREAMING_SNAKE_CASE       :     Tuple				= output.images

			SCREAMING_SNAKE_CASE       :     Tuple				= torch.Generator(device=lowerCamelCase_					).manual_seed(0					)
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= sd_pipe(
			    [prompt]		, generator=lowerCamelCase_		, guidance_scale=6.0		, num_inference_steps=2		, output_type='''np'''		, return_dict=lowerCamelCase_		, )[0]

			SCREAMING_SNAKE_CASE       :     Any				= image[0, -3:, -3:, -1]
			SCREAMING_SNAKE_CASE       :     List[Any]				= image_from_tuple[0, -3:, -3:, -1]

			assert image.shape == (1, 64, 64, 3)
			SCREAMING_SNAKE_CASE       :     Optional[int]				= np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4]					)

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





	def   __lowerCAmelCase (						self    :int					)							->			Any:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     int				= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
			SCREAMING_SNAKE_CASE       :     int				= self.dummy_cond_unet
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= PNDMScheduler(skip_prk_steps=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     List[str]				= self.dummy_vae
			SCREAMING_SNAKE_CASE       :     Optional[int]				= self.dummy_text_encoder
			SCREAMING_SNAKE_CASE       :     int				= CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''					)

			# make sure here that pndm scheduler skips prk
			SCREAMING_SNAKE_CASE       :     Optional[int]				= StableDiffusionPipeline(
			    unet=lowerCamelCase_		, scheduler=lowerCamelCase_		, vae=lowerCamelCase_		, text_encoder=lowerCamelCase_		, tokenizer=lowerCamelCase_		, safety_checker=lowerCamelCase_		, feature_extractor=self.dummy_extractor		, )
			SCREAMING_SNAKE_CASE       :     List[Any]				= sd_pipe.to(lowerCamelCase_					)
			sd_pipe.set_progress_bar_config(disable=lowerCamelCase_					)

			SCREAMING_SNAKE_CASE       :     str				= '''A painting of a squirrel eating a burger'''
			SCREAMING_SNAKE_CASE       :     Dict				= torch.Generator(device=lowerCamelCase_					).manual_seed(0					)
			SCREAMING_SNAKE_CASE       :     Optional[int]				= sd_pipe([prompt]		, generator=lowerCamelCase_		, guidance_scale=6.0		, num_inference_steps=2		, output_type='''np'''					)

			SCREAMING_SNAKE_CASE       :     List[Any]				= output.images

			SCREAMING_SNAKE_CASE       :     Any				= torch.Generator(device=lowerCamelCase_					).manual_seed(0					)
			SCREAMING_SNAKE_CASE       :     str				= sd_pipe(
			    [prompt]		, generator=lowerCamelCase_		, guidance_scale=6.0		, num_inference_steps=2		, output_type='''np'''		, return_dict=lowerCamelCase_		, )[0]

			SCREAMING_SNAKE_CASE       :     Any				= image[0, -3:, -3:, -1]
			SCREAMING_SNAKE_CASE       :     Optional[int]				= image_from_tuple[0, -3:, -3:, -1]

			assert image.shape == (1, 64, 64, 3)
			SCREAMING_SNAKE_CASE       :     Optional[int]				= np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3]					)

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





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     str				= StableDiffusionPipeline.from_pretrained(
			    '''hf-internal-testing/tiny-stable-diffusion-lms-pipe'''		, safety_checker=lowerCamelCase_					)
			assert isinstance(lowerCamelCase_		, lowerCamelCase_					)
			assert isinstance(pipe.scheduler		, lowerCamelCase_					)
			assert pipe.safety_checker is None

			SCREAMING_SNAKE_CASE       :     List[str]				= pipe('''example prompt'''		, num_inference_steps=2					).images[0]
			assert image is not None

			# check that there's no error when saving a pipeline with one of the models being None
			with tempfile.TemporaryDirectory() as tmpdirname:
					pipe.save_pretrained(lowerCamelCase_					)
					SCREAMING_SNAKE_CASE       :     Dict				= StableDiffusionPipeline.from_pretrained(lowerCamelCase_					)

			# sanity check that the pipeline still works
			assert pipe.safety_checker is None
			SCREAMING_SNAKE_CASE       :     List[str]				= pipe('''example prompt'''		, num_inference_steps=2					).images[0]
			assert image is not None







	@unittest.skipIf(torch_device != '''cuda'''		, '''This test requires a GPU'''					)
	def   __lowerCAmelCase (						self    :Tuple					)							->			int:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Dict				= self.dummy_cond_unet
			SCREAMING_SNAKE_CASE       :     Tuple				= PNDMScheduler(skip_prk_steps=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Dict				= self.dummy_vae
			SCREAMING_SNAKE_CASE       :     List[Any]				= self.dummy_text_encoder
			SCREAMING_SNAKE_CASE       :     str				= CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''					)

			# put models in fp16
			SCREAMING_SNAKE_CASE       :     Dict				= unet.half()
			SCREAMING_SNAKE_CASE       :     Optional[int]				= vae.half()
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= bert.half()

			# make sure here that pndm scheduler skips prk
			SCREAMING_SNAKE_CASE       :     List[str]				= StableDiffusionPipeline(
			    unet=lowerCamelCase_		, scheduler=lowerCamelCase_		, vae=lowerCamelCase_		, text_encoder=lowerCamelCase_		, tokenizer=lowerCamelCase_		, safety_checker=lowerCamelCase_		, feature_extractor=self.dummy_extractor		, )
			SCREAMING_SNAKE_CASE       :     str				= sd_pipe.to(lowerCamelCase_					)
			sd_pipe.set_progress_bar_config(disable=lowerCamelCase_					)

			SCREAMING_SNAKE_CASE       :     str				= '''A painting of a squirrel eating a burger'''
			SCREAMING_SNAKE_CASE       :     Dict				= sd_pipe([prompt]		, num_inference_steps=2		, output_type='''np'''					).images

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





@nightly
@require_torch_gpu
class 				lowercase__(				unittest.TestCase   ):
	'''simple docstring'''

	def   __lowerCAmelCase (						self    :int					)							->			List[str]:







			'''simple docstring'''




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





	def   __lowerCAmelCase (						self    :List[str]					)							->			str:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Tuple				= StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''		, safety_checker=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config					)
			SCREAMING_SNAKE_CASE       :     Any				= sd_pipe.to(lowerCamelCase_					)
			sd_pipe.set_progress_bar_config(disable=lowerCamelCase_					)

			SCREAMING_SNAKE_CASE       :     int				= (
			    '''portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'''
			    ''' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'''
			    ''' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'''
			    ''' children from bahnhof zoo, detailed '''
			)
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= 40_03_66_03_46
			SCREAMING_SNAKE_CASE       :     Optional[int]				= 7

			# without safety guidance (sld_guidance_scale = 0)
			SCREAMING_SNAKE_CASE       :     Any				= torch.manual_seed(lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Dict				= sd_pipe(
			    [prompt]		, generator=lowerCamelCase_		, guidance_scale=lowerCamelCase_		, num_inference_steps=50		, output_type='''np'''		, width=5_12		, height=5_12		, sld_guidance_scale=0		, )

			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= output.images
			SCREAMING_SNAKE_CASE       :     List[str]				= image[0, -3:, -3:, -1]
			SCREAMING_SNAKE_CASE       :     Any				= [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6]

			assert image.shape == (1, 5_12, 5_12, 3)

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

			# without safety guidance (strong configuration)
			SCREAMING_SNAKE_CASE       :     str				= torch.manual_seed(lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= sd_pipe(
			    [prompt]		, generator=lowerCamelCase_		, guidance_scale=lowerCamelCase_		, num_inference_steps=50		, output_type='''np'''		, width=5_12		, height=5_12		, sld_guidance_scale=20_00		, sld_warmup_steps=7		, sld_threshold=0.0_2_5		, sld_momentum_scale=0.5		, sld_mom_beta=0.7		, )

			SCREAMING_SNAKE_CASE       :     str				= output.images
			SCREAMING_SNAKE_CASE       :     List[str]				= image[0, -3:, -3:, -1]
			SCREAMING_SNAKE_CASE       :     Any				= [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9]

			assert image.shape == (1, 5_12, 5_12, 3)

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





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Tuple				= StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''		, safety_checker=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     str				= LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config					)
			SCREAMING_SNAKE_CASE       :     Dict				= sd_pipe.to(lowerCamelCase_					)
			sd_pipe.set_progress_bar_config(disable=lowerCamelCase_					)

			SCREAMING_SNAKE_CASE       :     int				= '''padme amidala taking a bath artwork, safe for work, no nudity'''
			SCREAMING_SNAKE_CASE       :     List[Any]				= 27_34_97_17_55
			SCREAMING_SNAKE_CASE       :     str				= 7

			SCREAMING_SNAKE_CASE       :     List[str]				= torch.manual_seed(lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Optional[int]				= sd_pipe(
			    [prompt]		, generator=lowerCamelCase_		, guidance_scale=lowerCamelCase_		, num_inference_steps=50		, output_type='''np'''		, width=5_12		, height=5_12		, sld_guidance_scale=0		, )

			SCREAMING_SNAKE_CASE       :     Optional[int]				= output.images
			SCREAMING_SNAKE_CASE       :     Dict				= image[0, -3:, -3:, -1]
			SCREAMING_SNAKE_CASE       :     List[str]				= [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7]

			assert image.shape == (1, 5_12, 5_12, 3)

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

			SCREAMING_SNAKE_CASE       :     Dict				= torch.manual_seed(lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= sd_pipe(
			    [prompt]		, generator=lowerCamelCase_		, guidance_scale=lowerCamelCase_		, num_inference_steps=50		, output_type='''np'''		, width=5_12		, height=5_12		, sld_guidance_scale=20_00		, sld_warmup_steps=7		, sld_threshold=0.0_2_5		, sld_momentum_scale=0.5		, sld_mom_beta=0.7		, )

			SCREAMING_SNAKE_CASE       :     List[Any]				= output.images
			SCREAMING_SNAKE_CASE       :     List[str]				= image[0, -3:, -3:, -1]
			SCREAMING_SNAKE_CASE       :     int				= [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3]

			assert image.shape == (1, 5_12, 5_12, 3)

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







	def   __lowerCAmelCase (						self    :Any					)							->			Any:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''					)
			SCREAMING_SNAKE_CASE       :     Optional[int]				= sd_pipe.to(lowerCamelCase_					)
			sd_pipe.set_progress_bar_config(disable=lowerCamelCase_					)

			SCREAMING_SNAKE_CASE       :     Tuple				= (
			    '''the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'''
			    ''' leyendecker'''
			)
			SCREAMING_SNAKE_CASE       :     List[str]				= 10_44_35_52_34
			SCREAMING_SNAKE_CASE       :     Any				= 12

			SCREAMING_SNAKE_CASE       :     int				= torch.manual_seed(lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Any				= sd_pipe(
			    [prompt]		, generator=lowerCamelCase_		, guidance_scale=lowerCamelCase_		, num_inference_steps=50		, output_type='''np'''		, width=5_12		, height=5_12		, sld_guidance_scale=0		, )

			SCREAMING_SNAKE_CASE       :     Any				= output.images
			SCREAMING_SNAKE_CASE       :     List[str]				= image[0, -3:, -3:, -1]
			SCREAMING_SNAKE_CASE       :     Any				= np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]					)

			assert image.shape == (1, 5_12, 5_12, 3)

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

			SCREAMING_SNAKE_CASE       :     int				= torch.manual_seed(lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= sd_pipe(
			    [prompt]		, generator=lowerCamelCase_		, guidance_scale=lowerCamelCase_		, num_inference_steps=50		, output_type='''np'''		, width=5_12		, height=5_12		, sld_guidance_scale=20_00		, sld_warmup_steps=7		, sld_threshold=0.0_2_5		, sld_momentum_scale=0.5		, sld_mom_beta=0.7		, )

			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= output.images
			SCREAMING_SNAKE_CASE       :     Dict				= image[0, -3:, -3:, -1]
			SCREAMING_SNAKE_CASE       :     str				= np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1]					)
			assert image.shape == (1, 5_12, 5_12, 3)

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







"""simple docstring"""






import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
					    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
					    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
					    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
					    LayoutLMvaConfig,
					    LayoutLMvaForQuestionAnswering,
					    LayoutLMvaForSequenceClassification,
					    LayoutLMvaForTokenClassification,
					    LayoutLMvaModel,
					)
					from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
					from PIL import Image

					from transformers import LayoutLMvaImageProcessor




class 				lowercase__:
	'''simple docstring'''

	def __init__(						self    :Tuple		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :Union[str, Any]=2		, lowerCamelCase_    :Any=3		, lowerCamelCase_    :Union[str, Any]=4		, lowerCamelCase_    :List[str]=2		, lowerCamelCase_    :str=7		, lowerCamelCase_    :Tuple=True		, lowerCamelCase_    :Dict=True		, lowerCamelCase_    :int=True		, lowerCamelCase_    :List[Any]=True		, lowerCamelCase_    :Optional[Any]=99		, lowerCamelCase_    :Any=36		, lowerCamelCase_    :Any=3		, lowerCamelCase_    :str=4		, lowerCamelCase_    :Tuple=37		, lowerCamelCase_    :Optional[int]="gelu"		, lowerCamelCase_    :str=0.1		, lowerCamelCase_    :Optional[int]=0.1		, lowerCamelCase_    :Tuple=5_12		, lowerCamelCase_    :Optional[Any]=16		, lowerCamelCase_    :List[str]=2		, lowerCamelCase_    :Optional[int]=0.0_2		, lowerCamelCase_    :int=6		, lowerCamelCase_    :str=6		, lowerCamelCase_    :Optional[Any]=3		, lowerCamelCase_    :Union[str, Any]=4		, lowerCamelCase_    :List[Any]=None		, lowerCamelCase_    :Tuple=10_00		, )							->			Union[str, Any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Dict				= parent
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= batch_size
			SCREAMING_SNAKE_CASE       :     List[str]				= num_channels
			SCREAMING_SNAKE_CASE       :     str				= image_size
			SCREAMING_SNAKE_CASE       :     Optional[int]				= patch_size
			SCREAMING_SNAKE_CASE       :     Tuple				= text_seq_length
			SCREAMING_SNAKE_CASE       :     Optional[int]				= is_training
			SCREAMING_SNAKE_CASE       :     Dict				= use_input_mask
			SCREAMING_SNAKE_CASE       :     Any				= use_token_type_ids
			SCREAMING_SNAKE_CASE       :     List[Any]				= use_labels
			SCREAMING_SNAKE_CASE       :     List[Any]				= vocab_size
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= hidden_size
			SCREAMING_SNAKE_CASE       :     Tuple				= num_hidden_layers
			SCREAMING_SNAKE_CASE       :     Optional[int]				= num_attention_heads
			SCREAMING_SNAKE_CASE       :     Optional[int]				= intermediate_size
			SCREAMING_SNAKE_CASE       :     List[str]				= hidden_act
			SCREAMING_SNAKE_CASE       :     Any				= hidden_dropout_prob
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= attention_probs_dropout_prob
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= max_position_embeddings
			SCREAMING_SNAKE_CASE       :     int				= type_vocab_size
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= type_sequence_label_size
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= initializer_range
			SCREAMING_SNAKE_CASE       :     Dict				= coordinate_size
			SCREAMING_SNAKE_CASE       :     List[Any]				= shape_size
			SCREAMING_SNAKE_CASE       :     Dict				= num_labels
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= num_choices
			SCREAMING_SNAKE_CASE       :     List[str]				= scope
			SCREAMING_SNAKE_CASE       :     Optional[int]				= range_bbox

			# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
			SCREAMING_SNAKE_CASE       :     str				= text_seq_length
			SCREAMING_SNAKE_CASE       :     int				= (image_size // patch_size) ** 2 + 1
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= self.text_seq_length + self.image_seq_length





	def   __lowerCAmelCase (						self    :List[Any]					)							->			Optional[int]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[int]				= ids_tensor([self.batch_size, self.text_seq_length]		, self.vocab_size					)

			SCREAMING_SNAKE_CASE       :     List[Any]				= ids_tensor([self.batch_size, self.text_seq_length, 4]		, self.range_bbox					)
			# Ensure that bbox is legal
			for i in range(bbox.shape[0]					):
					for j in range(bbox.shape[1]					):
							if bbox[i, j, 3] < bbox[i, j, 1]:
									SCREAMING_SNAKE_CASE       :     str				= bbox[i, j, 3]
									SCREAMING_SNAKE_CASE       :     List[str]				= bbox[i, j, 1]
									SCREAMING_SNAKE_CASE       :     Any				= t
							if bbox[i, j, 2] < bbox[i, j, 0]:
									SCREAMING_SNAKE_CASE       :     Any				= bbox[i, j, 2]
									SCREAMING_SNAKE_CASE       :     Any				= bbox[i, j, 0]
									SCREAMING_SNAKE_CASE       :     Optional[Any]				= t

			SCREAMING_SNAKE_CASE       :     Dict				= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

			SCREAMING_SNAKE_CASE       :     Optional[Any]				= None
			if self.use_input_mask:
					SCREAMING_SNAKE_CASE       :     Dict				= random_attention_mask([self.batch_size, self.text_seq_length]					)

			SCREAMING_SNAKE_CASE       :     Any				= None
			if self.use_token_type_ids:
					SCREAMING_SNAKE_CASE       :     Tuple				= ids_tensor([self.batch_size, self.text_seq_length]		, self.type_vocab_size					)

			SCREAMING_SNAKE_CASE       :     Tuple				= None
			SCREAMING_SNAKE_CASE       :     Optional[int]				= None
			if self.use_labels:
					SCREAMING_SNAKE_CASE       :     List[str]				= ids_tensor([self.batch_size]		, self.type_sequence_label_size					)
					SCREAMING_SNAKE_CASE       :     Dict				= ids_tensor([self.batch_size, self.text_seq_length]		, self.num_labels					)

			SCREAMING_SNAKE_CASE       :     List[str]				= LayoutLMvaConfig(
			    vocab_size=self.vocab_size		, hidden_size=self.hidden_size		, num_hidden_layers=self.num_hidden_layers		, num_attention_heads=self.num_attention_heads		, intermediate_size=self.intermediate_size		, hidden_act=self.hidden_act		, hidden_dropout_prob=self.hidden_dropout_prob		, attention_probs_dropout_prob=self.attention_probs_dropout_prob		, max_position_embeddings=self.max_position_embeddings		, type_vocab_size=self.type_vocab_size		, initializer_range=self.initializer_range		, coordinate_size=self.coordinate_size		, shape_size=self.shape_size		, input_size=self.image_size		, patch_size=self.patch_size		, )

			return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels





	def   __lowerCAmelCase (						self    :int		, lowerCamelCase_    :Union[str, Any]		, lowerCamelCase_    :int		, lowerCamelCase_    :str		, lowerCamelCase_    :int		, lowerCamelCase_    :Union[str, Any]		, lowerCamelCase_    :Any		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Union[str, Any]					)							->			Any:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Dict				= LayoutLMvaModel(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()

			# text + image
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= model(lowerCamelCase_		, pixel_values=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     List[str]				= model(
			    lowerCamelCase_		, bbox=lowerCamelCase_		, pixel_values=lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     List[Any]				= model(lowerCamelCase_		, bbox=lowerCamelCase_		, pixel_values=lowerCamelCase_		, token_type_ids=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= model(lowerCamelCase_		, bbox=lowerCamelCase_		, pixel_values=lowerCamelCase_					)

			self.parent.assertEqual(result.last_hidden_state.shape		, (self.batch_size, self.seq_length, self.hidden_size)					)

			# text only
			SCREAMING_SNAKE_CASE       :     List[str]				= model(lowerCamelCase_					)
			self.parent.assertEqual(
			    result.last_hidden_state.shape		, (self.batch_size, self.text_seq_length, self.hidden_size)					)

			# image only
			SCREAMING_SNAKE_CASE       :     List[str]				= model(pixel_values=lowerCamelCase_					)
			self.parent.assertEqual(
			    result.last_hidden_state.shape		, (self.batch_size, self.image_seq_length, self.hidden_size)					)





	def   __lowerCAmelCase (						self    :str		, lowerCamelCase_    :Union[str, Any]		, lowerCamelCase_    :Union[str, Any]		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :List[str]		, lowerCamelCase_    :Any		, lowerCamelCase_    :int		, lowerCamelCase_    :List[Any]		, lowerCamelCase_    :List[str]					)							->			Tuple:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[Any]				= self.num_labels
			SCREAMING_SNAKE_CASE       :     Dict				= LayoutLMvaForSequenceClassification(lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     int				= model(
			    lowerCamelCase_		, bbox=lowerCamelCase_		, pixel_values=lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, labels=lowerCamelCase_		, )
			self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.num_labels)					)





	def   __lowerCAmelCase (						self    :Union[str, Any]		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :Any		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :Any		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :int		, lowerCamelCase_    :str		, lowerCamelCase_    :Any					)							->			Union[str, Any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     int				= self.num_labels
			SCREAMING_SNAKE_CASE       :     int				= LayoutLMvaForTokenClassification(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= model(
			    lowerCamelCase_		, bbox=lowerCamelCase_		, pixel_values=lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, labels=lowerCamelCase_		, )
			self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.text_seq_length, self.num_labels)					)





	def   __lowerCAmelCase (						self    :Optional[Any]		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Dict		, lowerCamelCase_    :int		, lowerCamelCase_    :List[str]		, lowerCamelCase_    :int		, lowerCamelCase_    :str		, lowerCamelCase_    :Optional[int]					)							->			Union[str, Any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[int]				= LayoutLMvaForQuestionAnswering(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     List[Any]				= model(
			    lowerCamelCase_		, bbox=lowerCamelCase_		, pixel_values=lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, start_positions=lowerCamelCase_		, end_positions=lowerCamelCase_		, )
			self.parent.assertEqual(result.start_logits.shape		, (self.batch_size, self.seq_length)					)
			self.parent.assertEqual(result.end_logits.shape		, (self.batch_size, self.seq_length)					)







	def   __lowerCAmelCase (						self    :Optional[int]					)							->			Optional[Any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[int]				= self.prepare_config_and_inputs()
			(
			    (
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					
			)       :     Tuple				= config_and_inputs
			SCREAMING_SNAKE_CASE       :     Dict				= {
			    '''input_ids''': input_ids,
			    '''bbox''': bbox,
			    '''pixel_values''': pixel_values,
			    '''token_type_ids''': token_type_ids,
			    '''attention_mask''': input_mask,
			}
			return config, inputs_dict





@require_torch
class 				lowercase__(				_UpperCAmelCase		,						_UpperCAmelCase		,						unittest.TestCase   ):
	'''simple docstring'''

	UpperCamelCase				=  False
	UpperCamelCase				=  False
	UpperCamelCase				=  False

	UpperCamelCase				=  (
	    (
	        LayoutLMvaModel,
	        LayoutLMvaForSequenceClassification,
	        LayoutLMvaForTokenClassification,
	        LayoutLMvaForQuestionAnswering,
	    )
	    if is_torch_available()
	    else ()
	)
	UpperCamelCase				=  (
	    {"""document-question-answering""": LayoutLMvaForQuestionAnswering, """feature-extraction""": LayoutLMvaModel}
	    if is_torch_available()
	    else {}
	)





	def   __lowerCAmelCase (						self    :int		, lowerCamelCase_    :Union[str, Any]		, lowerCamelCase_    :str		, lowerCamelCase_    :str		, lowerCamelCase_    :Optional[Any]		, lowerCamelCase_    :List[str]					)							->			Union[str, Any]:







			'''simple docstring'''




			return True





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     str				= LayoutLMvaModelTester(self					)
			SCREAMING_SNAKE_CASE       :     List[Any]				= ConfigTester(self		, config_class=lowerCamelCase_		, hidden_size=37					)





	def   __lowerCAmelCase (						self    :Any		, lowerCamelCase_    :Dict		, lowerCamelCase_    :List[str]		, lowerCamelCase_    :str=False					)							->			Tuple:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[Any]				= copy.deepcopy(lowerCamelCase_					)
			if model_class in get_values(lowerCamelCase_					):
					SCREAMING_SNAKE_CASE       :     Tuple				= {
					    k: v.unsqueeze(1					).expand(-1		, self.model_tester.num_choices		, -1					).contiguous()
					    if isinstance(lowerCamelCase_		, torch.Tensor					) and v.ndim > 1
					    else v
					    for k, v in inputs_dict.items()
					}
			if return_labels:
					if model_class in get_values(lowerCamelCase_					):
							SCREAMING_SNAKE_CASE       :     Union[str, Any]				= torch.ones(self.model_tester.batch_size		, dtype=torch.long		, device=lowerCamelCase_					)
					elif model_class in get_values(lowerCamelCase_					):
							SCREAMING_SNAKE_CASE       :     List[Any]				= torch.zeros(
							    self.model_tester.batch_size		, dtype=torch.long		, device=lowerCamelCase_					)
							SCREAMING_SNAKE_CASE       :     Any				= torch.zeros(
							    self.model_tester.batch_size		, dtype=torch.long		, device=lowerCamelCase_					)
					elif model_class in [
					    *get_values(lowerCamelCase_					),
					]:
							SCREAMING_SNAKE_CASE       :     str				= torch.zeros(
							    self.model_tester.batch_size		, dtype=torch.long		, device=lowerCamelCase_					)
					elif model_class in [
					    *get_values(lowerCamelCase_					),
					]:
							SCREAMING_SNAKE_CASE       :     Dict				= torch.zeros(
							    (self.model_tester.batch_size, self.model_tester.text_seq_length)		, dtype=torch.long		, device=lowerCamelCase_		, )

			return inputs_dict





	def   __lowerCAmelCase (						self    :Optional[Any]					)							->			Optional[int]:







			'''simple docstring'''




			self.config_tester.run_common_tests()





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     int				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*lowerCamelCase_					)





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     int				= self.model_tester.prepare_config_and_inputs()
			for type in ["absolute", "relative_key", "relative_key_query"]:
					SCREAMING_SNAKE_CASE       :     str				= type
					self.model_tester.create_and_check_model(*lowerCamelCase_					)





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[Any]				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :str					)							->			Any:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[Any]				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_token_classification(*lowerCamelCase_					)





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     int				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_question_answering(*lowerCamelCase_					)







	@slow
	def   __lowerCAmelCase (						self    :int					)							->			Union[str, Any]:







			'''simple docstring'''




			for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					SCREAMING_SNAKE_CASE       :     Optional[int]				= LayoutLMvaModel.from_pretrained(lowerCamelCase_					)
					self.assertIsNotNone(lowerCamelCase_					)





def __A						(   )->							Optional[int]:




		'''simple docstring'''






		SCREAMING_SNAKE_CASE       :     Tuple				= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
		return image




@require_torch
class 				lowercase__(				unittest.TestCase   ):
	'''simple docstring'''

	@cached_property
	def   __lowerCAmelCase (						self    :str					)							->			int:







			'''simple docstring'''




			return LayoutLMvaImageProcessor(apply_ocr=lowerCamelCase_					) if is_vision_available() else None







	@slow
	def   __lowerCAmelCase (						self    :Optional[Any]					)							->			Dict:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= LayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base'''					).to(lowerCamelCase_					)

			SCREAMING_SNAKE_CASE       :     Any				= self.default_image_processor
			SCREAMING_SNAKE_CASE       :     List[Any]				= prepare_img()
			SCREAMING_SNAKE_CASE       :     Tuple				= image_processor(images=lowerCamelCase_		, return_tensors='''pt'''					).pixel_values.to(lowerCamelCase_					)

			SCREAMING_SNAKE_CASE       :     Optional[Any]				= torch.tensor([[1, 2]]					)
			SCREAMING_SNAKE_CASE       :     Dict				= torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]					).unsqueeze(0					)

			# forward pass
			SCREAMING_SNAKE_CASE       :     Tuple				= model(
			    input_ids=input_ids.to(lowerCamelCase_					)		, bbox=bbox.to(lowerCamelCase_					)		, pixel_values=pixel_values.to(lowerCamelCase_					)		, )

			# verify the logits
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= torch.Size((1, 1_99, 7_68)					)
			self.assertEqual(outputs.last_hidden_state.shape		, lowerCamelCase_					)

			SCREAMING_SNAKE_CASE       :     List[Any]				= torch.tensor(
			    [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]]					).to(lowerCamelCase_					)

			self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]		, lowerCamelCase_		, atol=1E-4					)					)





