




import unittest

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

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


if is_torch_available():
						import torch

						from transformers import (
						    RemBertConfig,
						    RemBertForCausalLM,
						    RemBertForMaskedLM,
						    RemBertForMultipleChoice,
						    RemBertForQuestionAnswering,
						    RemBertForSequenceClassification,
						    RemBertForTokenClassification,
						    RemBertModel,
						)
						from transformers.models.rembert.modeling_rembert import REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST







class       UpperCAmelCase:



	"""simple docstring"""






	def __init__(     self       ,      lowerCamelCase       ,      lowerCamelCase=13       ,      lowerCamelCase=7       ,      lowerCamelCase=True       ,      lowerCamelCase=True       ,      lowerCamelCase=True       ,      lowerCamelCase=True       ,      lowerCamelCase=99       ,      lowerCamelCase=32       ,      lowerCamelCase=18       ,      lowerCamelCase=43       ,      lowerCamelCase=5       ,      lowerCamelCase=4       ,      lowerCamelCase=37       ,      lowerCamelCase="gelu"       ,      lowerCamelCase=0.1       ,      lowerCamelCase=0.1       ,      lowerCamelCase=512       ,      lowerCamelCase=16       ,      lowerCamelCase=2       ,      lowerCamelCase=0.02       ,      lowerCamelCase=3       ,      lowerCamelCase=4       ,      lowerCamelCase=None       ,      )					->			int:





								"""simple docstring"""


								lowercase__  :       List[str]   					=							parent
								lowercase__  :       Dict   					=							batch_size
								lowercase__  :       Any   					=							seq_length
								lowercase__  :       Tuple   					=							is_training
								lowercase__  :       Tuple   					=							use_input_mask
								lowercase__  :       List[str]   					=							use_token_type_ids
								lowercase__  :       Tuple   					=							use_labels
								lowercase__  :       List[str]   					=							vocab_size
								lowercase__  :       int   					=							hidden_size
								lowercase__  :       Union[str, Any]   					=							input_embedding_size
								lowercase__  :       Tuple   					=							output_embedding_size
								lowercase__  :       Dict   					=							num_hidden_layers
								lowercase__  :       Tuple   					=							num_attention_heads
								lowercase__  :       Tuple   					=							intermediate_size
								lowercase__  :       Optional[Any]   					=							hidden_act
								lowercase__  :       List[str]   					=							hidden_dropout_prob
								lowercase__  :       Optional[int]   					=							attention_probs_dropout_prob
								lowercase__  :       str   					=							max_position_embeddings
								lowercase__  :       Optional[Any]   					=							type_vocab_size
								lowercase__  :       List[str]   					=							type_sequence_label_size
								lowercase__  :       Optional[Any]   					=							initializer_range
								lowercase__  :       Any   					=							num_labels
								lowercase__  :       Any   					=							num_choices
								lowercase__  :       Optional[Any]   					=							scope

	def     __a	(     self				)					->			int:





								"""simple docstring"""


								lowercase__  :       Dict   					=							ids_tensor([self.batch_size, self.seq_length]       ,      self.vocab_size				)

								lowercase__  :       Dict   					=							None
								if self.use_input_mask:
															lowercase__  :       Dict   					=							random_attention_mask([self.batch_size, self.seq_length]				)

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

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

								lowercase__  :       Any   					=							RemBertConfig(
								    vocab_size=self.vocab_size       ,      hidden_size=self.hidden_size       ,      input_embedding_size=self.input_embedding_size       ,      output_embedding_size=self.output_embedding_size       ,      num_hidden_layers=self.num_hidden_layers       ,      num_attention_heads=self.num_attention_heads       ,      intermediate_size=self.intermediate_size       ,      hidden_act=self.hidden_act       ,      hidden_dropout_prob=self.hidden_dropout_prob       ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,      max_position_embeddings=self.max_position_embeddings       ,      type_vocab_size=self.type_vocab_size       ,      is_decoder=__SCREAMING_SNAKE_CASE       ,      initializer_range=self.initializer_range       ,      )

								return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

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





								"""simple docstring"""


								(
								    (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,         
								)  :       List[str]   					=							self.prepare_config_and_inputs()

								lowercase__  :       Dict   					=							True
								lowercase__  :       Any   					=							floats_tensor([self.batch_size, self.seq_length, self.hidden_size]				)
								lowercase__  :       List[str]   					=							ids_tensor([self.batch_size, self.seq_length]       ,      vocab_size=2				)

								return (
								    config,
								    input_ids,
								    token_type_ids,
								    input_mask,
								    sequence_labels,
								    token_labels,
								    choice_labels,
								    encoder_hidden_states,
								    encoder_attention_mask,
								)

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





								"""simple docstring"""


								lowercase__  :       Optional[Any]   					=							RemBertModel(config=__SCREAMING_SNAKE_CASE				)
								model.to(__SCREAMING_SNAKE_CASE				)
								model.eval()
								lowercase__  :       Union[str, Any]   					=							model(__SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE				)
								lowercase__  :       List[str]   					=							model(__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE				)
								lowercase__  :       Any   					=							model(__SCREAMING_SNAKE_CASE				)
								self.parent.assertEqual(result.last_hidden_state.shape       ,      (self.batch_size, self.seq_length, self.hidden_size)				)

	def     __a	(     self       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      )					->			Optional[int]:





								"""simple docstring"""


								lowercase__  :       Dict   					=							True
								lowercase__  :       List[Any]   					=							RemBertModel(__SCREAMING_SNAKE_CASE				)
								model.to(__SCREAMING_SNAKE_CASE				)
								model.eval()
								lowercase__  :       Any   					=							model(
								    __SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE       ,      encoder_hidden_states=__SCREAMING_SNAKE_CASE       ,      encoder_attention_mask=__SCREAMING_SNAKE_CASE       ,      )
								lowercase__  :       Any   					=							model(
								    __SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE       ,      encoder_hidden_states=__SCREAMING_SNAKE_CASE       ,      )
								lowercase__  :       Optional[int]   					=							model(__SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE				)
								self.parent.assertEqual(result.last_hidden_state.shape       ,      (self.batch_size, self.seq_length, self.hidden_size)				)

	def     __a	(     self       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      )					->			Any:





								"""simple docstring"""


								lowercase__  :       Optional[Any]   					=							RemBertForCausalLM(config=__SCREAMING_SNAKE_CASE				)
								model.to(__SCREAMING_SNAKE_CASE				)
								model.eval()
								lowercase__  :       List[Any]   					=							model(__SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE       ,      labels=__SCREAMING_SNAKE_CASE				)
								self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.seq_length, self.vocab_size)				)

	def     __a	(     self       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase				)					->			Any:





								"""simple docstring"""


								lowercase__  :       Optional[Any]   					=							RemBertForMaskedLM(config=__SCREAMING_SNAKE_CASE				)
								model.to(__SCREAMING_SNAKE_CASE				)
								model.eval()
								lowercase__  :       List[str]   					=							model(__SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE       ,      labels=__SCREAMING_SNAKE_CASE				)
								self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.seq_length, self.vocab_size)				)

	def     __a	(     self       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      )					->			Optional[int]:





								"""simple docstring"""


								lowercase__  :       List[Any]   					=							True
								lowercase__  :       List[str]   					=							True
								lowercase__  :       Any   					=							RemBertForCausalLM(config=__SCREAMING_SNAKE_CASE				)
								model.to(__SCREAMING_SNAKE_CASE				)
								model.eval()

								# first forward pass
								lowercase__  :       Optional[Any]   					=							model(
								    __SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      encoder_hidden_states=__SCREAMING_SNAKE_CASE       ,      encoder_attention_mask=__SCREAMING_SNAKE_CASE       ,      use_cache=__SCREAMING_SNAKE_CASE       ,      )
								lowercase__  :       Tuple   					=							outputs.past_key_values

								# create hypothetical multiple next token and extent to next_input_ids
								lowercase__  :       Tuple   					=							ids_tensor((self.batch_size, 3)       ,      config.vocab_size				)
								lowercase__  :       List[str]   					=							ids_tensor((self.batch_size, 3)       ,      vocab_size=2				)

								# append to next input_ids and
								lowercase__  :       List[Any]   					=							torch.cat([input_ids, next_tokens]       ,      dim=-1				)
								lowercase__  :       int   					=							torch.cat([input_mask, next_mask]       ,      dim=-1				)

								lowercase__  :       List[Any]   					=							model(
								    __SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      encoder_hidden_states=__SCREAMING_SNAKE_CASE       ,      encoder_attention_mask=__SCREAMING_SNAKE_CASE       ,      output_hidden_states=__SCREAMING_SNAKE_CASE       ,      )["hidden_states"][0]
								lowercase__  :       int   					=							model(
								    __SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      encoder_hidden_states=__SCREAMING_SNAKE_CASE       ,      encoder_attention_mask=__SCREAMING_SNAKE_CASE       ,      past_key_values=__SCREAMING_SNAKE_CASE       ,      output_hidden_states=__SCREAMING_SNAKE_CASE       ,      )["hidden_states"][0]

								# select random slice
								lowercase__  :       Dict   					=							ids_tensor((1,)       ,      output_from_past.shape[-1]				).item()
								lowercase__  :       int   					=							output_from_no_past[:, -3:, random_slice_idx].detach()
								lowercase__  :       Tuple   					=							output_from_past[:, :, random_slice_idx].detach()

								self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]				)

								# test that outputs are equal for slice
								self.parent.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE       ,      __SCREAMING_SNAKE_CASE       ,      atol=1E-3				)				)

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





								"""simple docstring"""


								lowercase__  :       Dict   					=							RemBertForQuestionAnswering(config=__SCREAMING_SNAKE_CASE				)
								model.to(__SCREAMING_SNAKE_CASE				)
								model.eval()
								lowercase__  :       Any   					=							model(
								    __SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE       ,      start_positions=__SCREAMING_SNAKE_CASE       ,      end_positions=__SCREAMING_SNAKE_CASE       ,      )
								self.parent.assertEqual(result.start_logits.shape       ,      (self.batch_size, self.seq_length)				)
								self.parent.assertEqual(result.end_logits.shape       ,      (self.batch_size, self.seq_length)				)

	def     __a	(     self       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase				)					->			Any:





								"""simple docstring"""


								lowercase__  :       List[str]   					=							self.num_labels
								lowercase__  :       str   					=							RemBertForSequenceClassification(__SCREAMING_SNAKE_CASE				)
								model.to(__SCREAMING_SNAKE_CASE				)
								model.eval()
								lowercase__  :       int   					=							model(__SCREAMING_SNAKE_CASE       ,      attention_mask=__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE       ,      labels=__SCREAMING_SNAKE_CASE				)
								self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.num_labels)				)

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





								"""simple docstring"""


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

	def     __a	(     self       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase				)					->			int:





								"""simple docstring"""


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







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





								"""simple docstring"""


								lowercase__  :       List[str]   					=							self.prepare_config_and_inputs()
								(
								    (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,         
								)  :       int   					=							config_and_inputs
								lowercase__  :       Optional[int]   					=							{"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
								return config, inputs_dict







@require_torch
class       UpperCAmelCase(     __lowerCAmelCase    ,	__lowerCAmelCase    ,	unittest.TestCase     ):



	"""simple docstring"""






	a	:					Union[str, Any]         =     (
	    (
	        RemBertModel,
	        RemBertForMaskedLM,
	        RemBertForCausalLM,
	        RemBertForMultipleChoice,
	        RemBertForQuestionAnswering,
	        RemBertForSequenceClassification,
	        RemBertForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	a	:					str         =     (RemBertForCausalLM,) if is_torch_available() else ()
	a	:					Optional[int]         =     (
	    {
	        """feature-extraction""": RemBertModel,
	        """fill-mask""": RemBertForMaskedLM,
	        """question-answering""": RemBertForQuestionAnswering,
	        """text-classification""": RemBertForSequenceClassification,
	        """text-generation""": RemBertForCausalLM,
	        """token-classification""": RemBertForTokenClassification,
	        """zero-shot""": RemBertForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)

	def     __a	(     self				)					->			Dict:





								"""simple docstring"""


								lowercase__  :       Dict   					=							RemBertModelTester(self				)
								lowercase__  :       List[Any]   					=							ConfigTester(self       ,      config_class=__SCREAMING_SNAKE_CASE       ,      hidden_size=37				)

	def     __a	(     self				)					->			int:





								"""simple docstring"""


								self.config_tester.run_common_tests()

	def     __a	(     self				)					->			Optional[Any]:





								"""simple docstring"""


								lowercase__  :       Dict   					=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE				)

	def     __a	(     self				)					->			Dict:





								"""simple docstring"""


								lowercase__  :       List[str]   					=							self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
															lowercase__  :       str   					=							type
															self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE				)

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





								"""simple docstring"""


								lowercase__  :       Optional[Any]   					=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_lm(*__SCREAMING_SNAKE_CASE				)

	def     __a	(     self				)					->			Dict:





								"""simple docstring"""


								lowercase__  :       Optional[int]   					=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_multiple_choice(*__SCREAMING_SNAKE_CASE				)

	def     __a	(     self				)					->			Optional[Any]:





								"""simple docstring"""


								lowercase__  :       Union[str, Any]   					=							self.model_tester.prepare_config_and_inputs_for_decoder()
								self.model_tester.create_and_check_decoder_model_past_large_inputs(*__SCREAMING_SNAKE_CASE				)

	def     __a	(     self				)					->			Any:





								"""simple docstring"""


								lowercase__  :       List[Any]   					=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE				)

	def     __a	(     self				)					->			Dict:





								"""simple docstring"""


								lowercase__  :       Optional[Any]   					=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE				)

	def     __a	(     self				)					->			Dict:





								"""simple docstring"""


								lowercase__  :       Any   					=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE				)

	def     __a	(     self				)					->			str:





								"""simple docstring"""


								lowercase__  :       Any   					=							self.model_tester.prepare_config_and_inputs_for_decoder()
								self.model_tester.create_and_check_model_as_decoder(*__SCREAMING_SNAKE_CASE				)

	def     __a	(     self				)					->			Optional[Any]:





								"""simple docstring"""


								(
								    (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,   (
								    lowercase__      
								)					,         
								)  :       str   					=							self.model_tester.prepare_config_and_inputs_for_decoder()

								lowercase__  :       Optional[int]   					=							None

								self.model_tester.create_and_check_model_as_decoder(
								    __SCREAMING_SNAKE_CASE       ,      __SCREAMING_SNAKE_CASE       ,      __SCREAMING_SNAKE_CASE       ,      __SCREAMING_SNAKE_CASE       ,      __SCREAMING_SNAKE_CASE       ,      __SCREAMING_SNAKE_CASE       ,      __SCREAMING_SNAKE_CASE       ,      __SCREAMING_SNAKE_CASE       ,      __SCREAMING_SNAKE_CASE       ,      )







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





								"""simple docstring"""


								for model_name in REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															lowercase__  :       int   					=							RemBertModel.from_pretrained(__SCREAMING_SNAKE_CASE				)
															self.assertIsNotNone(__SCREAMING_SNAKE_CASE				)







@require_torch
class       UpperCAmelCase(     unittest.TestCase     ):



	"""simple docstring"""






	@slow
	def     __a	(     self				)					->			Optional[int]:





								"""simple docstring"""


								lowercase__  :       int   					=							RemBertModel.from_pretrained("google/rembert"				)
								lowercase__  :       Tuple   					=							torch.tensor([[312, 56498, 313, 2125, 313]]				)
								lowercase__  :       Optional[Any]   					=							torch.tensor([[0, 0, 0, 1, 1]]				)
								with torch.no_grad():
															lowercase__  :       Optional[Any]   					=							model(__SCREAMING_SNAKE_CASE       ,      token_type_ids=__SCREAMING_SNAKE_CASE       ,      output_hidden_states=__SCREAMING_SNAKE_CASE				)

								lowercase__  :       Tuple   					=							1152

								lowercase__  :       List[Any]   					=							torch.Size((1, 5, hidden_size)				)
								self.assertEqual(output["last_hidden_state"].shape       ,      __SCREAMING_SNAKE_CASE				)

								lowercase__  :       Any   					=							torch.tensor(
								    [
								        [
								            [0.07_54, -0.20_22, 0.19_04],
								            [-0.33_54, -0.36_92, -0.47_91],
								            [-0.23_14, -0.67_29, -0.07_49],
								            [-0.03_96, -0.31_05, -0.42_34],
								            [-0.15_71, -0.05_25, 0.53_53],
								        ]
								    ]				)

								# Running on the original tf implementation gives slightly different results here.
								# Not clear why this variations is present
								# TODO: Find reason for discrepancy
								# expected_original_implementation = [[
								#     [0.07630594074726105, -0.20146065950393677, 0.19107051193714142],
								#     [-0.3405614495277405, -0.36971670389175415, -0.4808273911476135],
								#     [-0.22587086260318756, -0.6656315922737122, -0.07844287157058716],
								#     [-0.04145475849509239, -0.3077218234539032, -0.42316967248916626],
								#     [-0.15887849032878876, -0.054529931396245956, 0.5356100797653198]
								# ]]

								self.assertTrue(torch.allclose(output["last_hidden_state"][:, :, :3]       ,      __SCREAMING_SNAKE_CASE       ,      atol=1E-4				)				)






"""simple docstring"""


import types
from typing import List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer
from transformers.models.clip.modeling_clip import CLIPTextModelOutput

from diffusers.models import PriorTransformer
from diffusers.pipelines import DiffusionPipeline, StableDiffusionImageVariationPipeline
from diffusers.schedulers import UnCLIPScheduler
from diffusers.utils import logging, randn_tensor


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





def 							a__	(     self		,   _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase		)			->     List[str]:

 '''simple docstring'''






 snake_case__										= image.to(device=_UpperCAmelCase		)
 snake_case__										= image  # take image as image_embeddings
 snake_case__										= image_embeddings.unsqueeze(1		)

 # duplicate image embeddings for each generation per prompt, using mps friendly method
 snake_case__							,      snake_case__							,      snake_case__										= image_embeddings.shape
 snake_case__										= image_embeddings.repeat(1		,   _UpperCAmelCase		,   1		)
 snake_case__										= image_embeddings.view(bs_embed * num_images_per_prompt		,   _UpperCAmelCase		,   -1		)

 if do_classifier_free_guidance:
  snake_case__										= torch.zeros_like(_UpperCAmelCase		)

  # For classifier free guidance, we need to do two forward passes.
  # Here we concatenate the unconditional and text embeddings into a single batch
  # to avoid doing two forward passes
  snake_case__										= torch.cat([uncond_embeddings, image_embeddings]		)

 return image_embeddings



class    lowercase_ (   __lowerCAmelCase							):

       def __init__(	self      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE = None      ,    ):






        '''simple docstring'''

        super().__init__()

        snake_case__										= {"image_encoder": None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs

        snake_case__										= decoder_pipe_kwargs.get("torch_dtype"      ,    __SCREAMING_SNAKE_CASE   ) or prior.dtype

        snake_case__										= StableDiffusionImageVariationPipeline.from_pretrained(
            "lambdalabs/sd-image-variations-diffusers"      ,    **__SCREAMING_SNAKE_CASE   )

        # replace `_encode_image` method
        snake_case__										= types.MethodType(_encode_image      ,    self.decoder_pipe   )

        self.register_modules(
            prior=__SCREAMING_SNAKE_CASE      ,    tokenizer=__SCREAMING_SNAKE_CASE      ,    text_encoder=__SCREAMING_SNAKE_CASE      ,    prior_scheduler=__SCREAMING_SNAKE_CASE      ,    )

       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE = None      ,    __SCREAMING_SNAKE_CASE = None      ,    ):






        '''simple docstring'''

        if text_model_output is None:
         snake_case__										= len(__SCREAMING_SNAKE_CASE   ) if isinstance(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ) else 1
         # get prompt text embeddings
         snake_case__										= self.tokenizer(
             __SCREAMING_SNAKE_CASE      ,    padding="max_length"      ,    max_length=self.tokenizer.model_max_length      ,    return_tensors="pt"      ,    )
         snake_case__										= text_inputs.input_ids
         snake_case__										= text_inputs.attention_mask.bool().to(__SCREAMING_SNAKE_CASE   )

         if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
          snake_case__										= self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]   )
          logger.warning(
              "The following part of your input was truncated because CLIP can only handle sequences up to"
              F" {self.tokenizer.model_max_length} tokens: {removed_text}"   )
          snake_case__										= text_input_ids[:, : self.tokenizer.model_max_length]

         snake_case__										= self.text_encoder(text_input_ids.to(__SCREAMING_SNAKE_CASE   )   )

         snake_case__										= text_encoder_output.text_embeds
         snake_case__										= text_encoder_output.last_hidden_state

        else:
         snake_case__										= text_model_output[0].shape[0]
         snake_case__							,      snake_case__										= text_model_output[0], text_model_output[1]
         snake_case__										= text_attention_mask

        snake_case__										= text_embeddings.repeat_interleave(__SCREAMING_SNAKE_CASE      ,    dim=0   )
        snake_case__										= text_encoder_hidden_states.repeat_interleave(__SCREAMING_SNAKE_CASE      ,    dim=0   )
        snake_case__										= text_mask.repeat_interleave(__SCREAMING_SNAKE_CASE      ,    dim=0   )

        if do_classifier_free_guidance:
         snake_case__										= [""] * batch_size

         snake_case__										= self.tokenizer(
             __SCREAMING_SNAKE_CASE      ,    padding="max_length"      ,    max_length=self.tokenizer.model_max_length      ,    truncation=__SCREAMING_SNAKE_CASE      ,    return_tensors="pt"      ,    )
         snake_case__										= uncond_input.attention_mask.bool().to(__SCREAMING_SNAKE_CASE   )
         snake_case__										= self.text_encoder(uncond_input.input_ids.to(__SCREAMING_SNAKE_CASE   )   )

         snake_case__										= uncond_embeddings_text_encoder_output.text_embeds
         snake_case__										= uncond_embeddings_text_encoder_output.last_hidden_state

         # duplicate unconditional embeddings for each generation per prompt, using mps friendly method

         snake_case__										= uncond_embeddings.shape[1]
         snake_case__										= uncond_embeddings.repeat(1      ,    __SCREAMING_SNAKE_CASE   )
         snake_case__										= uncond_embeddings.view(batch_size * num_images_per_prompt      ,    __SCREAMING_SNAKE_CASE   )

         snake_case__										= uncond_text_encoder_hidden_states.shape[1]
         snake_case__										= uncond_text_encoder_hidden_states.repeat(1      ,    __SCREAMING_SNAKE_CASE      ,    1   )
         snake_case__										= uncond_text_encoder_hidden_states.view(
             batch_size * num_images_per_prompt      ,    __SCREAMING_SNAKE_CASE      ,    -1   )
         snake_case__										= uncond_text_mask.repeat_interleave(__SCREAMING_SNAKE_CASE      ,    dim=0   )

         # done duplicates

         # For classifier free guidance, we need to do two forward passes.
         # Here we concatenate the unconditional and text embeddings into a single batch
         # to avoid doing two forward passes
         snake_case__										= torch.cat([uncond_embeddings, text_embeddings]   )
         snake_case__										= torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]   )

         snake_case__										= torch.cat([uncond_text_mask, text_mask]   )

        return text_embeddings, text_encoder_hidden_states, text_mask

       @property
       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        if self.device != torch.device("meta"   ) or not hasattr(self.prior      ,    "_hf_hook"   ):
         return self.device
        for module in self.prior.modules():
         if (
             hasattr(__SCREAMING_SNAKE_CASE      ,    "_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

       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        if latents is None:
         snake_case__										= randn_tensor(__SCREAMING_SNAKE_CASE      ,    generator=__SCREAMING_SNAKE_CASE      ,    device=__SCREAMING_SNAKE_CASE      ,    dtype=__SCREAMING_SNAKE_CASE   )
        else:
         if latents.shape != shape:
          raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"   )
         snake_case__										= latents.to(__SCREAMING_SNAKE_CASE   )

        snake_case__										= latents * scheduler.init_noise_sigma
        return latents

       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE = None   ):






        '''simple docstring'''

        self.decoder_pipe.to(__SCREAMING_SNAKE_CASE   )
        super().to(__SCREAMING_SNAKE_CASE   )

       @torch.no_grad()
       def __call__(	self      ,    __SCREAMING_SNAKE_CASE = None      ,    __SCREAMING_SNAKE_CASE = None      ,    __SCREAMING_SNAKE_CASE = None      ,    __SCREAMING_SNAKE_CASE = 1      ,    __SCREAMING_SNAKE_CASE = 25      ,    __SCREAMING_SNAKE_CASE = None      ,    __SCREAMING_SNAKE_CASE = None      ,    __SCREAMING_SNAKE_CASE = None      ,    __SCREAMING_SNAKE_CASE = None      ,    __SCREAMING_SNAKE_CASE = 4.0      ,    __SCREAMING_SNAKE_CASE = 8.0      ,    __SCREAMING_SNAKE_CASE = 50      ,    __SCREAMING_SNAKE_CASE = 1      ,    __SCREAMING_SNAKE_CASE = 0.0      ,    __SCREAMING_SNAKE_CASE = "pil"      ,    __SCREAMING_SNAKE_CASE = True      ,    ):






        '''simple docstring'''

        if prompt is not None:
         if isinstance(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ):
          snake_case__										= 1
         elif isinstance(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ):
          snake_case__										= len(__SCREAMING_SNAKE_CASE   )
         else:
          raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(__SCREAMING_SNAKE_CASE   )}"   )
        else:
         snake_case__										= text_model_output[0].shape[0]

        snake_case__										= self._execution_device

        snake_case__										= batch_size * num_images_per_prompt

        snake_case__										= prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0

        snake_case__							,      snake_case__							,      snake_case__										= self._encode_prompt(
            __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   )

        # prior

        self.prior_scheduler.set_timesteps(__SCREAMING_SNAKE_CASE      ,    device=__SCREAMING_SNAKE_CASE   )
        snake_case__										= self.prior_scheduler.timesteps

        snake_case__										= self.prior.config.embedding_dim

        snake_case__										= self.prepare_latents(
            (batch_size, embedding_dim)      ,    text_embeddings.dtype      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    self.prior_scheduler      ,    )

        for i, t in enumerate(self.progress_bar(__SCREAMING_SNAKE_CASE   )   ):
         # expand the latents if we are doing classifier free guidance
         snake_case__										= torch.cat([prior_latents] * 2   ) if do_classifier_free_guidance else prior_latents

         snake_case__										= self.prior(
             __SCREAMING_SNAKE_CASE      ,    timestep=__SCREAMING_SNAKE_CASE      ,    proj_embedding=__SCREAMING_SNAKE_CASE      ,    encoder_hidden_states=__SCREAMING_SNAKE_CASE      ,    attention_mask=__SCREAMING_SNAKE_CASE      ,    ).predicted_image_embedding

         if do_classifier_free_guidance:
          snake_case__							,      snake_case__										= predicted_image_embedding.chunk(2   )
          snake_case__										= predicted_image_embedding_uncond + prior_guidance_scale * (
              predicted_image_embedding_text - predicted_image_embedding_uncond
          )

         if i + 1 == prior_timesteps_tensor.shape[0]:
          snake_case__										= None
         else:
          snake_case__										= prior_timesteps_tensor[i + 1]

         snake_case__										= self.prior_scheduler.step(
             __SCREAMING_SNAKE_CASE      ,    timestep=__SCREAMING_SNAKE_CASE      ,    sample=__SCREAMING_SNAKE_CASE      ,    generator=__SCREAMING_SNAKE_CASE      ,    prev_timestep=__SCREAMING_SNAKE_CASE      ,    ).prev_sample

        snake_case__										= self.prior.post_process_latents(__SCREAMING_SNAKE_CASE   )

        snake_case__										= prior_latents

        snake_case__										= self.decoder_pipe(
            image=__SCREAMING_SNAKE_CASE      ,    height=__SCREAMING_SNAKE_CASE      ,    width=__SCREAMING_SNAKE_CASE      ,    num_inference_steps=__SCREAMING_SNAKE_CASE      ,    guidance_scale=__SCREAMING_SNAKE_CASE      ,    generator=__SCREAMING_SNAKE_CASE      ,    output_type=__SCREAMING_SNAKE_CASE      ,    return_dict=__SCREAMING_SNAKE_CASE      ,    num_images_per_prompt=__SCREAMING_SNAKE_CASE      ,    eta=__SCREAMING_SNAKE_CASE      ,    )
        return output

