
"""simple docstring"""




from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import tensorflow as tf

					from transformers import (
					    TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
					    TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
					    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
					    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
					    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
					    LayoutLMvaConfig,
					    TFLayoutLMvaForQuestionAnswering,
					    TFLayoutLMvaForSequenceClassification,
					    TFLayoutLMvaForTokenClassification,
					    TFLayoutLMvaModel,
					)

if is_vision_available():
					from PIL import Image

					from transformers import LayoutLMvaImageProcessor



class 	lowerCAmelCase_						:


				"""simple docstring"""



				def __init__(self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=2   ,       SCREAMING_SNAKE_CASE__=3   ,       SCREAMING_SNAKE_CASE__=4   ,       SCREAMING_SNAKE_CASE__=2   ,       SCREAMING_SNAKE_CASE__=7   ,       SCREAMING_SNAKE_CASE__=True   ,       SCREAMING_SNAKE_CASE__=True   ,       SCREAMING_SNAKE_CASE__=True   ,       SCREAMING_SNAKE_CASE__=True   ,       SCREAMING_SNAKE_CASE__=99   ,       SCREAMING_SNAKE_CASE__=36   ,       SCREAMING_SNAKE_CASE__=2   ,       SCREAMING_SNAKE_CASE__=4   ,       SCREAMING_SNAKE_CASE__=37   ,       SCREAMING_SNAKE_CASE__="gelu"   ,       SCREAMING_SNAKE_CASE__=0.1   ,       SCREAMING_SNAKE_CASE__=0.1   ,       SCREAMING_SNAKE_CASE__=5_12   ,       SCREAMING_SNAKE_CASE__=16   ,       SCREAMING_SNAKE_CASE__=2   ,       SCREAMING_SNAKE_CASE__=0.02   ,       SCREAMING_SNAKE_CASE__=6   ,       SCREAMING_SNAKE_CASE__=6   ,       SCREAMING_SNAKE_CASE__=3   ,       SCREAMING_SNAKE_CASE__=4   ,       SCREAMING_SNAKE_CASE__=None   ,       SCREAMING_SNAKE_CASE__=10_00   ,       )					->		Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   parent
											SCREAMING_SNAKE_CASE__						:       str           =   batch_size
											SCREAMING_SNAKE_CASE__						:       Dict           =   num_channels
											SCREAMING_SNAKE_CASE__						:       Dict           =   image_size
											SCREAMING_SNAKE_CASE__						:       int           =   patch_size
											SCREAMING_SNAKE_CASE__						:       str           =   is_training
											SCREAMING_SNAKE_CASE__						:       int           =   use_input_mask
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   use_token_type_ids
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   use_labels
											SCREAMING_SNAKE_CASE__						:       str           =   vocab_size
											SCREAMING_SNAKE_CASE__						:       List[str]           =   hidden_size
											SCREAMING_SNAKE_CASE__						:       List[str]           =   num_hidden_layers
											SCREAMING_SNAKE_CASE__						:       str           =   num_attention_heads
											SCREAMING_SNAKE_CASE__						:       Dict           =   intermediate_size
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   hidden_act
											SCREAMING_SNAKE_CASE__						:       str           =   hidden_dropout_prob
											SCREAMING_SNAKE_CASE__						:       Dict           =   attention_probs_dropout_prob
											SCREAMING_SNAKE_CASE__						:       Dict           =   max_position_embeddings
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   type_vocab_size
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   type_sequence_label_size
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   initializer_range
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   coordinate_size
											SCREAMING_SNAKE_CASE__						:       Any           =   shape_size
											SCREAMING_SNAKE_CASE__						:       Dict           =   num_labels
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   num_choices
											SCREAMING_SNAKE_CASE__						:       List[str]           =   scope
											SCREAMING_SNAKE_CASE__						:       Any           =   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__						:       List[Any]           =   text_seq_length
											SCREAMING_SNAKE_CASE__						:       Any           =   (image_size // patch_size) ** 2 + 1
											SCREAMING_SNAKE_CASE__						:       Dict           =   self.text_seq_length + self.image_seq_length



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



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Dict           =   ids_tensor([self.batch_size, self.text_seq_length]   ,       self.vocab_size    )

											SCREAMING_SNAKE_CASE__						:       str           =   ids_tensor([self.batch_size, self.text_seq_length, 4]   ,       self.range_bbox    )
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   bbox.numpy()
											# 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__						:       Any           =   bbox[i, j, 3]
																																SCREAMING_SNAKE_CASE__						:       Dict           =   bbox[i, j, 1]
																																SCREAMING_SNAKE_CASE__						:       Any           =   tmp_coordinate
																									if bbox[i, j, 2] < bbox[i, j, 0]:
																																SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   bbox[i, j, 2]
																																SCREAMING_SNAKE_CASE__						:       Dict           =   bbox[i, j, 0]
																																SCREAMING_SNAKE_CASE__						:       Optional[int]           =   tmp_coordinate
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   tf.constant(SCREAMING_SNAKE_CASE__    )

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

											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   None
											if self.use_input_mask:
																		SCREAMING_SNAKE_CASE__						:       Tuple           =   random_attention_mask([self.batch_size, self.text_seq_length]    )

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

											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   None
											SCREAMING_SNAKE_CASE__						:       Any           =   None
											if self.use_labels:
																		SCREAMING_SNAKE_CASE__						:       List[Any]           =   ids_tensor([self.batch_size]   ,       self.type_sequence_label_size    )
																		SCREAMING_SNAKE_CASE__						:       Optional[int]           =   ids_tensor([self.batch_size, self.text_seq_length]   ,       self.num_labels    )

											SCREAMING_SNAKE_CASE__						:       List[Any]           =   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 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )					->		Optional[int]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       List[str]           =   TFLayoutLMvaModel(config=SCREAMING_SNAKE_CASE__    )

											# text + image
											SCREAMING_SNAKE_CASE__						:       Tuple           =   model(SCREAMING_SNAKE_CASE__   ,       pixel_values=SCREAMING_SNAKE_CASE__   ,       training=SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   model(
											    SCREAMING_SNAKE_CASE__   ,       bbox=SCREAMING_SNAKE_CASE__   ,       pixel_values=SCREAMING_SNAKE_CASE__   ,       attention_mask=SCREAMING_SNAKE_CASE__   ,       token_type_ids=SCREAMING_SNAKE_CASE__   ,       training=SCREAMING_SNAKE_CASE__   ,       )
											SCREAMING_SNAKE_CASE__						:       Dict           =   model(SCREAMING_SNAKE_CASE__   ,       bbox=SCREAMING_SNAKE_CASE__   ,       pixel_values=SCREAMING_SNAKE_CASE__   ,       training=SCREAMING_SNAKE_CASE__    )

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

											# text only
											SCREAMING_SNAKE_CASE__						:       Any           =   model(SCREAMING_SNAKE_CASE__   ,       training=SCREAMING_SNAKE_CASE__    )
											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""": pixel_values}   ,       training=SCREAMING_SNAKE_CASE__    )
											self.parent.assertEqual(
											    result.last_hidden_state.shape   ,       (self.batch_size, self.image_seq_length, self.hidden_size)    )



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



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Any           =   self.num_labels
											SCREAMING_SNAKE_CASE__						:       List[str]           =   TFLayoutLMvaForSequenceClassification(config=SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   model(
											    SCREAMING_SNAKE_CASE__   ,       bbox=SCREAMING_SNAKE_CASE__   ,       pixel_values=SCREAMING_SNAKE_CASE__   ,       attention_mask=SCREAMING_SNAKE_CASE__   ,       token_type_ids=SCREAMING_SNAKE_CASE__   ,       labels=SCREAMING_SNAKE_CASE__   ,       training=SCREAMING_SNAKE_CASE__   ,       )
											self.parent.assertEqual(result.logits.shape   ,       (self.batch_size, self.num_labels)    )



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )					->		Dict:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       str           =   self.num_labels
											SCREAMING_SNAKE_CASE__						:       Tuple           =   TFLayoutLMvaForTokenClassification(config=SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   model(
											    SCREAMING_SNAKE_CASE__   ,       bbox=SCREAMING_SNAKE_CASE__   ,       pixel_values=SCREAMING_SNAKE_CASE__   ,       attention_mask=SCREAMING_SNAKE_CASE__   ,       token_type_ids=SCREAMING_SNAKE_CASE__   ,       labels=SCREAMING_SNAKE_CASE__   ,       training=SCREAMING_SNAKE_CASE__   ,       )
											self.parent.assertEqual(result.logits.shape   ,       (self.batch_size, self.text_seq_length, self.num_labels)    )



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )					->		List[Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       List[Any]           =   2
											SCREAMING_SNAKE_CASE__						:       List[str]           =   TFLayoutLMvaForQuestionAnswering(config=SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       List[str]           =   model(
											    SCREAMING_SNAKE_CASE__   ,       bbox=SCREAMING_SNAKE_CASE__   ,       pixel_values=SCREAMING_SNAKE_CASE__   ,       attention_mask=SCREAMING_SNAKE_CASE__   ,       token_type_ids=SCREAMING_SNAKE_CASE__   ,       start_positions=SCREAMING_SNAKE_CASE__   ,       end_positions=SCREAMING_SNAKE_CASE__   ,       training=SCREAMING_SNAKE_CASE__   ,       )
											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 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       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__))						:       Optional[int]           =   config_and_inputs
											SCREAMING_SNAKE_CASE__						:       str           =   {
											    """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_tf
class 	lowerCAmelCase_						(a__ ,					a__ ,					unittest.TestCase  ):


				"""simple docstring"""



				__UpperCamelCase      :						Optional[int]					       =   (
				    (
				        TFLayoutLMvaModel,
				        TFLayoutLMvaForQuestionAnswering,
				        TFLayoutLMvaForSequenceClassification,
				        TFLayoutLMvaForTokenClassification,
				    )
				    if is_tf_available()
				    else ()
				)
				__UpperCamelCase      :						Optional[Any]					       =   (
				    {'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel}
				    if is_tf_available()
				    else {}
				)

				__UpperCamelCase      :						Tuple					       =   False
				__UpperCamelCase      :						List[Any]					       =   False
				__UpperCamelCase      :						str					       =   False



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )					->		List[str]:



											"""simple docstring"""




											return True



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=False    )					->		dict:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Dict           =   copy.deepcopy(SCREAMING_SNAKE_CASE__    )

											if model_class in get_values(SCREAMING_SNAKE_CASE__    ):
																		SCREAMING_SNAKE_CASE__						:       List[Any]           =   {
																		    k: tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__   ,       1    )   ,       (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)    )
																		    if isinstance(SCREAMING_SNAKE_CASE__   ,       tf.Tensor    ) and v.ndim > 0
																		    else v
																		    for k, v in inputs_dict.items()
																		}

											if return_labels:
																		if model_class in get_values(SCREAMING_SNAKE_CASE__    ):
																									SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   tf.ones(self.model_tester.batch_size   ,       dtype=tf.intaa    )
																		elif model_class in get_values(SCREAMING_SNAKE_CASE__    ):
																									SCREAMING_SNAKE_CASE__						:       Tuple           =   tf.zeros(self.model_tester.batch_size   ,       dtype=tf.intaa    )
																									SCREAMING_SNAKE_CASE__						:       Dict           =   tf.zeros(self.model_tester.batch_size   ,       dtype=tf.intaa    )
																		elif model_class in get_values(SCREAMING_SNAKE_CASE__    ):
																									SCREAMING_SNAKE_CASE__						:       List[str]           =   tf.zeros(self.model_tester.batch_size   ,       dtype=tf.intaa    )
																		elif model_class in get_values(SCREAMING_SNAKE_CASE__    ):
																									SCREAMING_SNAKE_CASE__						:       Any           =   tf.zeros(
																									    (self.model_tester.batch_size, self.model_tester.text_seq_length)   ,       dtype=tf.intaa    )

											return inputs_dict



				def 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       List[str]           =   TFLayoutLMvaModelTester(self    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   ConfigTester(self   ,       config_class=SCREAMING_SNAKE_CASE__   ,       hidden_size=37    )



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



											"""simple docstring"""




											self.config_tester.run_common_tests()



				def 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__      ,      SCREAMING_SNAKE_CASE__						:       Optional[int]           =   self.model_tester.prepare_config_and_inputs_for_common()
											for model_class in self.all_model_classes:
																		SCREAMING_SNAKE_CASE__						:       Any           =   model_class(SCREAMING_SNAKE_CASE__    )
																		if getattr(SCREAMING_SNAKE_CASE__   ,       """hf_compute_loss"""   ,       SCREAMING_SNAKE_CASE__    ):
																									# The number of elements in the loss should be the same as the number of elements in the label
																									SCREAMING_SNAKE_CASE__						:       Dict           =   self._prepare_for_class(inputs_dict.copy()   ,       SCREAMING_SNAKE_CASE__   ,       return_labels=SCREAMING_SNAKE_CASE__    )
																									SCREAMING_SNAKE_CASE__						:       List[Any]           =   prepared_for_class[
																									    sorted(prepared_for_class.keys() - inputs_dict.keys()   ,       reverse=SCREAMING_SNAKE_CASE__    )[0]
																									]
																									SCREAMING_SNAKE_CASE__						:       str           =   added_label.shape.as_list()[:1]

																									# Test that model correctly compute the loss with kwargs
																									SCREAMING_SNAKE_CASE__						:       List[str]           =   self._prepare_for_class(inputs_dict.copy()   ,       SCREAMING_SNAKE_CASE__   ,       return_labels=SCREAMING_SNAKE_CASE__    )
																									SCREAMING_SNAKE_CASE__						:       Optional[int]           =   prepared_for_class.pop("""input_ids"""    )

																									SCREAMING_SNAKE_CASE__						:       Dict           =   model(SCREAMING_SNAKE_CASE__   ,       **SCREAMING_SNAKE_CASE__    )[0]
																									self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]    )

																									# Test that model correctly compute the loss when we mask some positions
																									SCREAMING_SNAKE_CASE__						:       str           =   self._prepare_for_class(inputs_dict.copy()   ,       SCREAMING_SNAKE_CASE__   ,       return_labels=SCREAMING_SNAKE_CASE__    )
																									SCREAMING_SNAKE_CASE__						:       Tuple           =   prepared_for_class.pop("""input_ids"""    )
																									if "labels" in prepared_for_class:
																																SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   prepared_for_class["""labels"""].numpy()
																																if len(labels.shape    ) > 1 and labels.shape[1] != 1:
																																							SCREAMING_SNAKE_CASE__						:       Dict           =   -1_00
																																							SCREAMING_SNAKE_CASE__						:       int           =   tf.convert_to_tensor(SCREAMING_SNAKE_CASE__    )
																																							SCREAMING_SNAKE_CASE__						:       Optional[int]           =   model(SCREAMING_SNAKE_CASE__   ,       **SCREAMING_SNAKE_CASE__    )[0]
																																							self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]    )
																																							self.assertTrue(not np.any(np.isnan(loss.numpy()    )    )    )

                # Test that model correctly compute the loss with a dict
																									SCREAMING_SNAKE_CASE__						:       Any           =   self._prepare_for_class(inputs_dict.copy()   ,       SCREAMING_SNAKE_CASE__   ,       return_labels=SCREAMING_SNAKE_CASE__    )
																									SCREAMING_SNAKE_CASE__						:       Optional[int]           =   model(SCREAMING_SNAKE_CASE__    )[0]
																									self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]    )

																									# Test that model correctly compute the loss with a tuple
																									SCREAMING_SNAKE_CASE__						:       List[Any]           =   self._prepare_for_class(inputs_dict.copy()   ,       SCREAMING_SNAKE_CASE__   ,       return_labels=SCREAMING_SNAKE_CASE__    )

																									# Get keys that were added with the _prepare_for_class function
																									SCREAMING_SNAKE_CASE__						:       int           =   prepared_for_class.keys() - inputs_dict.keys()
																									SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   inspect.signature(model.call    ).parameters
																									SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   list(signature.keys()    )

																									# Create a dictionary holding the location of the tensors in the tuple
																									SCREAMING_SNAKE_CASE__						:       int           =   {0: """input_ids"""}
																									for label_key in label_keys:
																																SCREAMING_SNAKE_CASE__						:       str           =   signature_names.index(SCREAMING_SNAKE_CASE__    )
																																SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   label_key
																									SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   sorted(tuple_index_mapping.items()    )
																									# Initialize a list with their default values, update the values and convert to a tuple
																									SCREAMING_SNAKE_CASE__						:       int           =   []

																									for name in signature_names:
																																if name != "kwargs":
																																							list_input.append(signature[name].default    )

																									for index, value in sorted_tuple_index_mapping:
																																SCREAMING_SNAKE_CASE__						:       List[str]           =   prepared_for_class[value]

																									SCREAMING_SNAKE_CASE__						:       int           =   tuple(SCREAMING_SNAKE_CASE__    )

																									# Send to model
																									SCREAMING_SNAKE_CASE__						:       Optional[int]           =   model(tuple_input[:-1]    )[0]

																									self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]    )



				def 	__magic_name__    (self    )					->		int:



											"""simple docstring"""




											(
											    (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      
											)						:       Optional[int]           =   self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )



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



											"""simple docstring"""




											(
											    (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      
											)						:       int           =   self.model_tester.prepare_config_and_inputs()
											for type in ["absolute", "relative_key", "relative_key_query"]:
																		SCREAMING_SNAKE_CASE__						:       Any           =   type
																		self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )



				def 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											(
											    (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      
											)						:       Union[str, Any]           =   self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_sequence_classification(
											    SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )



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



											"""simple docstring"""




											(
											    (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      
											)						:       Optional[Any]           =   self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_token_classification(
											    SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )



				def 	__magic_name__    (self    )					->		Optional[int]:



											"""simple docstring"""




											(
											    (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      (
											    SCREAMING_SNAKE_CASE__
											)      ,      
											)						:       Optional[int]           =   self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_question_answering(
											    SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )



				@slow
				def 	__magic_name__    (self    )					->		int:



											"""simple docstring"""




											for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		SCREAMING_SNAKE_CASE__						:       Tuple           =   TFLayoutLMvaModel.from_pretrained(SCREAMING_SNAKE_CASE__    )
																		self.assertIsNotNone(SCREAMING_SNAKE_CASE__    )






def lowercase_  (   ):
							SCREAMING_SNAKE_CASE__						:       Tuple           =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
							return image



@require_tf
class 	lowerCAmelCase_						(unittest.TestCase  ):


				"""simple docstring"""



				@cached_property
				def 	__magic_name__    (self    )					->		Optional[int]:



											"""simple docstring"""




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



				@slow
				def 	__magic_name__    (self    )					->		List[str]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""    )

											SCREAMING_SNAKE_CASE__						:       List[str]           =   self.default_image_processor
											SCREAMING_SNAKE_CASE__						:       Tuple           =   prepare_img()
											SCREAMING_SNAKE_CASE__						:       str           =   image_processor(images=SCREAMING_SNAKE_CASE__   ,       return_tensors="""tf"""    ).pixel_values

											SCREAMING_SNAKE_CASE__						:       int           =   tf.constant([[1, 2]]    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]    )   ,       axis=0    )

											# forward pass
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   model(input_ids=SCREAMING_SNAKE_CASE__   ,       bbox=SCREAMING_SNAKE_CASE__   ,       pixel_values=SCREAMING_SNAKE_CASE__   ,       training=SCREAMING_SNAKE_CASE__    )

											# verify the logits
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   (1, 1_99, 7_68)
											self.assertEqual(outputs.last_hidden_state.shape   ,       SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   tf.constant(
											    [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]    )

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






"""simple docstring"""




import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin



@skip_mps
class 	lowerCAmelCase_						(a__ ,					a__ ,					unittest.TestCase  ):


				"""simple docstring"""



				__UpperCamelCase      :						Optional[Any]					       =   IFPipeline
				__UpperCamelCase      :						Dict					       =   TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''}
				__UpperCamelCase      :						Any					       =   TEXT_TO_IMAGE_BATCH_PARAMS
				__UpperCamelCase      :						Union[str, Any]					       =   PipelineTesterMixin.required_optional_params - {'''latents'''}



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



											"""simple docstring"""




											return self._get_dummy_components()



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=0    )					->		List[Any]:



											"""simple docstring"""




											if str(SCREAMING_SNAKE_CASE__    ).startswith("""mps"""    ):
																		SCREAMING_SNAKE_CASE__						:       Dict           =   torch.manual_seed(SCREAMING_SNAKE_CASE__    )
											else:
																		SCREAMING_SNAKE_CASE__						:       Any           =   torch.Generator(device=SCREAMING_SNAKE_CASE__    ).manual_seed(SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       int           =   {
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """generator""": generator,
											    """num_inference_steps""": 2,
											    """output_type""": """numpy""",
											}

											return inputs



				def 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											self._test_save_load_optional_components()



				@unittest.skipIf(torch_device != """cuda"""   ,       reason="""float16 requires CUDA"""    )
				def 	__magic_name__    (self    )					->		List[str]:



											"""simple docstring"""




											super().test_save_load_floataa(expected_max_diff=1E-1    )



				def 	__magic_name__    (self    )					->		List[Any]:



											"""simple docstring"""




											self._test_attention_slicing_forward_pass(expected_max_diff=1E-2    )



				def 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											self._test_save_load_local()



				def 	__magic_name__    (self    )					->		Dict:



											"""simple docstring"""




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



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



											"""simple docstring"""




											self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3    )






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


				"""simple docstring"""



				def 	__magic_name__    (self    )					->		Dict:



											"""simple docstring"""




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



				def 	__magic_name__    (self    )					->		Optional[int]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0"""   ,       variant="""fp16"""   ,       torch_dtype=torch.floataa    )

											SCREAMING_SNAKE_CASE__						:       Dict           =   IFSuperResolutionPipeline.from_pretrained(
											    """DeepFloyd/IF-II-L-v1.0"""   ,       variant="""fp16"""   ,       torch_dtype=torch.floataa   ,       text_encoder=SCREAMING_SNAKE_CASE__   ,       tokenizer=SCREAMING_SNAKE_CASE__    )

											# pre compute text embeddings and remove T5 to save memory

											pipe_a.text_encoder.to("""cuda"""    )

											SCREAMING_SNAKE_CASE__      ,      SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   pipe_a.encode_prompt("""anime turtle"""   ,       device="""cuda"""    )

											del pipe_a.tokenizer
											del pipe_a.text_encoder
											gc.collect()

											SCREAMING_SNAKE_CASE__						:       List[str]           =   None
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   None

											pipe_a.enable_model_cpu_offload()
											pipe_a.enable_model_cpu_offload()

											pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()    )
											pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()    )

											self._test_if(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )

											pipe_a.remove_all_hooks()
											pipe_a.remove_all_hooks()

											# img2img

											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   IFImgaImgPipeline(**pipe_a.components    )
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   IFImgaImgSuperResolutionPipeline(**pipe_a.components    )

											pipe_a.enable_model_cpu_offload()
											pipe_a.enable_model_cpu_offload()

											pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()    )
											pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()    )

											self._test_if_imgaimg(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )

											pipe_a.remove_all_hooks()
											pipe_a.remove_all_hooks()

											# inpainting

											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   IFInpaintingPipeline(**pipe_a.components    )
											SCREAMING_SNAKE_CASE__						:       int           =   IFInpaintingSuperResolutionPipeline(**pipe_a.components    )

											pipe_a.enable_model_cpu_offload()
											pipe_a.enable_model_cpu_offload()

											pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()    )
											pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()    )

											self._test_if_inpainting(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )					->		Optional[int]:



											"""simple docstring"""




											_start_torch_memory_measurement()

											SCREAMING_SNAKE_CASE__						:       Tuple           =   torch.Generator(device="""cpu"""    ).manual_seed(0    )
											SCREAMING_SNAKE_CASE__						:       Dict           =   pipe_a(
											    prompt_embeds=SCREAMING_SNAKE_CASE__   ,       negative_prompt_embeds=SCREAMING_SNAKE_CASE__   ,       num_inference_steps=2   ,       generator=SCREAMING_SNAKE_CASE__   ,       output_type="""np"""   ,       )

											SCREAMING_SNAKE_CASE__						:       int           =   output.images[0]

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

											SCREAMING_SNAKE_CASE__						:       Any           =   torch.cuda.max_memory_allocated()
											assert mem_bytes < 13 * 10**9

											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   load_numpy(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"""    )
											assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )

											# pipeline 2

											_start_torch_memory_measurement()

											SCREAMING_SNAKE_CASE__						:       int           =   torch.Generator(device="""cpu"""    ).manual_seed(0    )

											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   floats_tensor((1, 3, 64, 64)   ,       rng=random.Random(0    )    ).to(SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   pipe_a(
											    prompt_embeds=SCREAMING_SNAKE_CASE__   ,       negative_prompt_embeds=SCREAMING_SNAKE_CASE__   ,       image=SCREAMING_SNAKE_CASE__   ,       generator=SCREAMING_SNAKE_CASE__   ,       num_inference_steps=2   ,       output_type="""np"""   ,       )

											SCREAMING_SNAKE_CASE__						:       List[str]           =   output.images[0]

											assert image.shape == (2_56, 2_56, 3)

											SCREAMING_SNAKE_CASE__						:       List[Any]           =   torch.cuda.max_memory_allocated()
											assert mem_bytes < 4 * 10**9

											SCREAMING_SNAKE_CASE__						:       int           =   load_numpy(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy"""    )
											assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )					->		str:



											"""simple docstring"""




											_start_torch_memory_measurement()

											SCREAMING_SNAKE_CASE__						:       int           =   floats_tensor((1, 3, 64, 64)   ,       rng=random.Random(0    )    ).to(SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Tuple           =   torch.Generator(device="""cpu"""    ).manual_seed(0    )

											SCREAMING_SNAKE_CASE__						:       Any           =   pipe_a(
											    prompt_embeds=SCREAMING_SNAKE_CASE__   ,       negative_prompt_embeds=SCREAMING_SNAKE_CASE__   ,       image=SCREAMING_SNAKE_CASE__   ,       num_inference_steps=2   ,       generator=SCREAMING_SNAKE_CASE__   ,       output_type="""np"""   ,       )

											SCREAMING_SNAKE_CASE__						:       Dict           =   output.images[0]

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

											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   torch.cuda.max_memory_allocated()
											assert mem_bytes < 10 * 10**9

											SCREAMING_SNAKE_CASE__						:       str           =   load_numpy(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy"""    )
											assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )

											# pipeline 2

											_start_torch_memory_measurement()

											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   torch.Generator(device="""cpu"""    ).manual_seed(0    )

											SCREAMING_SNAKE_CASE__						:       List[Any]           =   floats_tensor((1, 3, 2_56, 2_56)   ,       rng=random.Random(0    )    ).to(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   floats_tensor((1, 3, 64, 64)   ,       rng=random.Random(0    )    ).to(SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   pipe_a(
											    prompt_embeds=SCREAMING_SNAKE_CASE__   ,       negative_prompt_embeds=SCREAMING_SNAKE_CASE__   ,       image=SCREAMING_SNAKE_CASE__   ,       original_image=SCREAMING_SNAKE_CASE__   ,       generator=SCREAMING_SNAKE_CASE__   ,       num_inference_steps=2   ,       output_type="""np"""   ,       )

											SCREAMING_SNAKE_CASE__						:       List[Any]           =   output.images[0]

											assert image.shape == (2_56, 2_56, 3)

											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   torch.cuda.max_memory_allocated()
											assert mem_bytes < 4 * 10**9

											SCREAMING_SNAKE_CASE__						:       str           =   load_numpy(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy"""    )
											assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )



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



											"""simple docstring"""




											_start_torch_memory_measurement()

											SCREAMING_SNAKE_CASE__						:       Dict           =   floats_tensor((1, 3, 64, 64)   ,       rng=random.Random(0    )    ).to(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Dict           =   floats_tensor((1, 3, 64, 64)   ,       rng=random.Random(1    )    ).to(SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Dict           =   torch.Generator(device="""cpu"""    ).manual_seed(0    )
											SCREAMING_SNAKE_CASE__						:       List[str]           =   pipe_a(
											    prompt_embeds=SCREAMING_SNAKE_CASE__   ,       negative_prompt_embeds=SCREAMING_SNAKE_CASE__   ,       image=SCREAMING_SNAKE_CASE__   ,       mask_image=SCREAMING_SNAKE_CASE__   ,       num_inference_steps=2   ,       generator=SCREAMING_SNAKE_CASE__   ,       output_type="""np"""   ,       )

											SCREAMING_SNAKE_CASE__						:       List[Any]           =   output.images[0]

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

											SCREAMING_SNAKE_CASE__						:       Tuple           =   torch.cuda.max_memory_allocated()
											assert mem_bytes < 10 * 10**9

											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   load_numpy(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"""    )
											assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )

											# pipeline 2

											_start_torch_memory_measurement()

											SCREAMING_SNAKE_CASE__						:       int           =   torch.Generator(device="""cpu"""    ).manual_seed(0    )

											SCREAMING_SNAKE_CASE__						:       Dict           =   floats_tensor((1, 3, 64, 64)   ,       rng=random.Random(0    )    ).to(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       int           =   floats_tensor((1, 3, 2_56, 2_56)   ,       rng=random.Random(0    )    ).to(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       int           =   floats_tensor((1, 3, 2_56, 2_56)   ,       rng=random.Random(1    )    ).to(SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       int           =   pipe_a(
											    prompt_embeds=SCREAMING_SNAKE_CASE__   ,       negative_prompt_embeds=SCREAMING_SNAKE_CASE__   ,       image=SCREAMING_SNAKE_CASE__   ,       mask_image=SCREAMING_SNAKE_CASE__   ,       original_image=SCREAMING_SNAKE_CASE__   ,       generator=SCREAMING_SNAKE_CASE__   ,       num_inference_steps=2   ,       output_type="""np"""   ,       )

											SCREAMING_SNAKE_CASE__						:       Dict           =   output.images[0]

											assert image.shape == (2_56, 2_56, 3)

											SCREAMING_SNAKE_CASE__						:       List[str]           =   torch.cuda.max_memory_allocated()
											assert mem_bytes < 4 * 10**9

											SCREAMING_SNAKE_CASE__						:       Any           =   load_numpy(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy"""    )
											assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )






def lowercase_  (   ):
							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()




