





"""simple docstring"""




import unittest

from transformers import FunnelConfig, FunnelTokenizer, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    MODEL_FOR_PRETRAINING_MAPPING,
						    FunnelBaseModel,
						    FunnelForMaskedLM,
						    FunnelForMultipleChoice,
						    FunnelForPreTraining,
						    FunnelForQuestionAnswering,
						    FunnelForSequenceClassification,
						    FunnelForTokenClassification,
						    FunnelModel,
						)




class 					_a		:






				def __init__(					self						:       int,					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       Optional[Any]=1_3,					lowerCAmelCase__						:       Optional[int]=7,					lowerCAmelCase__						:       int=True,					lowerCAmelCase__						:       Dict=True,					lowerCAmelCase__						:       List[Any]=True,					lowerCAmelCase__						:       Tuple=True,					lowerCAmelCase__						:       Union[str, Any]=9_9,					lowerCAmelCase__						:       int=[1, 1, 2],					lowerCAmelCase__						:       int=1,					lowerCAmelCase__						:       Dict=3_2,					lowerCAmelCase__						:       int=4,					lowerCAmelCase__						:       Dict=8,					lowerCAmelCase__						:       Optional[int]=3_7,					lowerCAmelCase__						:       List[str]="gelu_new",					lowerCAmelCase__						:       Dict=0.1,					lowerCAmelCase__						:       Optional[int]=0.1,					lowerCAmelCase__						:       Dict=0.0,					lowerCAmelCase__						:       Optional[int]=5_1_2,					lowerCAmelCase__						:       List[Any]=3,					lowerCAmelCase__						:       List[Any]=0.02,					lowerCAmelCase__						:       Tuple=3,					lowerCAmelCase__						:       int=4,					lowerCAmelCase__						:       Union[str, Any]=None,					lowerCAmelCase__						:       Tuple=False,					)      -> Tuple:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       parent
										_UpperCamelCase     :   Dict      =       batch_size
										_UpperCamelCase     :   List[Any]      =       seq_length
										_UpperCamelCase     :   Any      =       is_training
										_UpperCamelCase     :   Union[str, Any]      =       use_input_mask
										_UpperCamelCase     :   Optional[int]      =       use_token_type_ids
										_UpperCamelCase     :   int      =       use_labels
										_UpperCamelCase     :   List[Any]      =       vocab_size
										_UpperCamelCase     :   Dict      =       block_sizes
										_UpperCamelCase     :   Any      =       num_decoder_layers
										_UpperCamelCase     :   Tuple      =       d_model
										_UpperCamelCase     :   Optional[Any]      =       n_head
										_UpperCamelCase     :   List[Any]      =       d_head
										_UpperCamelCase     :   Optional[Any]      =       d_inner
										_UpperCamelCase     :   int      =       hidden_act
										_UpperCamelCase     :   str      =       hidden_dropout
										_UpperCamelCase     :   Dict      =       attention_dropout
										_UpperCamelCase     :   Optional[int]      =       activation_dropout
										_UpperCamelCase     :   List[Any]      =       max_position_embeddings
										_UpperCamelCase     :   str      =       type_vocab_size
										_UpperCamelCase     :   List[str]      =       2
										_UpperCamelCase     :   Tuple      =       num_labels
										_UpperCamelCase     :   Any      =       num_choices
										_UpperCamelCase     :   Optional[Any]      =       scope
										_UpperCamelCase     :   Dict      =       initializer_std

										# Used in the tests to check the size of the first attention layer
										_UpperCamelCase     :   Any      =       n_head
										# Used in the tests to check the size of the first hidden state
										_UpperCamelCase     :   int      =       self.d_model
										# Used in the tests to check the number of output hidden states/attentions
										_UpperCamelCase     :   Dict      =       sum(self.block_sizes				) + (0 if base else self.num_decoder_layers)
										# FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
										# the last hidden state of the first block (which is the first hidden state of the decoder).
										if not base:
																_UpperCamelCase     :   List[Any]      =       self.num_hidden_layers + 2






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




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       ids_tensor([self.batch_size, self.seq_length],					self.vocab_size				)

										_UpperCamelCase     :   Optional[Any]      =       None
										if self.use_input_mask:
																_UpperCamelCase     :   Union[str, Any]      =       ids_tensor([self.batch_size, self.seq_length],					vocab_size=2				)

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

										_UpperCamelCase     :   Optional[int]      =       None
										_UpperCamelCase     :   Optional[Any]      =       None
										_UpperCamelCase     :   Optional[int]      =       None
										if self.use_labels:
																_UpperCamelCase     :   Optional[int]      =       ids_tensor([self.batch_size],					self.type_sequence_label_size				)
																_UpperCamelCase     :   Tuple      =       ids_tensor([self.batch_size, self.seq_length],					self.num_labels				)
																_UpperCamelCase     :   Union[str, Any]      =       ids_tensor([self.batch_size],					self.num_choices				)
																_UpperCamelCase     :   List[Any]      =       ids_tensor([self.batch_size, self.seq_length],					1				)

										_UpperCamelCase     :   Any      =       self.get_config()

										return (
										    config,
										    input_ids,
										    token_type_ids,
										    input_mask,
										    sequence_labels,
										    token_labels,
										    choice_labels,
										    fake_token_labels,
										)






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




										'''simple docstring'''



										return FunnelConfig(
										    vocab_size=self.vocab_size,					block_sizes=self.block_sizes,					num_decoder_layers=self.num_decoder_layers,					d_model=self.d_model,					n_head=self.n_head,					d_head=self.d_head,					d_inner=self.d_inner,					hidden_act=self.hidden_act,					hidden_dropout=self.hidden_dropout,					attention_dropout=self.attention_dropout,					activation_dropout=self.activation_dropout,					max_position_embeddings=self.max_position_embeddings,					type_vocab_size=self.type_vocab_size,					initializer_std=self.initializer_std,					)






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




										'''simple docstring'''



										_UpperCamelCase     :   str      =       FunnelModel(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   int      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       model(lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.d_model)				)

										_UpperCamelCase     :   Tuple      =       False
										_UpperCamelCase     :   Any      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.d_model)				)

										_UpperCamelCase     :   Optional[int]      =       False
										_UpperCamelCase     :   List[Any]      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.d_model)				)






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




										'''simple docstring'''



										_UpperCamelCase     :   int      =       FunnelBaseModel(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   List[str]      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)
										_UpperCamelCase     :   Union[str, Any]      =       model(lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)
										_UpperCamelCase     :   str      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, 2, self.d_model)				)

										_UpperCamelCase     :   str      =       False
										_UpperCamelCase     :   Dict      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, 3, self.d_model)				)

										_UpperCamelCase     :   Tuple      =       False
										_UpperCamelCase     :   Optional[int]      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, 2, self.d_model)				)






				def 							snake_case      (					self						:       Optional[int],					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       int,					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       List[Any],					lowerCAmelCase__						:       Tuple,					lowerCAmelCase__						:       List[str],					)      -> Union[str, Any]:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       self.num_labels
										_UpperCamelCase     :   List[str]      =       FunnelForPreTraining(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   Dict      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__,					labels=lowerCAmelCase__				)
										self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.seq_length)				)






				def 							snake_case      (					self						:       Optional[int],					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       str,					)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       FunnelForMaskedLM(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   List[Any]      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__,					labels=lowerCAmelCase__				)
										self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.seq_length, self.vocab_size)				)






				def 							snake_case      (					self						:       Dict,					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       List[Any],					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       str,					)      -> Any:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       self.num_labels
										_UpperCamelCase     :   List[str]      =       FunnelForSequenceClassification(lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   Union[str, Any]      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__,					labels=lowerCAmelCase__				)
										self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.num_labels)				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       self.num_choices
										_UpperCamelCase     :   Union[str, Any]      =       FunnelForMultipleChoice(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   Union[str, Any]      =       input_ids.unsqueeze(1				).expand(-1,					self.num_choices,					-1				).contiguous()
										_UpperCamelCase     :   Union[str, Any]      =       token_type_ids.unsqueeze(1				).expand(-1,					self.num_choices,					-1				).contiguous()
										_UpperCamelCase     :   Dict      =       input_mask.unsqueeze(1				).expand(-1,					self.num_choices,					-1				).contiguous()
										_UpperCamelCase     :   List[str]      =       model(
										    lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__,					labels=lowerCAmelCase__,					)
										self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.num_choices)				)






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




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       self.num_labels
										_UpperCamelCase     :   List[Any]      =       FunnelForTokenClassification(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   int      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__,					labels=lowerCAmelCase__				)
										self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.seq_length, self.num_labels)				)






				def 							snake_case      (					self						:       Tuple,					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Any,					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       str,					)      -> List[str]:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       FunnelForQuestionAnswering(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   Dict      =       model(
										    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 							snake_case      (					self						:       int				)      -> List[str]:




										'''simple docstring'''



										_UpperCamelCase     :   str      =       self.prepare_config_and_inputs()
										(
										    (
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				
										)     :   Any      =       config_and_inputs
										_UpperCamelCase     :   Optional[Any]      =       {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
										return config, inputs_dict




@require_torch
class 					_a		( _lowerCAmelCase      ,							_lowerCAmelCase      ,							unittest.TestCase							):
				UpperCamelCase								=       False
				UpperCamelCase								=       False
				UpperCamelCase								=       (
				    (
				        FunnelModel,
				        FunnelForMaskedLM,
				        FunnelForPreTraining,
				        FunnelForQuestionAnswering,
				        FunnelForTokenClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				UpperCamelCase								=       (
				    {
				        '''feature-extraction''': (FunnelBaseModel, FunnelModel),
				        '''fill-mask''': FunnelForMaskedLM,
				        '''question-answering''': FunnelForQuestionAnswering,
				        '''text-classification''': FunnelForSequenceClassification,
				        '''token-classification''': FunnelForTokenClassification,
				        '''zero-shot''': FunnelForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)






				def 							snake_case      (					self						:       Union[str, Any],					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Any,					lowerCAmelCase__						:       List[str]=False				)      -> Union[str, Any]:




										'''simple docstring'''



										_UpperCamelCase     :   str      =       super()._prepare_for_class(lowerCAmelCase__,					lowerCAmelCase__,					return_labels=lowerCAmelCase__				)

										if return_labels:
																if model_class in get_values(lowerCAmelCase__				):
																						_UpperCamelCase     :   List[str]      =       torch.zeros(
																						    (self.model_tester.batch_size, self.model_tester.seq_length),					dtype=torch.long,					device=lowerCAmelCase__				)
										return inputs_dict






				def 							snake_case      (					self						:       Any				)      -> str:




										'''simple docstring'''



										_UpperCamelCase     :   Tuple      =       FunnelModelTester(self				)
										_UpperCamelCase     :   List[Any]      =       ConfigTester(self,					config_class=lowerCAmelCase__				)






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




										'''simple docstring'''



										self.config_tester.run_common_tests()






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




										'''simple docstring'''



										_UpperCamelCase     :   int      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase__				)






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




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase__				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       int,					lowerCAmelCase__						:       int				)      -> Any:




										'''simple docstring'''



										if hasattr(lowerCAmelCase__,					'''weight'''				) and module.weight is not None:
																module.weight.data.fill_(3				)
										if hasattr(lowerCAmelCase__,					'''bias'''				) and module.bias is not None:
																module.bias.data.fill_(3				)

										for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
																if hasattr(lowerCAmelCase__,					lowerCAmelCase__				) and getattr(lowerCAmelCase__,					lowerCAmelCase__				) is not None:
																						_UpperCamelCase     :   str      =       getattr(lowerCAmelCase__,					lowerCAmelCase__				)
																						weight.data.fill_(3				)




@require_torch
class 					_a		( _lowerCAmelCase      ,							unittest.TestCase							):
				UpperCamelCase								=       False
				UpperCamelCase								=       False
				UpperCamelCase								=       (
				    (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
				)






				def 							snake_case      (					self						:       Tuple				)      -> str:




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       FunnelModelTester(self,					base=lowerCAmelCase__				)
										_UpperCamelCase     :   Optional[Any]      =       ConfigTester(self,					config_class=lowerCAmelCase__				)






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




										'''simple docstring'''



										self.config_tester.run_common_tests()






				def 							snake_case      (					self						:       Any				)      -> int:




										'''simple docstring'''



										_UpperCamelCase     :   Any      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_base_model(*lowerCAmelCase__				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       Any				)      -> Any:




										'''simple docstring'''



										_UpperCamelCase     :   Any      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       int				)      -> Dict:




										'''simple docstring'''



										_UpperCamelCase  ,				_UpperCamelCase     :   Union[str, Any]      =       self.model_tester.prepare_config_and_inputs_for_common()
										_UpperCamelCase     :   Tuple      =       True

										for model_class in self.all_model_classes:
																if model_class.__name__ == "FunnelBaseModel":
																						continue
																_UpperCamelCase     :   Any      =       model_class(lowerCAmelCase__				)
																model.to(lowerCAmelCase__				)
																model.train()
																_UpperCamelCase     :   Union[str, Any]      =       self._prepare_for_class(lowerCAmelCase__,					lowerCAmelCase__,					return_labels=lowerCAmelCase__				)
																_UpperCamelCase     :   Optional[Any]      =       model(**lowerCAmelCase__				).loss
																loss.backward()






				def 							snake_case      (					self						:       Tuple,					lowerCAmelCase__						:       Tuple				)      -> Tuple:




										'''simple docstring'''



										if hasattr(lowerCAmelCase__,					'''weight'''				) and module.weight is not None:
																module.weight.data.fill_(3				)
										if hasattr(lowerCAmelCase__,					'''bias'''				) and module.bias is not None:
																module.bias.data.fill_(3				)

										for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
																if hasattr(lowerCAmelCase__,					lowerCAmelCase__				) and getattr(lowerCAmelCase__,					lowerCAmelCase__				) is not None:
																						_UpperCamelCase     :   Optional[Any]      =       getattr(lowerCAmelCase__,					lowerCAmelCase__				)
																						weight.data.fill_(3				)




@require_torch
@require_sentencepiece
@require_tokenizers
class 					_a		( unittest.TestCase							):






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




										'''simple docstring'''



										_UpperCamelCase     :   List[Any]      =       1_3
										_UpperCamelCase     :   List[Any]      =       7
										_UpperCamelCase     :   int      =       torch.arange(0,					batch_size * sequence_length				).long().reshape(lowerCAmelCase__,					lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       [0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
										_UpperCamelCase     :   Optional[int]      =       torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths]				)

										_UpperCamelCase     :   List[Any]      =       FunnelModel.from_pretrained('''sgugger/funnel-random-tiny'''				)
										_UpperCamelCase     :   str      =       model(lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)[0].abs()

										_UpperCamelCase     :   Optional[Any]      =       torch.tensor(2_344.8_352				)
										_UpperCamelCase     :   Union[str, Any]      =       torch.tensor(0.8_052				)
										self.assertTrue(torch.allclose(output.sum(),					lowerCAmelCase__,					atol=1e-4				)				)
										self.assertTrue(torch.allclose(output.mean(),					lowerCAmelCase__,					atol=1e-4				)				)

										_UpperCamelCase     :   Union[str, Any]      =       torch.tensor([[1] * 7, [1] * 4 + [0] * 3] * 6 + [[0, 1, 1, 0, 0, 1, 1]]				)
										_UpperCamelCase     :   Optional[Any]      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)[0].abs()

										_UpperCamelCase     :   str      =       torch.tensor(2_343.8_425				)
										_UpperCamelCase     :   List[Any]      =       torch.tensor(0.8_049				)
										self.assertTrue(torch.allclose(output.sum(),					lowerCAmelCase__,					atol=1e-4				)				)
										self.assertTrue(torch.allclose(output.mean(),					lowerCAmelCase__,					atol=1e-4				)				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       FunnelTokenizer.from_pretrained('''huggingface/funnel-small'''				)
										_UpperCamelCase     :   Optional[Any]      =       FunnelModel.from_pretrained('''huggingface/funnel-small'''				)
										_UpperCamelCase     :   Tuple      =       tokenizer('''Hello! I am the Funnel Transformer model.''',					return_tensors='''pt'''				)
										_UpperCamelCase     :   Union[str, Any]      =       model(**lowerCAmelCase__				)[0]

										_UpperCamelCase     :   Tuple      =       torch.tensor(235.7_246				)
										_UpperCamelCase     :   Union[str, Any]      =       torch.tensor(0.0_256				)
										self.assertTrue(torch.allclose(output.sum(),					lowerCAmelCase__,					atol=1e-4				)				)
										self.assertTrue(torch.allclose(output.mean(),					lowerCAmelCase__,					atol=1e-4				)				)










"""simple docstring"""




# This model implementation is heavily based on:

import gc
import random
import tempfile
import unittest

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

from diffusers import (
    AutoencoderKL,
    ControlNetModel,
    DDIMScheduler,
    StableDiffusionControlNetInpaintPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
    TEXT_TO_IMAGE_IMAGE_PARAMS,
)
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
)


enable_full_determinism()




class 					_a		( _lowerCAmelCase      ,							_lowerCAmelCase      ,							_lowerCAmelCase      ,							unittest.TestCase							):
				UpperCamelCase								=       StableDiffusionControlNetInpaintPipeline
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
				UpperCamelCase								=       frozenset({'''control_image'''}							)  # skip `image` and `mask` for now, only test for control_image
				UpperCamelCase								=       TEXT_TO_IMAGE_IMAGE_PARAMS






				def 							snake_case      (					self						:       Tuple				)      -> Any:




										'''simple docstring'''



										torch.manual_seed(0				)
										_UpperCamelCase     :   Tuple      =       UNetaDConditionModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					sample_size=3_2,					in_channels=9,					out_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D'''),					cross_attention_dim=3_2,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   List[str]      =       ControlNetModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					in_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					cross_attention_dim=3_2,					conditioning_embedding_out_channels=(1_6, 3_2),					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   Optional[Any]      =       DDIMScheduler(
										    beta_start=0.00_085,					beta_end=0.012,					beta_schedule='''scaled_linear''',					clip_sample=lowerCAmelCase__,					set_alpha_to_one=lowerCAmelCase__,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   Any      =       AutoencoderKL(
										    block_out_channels=[3_2, 6_4],					in_channels=3,					out_channels=3,					down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],					up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],					latent_channels=4,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   List[str]      =       CLIPTextConfig(
										    bos_token_id=0,					eos_token_id=2,					hidden_size=3_2,					intermediate_size=3_7,					layer_norm_eps=1e-0_5,					num_attention_heads=4,					num_hidden_layers=5,					pad_token_id=1,					vocab_size=1_0_0_0,					)
										_UpperCamelCase     :   List[str]      =       CLIPTextModel(lowerCAmelCase__				)
										_UpperCamelCase     :   Dict      =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)

										_UpperCamelCase     :   Tuple      =       {
										    '''unet''': unet,
										    '''controlnet''': controlnet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''safety_checker''': None,
										    '''feature_extractor''': None,
										}
										return components






				def 							snake_case      (					self						:       Dict,					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Optional[int]=0				)      -> Optional[int]:




										'''simple docstring'''



										if str(lowerCAmelCase__				).startswith('''mps'''				):
																_UpperCamelCase     :   str      =       torch.manual_seed(lowerCAmelCase__				)
										else:
																_UpperCamelCase     :   Any      =       torch.Generator(device=lowerCAmelCase__				).manual_seed(lowerCAmelCase__				)

										_UpperCamelCase     :   Optional[Any]      =       2
										_UpperCamelCase     :   int      =       randn_tensor(
										    (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor),					generator=lowerCAmelCase__,					device=torch.device(lowerCAmelCase__				),					)
										_UpperCamelCase     :   int      =       floats_tensor((1, 3, 3_2, 3_2),					rng=random.Random(lowerCAmelCase__				)				).to(lowerCAmelCase__				)
										_UpperCamelCase     :   List[str]      =       init_image.cpu().permute(0,					2,					3,					1				)[0]

										_UpperCamelCase     :   Optional[int]      =       Image.fromarray(np.uinta(lowerCAmelCase__				)				).convert('''RGB'''				).resize((6_4, 6_4)				)
										_UpperCamelCase     :   Any      =       Image.fromarray(np.uinta(init_image + 4				)				).convert('''RGB'''				).resize((6_4, 6_4)				)

										_UpperCamelCase     :   Tuple      =       {
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 6.0,
										    '''output_type''': '''numpy''',
										    '''image''': image,
										    '''mask_image''': mask_image,
										    '''control_image''': control_image,
										}

										return inputs






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




										'''simple docstring'''



										return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3				)






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




										'''simple docstring'''



										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3				)






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




										'''simple docstring'''



										self._test_inference_batch_single_identical(expected_max_diff=2e-3				)




class 					_a		( _lowerCAmelCase							):
				UpperCamelCase								=       StableDiffusionControlNetInpaintPipeline
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
				UpperCamelCase								=       frozenset([]							)






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




										'''simple docstring'''



										torch.manual_seed(0				)
										_UpperCamelCase     :   List[Any]      =       UNetaDConditionModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					sample_size=3_2,					in_channels=4,					out_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D'''),					cross_attention_dim=3_2,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   Optional[int]      =       ControlNetModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					in_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					cross_attention_dim=3_2,					conditioning_embedding_out_channels=(1_6, 3_2),					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   List[str]      =       DDIMScheduler(
										    beta_start=0.00_085,					beta_end=0.012,					beta_schedule='''scaled_linear''',					clip_sample=lowerCAmelCase__,					set_alpha_to_one=lowerCAmelCase__,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   Optional[int]      =       AutoencoderKL(
										    block_out_channels=[3_2, 6_4],					in_channels=3,					out_channels=3,					down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],					up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],					latent_channels=4,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   List[str]      =       CLIPTextConfig(
										    bos_token_id=0,					eos_token_id=2,					hidden_size=3_2,					intermediate_size=3_7,					layer_norm_eps=1e-0_5,					num_attention_heads=4,					num_hidden_layers=5,					pad_token_id=1,					vocab_size=1_0_0_0,					)
										_UpperCamelCase     :   int      =       CLIPTextModel(lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)

										_UpperCamelCase     :   str      =       {
										    '''unet''': unet,
										    '''controlnet''': controlnet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''safety_checker''': None,
										    '''feature_extractor''': None,
										}
										return components




class 					_a		( _lowerCAmelCase      ,							_lowerCAmelCase      ,							unittest.TestCase							):
				UpperCamelCase								=       StableDiffusionControlNetInpaintPipeline
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS






				def 							snake_case      (					self						:       Any				)      -> Dict:




										'''simple docstring'''



										torch.manual_seed(0				)
										_UpperCamelCase     :   int      =       UNetaDConditionModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					sample_size=3_2,					in_channels=9,					out_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D'''),					cross_attention_dim=3_2,					)
										torch.manual_seed(0				)

										def init_weights(lowerCAmelCase__						:       Optional[Any]				):
																if isinstance(lowerCAmelCase__,					torch.nn.Convad				):
																						torch.nn.init.normal(m.weight				)
																						m.bias.data.fill_(1.0				)

										_UpperCamelCase     :   List[Any]      =       ControlNetModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					in_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					cross_attention_dim=3_2,					conditioning_embedding_out_channels=(1_6, 3_2),					)
										controlneta.controlnet_down_blocks.apply(lowerCAmelCase__				)

										torch.manual_seed(0				)
										_UpperCamelCase     :   int      =       ControlNetModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					in_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					cross_attention_dim=3_2,					conditioning_embedding_out_channels=(1_6, 3_2),					)
										controlneta.controlnet_down_blocks.apply(lowerCAmelCase__				)

										torch.manual_seed(0				)
										_UpperCamelCase     :   Tuple      =       DDIMScheduler(
										    beta_start=0.00_085,					beta_end=0.012,					beta_schedule='''scaled_linear''',					clip_sample=lowerCAmelCase__,					set_alpha_to_one=lowerCAmelCase__,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   str      =       AutoencoderKL(
										    block_out_channels=[3_2, 6_4],					in_channels=3,					out_channels=3,					down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],					up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],					latent_channels=4,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   List[Any]      =       CLIPTextConfig(
										    bos_token_id=0,					eos_token_id=2,					hidden_size=3_2,					intermediate_size=3_7,					layer_norm_eps=1e-0_5,					num_attention_heads=4,					num_hidden_layers=5,					pad_token_id=1,					vocab_size=1_0_0_0,					)
										_UpperCamelCase     :   Any      =       CLIPTextModel(lowerCAmelCase__				)
										_UpperCamelCase     :   Union[str, Any]      =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)

										_UpperCamelCase     :   str      =       MultiControlNetModel([controlneta, controlneta]				)

										_UpperCamelCase     :   str      =       {
										    '''unet''': unet,
										    '''controlnet''': controlnet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''safety_checker''': None,
										    '''feature_extractor''': None,
										}
										return components






				def 							snake_case      (					self						:       Union[str, Any],					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Tuple=0				)      -> str:




										'''simple docstring'''



										if str(lowerCAmelCase__				).startswith('''mps'''				):
																_UpperCamelCase     :   List[Any]      =       torch.manual_seed(lowerCAmelCase__				)
										else:
																_UpperCamelCase     :   List[str]      =       torch.Generator(device=lowerCAmelCase__				).manual_seed(lowerCAmelCase__				)

										_UpperCamelCase     :   Any      =       2

										_UpperCamelCase     :   Union[str, Any]      =       [
										    randn_tensor(
										        (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor),					generator=lowerCAmelCase__,					device=torch.device(lowerCAmelCase__				),					),
										    randn_tensor(
										        (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor),					generator=lowerCAmelCase__,					device=torch.device(lowerCAmelCase__				),					),
										]
										_UpperCamelCase     :   int      =       floats_tensor((1, 3, 3_2, 3_2),					rng=random.Random(lowerCAmelCase__				)				).to(lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       init_image.cpu().permute(0,					2,					3,					1				)[0]

										_UpperCamelCase     :   List[str]      =       Image.fromarray(np.uinta(lowerCAmelCase__				)				).convert('''RGB'''				).resize((6_4, 6_4)				)
										_UpperCamelCase     :   int      =       Image.fromarray(np.uinta(init_image + 4				)				).convert('''RGB'''				).resize((6_4, 6_4)				)

										_UpperCamelCase     :   Dict      =       {
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 6.0,
										    '''output_type''': '''numpy''',
										    '''image''': image,
										    '''mask_image''': mask_image,
										    '''control_image''': control_image,
										}

										return inputs






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




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       self.get_dummy_components()
										_UpperCamelCase     :   Optional[int]      =       self.pipeline_class(**lowerCAmelCase__				)
										pipe.to(lowerCAmelCase__				)

										_UpperCamelCase     :   int      =       10.0
										_UpperCamelCase     :   List[Any]      =       4

										_UpperCamelCase     :   List[str]      =       self.get_dummy_inputs(lowerCAmelCase__				)
										_UpperCamelCase     :   Union[str, Any]      =       steps
										_UpperCamelCase     :   Union[str, Any]      =       scale
										_UpperCamelCase     :   List[Any]      =       pipe(**lowerCAmelCase__				)[0]

										_UpperCamelCase     :   Dict      =       self.get_dummy_inputs(lowerCAmelCase__				)
										_UpperCamelCase     :   List[str]      =       steps
										_UpperCamelCase     :   Union[str, Any]      =       scale
										_UpperCamelCase     :   Union[str, Any]      =       pipe(**lowerCAmelCase__,					control_guidance_start=0.1,					control_guidance_end=0.2				)[0]

										_UpperCamelCase     :   int      =       self.get_dummy_inputs(lowerCAmelCase__				)
										_UpperCamelCase     :   Any      =       steps
										_UpperCamelCase     :   Optional[Any]      =       scale
										_UpperCamelCase     :   Optional[int]      =       pipe(**lowerCAmelCase__,					control_guidance_start=[0.1, 0.3],					control_guidance_end=[0.2, 0.7]				)[0]

										_UpperCamelCase     :   Tuple      =       self.get_dummy_inputs(lowerCAmelCase__				)
										_UpperCamelCase     :   Tuple      =       steps
										_UpperCamelCase     :   int      =       scale
										_UpperCamelCase     :   Optional[Any]      =       pipe(**lowerCAmelCase__,					control_guidance_start=0.4,					control_guidance_end=[0.5, 0.8]				)[0]

										# make sure that all outputs are different
										assert np.sum(np.abs(output_a - output_a				)				) > 1e-3
										assert np.sum(np.abs(output_a - output_a				)				) > 1e-3
										assert np.sum(np.abs(output_a - output_a				)				) > 1e-3






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




										'''simple docstring'''



										return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3				)






				@unittest.skipIf(
				    torch_device != '''cuda''' or not is_xformers_available(),					reason='''XFormers attention is only available with CUDA and `xformers` installed''',					)
				def 							snake_case      (					self						:       str				)      -> Union[str, Any]:




										'''simple docstring'''



										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3				)






				def 							snake_case      (					self						:       List[str]				)      -> Tuple:




										'''simple docstring'''



										self._test_inference_batch_single_identical(expected_max_diff=2e-3				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       self.get_dummy_components()
										_UpperCamelCase     :   Union[str, Any]      =       self.pipeline_class(**lowerCAmelCase__				)
										pipe.to(lowerCAmelCase__				)
										pipe.set_progress_bar_config(disable=lowerCAmelCase__				)
										with tempfile.TemporaryDirectory() as tmpdir:
																try:
																						# save_pretrained is not implemented for Multi-ControlNet
																						pipe.save_pretrained(lowerCAmelCase__				)
																except NotImplementedError:
																						pass




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






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




										'''simple docstring'''



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






				def 							snake_case      (					self						:       Any				)      -> int:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       ControlNetModel.from_pretrained('''lllyasviel/sd-controlnet-canny'''				)

										_UpperCamelCase     :   int      =       StableDiffusionControlNetInpaintPipeline.from_pretrained(
										    '''runwayml/stable-diffusion-inpainting''',					safety_checker=lowerCAmelCase__,					controlnet=lowerCAmelCase__				)
										pipe.enable_model_cpu_offload()
										pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

										_UpperCamelCase     :   str      =       torch.Generator(device='''cpu'''				).manual_seed(0				)
										_UpperCamelCase     :   Optional[int]      =       load_image(
										    '''https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png'''				).resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   List[str]      =       load_image(
										    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
										    '''/stable_diffusion_inpaint/input_bench_mask.png'''				).resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   int      =       '''pitch black hole'''

										_UpperCamelCase     :   List[Any]      =       load_image(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png'''				).resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   List[Any]      =       pipe(
										    lowerCAmelCase__,					image=lowerCAmelCase__,					mask_image=lowerCAmelCase__,					control_image=lowerCAmelCase__,					generator=lowerCAmelCase__,					output_type='''np''',					num_inference_steps=3,					)

										_UpperCamelCase     :   Union[str, Any]      =       output.images[0]

										assert image.shape == (5_1_2, 5_1_2, 3)

										_UpperCamelCase     :   Union[str, Any]      =       load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/inpaint.npy'''				)

										assert np.abs(expected_image - image				).max() < 9e-2






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




										'''simple docstring'''



										_UpperCamelCase     :   Tuple      =       ControlNetModel.from_pretrained('''lllyasviel/control_v11p_sd15_inpaint'''				)

										_UpperCamelCase     :   Tuple      =       StableDiffusionControlNetInpaintPipeline.from_pretrained(
										    '''runwayml/stable-diffusion-v1-5''',					safety_checker=lowerCAmelCase__,					controlnet=lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       DDIMScheduler.from_config(pipe.scheduler.config				)
										pipe.enable_model_cpu_offload()
										pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

										_UpperCamelCase     :   Any      =       torch.Generator(device='''cpu'''				).manual_seed(3_3				)

										_UpperCamelCase     :   Union[str, Any]      =       load_image(
										    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png'''				)
										_UpperCamelCase     :   Optional[int]      =       init_image.resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   List[Any]      =       load_image(
										    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png'''				)
										_UpperCamelCase     :   Dict      =       mask_image.resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   Tuple      =       '''a handsome man with ray-ban sunglasses'''

										def make_inpaint_condition(lowerCAmelCase__						:       int,					lowerCAmelCase__						:       Optional[Any]				):
																_UpperCamelCase     :   Union[str, Any]      =       np.array(image.convert('''RGB'''				)				).astype(np.floataa				) / 255.0
																_UpperCamelCase     :   Optional[int]      =       np.array(image_mask.convert('''L'''				)				).astype(np.floataa				) / 255.0

																assert image.shape[0:1] == image_mask.shape[0:1], "image and image_mask must have the same image size"
																_UpperCamelCase     :   Union[str, Any]      =       -1.0  # set as masked pixel
																_UpperCamelCase     :   Union[str, Any]      =       np.expand_dims(lowerCAmelCase__,					0				).transpose(0,					3,					1,					2				)
																_UpperCamelCase     :   List[Any]      =       torch.from_numpy(lowerCAmelCase__				)
																return image

										_UpperCamelCase     :   Any      =       make_inpaint_condition(lowerCAmelCase__,					lowerCAmelCase__				)

										_UpperCamelCase     :   Optional[int]      =       pipe(
										    lowerCAmelCase__,					image=lowerCAmelCase__,					mask_image=lowerCAmelCase__,					control_image=lowerCAmelCase__,					guidance_scale=9.0,					eta=1.0,					generator=lowerCAmelCase__,					num_inference_steps=2_0,					output_type='''np''',					)
										_UpperCamelCase     :   Union[str, Any]      =       output.images[0]

										assert image.shape == (5_1_2, 5_1_2, 3)

										_UpperCamelCase     :   List[str]      =       load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/boy_ray_ban.npy'''				)

										assert np.abs(expected_image - image				).max() < 9e-2



