
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 			UpperCamelCase_			:




							'''simple docstring'''

							def __init__(				self     ,						UpperCamelCase     ,						UpperCamelCase=13     ,						UpperCamelCase=7     ,						UpperCamelCase=True     ,						UpperCamelCase=True     ,						UpperCamelCase=True     ,						UpperCamelCase=True     ,						UpperCamelCase=99     ,						UpperCamelCase=[1, 1, 2]     ,						UpperCamelCase=1     ,						UpperCamelCase=32     ,						UpperCamelCase=4     ,						UpperCamelCase=8     ,						UpperCamelCase=37     ,						UpperCamelCase="gelu_new"     ,						UpperCamelCase=0.1     ,						UpperCamelCase=0.1     ,						UpperCamelCase=0.0     ,						UpperCamelCase=5_12     ,						UpperCamelCase=3     ,						UpperCamelCase=0.02     ,						UpperCamelCase=3     ,						UpperCamelCase=4     ,						UpperCamelCase=None     ,						UpperCamelCase=False     ,						) ->	Optional[Any]:
										UpperCamelCase__    :		Tuple     =				parent
										UpperCamelCase__    :		str     =				batch_size
										UpperCamelCase__    :		Dict     =				seq_length
										UpperCamelCase__    :		Any     =				is_training
										UpperCamelCase__    :		Union[str, Any]     =				use_input_mask
										UpperCamelCase__    :		Optional[Any]     =				use_token_type_ids
										UpperCamelCase__    :		Union[str, Any]     =				use_labels
										UpperCamelCase__    :		Optional[Any]     =				vocab_size
										UpperCamelCase__    :		Optional[Any]     =				block_sizes
										UpperCamelCase__    :		Optional[int]     =				num_decoder_layers
										UpperCamelCase__    :		Optional[int]     =				d_model
										UpperCamelCase__    :		Tuple     =				n_head
										UpperCamelCase__    :		List[Any]     =				d_head
										UpperCamelCase__    :		Any     =				d_inner
										UpperCamelCase__    :		List[Any]     =				hidden_act
										UpperCamelCase__    :		Dict     =				hidden_dropout
										UpperCamelCase__    :		Dict     =				attention_dropout
										UpperCamelCase__    :		Optional[Any]     =				activation_dropout
										UpperCamelCase__    :		Optional[int]     =				max_position_embeddings
										UpperCamelCase__    :		Optional[Any]     =				type_vocab_size
										UpperCamelCase__    :		Optional[Any]     =				2
										UpperCamelCase__    :		Tuple     =				num_labels
										UpperCamelCase__    :		List[Any]     =				num_choices
										UpperCamelCase__    :		int     =				scope
										UpperCamelCase__    :		Optional[Any]     =				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__    :		Any     =				self.d_model
										# Used in the tests to check the number of output hidden states/attentions
										UpperCamelCase__    :		Optional[Any]     =				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__    :		Union[str, Any]     =				self.num_hidden_layers + 2
							def        lowerCAmelCase__ (				self) ->	List[str]:
										UpperCamelCase__    :		Union[str, Any]     =				ids_tensor([self.batch_size, self.seq_length]     ,						self.vocab_size)

										UpperCamelCase__    :		Optional[Any]     =				None
										if self.use_input_mask:
													UpperCamelCase__    :		Dict     =				ids_tensor([self.batch_size, self.seq_length]     ,						vocab_size=2)

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

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

										UpperCamelCase__    :		Tuple     =				self.get_config()

										return (
										    config,
										    input_ids,
										    token_type_ids,
										    input_mask,
										    sequence_labels,
										    token_labels,
										    choice_labels,
										    fake_token_labels,
										)
							def        lowerCAmelCase__ (				self) ->	str:
										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        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						) ->	Any:
										UpperCamelCase__    :		Optional[int]     =				FunnelModel(config=UpperCamelCase)
										model.to(UpperCamelCase)
										model.eval()
										UpperCamelCase__    :		str     =				model(UpperCamelCase     ,						attention_mask=UpperCamelCase     ,						token_type_ids=UpperCamelCase)
										UpperCamelCase__    :		Dict     =				model(UpperCamelCase     ,						token_type_ids=UpperCamelCase)
										UpperCamelCase__    :		Optional[int]     =				model(UpperCamelCase)
										self.parent.assertEqual(result.last_hidden_state.shape     ,						(self.batch_size, self.seq_length, self.d_model))

										UpperCamelCase__    :		Dict     =				False
										UpperCamelCase__    :		Optional[Any]     =				model(UpperCamelCase)
										self.parent.assertEqual(result.last_hidden_state.shape     ,						(self.batch_size, self.seq_length, self.d_model))

										UpperCamelCase__    :		Optional[int]     =				False
										UpperCamelCase__    :		Dict     =				model(UpperCamelCase)
										self.parent.assertEqual(result.last_hidden_state.shape     ,						(self.batch_size, self.seq_length, self.d_model))
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						) ->	Any:
										UpperCamelCase__    :		List[Any]     =				FunnelBaseModel(config=UpperCamelCase)
										model.to(UpperCamelCase)
										model.eval()
										UpperCamelCase__    :		List[Any]     =				model(UpperCamelCase     ,						attention_mask=UpperCamelCase     ,						token_type_ids=UpperCamelCase)
										UpperCamelCase__    :		List[str]     =				model(UpperCamelCase     ,						token_type_ids=UpperCamelCase)
										UpperCamelCase__    :		Tuple     =				model(UpperCamelCase)
										self.parent.assertEqual(result.last_hidden_state.shape     ,						(self.batch_size, 2, self.d_model))

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

										UpperCamelCase__    :		List[str]     =				False
										UpperCamelCase__    :		List[Any]     =				model(UpperCamelCase)
										self.parent.assertEqual(result.last_hidden_state.shape     ,						(self.batch_size, 2, self.d_model))
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						) ->	Any:
										UpperCamelCase__    :		Optional[Any]     =				self.num_labels
										UpperCamelCase__    :		str     =				FunnelForPreTraining(config=UpperCamelCase)
										model.to(UpperCamelCase)
										model.eval()
										UpperCamelCase__    :		Optional[Any]     =				model(UpperCamelCase     ,						attention_mask=UpperCamelCase     ,						token_type_ids=UpperCamelCase     ,						labels=UpperCamelCase)
										self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.seq_length))
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						) ->	str:
										UpperCamelCase__    :		Optional[Any]     =				FunnelForMaskedLM(config=UpperCamelCase)
										model.to(UpperCamelCase)
										model.eval()
										UpperCamelCase__    :		List[Any]     =				model(UpperCamelCase     ,						attention_mask=UpperCamelCase     ,						token_type_ids=UpperCamelCase     ,						labels=UpperCamelCase)
										self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.seq_length, self.vocab_size))
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						) ->	List[Any]:
										UpperCamelCase__    :		Dict     =				self.num_labels
										UpperCamelCase__    :		str     =				FunnelForSequenceClassification(UpperCamelCase)
										model.to(UpperCamelCase)
										model.eval()
										UpperCamelCase__    :		Union[str, Any]     =				model(UpperCamelCase     ,						attention_mask=UpperCamelCase     ,						token_type_ids=UpperCamelCase     ,						labels=UpperCamelCase)
										self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.num_labels))
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						) ->	int:
										UpperCamelCase__    :		List[Any]     =				self.num_choices
										UpperCamelCase__    :		Union[str, Any]     =				FunnelForMultipleChoice(config=UpperCamelCase)
										model.to(UpperCamelCase)
										model.eval()
										UpperCamelCase__    :		str     =				input_ids.unsqueeze(1).expand(-1     ,						self.num_choices     ,						-1).contiguous()
										UpperCamelCase__    :		int     =				token_type_ids.unsqueeze(1).expand(-1     ,						self.num_choices     ,						-1).contiguous()
										UpperCamelCase__    :		Optional[Any]     =				input_mask.unsqueeze(1).expand(-1     ,						self.num_choices     ,						-1).contiguous()
										UpperCamelCase__    :		List[Any]     =				model(
										    UpperCamelCase     ,						attention_mask=UpperCamelCase     ,						token_type_ids=UpperCamelCase     ,						labels=UpperCamelCase     ,						)
										self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.num_choices))
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						) ->	int:
										UpperCamelCase__    :		int     =				self.num_labels
										UpperCamelCase__    :		str     =				FunnelForTokenClassification(config=UpperCamelCase)
										model.to(UpperCamelCase)
										model.eval()
										UpperCamelCase__    :		List[Any]     =				model(UpperCamelCase     ,						attention_mask=UpperCamelCase     ,						token_type_ids=UpperCamelCase     ,						labels=UpperCamelCase)
										self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.seq_length, self.num_labels))
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						) ->	List[str]:
										UpperCamelCase__    :		List[Any]     =				FunnelForQuestionAnswering(config=UpperCamelCase)
										model.to(UpperCamelCase)
										model.eval()
										UpperCamelCase__    :		Optional[Any]     =				model(
										    UpperCamelCase     ,						attention_mask=UpperCamelCase     ,						token_type_ids=UpperCamelCase     ,						start_positions=UpperCamelCase     ,						end_positions=UpperCamelCase     ,						)
										self.parent.assertEqual(result.start_logits.shape     ,						(self.batch_size, self.seq_length))
										self.parent.assertEqual(result.end_logits.shape     ,						(self.batch_size, self.seq_length))






							def        lowerCAmelCase__ (				self) ->	List[str]:
										UpperCamelCase__    :		Dict     =				self.prepare_config_and_inputs()
										(
										    (
										    UpperCamelCase__
										)   ,			(
										    UpperCamelCase__
										)   ,			(
										    UpperCamelCase__
										)   ,			(
										    UpperCamelCase__
										)   ,			(
										    UpperCamelCase__
										)   ,			(
										    UpperCamelCase__
										)   ,			(
										    UpperCamelCase__
										)   ,			(
										    UpperCamelCase__
										)   ,			
										)    :		Optional[Any]     =				config_and_inputs
										UpperCamelCase__    :		Dict     =				{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
										return config, inputs_dict



@require_torch
class 			UpperCamelCase_			(						__UpperCamelCase	,     __UpperCamelCase	,     unittest.TestCase   ):




							'''simple docstring'''

							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        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase=False) ->	Union[str, Any]:
										UpperCamelCase__    :		int     =				super()._prepare_for_class(UpperCamelCase     ,						UpperCamelCase     ,						return_labels=UpperCamelCase)

										if return_labels:
													if model_class in get_values(UpperCamelCase):
																UpperCamelCase__    :		Optional[Any]     =				torch.zeros(
																    (self.model_tester.batch_size, self.model_tester.seq_length)     ,						dtype=torch.long     ,						device=UpperCamelCase)
										return inputs_dict
							def        lowerCAmelCase__ (				self) ->	int:
										UpperCamelCase__    :		Union[str, Any]     =				FunnelModelTester(self)
										UpperCamelCase__    :		List[str]     =				ConfigTester(self     ,						config_class=UpperCamelCase)
							def        lowerCAmelCase__ (				self) ->	Dict:
										self.config_tester.run_common_tests()
							def        lowerCAmelCase__ (				self) ->	str:
										UpperCamelCase__    :		int     =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*UpperCamelCase)
							def        lowerCAmelCase__ (				self) ->	Optional[Any]:
										UpperCamelCase__    :		Dict     =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_pretraining(*UpperCamelCase)
							def        lowerCAmelCase__ (				self) ->	List[Any]:
										UpperCamelCase__    :		Union[str, Any]     =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase)
							def        lowerCAmelCase__ (				self) ->	Optional[Any]:
										UpperCamelCase__    :		Tuple     =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_token_classification(*UpperCamelCase)
							def        lowerCAmelCase__ (				self) ->	Any:
										UpperCamelCase__    :		Union[str, Any]     =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_question_answering(*UpperCamelCase)






							def        lowerCAmelCase__ (				self     ,						UpperCamelCase) ->	List[str]:
										if hasattr(UpperCamelCase     ,						'weight') and module.weight is not None:
													module.weight.data.fill_(3)
										if hasattr(UpperCamelCase     ,						'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(UpperCamelCase     ,						UpperCamelCase) and getattr(UpperCamelCase     ,						UpperCamelCase) is not None:
																UpperCamelCase__    :		Optional[Any]     =				getattr(UpperCamelCase     ,						UpperCamelCase)
																weight.data.fill_(3)



@require_torch
class 			UpperCamelCase_			(						__UpperCamelCase	,     unittest.TestCase   ):




							'''simple docstring'''

							UpperCamelCase_					   =							False
							UpperCamelCase_					   =							False
							UpperCamelCase_					   =							(
							    (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
							)
							def        lowerCAmelCase__ (				self) ->	str:
										UpperCamelCase__    :		Optional[int]     =				FunnelModelTester(self     ,						base=UpperCamelCase)
										UpperCamelCase__    :		int     =				ConfigTester(self     ,						config_class=UpperCamelCase)
							def        lowerCAmelCase__ (				self) ->	Optional[int]:
										self.config_tester.run_common_tests()
							def        lowerCAmelCase__ (				self) ->	Dict:
										UpperCamelCase__    :		Optional[Any]     =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_base_model(*UpperCamelCase)
							def        lowerCAmelCase__ (				self) ->	Any:
										UpperCamelCase__    :		int     =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase)
							def        lowerCAmelCase__ (				self) ->	Dict:
										UpperCamelCase__    :		List[Any]     =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase)
							def        lowerCAmelCase__ (				self) ->	List[Any]:
										UpperCamelCase__   ,			UpperCamelCase__    :		List[str]     =				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__    :		Dict     =				model_class(UpperCamelCase)
													model.to(UpperCamelCase)
													model.train()
													UpperCamelCase__    :		str     =				self._prepare_for_class(UpperCamelCase     ,						UpperCamelCase     ,						return_labels=UpperCamelCase)
													UpperCamelCase__    :		Optional[Any]     =				model(**UpperCamelCase).loss
													loss.backward()






							def        lowerCAmelCase__ (				self     ,						UpperCamelCase) ->	Tuple:
										if hasattr(UpperCamelCase     ,						'weight') and module.weight is not None:
													module.weight.data.fill_(3)
										if hasattr(UpperCamelCase     ,						'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(UpperCamelCase     ,						UpperCamelCase) and getattr(UpperCamelCase     ,						UpperCamelCase) is not None:
																UpperCamelCase__    :		str     =				getattr(UpperCamelCase     ,						UpperCamelCase)
																weight.data.fill_(3)



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




							'''simple docstring'''

							def        lowerCAmelCase__ (				self) ->	Union[str, Any]:
										UpperCamelCase__    :		int     =				13
										UpperCamelCase__    :		int     =				7
										UpperCamelCase__    :		str     =				torch.arange(0     ,						batch_size * sequence_length).long().reshape(UpperCamelCase     ,						UpperCamelCase)
										UpperCamelCase__    :		Tuple     =				[0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
										UpperCamelCase__    :		int     =				torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths])

										UpperCamelCase__    :		Union[str, Any]     =				FunnelModel.from_pretrained('sgugger/funnel-random-tiny')
										UpperCamelCase__    :		Optional[Any]     =				model(UpperCamelCase     ,						token_type_ids=UpperCamelCase)[0].abs()

										UpperCamelCase__    :		List[Any]     =				torch.tensor(2344.8352)
										UpperCamelCase__    :		Any     =				torch.tensor(0.8052)
										self.assertTrue(torch.allclose(output.sum()     ,						UpperCamelCase     ,						atol=1E-4))
										self.assertTrue(torch.allclose(output.mean()     ,						UpperCamelCase     ,						atol=1E-4))

										UpperCamelCase__    :		Optional[int]     =				torch.tensor([[1] * 7, [1] * 4 + [0] * 3] * 6 + [[0, 1, 1, 0, 0, 1, 1]])
										UpperCamelCase__    :		Optional[int]     =				model(UpperCamelCase     ,						attention_mask=UpperCamelCase     ,						token_type_ids=UpperCamelCase)[0].abs()

										UpperCamelCase__    :		str     =				torch.tensor(2343.8425)
										UpperCamelCase__    :		List[str]     =				torch.tensor(0.8049)
										self.assertTrue(torch.allclose(output.sum()     ,						UpperCamelCase     ,						atol=1E-4))
										self.assertTrue(torch.allclose(output.mean()     ,						UpperCamelCase     ,						atol=1E-4))






							@slow
							def        lowerCAmelCase__ (				self) ->	List[str]:
										UpperCamelCase__    :		Union[str, Any]     =				FunnelTokenizer.from_pretrained('huggingface/funnel-small')
										UpperCamelCase__    :		List[str]     =				FunnelModel.from_pretrained('huggingface/funnel-small')
										UpperCamelCase__    :		Union[str, Any]     =				tokenizer('Hello! I am the Funnel Transformer model.'     ,						return_tensors='pt')
										UpperCamelCase__    :		Any     =				model(**UpperCamelCase)[0]

										UpperCamelCase__    :		str     =				torch.tensor(235.7246)
										UpperCamelCase__    :		Union[str, Any]     =				torch.tensor(0.0256)
										self.assertTrue(torch.allclose(output.sum()     ,						UpperCamelCase     ,						atol=1E-4))
										self.assertTrue(torch.allclose(output.mean()     ,						UpperCamelCase     ,						atol=1E-4))





from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


UpperCAmelCase__				:  Optional[int]       					=				logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCAmelCase__				:  Optional[int]       					=				'''
    Examples:
        ```py
        >>> import torch
        >>> import numpy as np

        >>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline
        >>> from transformers import pipeline
        >>> from diffusers.utils import load_image


        >>> def make_hint(image, depth_estimator):
        ...     image = depth_estimator(image)["depth"]
        ...     image = np.array(image)
        ...     image = image[:, :, None]
        ...     image = np.concatenate([image, image, image], axis=2)
        ...     detected_map = torch.from_numpy(image).float() / 255.0
        ...     hint = detected_map.permute(2, 0, 1)
        ...     return hint


        >>> depth_estimator = pipeline("depth-estimation")

        >>> pipe_prior = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(
        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
        ... )
        >>> pipe_prior = pipe_prior.to("cuda")

        >>> pipe = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(
        ...     "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to("cuda")

        >>> img = load_image(
        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
        ...     "/kandinsky/cat.png"
        ... ).resize((768, 768))


        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")

        >>> prompt = "A robot, 4k photo"
        >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"

        >>> generator = torch.Generator(device="cuda").manual_seed(43)

        >>> img_emb = pipe_prior(prompt=prompt, image=img, strength=0.85, generator=generator)
        >>> negative_emb = pipe_prior(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)

        >>> images = pipe(
        ...     image=img,
        ...     strength=0.5,
        ...     image_embeds=img_emb.image_embeds,
        ...     negative_image_embeds=negative_emb.image_embeds,
        ...     hint=hint,
        ...     num_inference_steps=50,
        ...     generator=generator,
        ...     height=768,
        ...     width=768,
        ... ).images

        >>> images[0].save("robot_cat.png")
        ```
'''



def       _lowercase					(      __SCREAMING_SNAKE_CASE				,    __SCREAMING_SNAKE_CASE				,    __SCREAMING_SNAKE_CASE=8 )	->     List[Any]:
			UpperCamelCase__    :		Union[str, Any]     =				height // scale_factor**2
			if height % scale_factor**2 != 0:
						new_height += 1
			UpperCamelCase__    :		Tuple     =				width // scale_factor**2
			if width % scale_factor**2 != 0:
						new_width += 1
			return new_height * scale_factor, new_width * scale_factor



def       _lowercase					(      __SCREAMING_SNAKE_CASE				,    __SCREAMING_SNAKE_CASE=512				,    __SCREAMING_SNAKE_CASE=512 )	->     Union[str, Any]:
			UpperCamelCase__    :		List[str]     =				pil_image.resize((w, h)				,    resample=Image.BICUBIC				,    reducing_gap=1 )
			UpperCamelCase__    :		List[str]     =				np.array(pil_image.convert('RGB' ) )
			UpperCamelCase__    :		Tuple     =				arr.astype(np.floataa ) / 127.5 - 1
			UpperCamelCase__    :		Tuple     =				np.transpose(__SCREAMING_SNAKE_CASE				,    [2, 0, 1] )
			UpperCamelCase__    :		int     =				torch.from_numpy(__SCREAMING_SNAKE_CASE ).unsqueeze(0 )
			return image



class 			UpperCamelCase_			(						__UpperCamelCase   ):




							'''simple docstring'''

							def __init__(				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						) ->	Any:
										super().__init__()

										self.register_modules(
										    unet=UpperCamelCase     ,						scheduler=UpperCamelCase     ,						movq=UpperCamelCase     ,						)
										UpperCamelCase__    :		str     =				2 ** (len(self.movq.config.block_out_channels) - 1)
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase) ->	Tuple:
										# get the original timestep using init_timestep
										UpperCamelCase__    :		str     =				min(int(num_inference_steps * strength)     ,						UpperCamelCase)

										UpperCamelCase__    :		int     =				max(num_inference_steps - init_timestep     ,						0)
										UpperCamelCase__    :		str     =				self.scheduler.timesteps[t_start:]

										return timesteps, num_inference_steps - t_start
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase=None) ->	Optional[Any]:
										if not isinstance(UpperCamelCase     ,						(torch.Tensor, PIL.Image.Image, list)):
													raise ValueError(
													    F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCamelCase)}""")

										UpperCamelCase__    :		int     =				image.to(device=UpperCamelCase     ,						dtype=UpperCamelCase)

										UpperCamelCase__    :		int     =				batch_size * num_images_per_prompt

										if image.shape[1] == 4:
													UpperCamelCase__    :		Tuple     =				image

										else:
													if isinstance(UpperCamelCase     ,						UpperCamelCase) and len(UpperCamelCase) != batch_size:
																raise ValueError(
																    F"""You have passed a list of generators of length {len(UpperCamelCase)}, but requested an effective batch"""
																    F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""")

													elif isinstance(UpperCamelCase     ,						UpperCamelCase):
																UpperCamelCase__    :		Union[str, Any]     =				[
																    self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(UpperCamelCase)
																]
																UpperCamelCase__    :		Any     =				torch.cat(UpperCamelCase     ,						dim=0)
													else:
																UpperCamelCase__    :		Any     =				self.movq.encode(UpperCamelCase).latent_dist.sample(UpperCamelCase)

													UpperCamelCase__    :		List[Any]     =				self.movq.config.scaling_factor * init_latents

										UpperCamelCase__    :		List[Any]     =				torch.cat([init_latents]     ,						dim=0)

										UpperCamelCase__    :		Union[str, Any]     =				init_latents.shape
										UpperCamelCase__    :		Union[str, Any]     =				randn_tensor(UpperCamelCase     ,						generator=UpperCamelCase     ,						device=UpperCamelCase     ,						dtype=UpperCamelCase)

										# get latents
										UpperCamelCase__    :		Optional[int]     =				self.scheduler.add_noise(UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase)

										UpperCamelCase__    :		List[Any]     =				init_latents

										return latents
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase=0) ->	str:
										if is_accelerate_available():
													from accelerate import cpu_offload
										else:
													raise ImportError('Please install accelerate via `pip install accelerate`')

										UpperCamelCase__    :		Any     =				torch.device(F"""cuda:{gpu_id}""")

										UpperCamelCase__    :		int     =				[
										    self.unet,
										    self.movq,
										]
										for cpu_offloaded_model in models:
													if cpu_offloaded_model is not None:
																cpu_offload(UpperCamelCase     ,						UpperCamelCase)
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase=0) ->	Tuple:
										if is_accelerate_available() and is_accelerate_version('>='     ,						'0.17.0.dev0'):
													from accelerate import cpu_offload_with_hook
										else:
													raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.')

										UpperCamelCase__    :		int     =				torch.device(F"""cuda:{gpu_id}""")

										if self.device.type != "cpu":
													self.to('cpu'     ,						silence_dtype_warnings=UpperCamelCase)
													torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

										UpperCamelCase__    :		Dict     =				None
										for cpu_offloaded_model in [self.unet, self.movq]:
													UpperCamelCase__   ,			UpperCamelCase__    :		Optional[int]     =				cpu_offload_with_hook(UpperCamelCase     ,						UpperCamelCase     ,						prev_module_hook=UpperCamelCase)

										# We'll offload the last model manually.
										UpperCamelCase__    :		List[Any]     =				hook
							@property
							# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
							def        lowerCAmelCase__ (				self) ->	Optional[Any]:
										if not hasattr(self.unet     ,						'_hf_hook'):
													return self.device
										for module in self.unet.modules():
													if (
													    hasattr(UpperCamelCase     ,						'_hf_hook')
													    and hasattr(module._hf_hook     ,						'execution_device')
													    and module._hf_hook.execution_device is not None
													):
																return torch.device(module._hf_hook.execution_device)
										return self.device






							@torch.no_grad()
							@replace_example_docstring(UpperCamelCase)
							def __call__(				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase = 5_12     ,						UpperCamelCase = 5_12     ,						UpperCamelCase = 1_00     ,						UpperCamelCase = 4.0     ,						UpperCamelCase = 0.3     ,						UpperCamelCase = 1     ,						UpperCamelCase = None     ,						UpperCamelCase = "pil"     ,						UpperCamelCase = True     ,						) ->	Optional[Any]:
										UpperCamelCase__    :		List[Any]     =				self._execution_device

										UpperCamelCase__    :		Union[str, Any]     =				guidance_scale > 1.0

										if isinstance(UpperCamelCase     ,						UpperCamelCase):
													UpperCamelCase__    :		Dict     =				torch.cat(UpperCamelCase     ,						dim=0)
										if isinstance(UpperCamelCase     ,						UpperCamelCase):
													UpperCamelCase__    :		List[Any]     =				torch.cat(UpperCamelCase     ,						dim=0)
										if isinstance(UpperCamelCase     ,						UpperCamelCase):
													UpperCamelCase__    :		Any     =				torch.cat(UpperCamelCase     ,						dim=0)

										UpperCamelCase__    :		Optional[Any]     =				image_embeds.shape[0]

										if do_classifier_free_guidance:
													UpperCamelCase__    :		List[str]     =				image_embeds.repeat_interleave(UpperCamelCase     ,						dim=0)
													UpperCamelCase__    :		Any     =				negative_image_embeds.repeat_interleave(UpperCamelCase     ,						dim=0)
													UpperCamelCase__    :		str     =				hint.repeat_interleave(UpperCamelCase     ,						dim=0)

										UpperCamelCase__    :		int     =				torch.cat([negative_image_embeds, image_embeds]     ,						dim=0).to(dtype=self.unet.dtype     ,						device=UpperCamelCase)
										UpperCamelCase__    :		Tuple     =				torch.cat([hint, hint]     ,						dim=0).to(dtype=self.unet.dtype     ,						device=UpperCamelCase)

										if not isinstance(UpperCamelCase     ,						UpperCamelCase):
													UpperCamelCase__    :		Tuple     =				[image]
										if not all(isinstance(UpperCamelCase     ,						(PIL.Image.Image, torch.Tensor)) for i in image):
													raise ValueError(
													    F"""Input is in incorrect format: {[type(UpperCamelCase) for i in image]}. Currently, we only support  PIL image and pytorch tensor""")

										UpperCamelCase__    :		List[str]     =				torch.cat([prepare_image(UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase) for i in image]     ,						dim=0)
										UpperCamelCase__    :		int     =				image.to(dtype=image_embeds.dtype     ,						device=UpperCamelCase)

										UpperCamelCase__    :		List[Any]     =				self.movq.encode(UpperCamelCase)['latents']
										UpperCamelCase__    :		str     =				latents.repeat_interleave(UpperCamelCase     ,						dim=0)
										self.scheduler.set_timesteps(UpperCamelCase     ,						device=UpperCamelCase)
										UpperCamelCase__   ,			UpperCamelCase__    :		List[str]     =				self.get_timesteps(UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase)
										UpperCamelCase__    :		List[str]     =				timesteps[:1].repeat(batch_size * num_images_per_prompt)
										UpperCamelCase__   ,			UpperCamelCase__    :		Optional[Any]     =				downscale_height_and_width(UpperCamelCase     ,						UpperCamelCase     ,						self.movq_scale_factor)
										UpperCamelCase__    :		int     =				self.prepare_latents(
										    UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						image_embeds.dtype     ,						UpperCamelCase     ,						UpperCamelCase)
										for i, t in enumerate(self.progress_bar(UpperCamelCase)):
													# expand the latents if we are doing classifier free guidance
													UpperCamelCase__    :		List[Any]     =				torch.cat([latents] * 2) if do_classifier_free_guidance else latents

													UpperCamelCase__    :		List[str]     =				{'image_embeds': image_embeds, 'hint': hint}
													UpperCamelCase__    :		List[Any]     =				self.unet(
													    sample=UpperCamelCase     ,						timestep=UpperCamelCase     ,						encoder_hidden_states=UpperCamelCase     ,						added_cond_kwargs=UpperCamelCase     ,						return_dict=UpperCamelCase     ,						)[0]

													if do_classifier_free_guidance:
																UpperCamelCase__   ,			UpperCamelCase__    :		str     =				noise_pred.split(latents.shape[1]     ,						dim=1)
																UpperCamelCase__   ,			UpperCamelCase__    :		Tuple     =				noise_pred.chunk(2)
																UpperCamelCase__   ,			UpperCamelCase__    :		Tuple     =				variance_pred.chunk(2)
																UpperCamelCase__    :		Tuple     =				noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
																UpperCamelCase__    :		Any     =				torch.cat([noise_pred, variance_pred_text]     ,						dim=1)

													if not (
													    hasattr(self.scheduler.config     ,						'variance_type')
													    and self.scheduler.config.variance_type in ["learned", "learned_range"]
													):
																UpperCamelCase__   ,			UpperCamelCase__    :		str     =				noise_pred.split(latents.shape[1]     ,						dim=1)

													# compute the previous noisy sample x_t -> x_t-1

													UpperCamelCase__    :		Union[str, Any]     =				self.scheduler.step(
													    UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						generator=UpperCamelCase     ,						)[0]

										# post-processing
										UpperCamelCase__    :		Optional[Any]     =				self.movq.decode(UpperCamelCase     ,						force_not_quantize=UpperCamelCase)['sample']

										if output_type not in ["pt", "np", "pil"]:
													raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""")

										if output_type in ["np", "pil"]:
													UpperCamelCase__    :		Any     =				image * 0.5 + 0.5
													UpperCamelCase__    :		Tuple     =				image.clamp(0     ,						1)
													UpperCamelCase__    :		Tuple     =				image.cpu().permute(0     ,						2     ,						3     ,						1).float().numpy()

										if output_type == "pil":
													UpperCamelCase__    :		Dict     =				self.numpy_to_pil(UpperCamelCase)

										if not return_dict:
													return (image,)

										return ImagePipelineOutput(images=UpperCamelCase)



