



import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import BlipImageProcessor







class 							a_  (		unittest.TestCase				):

						def __init__(    self	:Optional[int]   ,						_lowercase	:str   ,						_lowercase	:Tuple=7   ,						_lowercase	:str=3   ,						_lowercase	:Dict=18   ,						_lowercase	:int=30   ,						_lowercase	:int=400   ,						_lowercase	:Dict=True   ,						_lowercase	:int=None   ,						_lowercase	:List[Any]=True   ,						_lowercase	:int=False   ,						_lowercase	:Dict=[0.48_145_466, 0.4_578_275, 0.40_821_073]   ,						_lowercase	:Union[str, Any]=[0.26_862_954, 0.26_130_258, 0.27_577_711]   ,						_lowercase	:Optional[Any]=True   ,						)		->					int:
												UpperCAmelCase_     							=     size if size is not None else {'''height''': 20, '''width''': 20}
												UpperCAmelCase_     							=     parent
												UpperCAmelCase_     							=     batch_size
												UpperCAmelCase_     							=     num_channels
												UpperCAmelCase_     							=     image_size
												UpperCAmelCase_     							=     min_resolution
												UpperCAmelCase_     							=     max_resolution
												UpperCAmelCase_     							=     do_resize
												UpperCAmelCase_     							=     size
												UpperCAmelCase_     							=     do_normalize
												UpperCAmelCase_     							=     image_mean
												UpperCAmelCase_     							=     image_std
												UpperCAmelCase_     							=     do_pad
												UpperCAmelCase_     							=     do_convert_rgb

						def 	__a       (    self	:int)		->					Optional[int]:
												return {
												    "do_resize": self.do_resize,
												    "size": self.size,
												    "do_normalize": self.do_normalize,
												    "image_mean": self.image_mean,
												    "image_std": self.image_std,
												    "do_convert_rgb": self.do_convert_rgb,
												    "do_pad": self.do_pad,
												}




						def 	__a       (    self	:Tuple   ,						_lowercase	:Dict=False   ,						_lowercase	:Union[str, Any]=False   ,						_lowercase	:Dict=False)		->					int:
												assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

												if equal_resolution:
																		UpperCAmelCase_     							=     []
																		for i in range(self.batch_size):
																								image_inputs.append(
																								    np.random.randint(
																								        255   ,						size=(self.num_channels, self.max_resolution, self.max_resolution)   ,						dtype=np.uinta))
												else:
																		UpperCAmelCase_     							=     []
																		for i in range(self.batch_size):
																								UpperCAmelCase_							,      UpperCAmelCase_     							=     np.random.choice(np.arange(self.min_resolution   ,						self.max_resolution)   ,						2)
																								image_inputs.append(np.random.randint(255   ,						size=(self.num_channels, width, height)   ,						dtype=np.uinta))

												if not numpify and not torchify:
																		# PIL expects the channel dimension as last dimension
																		UpperCAmelCase_     							=     [Image.fromarray(np.moveaxis(_lowercase   ,						0   ,						-1)) for x in image_inputs]

												if torchify:
																		UpperCAmelCase_     							=     [torch.from_numpy(_lowercase) for x in image_inputs]

												return image_inputs







@require_torch
@require_vision
class 							a_  (		_snake_case					, unittest.TestCase				):
						UpperCamelCase__      :						Tuple				       =BlipImageProcessor if is_vision_available() else None

						def 	__a       (    self	:Optional[int])		->					str:
												UpperCAmelCase_     							=     BlipImageProcessingTester(self)

						@property
						def 	__a       (    self	:Optional[Any])		->					Dict:
												return self.image_processor_tester.prepare_image_processor_dict()

						def 	__a       (    self	:Union[str, Any])		->					str:
												UpperCAmelCase_     							=     self.image_processing_class(**self.image_processor_dict)
												self.assertTrue(hasattr(_lowercase   ,						'''do_resize'''))
												self.assertTrue(hasattr(_lowercase   ,						'''size'''))
												self.assertTrue(hasattr(_lowercase   ,						'''do_normalize'''))
												self.assertTrue(hasattr(_lowercase   ,						'''image_mean'''))
												self.assertTrue(hasattr(_lowercase   ,						'''image_std'''))
												self.assertTrue(hasattr(_lowercase   ,						'''do_convert_rgb'''))

						def 	__a       (    self	:Tuple)		->					int:
												pass

						def 	__a       (    self	:Optional[Any])		->					Union[str, Any]:
												# Initialize image_processor
												UpperCAmelCase_     							=     self.image_processing_class(**self.image_processor_dict)
												# create random PIL images
												UpperCAmelCase_     							=     self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase)
												for image in image_inputs:
																		self.assertIsInstance(_lowercase   ,						Image.Image)

												# Test not batched input
												UpperCAmelCase_     							=     image_processor(image_inputs[0]   ,						return_tensors='''pt''').pixel_values
												self.assertEqual(
												    encoded_images.shape   ,						(
												        1,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.size['''height'''],
												        self.image_processor_tester.size['''width'''],
												    )   ,						)

												# Test batched
												UpperCAmelCase_     							=     image_processor(_lowercase   ,						return_tensors='''pt''').pixel_values
												self.assertEqual(
												    encoded_images.shape   ,						(
												        self.image_processor_tester.batch_size,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.size['''height'''],
												        self.image_processor_tester.size['''width'''],
												    )   ,						)

						def 	__a       (    self	:str)		->					int:
												# Initialize image_processor
												UpperCAmelCase_     							=     self.image_processing_class(**self.image_processor_dict)
												# create random numpy tensors
												UpperCAmelCase_     							=     self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase   ,						numpify=_lowercase)
												for image in image_inputs:
																		self.assertIsInstance(_lowercase   ,						np.ndarray)

												# Test not batched input
												UpperCAmelCase_     							=     image_processor(image_inputs[0]   ,						return_tensors='''pt''').pixel_values
												self.assertEqual(
												    encoded_images.shape   ,						(
												        1,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.size['''height'''],
												        self.image_processor_tester.size['''width'''],
												    )   ,						)

												# Test batched
												UpperCAmelCase_     							=     image_processor(_lowercase   ,						return_tensors='''pt''').pixel_values
												self.assertEqual(
												    encoded_images.shape   ,						(
												        self.image_processor_tester.batch_size,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.size['''height'''],
												        self.image_processor_tester.size['''width'''],
												    )   ,						)




						def 	__a       (    self	:Optional[Any])		->					str:
												# Initialize image_processor
												UpperCAmelCase_     							=     self.image_processing_class(**self.image_processor_dict)
												# create random PyTorch tensors
												UpperCAmelCase_     							=     self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase   ,						torchify=_lowercase)
												for image in image_inputs:
																		self.assertIsInstance(_lowercase   ,						torch.Tensor)

												# Test not batched input
												UpperCAmelCase_     							=     image_processor(image_inputs[0]   ,						return_tensors='''pt''').pixel_values
												self.assertEqual(
												    encoded_images.shape   ,						(
												        1,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.size['''height'''],
												        self.image_processor_tester.size['''width'''],
												    )   ,						)

												# Test batched
												UpperCAmelCase_     							=     image_processor(_lowercase   ,						return_tensors='''pt''').pixel_values
												self.assertEqual(
												    encoded_images.shape   ,						(
												        self.image_processor_tester.batch_size,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.size['''height'''],
												        self.image_processor_tester.size['''width'''],
												    )   ,						)







@require_torch
@require_vision
class 							a_  (		_snake_case					, unittest.TestCase				):
						UpperCamelCase__      :						Dict				       =BlipImageProcessor if is_vision_available() else None

						def 	__a       (    self	:Tuple)		->					Dict:
												UpperCAmelCase_     							=     BlipImageProcessingTester(self   ,						num_channels=4)
												UpperCAmelCase_     							=     3

						@property
						def 	__a       (    self	:str)		->					Dict:
												return self.image_processor_tester.prepare_image_processor_dict()

						def 	__a       (    self	:Any)		->					int:
												UpperCAmelCase_     							=     self.image_processing_class(**self.image_processor_dict)
												self.assertTrue(hasattr(_lowercase   ,						'''do_resize'''))
												self.assertTrue(hasattr(_lowercase   ,						'''size'''))
												self.assertTrue(hasattr(_lowercase   ,						'''do_normalize'''))
												self.assertTrue(hasattr(_lowercase   ,						'''image_mean'''))
												self.assertTrue(hasattr(_lowercase   ,						'''image_std'''))
												self.assertTrue(hasattr(_lowercase   ,						'''do_convert_rgb'''))

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




						def 	__a       (    self	:Dict)		->					str:
												# Initialize image_processor
												UpperCAmelCase_     							=     self.image_processing_class(**self.image_processor_dict)
												# create random PIL images
												UpperCAmelCase_     							=     self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase)
												for image in image_inputs:
																		self.assertIsInstance(_lowercase   ,						Image.Image)

												# Test not batched input
												UpperCAmelCase_     							=     image_processor(image_inputs[0]   ,						return_tensors='''pt''').pixel_values
												self.assertEqual(
												    encoded_images.shape   ,						(
												        1,
												        self.expected_encoded_image_num_channels,
												        self.image_processor_tester.size['''height'''],
												        self.image_processor_tester.size['''width'''],
												    )   ,						)

												# Test batched
												UpperCAmelCase_     							=     image_processor(_lowercase   ,						return_tensors='''pt''').pixel_values
												self.assertEqual(
												    encoded_images.shape   ,						(
												        self.image_processor_tester.batch_size,
												        self.expected_encoded_image_num_channels,
												        self.image_processor_tester.size['''height'''],
												        self.image_processor_tester.size['''width'''],
												    )   ,						)












"""simple docstring"""
from __future__ import annotations

import unittest

from transformers import MPNetConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
       import tensorflow as tf

       from transformers.models.mpnet.modeling_tf_mpnet import (
           TFMPNetForMaskedLM,
           TFMPNetForMultipleChoice,
           TFMPNetForQuestionAnswering,
           TFMPNetForSequenceClassification,
           TFMPNetForTokenClassification,
           TFMPNetModel,
       )







class 	a				:



 def __init__(			self							,    _snake_case							,    _snake_case=13							,    _snake_case=7							,    _snake_case=True							,    _snake_case=True							,    _snake_case=False							,    _snake_case=True							,    _snake_case=99							,    _snake_case=64							,    _snake_case=2							,    _snake_case=4							,    _snake_case=64							,    _snake_case="gelu"							,    _snake_case=0.1							,    _snake_case=0.1							,    _snake_case=5_12							,    _snake_case=16							,    _snake_case=2							,    _snake_case=0.02							,    _snake_case=3							,    _snake_case=4							,    _snake_case=None							,    ):







  """simple docstring"""






  lowerCAmelCase  							=      parent
  lowerCAmelCase  							=      batch_size
  lowerCAmelCase  							=      seq_length
  lowerCAmelCase  							=      is_training
  lowerCAmelCase  							=      use_input_mask
  lowerCAmelCase  							=      use_token_type_ids
  lowerCAmelCase  							=      use_labels
  lowerCAmelCase  							=      vocab_size
  lowerCAmelCase  							=      hidden_size
  lowerCAmelCase  							=      num_hidden_layers
  lowerCAmelCase  							=      num_attention_heads
  lowerCAmelCase  							=      intermediate_size
  lowerCAmelCase  							=      hidden_act
  lowerCAmelCase  							=      hidden_dropout_prob
  lowerCAmelCase  							=      attention_probs_dropout_prob
  lowerCAmelCase  							=      max_position_embeddings
  lowerCAmelCase  							=      type_vocab_size
  lowerCAmelCase  							=      type_sequence_label_size
  lowerCAmelCase  							=      initializer_range
  lowerCAmelCase  							=      num_labels
  lowerCAmelCase  							=      num_choices
  lowerCAmelCase  							=      scope



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      ids_tensor([self.batch_size, self.seq_length]							,    self.vocab_size			)

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

  lowerCAmelCase  							=      None
  lowerCAmelCase  							=      None
  lowerCAmelCase  							=      None
  if self.use_labels:
   lowerCAmelCase  							=      ids_tensor([self.batch_size]							,    self.type_sequence_label_size			)
   lowerCAmelCase  							=      ids_tensor([self.batch_size, self.seq_length]							,    self.num_labels			)
   lowerCAmelCase  							=      ids_tensor([self.batch_size]							,    self.num_choices			)

  lowerCAmelCase  							=      MPNetConfig(
      vocab_size=self.vocab_size							,    hidden_size=self.hidden_size							,    num_hidden_layers=self.num_hidden_layers							,    num_attention_heads=self.num_attention_heads							,    intermediate_size=self.intermediate_size							,    hidden_act=self.hidden_act							,    hidden_dropout_prob=self.hidden_dropout_prob							,    attention_probs_dropout_prob=self.attention_probs_dropout_prob							,    max_position_embeddings=self.max_position_embeddings							,    initializer_range=self.initializer_range							,    )
  return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetModel(config=_snake_case			)
  lowerCAmelCase  							=      {'input_ids': input_ids, 'attention_mask': input_mask}
  lowerCAmelCase  							=      model(_snake_case			)
  lowerCAmelCase  							=      [input_ids, input_mask]
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.last_hidden_state.shape							,    (self.batch_size, self.seq_length, self.hidden_size)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetForMaskedLM(config=_snake_case			)
  lowerCAmelCase  							=      {'input_ids': input_ids, 'attention_mask': input_mask}
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.seq_length, self.vocab_size)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetForQuestionAnswering(config=_snake_case			)
  lowerCAmelCase  							=      {
      'input_ids': input_ids,
      'attention_mask': input_mask,
  }
  lowerCAmelCase  							=      model(_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 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      self.num_labels
  lowerCAmelCase  							=      TFMPNetForSequenceClassification(_snake_case			)
  lowerCAmelCase  							=      {'input_ids': input_ids, 'attention_mask': input_mask}
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_labels)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      self.num_choices
  lowerCAmelCase  							=      TFMPNetForMultipleChoice(_snake_case			)
  lowerCAmelCase  							=      tf.tile(tf.expand_dims(_snake_case							,    1			)							,    (1, self.num_choices, 1)			)
  lowerCAmelCase  							=      tf.tile(tf.expand_dims(_snake_case							,    1			)							,    (1, self.num_choices, 1)			)
  lowerCAmelCase  							=      {
      'input_ids': multiple_choice_inputs_ids,
      'attention_mask': multiple_choice_input_mask,
  }
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_choices)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      self.num_labels
  lowerCAmelCase  							=      TFMPNetForTokenClassification(_snake_case			)
  lowerCAmelCase  							=      {'input_ids': input_ids, 'attention_mask': input_mask}
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.seq_length, self.num_labels)			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.prepare_config_and_inputs()
  ((lowerCAmelCase)							,(lowerCAmelCase)							,(lowerCAmelCase)							,(lowerCAmelCase)							,(lowerCAmelCase)							,(lowerCAmelCase))  							=      config_and_inputs
  lowerCAmelCase  							=      {'input_ids': input_ids, 'attention_mask': input_mask}
  return config, inputs_dict







@require_tf
class 	a				(					a__					,      a__					,      unittest.TestCase   ):
 snake_case__    	=    (
     (
         TFMPNetForMaskedLM,
         TFMPNetForMultipleChoice,
         TFMPNetForQuestionAnswering,
         TFMPNetForSequenceClassification,
         TFMPNetForTokenClassification,
         TFMPNetModel,
     )
     if is_tf_available()
     else ()
 )
 snake_case__    	=    (
     {
         '''feature-extraction''': TFMPNetModel,
         '''fill-mask''': TFMPNetForMaskedLM,
         '''question-answering''': TFMPNetForQuestionAnswering,
         '''text-classification''': TFMPNetForSequenceClassification,
         '''token-classification''': TFMPNetForTokenClassification,
         '''zero-shot''': TFMPNetForSequenceClassification,
     }
     if is_tf_available()
     else {}
 )
 snake_case__    	=    False
 snake_case__    	=    False



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetModelTester(self			)
  lowerCAmelCase  							=      ConfigTester(self							,    config_class=_snake_case							,    hidden_size=37			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  self.config_tester.run_common_tests()



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_model(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_masked_lm(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_question_answering(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_sequence_classification(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_multiple_choice(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_token_classification(*_snake_case			)



 @slow
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  for model_name in ["microsoft/mpnet-base"]:
   lowerCAmelCase  							=      TFMPNetModel.from_pretrained(_snake_case			)
   self.assertIsNotNone(_snake_case			)







@require_tf
class 	a				(					unittest.TestCase   ):



 @slow
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetModel.from_pretrained('microsoft/mpnet-base'			)
  lowerCAmelCase  							=      tf.constant([[0, 1, 2, 3, 4, 5]]			)
  lowerCAmelCase  							=      model(_snake_case			)[0]

  lowerCAmelCase  							=      [1, 6, 7_68]
  self.assertEqual(output.shape							,    _snake_case			)

  lowerCAmelCase  							=      tf.constant(
      [
          [
              [-0.1_067_172, 0.08_216_473, 0.0_024_543],
              [-0.03_465_879, 0.8_354_118, -0.03_252_288],
              [-0.06_569_476, -0.12_424_111, -0.0_494_436],
          ]
      ]			)
  tf.debugging.assert_near(output[:, :3, :3]							,    _snake_case							,    atol=1E-4			)





