

import argparse
import json

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation



def    _lowercase			(	a__						:			int					)							->					List[str]:





	"""simple docstring"""


	_UpperCamelCase			=   3_84
	if "tiny" in model_name:
		_UpperCamelCase			=   [3, 3, 9, 3]
		_UpperCamelCase			=   [96, 1_92, 3_84, 7_68]
	if "small" in model_name:
		_UpperCamelCase			=   [3, 3, 27, 3]
		_UpperCamelCase			=   [96, 1_92, 3_84, 7_68]
	if "base" in model_name:
		_UpperCamelCase			=   [3, 3, 27, 3]
		_UpperCamelCase			=   [1_28, 2_56, 5_12, 10_24]
		_UpperCamelCase			=   5_12
	if "large" in model_name:
		_UpperCamelCase			=   [3, 3, 27, 3]
		_UpperCamelCase			=   [1_92, 3_84, 7_68, 15_36]
		_UpperCamelCase			=   7_68
	if "xlarge" in model_name:
		_UpperCamelCase			=   [3, 3, 27, 3]
		_UpperCamelCase			=   [2_56, 5_12, 10_24, 20_48]
		_UpperCamelCase			=   10_24

	# set label information
	_UpperCamelCase			=   1_50
	_UpperCamelCase			=   """huggingface/label-files"""
	_UpperCamelCase			=   """ade20k-id2label.json"""
	_UpperCamelCase			=   json.load(open(hf_hub_download(A__							,  A__							,  repo_type="dataset"					)							,  "r"					)					)
	_UpperCamelCase			=   {int(A__					): v for k, v in idalabel.items()}
	_UpperCamelCase			=   {v: k for k, v in idalabel.items()}

	_UpperCamelCase			=   ConvNextConfig(
	    depths=A__							,  hidden_sizes=A__							,  out_features=["stage1", "stage2", "stage3", "stage4"]					)
	_UpperCamelCase			=   UperNetConfig(
	    backbone_config=A__							,  auxiliary_in_channels=A__							,  num_labels=A__							,  idalabel=A__							,  labelaid=A__							,  )

	return config



def    _lowercase			(	a__						:			Optional[Any]					)							->					Optional[Any]:





	"""simple docstring"""


	_UpperCamelCase			=   []

	# fmt: off
	# stem
	rename_keys.append(("backbone.downsample_layers.0.0.weight", "backbone.embeddings.patch_embeddings.weight")					)
	rename_keys.append(("backbone.downsample_layers.0.0.bias", "backbone.embeddings.patch_embeddings.bias")					)
	rename_keys.append(("backbone.downsample_layers.0.1.weight", "backbone.embeddings.layernorm.weight")					)
	rename_keys.append(("backbone.downsample_layers.0.1.bias", "backbone.embeddings.layernorm.bias")					)
	# stages
	for i in range(len(config.backbone_config.depths					)					):
		for j in range(config.backbone_config.depths[i]					):
			rename_keys.append((f'''backbone.stages.{i}.{j}.gamma''', f'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''')					)
			rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''')					)
			rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''')					)
			rename_keys.append((f'''backbone.stages.{i}.{j}.norm.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''')					)
			rename_keys.append((f'''backbone.stages.{i}.{j}.norm.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''')					)
			rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''')					)
			rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''')					)
			rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''')					)
			rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''')					)
		if i > 0:
			rename_keys.append((f'''backbone.downsample_layers.{i}.0.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''')					)
			rename_keys.append((f'''backbone.downsample_layers.{i}.0.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''')					)
			rename_keys.append((f'''backbone.downsample_layers.{i}.1.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''')					)
			rename_keys.append((f'''backbone.downsample_layers.{i}.1.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''')					)

		rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''')					)
		rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''')					)

	# decode head
	rename_keys.extend(
	    [
	        ("decode_head.conv_seg.weight", "decode_head.classifier.weight"),
	        ("decode_head.conv_seg.bias", "decode_head.classifier.bias"),
	        ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"),
	        ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"),
	    ]					)
	# fmt: on

	return rename_keys



def    _lowercase			(	a__						:			Optional[Any]							,  a__						:			List[Any]							,  a__						:			int					)							->					Union[str, Any]:





	"""simple docstring"""


	_UpperCamelCase			=   dct.pop(A__					)
	_UpperCamelCase			=   val



def    _lowercase			(	a__						:			Tuple							,  a__						:			str							,  a__						:			Any					)							->					Optional[int]:





	"""simple docstring"""


	_UpperCamelCase			=   {
	    """upernet-convnext-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth""",
	    """upernet-convnext-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth""",
	    """upernet-convnext-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth""",
	    """upernet-convnext-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth""",
	    """upernet-convnext-xlarge""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth""",
	}
	_UpperCamelCase			=   model_name_to_url[model_name]
	_UpperCamelCase			=   torch.hub.load_state_dict_from_url(A__							,  map_location="cpu"					)["""state_dict"""]

	_UpperCamelCase			=   get_upernet_config(A__					)
	_UpperCamelCase			=   UperNetForSemanticSegmentation(A__					)
	model.eval()

	# replace "bn" => "batch_norm"
	for key in state_dict.copy().keys():
		_UpperCamelCase			=   state_dict.pop(A__					)
		if "bn" in key:
			_UpperCamelCase			=   key.replace("bn"							,  "batch_norm"					)
		_UpperCamelCase			=   val

	# rename keys
	_UpperCamelCase			=   create_rename_keys(A__					)
	for src, dest in rename_keys:
		rename_key(A__							,  A__							,  A__					)

	model.load_state_dict(A__					)

	# verify on image
	_UpperCamelCase			=   """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"""
	_UpperCamelCase			=   Image.open(requests.get(A__							,  stream=A__					).raw					).convert("RGB"					)

	_UpperCamelCase			=   SegformerImageProcessor()
	_UpperCamelCase			=   processor(A__							,  return_tensors="pt"					).pixel_values

	with torch.no_grad():
		_UpperCamelCase			=   model(A__					)

	if model_name == "upernet-convnext-tiny":
		_UpperCamelCase			=   torch.tensor(
		    [[-8.8_110, -8.8_110, -8.6_521], [-8.8_110, -8.8_110, -8.6_521], [-8.7_746, -8.7_746, -8.6_130]]					)
	elif model_name == "upernet-convnext-small":
		_UpperCamelCase			=   torch.tensor(
		    [[-8.8_236, -8.8_236, -8.6_771], [-8.8_236, -8.8_236, -8.6_771], [-8.7_638, -8.7_638, -8.6_240]]					)
	elif model_name == "upernet-convnext-base":
		_UpperCamelCase			=   torch.tensor(
		    [[-8.8_558, -8.8_558, -8.6_905], [-8.8_558, -8.8_558, -8.6_905], [-8.7_669, -8.7_669, -8.6_021]]					)
	elif model_name == "upernet-convnext-large":
		_UpperCamelCase			=   torch.tensor(
		    [[-8.6_660, -8.6_660, -8.6_210], [-8.6_660, -8.6_660, -8.6_210], [-8.6_310, -8.6_310, -8.5_964]]					)
	elif model_name == "upernet-convnext-xlarge":
		_UpperCamelCase			=   torch.tensor(
		    [[-8.4_980, -8.4_980, -8.3_977], [-8.4_980, -8.4_980, -8.3_977], [-8.4_379, -8.4_379, -8.3_412]]					)
	print("Logits:"							,  outputs.logits[0, 0, :3, :3]					)
	assert torch.allclose(outputs.logits[0, 0, :3, :3]							,  A__							,  atol=1e-4					)
	print("Looks ok!"					)

	if pytorch_dump_folder_path is not None:
		print(f'''Saving model {model_name} to {pytorch_dump_folder_path}'''					)
		model.save_pretrained(A__					)
		print(f'''Saving processor to {pytorch_dump_folder_path}'''					)
		processor.save_pretrained(A__					)

	if push_to_hub:
		print(f'''Pushing model and processor for {model_name} to hub'''					)
		model.push_to_hub(f'''openmmlab/{model_name}'''					)
		processor.push_to_hub(f'''openmmlab/{model_name}'''					)


if __name__ == "__main__":
	__lowerCAmelCase			     =       argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    """--model_name""",
	    default="""upernet-convnext-tiny""",
	    type=str,
	    choices=[F'''upernet-convnext-{size}''' for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]],
	    help="""Name of the ConvNext UperNet model you\'d like to convert.""",
	)
	parser.add_argument(
	    """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
	)
	parser.add_argument(
	    """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
	)

	__lowerCAmelCase			     =       parser.parse_args()
	convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)








import unittest

from transformers import MobileBertConfig, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          MODEL_FOR_PRETRAINING_MAPPING,
          MobileBertForMaskedLM,
          MobileBertForMultipleChoice,
          MobileBertForNextSentencePrediction,
          MobileBertForPreTraining,
          MobileBertForQuestionAnswering,
          MobileBertForSequenceClassification,
          MobileBertForTokenClassification,
          MobileBertModel,
      )





class   SCREAMING_SNAKE_CASE_			:




       '''simple docstring'''



       def __init__(						self				:				Optional[Any]		,				__a				:				int		,				__a				:				str=13		,				__a				:				Tuple=7		,				__a				:				int=True		,				__a				:				int=True		,				__a				:				Dict=True		,				__a				:				str=True		,				__a				:				List[str]=99		,				__a				:				Dict=64		,				__a				:				Optional[Any]=32		,				__a				:				List[Any]=5		,				__a				:				Optional[int]=4		,				__a				:				str=37		,				__a				:				str="gelu"		,				__a				:				Optional[Any]=0.1		,				__a				:				Union[str, Any]=0.1		,				__a				:				int=512		,				__a				:				Optional[Any]=16		,				__a				:				Any=2		,				__a				:				Dict=0.02		,				__a				:				str=3		,				__a				:				List[Any]=4		,				__a				:				List[str]=None		,				)					->Optional[int]:
          lowerCamelCase_						:   Dict		= parent
          lowerCamelCase_						:   Optional[Any]		= batch_size
          lowerCamelCase_						:   Any		= seq_length
          lowerCamelCase_						:   Union[str, Any]		= is_training
          lowerCamelCase_						:   int		= use_input_mask
          lowerCamelCase_						:   int		= use_token_type_ids
          lowerCamelCase_						:   int		= use_labels
          lowerCamelCase_						:   List[str]		= vocab_size
          lowerCamelCase_						:   Any		= hidden_size
          lowerCamelCase_						:   Any		= embedding_size
          lowerCamelCase_						:   int		= num_hidden_layers
          lowerCamelCase_						:   Union[str, Any]		= num_attention_heads
          lowerCamelCase_						:   Optional[Any]		= intermediate_size
          lowerCamelCase_						:   Optional[int]		= hidden_act
          lowerCamelCase_						:   Dict		= hidden_dropout_prob
          lowerCamelCase_						:   Any		= attention_probs_dropout_prob
          lowerCamelCase_						:   Optional[int]		= max_position_embeddings
          lowerCamelCase_						:   Dict		= type_vocab_size
          lowerCamelCase_						:   List[str]		= type_sequence_label_size
          lowerCamelCase_						:   Any		= initializer_range
          lowerCamelCase_						:   Union[str, Any]		= num_labels
          lowerCamelCase_						:   List[Any]		= num_choices
          lowerCamelCase_						:   Dict		= scope



       def 				_lowerCAmelCase							(						self				:				int							)					->str:
          lowerCamelCase_						:   Dict		= ids_tensor([self.batch_size, self.seq_length]		,				self.vocab_size							)

          lowerCamelCase_						:   Tuple		= None
          if self.use_input_mask:
             lowerCamelCase_						:   Any		= random_attention_mask([self.batch_size, self.seq_length]							)

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

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

          lowerCamelCase_						:   str		= self.get_config()

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



       def 				_lowerCAmelCase							(						self				:				Tuple							)					->Optional[Any]:
          return MobileBertConfig(
              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		,				embedding_size=self.embedding_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=__a		,				initializer_range=self.initializer_range		,				)



       def 				_lowerCAmelCase							(						self				:				Tuple		,				__a				:				int		,				__a				:				List[str]		,				__a				:				Tuple		,				__a				:				Any		,				__a				:				Union[str, Any]		,				__a				:				int		,				__a				:				Any							)					->Tuple:
          lowerCamelCase_						:   Tuple		= MobileBertModel(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Dict		= model(__a		,				attention_mask=__a		,				token_type_ids=__a							)
          lowerCamelCase_						:   Optional[int]		= model(__a		,				token_type_ids=__a							)
          lowerCamelCase_						:   Tuple		= model(__a							)

          self.parent.assertEqual(result.last_hidden_state.shape		,				(self.batch_size, self.seq_length, self.hidden_size)							)
          self.parent.assertEqual(result.pooler_output.shape		,				(self.batch_size, self.hidden_size)							)



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				str		,				__a				:				Union[str, Any]		,				__a				:				int		,				__a				:				List[Any]		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				List[str]							)					->Tuple:
          lowerCamelCase_						:   List[Any]		= MobileBertForMaskedLM(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Union[str, Any]		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)



       def 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				Tuple		,				__a				:				Tuple		,				__a				:				Dict		,				__a				:				Tuple		,				__a				:				Optional[Any]		,				__a				:				Union[str, Any]		,				__a				:				Dict							)					->int:
          lowerCamelCase_						:   Tuple		= MobileBertForNextSentencePrediction(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Any		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, 2)							)



       def 				_lowerCAmelCase							(						self				:				str		,				__a				:				Optional[Any]		,				__a				:				int		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Dict							)					->List[Any]:
          lowerCamelCase_						:   Optional[int]		= MobileBertForPreTraining(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   List[Any]		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				next_sentence_label=__a		,				)
          self.parent.assertEqual(result.prediction_logits.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)
          self.parent.assertEqual(result.seq_relationship_logits.shape		,				(self.batch_size, 2)							)



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				Tuple		,				__a				:				int		,				__a				:				Optional[Any]		,				__a				:				Optional[Any]		,				__a				:				Tuple		,				__a				:				Optional[Any]		,				__a				:				Any							)					->List[str]:
          lowerCamelCase_						:   Dict		= MobileBertForQuestionAnswering(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Tuple		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				start_positions=__a		,				end_positions=__a		,				)
          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				:				Optional[Any]		,				__a				:				List[Any]		,				__a				:				str		,				__a				:				int		,				__a				:				Dict		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				str							)					->Tuple:
          lowerCamelCase_						:   Dict		= self.num_labels
          lowerCamelCase_						:   Optional[Any]		= MobileBertForSequenceClassification(__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   str		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)							)



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				str		,				__a				:				List[str]		,				__a				:				Optional[int]		,				__a				:				int		,				__a				:				str		,				__a				:				str		,				__a				:				Optional[Any]							)					->Tuple:
          lowerCamelCase_						:   int		= self.num_labels
          lowerCamelCase_						:   List[str]		= MobileBertForTokenClassification(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Optional[Any]		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.num_labels)							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]		,				__a				:				Any		,				__a				:				Tuple		,				__a				:				Dict		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				Optional[int]		,				__a				:				Optional[Any]							)					->List[str]:
          lowerCamelCase_						:   Any		= self.num_choices
          lowerCamelCase_						:   int		= MobileBertForMultipleChoice(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Tuple		= input_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Tuple		= token_type_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Any		= input_mask.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Tuple		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_choices)							)




       def 				_lowerCAmelCase							(						self				:				List[str]							)					->int:
          lowerCamelCase_						:   Optional[Any]		= self.prepare_config_and_inputs()
          (
              (
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	
          )						:   Optional[Any]		= config_and_inputs
          lowerCamelCase_						:   List[Any]		= {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
          return config, inputs_dict







@require_torch
class   SCREAMING_SNAKE_CASE_			(a__						,       a__						,       unittest.TestCase						):




       '''simple docstring'''



       _a   							=							(
           (
               MobileBertModel,
               MobileBertForMaskedLM,
               MobileBertForMultipleChoice,
               MobileBertForNextSentencePrediction,
               MobileBertForPreTraining,
               MobileBertForQuestionAnswering,
               MobileBertForSequenceClassification,
               MobileBertForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       _a   							=							(
           {
               "feature-extraction": MobileBertModel,
               "fill-mask": MobileBertForMaskedLM,
               "question-answering": MobileBertForQuestionAnswering,
               "text-classification": MobileBertForSequenceClassification,
               "token-classification": MobileBertForTokenClassification,
               "zero-shot": MobileBertForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       _a   							=							True



       def 				_lowerCAmelCase							(						self				:				Optional[int]		,				__a				:				Union[str, Any]		,				__a				:				Dict		,				__a				:				str=False							)					->Any:
          lowerCamelCase_						:   Optional[int]		= super()._prepare_for_class(__a		,				__a		,				return_labels=__a							)

          if return_labels:
             if model_class in get_values(__a							):
                lowerCamelCase_						:   str		= torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.seq_length)		,				dtype=torch.long		,				device=__a							)
                lowerCamelCase_						:   str		= torch.zeros(
                    self.model_tester.batch_size		,				dtype=torch.long		,				device=__a							)
          return inputs_dict



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->Union[str, Any]:
          lowerCamelCase_						:   List[Any]		= MobileBertModelTester(self							)
          lowerCamelCase_						:   int		= ConfigTester(self		,				config_class=__a		,				hidden_size=37							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->List[Any]:
          self.config_tester.run_common_tests()



       def 				_lowerCAmelCase							(						self				:				str							)					->Any:
          lowerCamelCase_						:   Union[str, Any]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_model(*__a							)



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->Tuple:
          lowerCamelCase_						:   List[str]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_masked_lm(*__a							)



       def 				_lowerCAmelCase							(						self				:				Optional[Any]							)					->Tuple:
          lowerCamelCase_						:   Union[str, Any]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__a							)



       def 				_lowerCAmelCase							(						self				:				Any							)					->List[Any]:
          lowerCamelCase_						:   Any		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__a							)



       def 				_lowerCAmelCase							(						self				:				Optional[int]							)					->str:
          lowerCamelCase_						:   List[str]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_pretraining(*__a							)



       def 				_lowerCAmelCase							(						self				:				str							)					->Optional[Any]:
          lowerCamelCase_						:   int		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_question_answering(*__a							)



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->int:
          lowerCamelCase_						:   Dict		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__a							)




       def 				_lowerCAmelCase							(						self				:				List[Any]							)					->Union[str, Any]:
          lowerCamelCase_						:   Dict		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_token_classification(*__a							)







def    __lowerCamelCase   (      A__						: List[str]					)     ->    Optional[int]:
   return torch.tensor(
       A__						,						dtype=torch.long						,						device=A__						,						)


snake_case__				:	List[str]					       =					1e-3





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




       '''simple docstring'''



       @slow
       def 				_lowerCAmelCase							(						self				:				List[Any]							)					->List[str]:
          lowerCamelCase_						:   Any		= MobileBertModel.from_pretrained("""google/mobilebert-uncased"""							).to(__a							)
          lowerCamelCase_						:   int		= _long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]]							)
          with torch.no_grad():
             lowerCamelCase_						:   Optional[Any]		= model(__a							)[0]
          lowerCamelCase_						:   Any		= torch.Size((1, 9, 512)							)
          self.assertEqual(output.shape		,				__a							)
          lowerCamelCase_						:   str		= torch.tensor(
              [
                  [
                      [-2.4_73_65_26e07, 8.2_69_16_56e04, 1.6_52_18_38e05],
                      [-5.7_54_17_04e-01, 3.9_05_60_22e00, 4.4_01_15_07e00],
                      [2.6_04_73_59e00, 1.5_67_76_52e00, -1.7_32_41_88e-01],
                  ]
              ]		,				device=__a		,				)

          # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a
          # ~1 difference, it's therefore not a good idea to measure using addition.
          # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the
          # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE
          lowerCamelCase_						:   str		= torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE							)
          lowerCamelCase_						:   Tuple		= torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE							)

          self.assertTrue(lower_bound and upper_bound							)





