

'''simple docstring'''





import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
							import torch

							from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
							from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import MobileNetVaImageProcessor





class 		__SCREAMING_SNAKE_CASE       ( lowercase__			):







				def    lowerCamelCase_  (					self    :		Optional[Any]      ):
										'''simple docstring'''
										lowercase   :       List[Any]								=self.config_class(**self.inputs_dict      )
										self.parent.assertTrue(hasattr(UpperCAmelCase__		,				'''tf_padding'''      )      )
										self.parent.assertTrue(hasattr(UpperCAmelCase__		,				'''depth_multiplier'''      )      )





class 		__SCREAMING_SNAKE_CASE       :







				def __init__(					self    :		int		,				UpperCAmelCase__    :		Optional[int]		,				UpperCAmelCase__    :		Union[str, Any]=13		,				UpperCAmelCase__    :		Any=3		,				UpperCAmelCase__    :		Union[str, Any]=32		,				UpperCAmelCase__    :		Union[str, Any]=0.25		,				UpperCAmelCase__    :		List[Any]=8		,				UpperCAmelCase__    :		Union[str, Any]=8		,				UpperCAmelCase__    :		str=6		,				UpperCAmelCase__    :		int=32		,				UpperCAmelCase__    :		Optional[Any]=True		,				UpperCAmelCase__    :		Union[str, Any]=True		,				UpperCAmelCase__    :		int=True		,				UpperCAmelCase__    :		Optional[int]="relu6"		,				UpperCAmelCase__    :		List[Any]=1280		,				UpperCAmelCase__    :		Union[str, Any]=0.1		,				UpperCAmelCase__    :		Optional[Any]=0.02		,				UpperCAmelCase__    :		str=True		,				UpperCAmelCase__    :		List[str]=True		,				UpperCAmelCase__    :		Union[str, Any]=10		,				UpperCAmelCase__    :		Tuple=None		,				):
										'''simple docstring'''
										lowercase   :       Optional[Any]								=parent
										lowercase   :       int								=batch_size
										lowercase   :       Any								=num_channels
										lowercase   :       Optional[Any]								=image_size
										lowercase   :       Optional[Any]								=depth_multiplier
										lowercase   :       int								=depth_divisible_by
										lowercase   :       str								=min_depth
										lowercase   :       List[str]								=expand_ratio
										lowercase   :       Dict								=tf_padding
										lowercase   :       Any								=output_stride
										lowercase   :       Any								=first_layer_is_expansion
										lowercase   :       Union[str, Any]								=finegrained_output
										lowercase   :       Union[str, Any]								=hidden_act
										lowercase   :       Union[str, Any]								=last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier      )
										lowercase   :       Optional[Any]								=classifier_dropout_prob
										lowercase   :       Optional[int]								=use_labels
										lowercase   :       List[str]								=is_training
										lowercase   :       Tuple								=num_labels
										lowercase   :       List[Any]								=initializer_range
										lowercase   :       Optional[int]								=scope







				def    lowerCamelCase_  (					self    :		List[Any]      ):
										'''simple docstring'''
										lowercase   :       Optional[Any]								=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

										lowercase   :       int								=None
										lowercase   :       Any								=None
										if self.use_labels:
																lowercase   :       str								=ids_tensor([self.batch_size]		,				self.num_labels      )
																lowercase   :       Optional[int]								=ids_tensor([self.batch_size, self.image_size, self.image_size]		,				self.num_labels      )

										lowercase   :       Any								=self.get_config()

										return config, pixel_values, labels, pixel_labels







				def    lowerCamelCase_  (					self    :		Optional[int]      ):
										'''simple docstring'''
										return MobileNetVaConfig(
										    num_channels=self.num_channels		,				image_size=self.image_size		,				depth_multiplier=self.depth_multiplier		,				depth_divisible_by=self.depth_divisible_by		,				min_depth=self.min_depth		,				expand_ratio=self.expand_ratio		,				output_stride=self.output_stride		,				first_layer_is_expansion=self.first_layer_is_expansion		,				finegrained_output=self.finegrained_output		,				hidden_act=self.hidden_act		,				tf_padding=self.tf_padding		,				classifier_dropout_prob=self.classifier_dropout_prob		,				initializer_range=self.initializer_range		,				)







				def    lowerCamelCase_  (					self    :		Tuple		,				UpperCAmelCase__    :		int		,				UpperCAmelCase__    :		Union[str, Any]		,				UpperCAmelCase__    :		int		,				UpperCAmelCase__    :		Dict      ):
										'''simple docstring'''
										lowercase   :       Dict								=MobileNetVaModel(config=UpperCAmelCase__      )
										model.to(UpperCAmelCase__      )
										model.eval()
										lowercase   :       List[str]								=model(UpperCAmelCase__      )
										self.parent.assertEqual(
										    result.last_hidden_state.shape		,				(
										        self.batch_size,
										        self.last_hidden_size,
										        self.image_size // self.output_stride,
										        self.image_size // self.output_stride,
										    )		,				)
										self.parent.assertEqual(
										    result.pooler_output.shape		,				(self.batch_size, self.last_hidden_size)		,				)







				def    lowerCamelCase_  (					self    :		Dict		,				UpperCAmelCase__    :		List[str]		,				UpperCAmelCase__    :		Optional[Any]		,				UpperCAmelCase__    :		Union[str, Any]		,				UpperCAmelCase__    :		Union[str, Any]      ):
										'''simple docstring'''
										lowercase   :       List[str]								=self.num_labels
										lowercase   :       str								=MobileNetVaForImageClassification(UpperCAmelCase__      )
										model.to(UpperCAmelCase__      )
										model.eval()
										lowercase   :       str								=model(UpperCAmelCase__		,				labels=UpperCAmelCase__      )
										self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)      )







				def    lowerCamelCase_  (					self    :		List[Any]		,				UpperCAmelCase__    :		Union[str, Any]		,				UpperCAmelCase__    :		Optional[int]		,				UpperCAmelCase__    :		List[Any]		,				UpperCAmelCase__    :		Any      ):
										'''simple docstring'''
										lowercase   :       Optional[int]								=self.num_labels
										lowercase   :       Any								=MobileNetVaForSemanticSegmentation(UpperCAmelCase__      )
										model.to(UpperCAmelCase__      )
										model.eval()
										lowercase   :       Any								=model(UpperCAmelCase__      )
										self.parent.assertEqual(
										    result.logits.shape		,				(
										        self.batch_size,
										        self.num_labels,
										        self.image_size // self.output_stride,
										        self.image_size // self.output_stride,
										    )		,				)
										lowercase   :       Optional[Any]								=model(UpperCAmelCase__		,				labels=UpperCAmelCase__      )
										self.parent.assertEqual(
										    result.logits.shape		,				(
										        self.batch_size,
										        self.num_labels,
										        self.image_size // self.output_stride,
										        self.image_size // self.output_stride,
										    )		,				)







				def    lowerCamelCase_  (					self    :		Dict      ):
										'''simple docstring'''
										lowercase   :       str								=self.prepare_config_and_inputs()
										lowercase		,  lowercase		,  lowercase		,  lowercase   :       Any								=config_and_inputs
										lowercase   :       str								={'''pixel_values''': pixel_values}
										return config, inputs_dict





@require_torch
class 		__SCREAMING_SNAKE_CASE       ( lowercase__	,       lowercase__	,       unittest.TestCase			):
				lowerCamelCase_							=						(
				    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)
				lowerCamelCase_							=						(
				    {
				        'feature-extraction': MobileNetVaModel,
				        'image-classification': MobileNetVaForImageClassification,
				        'image-segmentation': MobileNetVaForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				lowerCamelCase_							=						False
				lowerCamelCase_							=						False
				lowerCamelCase_							=						False
				lowerCamelCase_							=						False







				def    lowerCamelCase_  (					self    :		Optional[int]      ):
										'''simple docstring'''
										lowercase   :       List[Any]								=MobileNetVaModelTester(self      )
										lowercase   :       Any								=MobileNetVaConfigTester(self		,				config_class=UpperCAmelCase__		,				has_text_modality=UpperCAmelCase__      )







				def    lowerCamelCase_  (					self    :		Dict      ):
										'''simple docstring'''
										self.config_tester.run_common_tests()







				@unittest.skip(reason='''MobileNetV2 does not use inputs_embeds'''      )
				def    lowerCamelCase_  (					self    :		int      ):
										'''simple docstring'''
										pass







				@unittest.skip(reason='''MobileNetV2 does not support input and output embeddings'''      )
				def    lowerCamelCase_  (					self    :		Optional[Any]      ):
										'''simple docstring'''
										pass







				@unittest.skip(reason='''MobileNetV2 does not output attentions'''      )
				def    lowerCamelCase_  (					self    :		Optional[Any]      ):
										'''simple docstring'''
										pass







				def    lowerCamelCase_  (					self    :		Dict      ):
										'''simple docstring'''
										lowercase		,  lowercase   :       Any								=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																lowercase   :       int								=model_class(UpperCAmelCase__      )
																lowercase   :       Any								=inspect.signature(model.forward      )
																# signature.parameters is an OrderedDict => so arg_names order is deterministic
																lowercase   :       str								=[*signature.parameters.keys()]

																lowercase   :       str								=['''pixel_values''']
																self.assertListEqual(arg_names[:1]		,				UpperCAmelCase__      )







				def    lowerCamelCase_  (					self    :		List[Any]      ):
										'''simple docstring'''
										lowercase   :       List[str]								=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*UpperCAmelCase__      )







				def    lowerCamelCase_  (					self    :		Union[str, Any]      ):
										'''simple docstring'''
										def check_hidden_states_output(UpperCAmelCase__    :		Optional[Any]		,				UpperCAmelCase__    :		Any		,				UpperCAmelCase__    :		Dict      ):
																lowercase   :       Tuple								=model_class(UpperCAmelCase__      )
																model.to(UpperCAmelCase__      )
																model.eval()

																with torch.no_grad():
																						lowercase   :       str								=model(**self._prepare_for_class(UpperCAmelCase__		,				UpperCAmelCase__      )      )

																lowercase   :       Union[str, Any]								=outputs.hidden_states

																lowercase   :       int								=16
																self.assertEqual(len(UpperCAmelCase__      )		,				UpperCAmelCase__      )

										lowercase		,  lowercase   :       int								=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																lowercase   :       str								=True
																check_hidden_states_output(UpperCAmelCase__		,				UpperCAmelCase__		,				UpperCAmelCase__      )

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																lowercase   :       int								=True

																check_hidden_states_output(UpperCAmelCase__		,				UpperCAmelCase__		,				UpperCAmelCase__      )







				def    lowerCamelCase_  (					self    :		Union[str, Any]      ):
										'''simple docstring'''
										lowercase   :       Dict								=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__      )







				def    lowerCamelCase_  (					self    :		Optional[int]      ):
										'''simple docstring'''
										lowercase   :       Optional[int]								=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase__      )







				@slow
				def    lowerCamelCase_  (					self    :		int      ):
										'''simple docstring'''
										for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																lowercase   :       List[str]								=MobileNetVaModel.from_pretrained(UpperCAmelCase__      )
																self.assertIsNotNone(UpperCAmelCase__      )






def 							_lowerCAmelCase (      )							->     Tuple:
						lowercase   :       str								=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
						return image







@require_torch
@require_vision
class 		__SCREAMING_SNAKE_CASE       ( unittest.TestCase			):







				@cached_property
				def    lowerCamelCase_  (					self    :		Union[str, Any]      ):
										'''simple docstring'''
										return (
										    MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224'''      ) if is_vision_available() else None
										)







				@slow
				def    lowerCamelCase_  (					self    :		List[str]      ):
										'''simple docstring'''
										lowercase   :       Optional[Any]								=MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224'''      ).to(UpperCAmelCase__      )

										lowercase   :       Optional[int]								=self.default_image_processor
										lowercase   :       Optional[int]								=prepare_img()
										lowercase   :       List[str]								=image_processor(images=UpperCAmelCase__		,				return_tensors='''pt'''      ).to(UpperCAmelCase__      )

										# forward pass
										with torch.no_grad():
																lowercase   :       Dict								=model(**UpperCAmelCase__      )

										# verify the logits
										lowercase   :       str								=torch.Size((1, 1001)      )
										self.assertEqual(outputs.logits.shape		,				UpperCAmelCase__      )

										lowercase   :       Any								=torch.tensor([0.24_45, -1.19_93, 0.19_05]      ).to(UpperCAmelCase__      )

										self.assertTrue(torch.allclose(outputs.logits[0, :3]		,				UpperCAmelCase__		,				atol=1E-4      )      )







				@slow
				def    lowerCamelCase_  (					self    :		Tuple      ):
										'''simple docstring'''
										lowercase   :       Optional[int]								=MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''      )
										lowercase   :       List[str]								=model.to(UpperCAmelCase__      )

										lowercase   :       List[Any]								=MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''      )

										lowercase   :       List[Any]								=prepare_img()
										lowercase   :       Any								=image_processor(images=UpperCAmelCase__		,				return_tensors='''pt'''      ).to(UpperCAmelCase__      )

										# forward pass
										with torch.no_grad():
																lowercase   :       Optional[Any]								=model(**UpperCAmelCase__      )
										lowercase   :       Any								=outputs.logits

										# verify the logits
										lowercase   :       Dict								=torch.Size((1, 21, 65, 65)      )
										self.assertEqual(logits.shape		,				UpperCAmelCase__      )

										lowercase   :       List[str]								=torch.tensor(
										    [
										        [[17.57_90, 17.75_81, 18.33_55], [18.32_57, 18.42_30, 18.89_73], [18.61_69, 18.86_50, 19.21_87]],
										        [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]],
										        [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]],
										    ]		,				device=UpperCAmelCase__		,				)

										self.assertTrue(torch.allclose(logits[0, :3, :3, :3]		,				UpperCAmelCase__		,				atol=1E-4      )      )








'''simple docstring'''





import json
import os
import unittest

from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer
from transformers.testing_utils import slow

from ...test_tokenization_common import TokenizerTesterMixin





class 		__SCREAMING_SNAKE_CASE       ( lowercase__	,       unittest.TestCase			):
				lowerCamelCase_							=						BioGptTokenizer
				lowerCamelCase_							=						False







				def    lowerCamelCase_  (					self    :		Optional[Any]      ):
										'''simple docstring'''
										super().setUp()

										# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
										lowercase   :       List[str]								=[
										    '''l''',
										    '''o''',
										    '''w''',
										    '''e''',
										    '''r''',
										    '''s''',
										    '''t''',
										    '''i''',
										    '''d''',
										    '''n''',
										    '''w</w>''',
										    '''r</w>''',
										    '''t</w>''',
										    '''lo''',
										    '''low''',
										    '''er</w>''',
										    '''low</w>''',
										    '''lowest</w>''',
										    '''newer</w>''',
										    '''wider</w>''',
										    '''<unk>''',
										]
										lowercase   :       Any								=dict(zip(UpperCAmelCase__		,				range(len(UpperCAmelCase__      )      )      )      )
										lowercase   :       Union[str, Any]								=['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', '''''']

										lowercase   :       Optional[int]								=os.path.join(self.tmpdirname		,				VOCAB_FILES_NAMES['''vocab_file''']      )
										lowercase   :       Union[str, Any]								=os.path.join(self.tmpdirname		,				VOCAB_FILES_NAMES['''merges_file''']      )
										with open(self.vocab_file		,				'''w'''      ) as fp:
																fp.write(json.dumps(UpperCAmelCase__      )      )
										with open(self.merges_file		,				'''w'''      ) as fp:
																fp.write('''\n'''.join(UpperCAmelCase__      )      )







				def    lowerCamelCase_  (					self    :		List[Any]		,				UpperCAmelCase__    :		Union[str, Any]      ):
										'''simple docstring'''
										lowercase   :       Dict								='''lower newer'''
										lowercase   :       str								='''lower newer'''
										return input_text, output_text







				def    lowerCamelCase_  (					self    :		List[Any]      ):
										'''simple docstring'''
										lowercase   :       List[Any]								=BioGptTokenizer(self.vocab_file		,				self.merges_file      )

										lowercase   :       Any								='''lower'''
										lowercase   :       int								=['''low''', '''er</w>''']
										lowercase   :       Optional[Any]								=tokenizer.tokenize(UpperCAmelCase__      )
										self.assertListEqual(UpperCAmelCase__		,				UpperCAmelCase__      )

										lowercase   :       Optional[int]								=tokens + ['''<unk>''']
										lowercase   :       Any								=[14, 15, 20]
										self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__      )		,				UpperCAmelCase__      )







				@slow
				def    lowerCamelCase_  (					self    :		int      ):
										'''simple docstring'''
										lowercase   :       Dict								=BioGptTokenizer.from_pretrained('''microsoft/biogpt'''      )

										lowercase   :       List[str]								=tokenizer.encode('''sequence builders'''		,				add_special_tokens=UpperCAmelCase__      )
										lowercase   :       Optional[int]								=tokenizer.encode('''multi-sequence build'''		,				add_special_tokens=UpperCAmelCase__      )

										lowercase   :       str								=tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__      )
										lowercase   :       Optional[Any]								=tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__		,				UpperCAmelCase__      )

										self.assertTrue(encoded_sentence == [2] + text      )
										self.assertTrue(encoded_pair == [2] + text + [2] + text_a      )





