


'''simple docstring'''



import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
	from transformers.models.mobilevitva.modeling_mobilevitva import (
	    MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
	    make_divisible,
	)


if is_vision_available():
	from PIL import Image

	from transformers import MobileViTImageProcessor






class  UpperCamelCase__(     lowerCAmelCase ):




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

										"""simple docstring"""




										UpperCAmelCase         =			self.config_class(**self.inputs_dict   )
										self.parent.assertTrue(hasattr(lowerCAmelCase   ,					'''width_multiplier'''   )   )







class  UpperCamelCase__:




				def __init__(	self    :				Tuple   ,					lowerCAmelCase    :				List[str]   ,					lowerCAmelCase    :				Optional[Any]=13   ,					lowerCAmelCase    :				Union[str, Any]=64   ,					lowerCAmelCase    :				Optional[Any]=2   ,					lowerCAmelCase    :				Union[str, Any]=3   ,					lowerCAmelCase    :				List[Any]="swish"   ,					lowerCAmelCase    :				List[Any]=3   ,					lowerCAmelCase    :				Any=32   ,					lowerCAmelCase    :				Tuple=0.1   ,					lowerCAmelCase    :				Tuple=0.02   ,					lowerCAmelCase    :				Optional[int]=True   ,					lowerCAmelCase    :				Any=True   ,					lowerCAmelCase    :				List[str]=10   ,					lowerCAmelCase    :				List[str]=None   ,					lowerCAmelCase    :				str=0.25   ,					lowerCAmelCase    :				int=0.0   ,					lowerCAmelCase    :				Tuple=0.0   ,					)->  int:

										"""simple docstring"""




										UpperCAmelCase         =			parent
										UpperCAmelCase         =			batch_size
										UpperCAmelCase         =			image_size
										UpperCAmelCase         =			patch_size
										UpperCAmelCase         =			num_channels
										UpperCAmelCase         =			make_divisible(512 * width_multiplier   ,					divisor=8   )
										UpperCAmelCase         =			hidden_act
										UpperCAmelCase         =			conv_kernel_size
										UpperCAmelCase         =			output_stride
										UpperCAmelCase         =			classifier_dropout_prob
										UpperCAmelCase         =			use_labels
										UpperCAmelCase         =			is_training
										UpperCAmelCase         =			num_labels
										UpperCAmelCase         =			initializer_range
										UpperCAmelCase         =			scope
										UpperCAmelCase         =			width_multiplier
										UpperCAmelCase         =			ffn_dropout
										UpperCAmelCase         =			attn_dropout




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

										"""simple docstring"""




										UpperCAmelCase         =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

										UpperCAmelCase         =			None
										UpperCAmelCase         =			None
										if self.use_labels:
																UpperCAmelCase         =			ids_tensor([self.batch_size]   ,					self.num_labels   )
																UpperCAmelCase         =			ids_tensor([self.batch_size, self.image_size, self.image_size]   ,					self.num_labels   )

										UpperCAmelCase         =			self.get_config()

										return config, pixel_values, labels, pixel_labels




				def   a__(	self    :				int   )->  Dict:

										"""simple docstring"""




										return MobileViTVaConfig(
										    image_size=self.image_size   ,					patch_size=self.patch_size   ,					num_channels=self.num_channels   ,					hidden_act=self.hidden_act   ,					conv_kernel_size=self.conv_kernel_size   ,					output_stride=self.output_stride   ,					classifier_dropout_prob=self.classifier_dropout_prob   ,					initializer_range=self.initializer_range   ,					width_multiplier=self.width_multiplier   ,					ffn_dropout=self.ffn_dropout_prob   ,					attn_dropout=self.attn_dropout_prob   ,					)




				def   a__(	self    :				str   ,					lowerCAmelCase    :				Optional[Any]   ,					lowerCAmelCase    :				int   ,					lowerCAmelCase    :				List[str]   ,					lowerCAmelCase    :				int   )->  Tuple:

										"""simple docstring"""




										UpperCAmelCase         =			MobileViTVaModel(config=lowerCAmelCase   )
										model.to(lowerCAmelCase   )
										model.eval()
										UpperCAmelCase         =			model(lowerCAmelCase   )
										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,
										    )   ,					)




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

										"""simple docstring"""




										UpperCAmelCase         =			self.num_labels
										UpperCAmelCase         =			MobileViTVaForImageClassification(lowerCAmelCase   )
										model.to(lowerCAmelCase   )
										model.eval()
										UpperCAmelCase         =			model(lowerCAmelCase   ,					labels=lowerCAmelCase   )
										self.parent.assertEqual(result.logits.shape   ,					(self.batch_size, self.num_labels)   )




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

										"""simple docstring"""




										UpperCAmelCase         =			self.num_labels
										UpperCAmelCase         =			MobileViTVaForSemanticSegmentation(lowerCAmelCase   )
										model.to(lowerCAmelCase   )
										model.eval()
										UpperCAmelCase         =			model(lowerCAmelCase   )
										self.parent.assertEqual(
										    result.logits.shape   ,					(
										        self.batch_size,
										        self.num_labels,
										        self.image_size // self.output_stride,
										        self.image_size // self.output_stride,
										    )   ,					)
										UpperCAmelCase         =			model(lowerCAmelCase   ,					labels=lowerCAmelCase   )
										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   a__(	self    :				List[str]   )->  Dict:

										"""simple docstring"""




										UpperCAmelCase         =			self.prepare_config_and_inputs()
										UpperCAmelCase       ,       UpperCAmelCase       ,       UpperCAmelCase       ,       UpperCAmelCase         =			config_and_inputs
										UpperCAmelCase         =			{'''pixel_values''': pixel_values}
										return config, inputs_dict







@require_torch
class  UpperCamelCase__(     lowerCAmelCase		,       lowerCAmelCase		,       unittest.TestCase ):
				__magic_name__       :   int							= (
				    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)

				__magic_name__       :   Optional[Any]							= (
				    {
				        "feature-extraction": MobileViTVaModel,
				        "image-classification": MobileViTVaForImageClassification,
				        "image-segmentation": MobileViTVaForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				__magic_name__       :   Optional[Any]							= False
				__magic_name__       :   Dict							= False
				__magic_name__       :   int							= False
				__magic_name__       :   Any							= False




				def   a__(	self    :				Optional[int]   )->  Dict:

										"""simple docstring"""




										UpperCAmelCase         =			MobileViTVaModelTester(self   )
										UpperCAmelCase         =			MobileViTVaConfigTester(self   ,					config_class=lowerCAmelCase   ,					has_text_modality=lowerCAmelCase   )




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

										"""simple docstring"""




										self.config_tester.run_common_tests()




				@unittest.skip(reason='''MobileViTV2 does not use inputs_embeds'''   )
				def   a__(	self    :				Union[str, Any]   )->  Union[str, Any]:

										"""simple docstring"""




										pass




				@unittest.skip(reason='''MobileViTV2 does not support input and output embeddings'''   )
				def   a__(	self    :				Dict   )->  Union[str, Any]:

										"""simple docstring"""




										pass




				@unittest.skip(reason='''MobileViTV2 does not output attentions'''   )
				def   a__(	self    :				Optional[Any]   )->  List[str]:

										"""simple docstring"""




										pass




				@require_torch_multi_gpu
				@unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.'''   )
				def   a__(	self    :				Union[str, Any]   )->  int:

										"""simple docstring"""




										pass




				@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
				def   a__(	self    :				str   )->  List[Any]:

										"""simple docstring"""




										pass




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

										"""simple docstring"""




										UpperCAmelCase       ,       UpperCAmelCase         =			self.model_tester.prepare_config_and_inputs_for_common()

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

																UpperCAmelCase         =			['''pixel_values''']
																self.assertListEqual(arg_names[:1]   ,					lowerCAmelCase   )




				def   a__(	self    :				int   )->  str:

										"""simple docstring"""




										UpperCAmelCase         =			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase   )




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

										"""simple docstring"""




										def check_hidden_states_output(lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				List[Any]   ):
																UpperCAmelCase         =			model_class(lowerCAmelCase   )
																model.to(lowerCAmelCase   )
																model.eval()

																with torch.no_grad():
																						UpperCAmelCase         =			model(**self._prepare_for_class(lowerCAmelCase   ,					lowerCAmelCase   )   )

																UpperCAmelCase         =			outputs.hidden_states

																UpperCAmelCase         =			5
																self.assertEqual(len(lowerCAmelCase   )   ,					lowerCAmelCase   )

																# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
																# with the width and height being successively divided by 2.
																UpperCAmelCase         =			2
																for i in range(len(lowerCAmelCase   )   ):
																						self.assertListEqual(
																						    list(hidden_states[i].shape[-2:]   )   ,					[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]   ,					)
																						divisor *= 2

																self.assertEqual(self.model_tester.output_stride   ,					divisor // 2   )

										UpperCAmelCase       ,       UpperCAmelCase         =			self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																UpperCAmelCase         =			True
																check_hidden_states_output(lowerCAmelCase   ,					lowerCAmelCase   ,					lowerCAmelCase   )

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																UpperCAmelCase         =			True

																check_hidden_states_output(lowerCAmelCase   ,					lowerCAmelCase   ,					lowerCAmelCase   )




				def   a__(	self    :				int   )->  List[Any]:

										"""simple docstring"""




										UpperCAmelCase         =			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase   )




				def   a__(	self    :				Optional[int]   )->  Dict:

										"""simple docstring"""




										UpperCAmelCase         =			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase   )





				@slow
				def   a__(	self    :				Tuple   )->  List[Any]:

										"""simple docstring"""




										for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																UpperCAmelCase         =			MobileViTVaModel.from_pretrained(lowerCAmelCase   )
																self.assertIsNotNone(lowerCAmelCase   )







def    lowerCamelCase__   ( ):




						'''simple docstring'''






						UpperCAmelCase         =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
						return image






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




				@cached_property
				def   a__(	self    :				int   )->  Union[str, Any]:

										"""simple docstring"""




										return (
										    MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''   )
										    if is_vision_available()
										    else None
										)




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

										"""simple docstring"""




										UpperCAmelCase         =			MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''   ).to(
										    lowerCAmelCase   )

										UpperCAmelCase         =			self.default_image_processor
										UpperCAmelCase         =			prepare_img()
										UpperCAmelCase         =			image_processor(images=lowerCAmelCase   ,					return_tensors='''pt'''   ).to(lowerCAmelCase   )

										# forward pass
										with torch.no_grad():
																UpperCAmelCase         =			model(**lowerCAmelCase   )

										# verify the logits
										UpperCAmelCase         =			torch.Size((1, 1000)   )
										self.assertEqual(outputs.logits.shape   ,					lowerCAmelCase   )

										UpperCAmelCase         =			torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01]   ).to(lowerCAmelCase   )

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




				@slow
				def   a__(	self    :				Union[str, Any]   )->  List[Any]:

										"""simple docstring"""




										UpperCAmelCase         =			MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''   )
										UpperCAmelCase         =			model.to(lowerCAmelCase   )

										UpperCAmelCase         =			MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''   )

										UpperCAmelCase         =			prepare_img()
										UpperCAmelCase         =			image_processor(images=lowerCAmelCase   ,					return_tensors='''pt'''   ).to(lowerCAmelCase   )

										# forward pass
										with torch.no_grad():
																UpperCAmelCase         =			model(**lowerCAmelCase   )
										UpperCAmelCase         =			outputs.logits

										# verify the logits
										UpperCAmelCase         =			torch.Size((1, 21, 32, 32)   )
										self.assertEqual(logits.shape   ,					lowerCAmelCase   )

										UpperCAmelCase         =			torch.tensor(
										    [
										        [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
										        [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
										        [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
										    ]   ,					device=lowerCAmelCase   ,					)

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





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

										"""simple docstring"""




										UpperCAmelCase         =			MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''   )
										UpperCAmelCase         =			model.to(lowerCAmelCase   )

										UpperCAmelCase         =			MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''   )

										UpperCAmelCase         =			prepare_img()
										UpperCAmelCase         =			image_processor(images=lowerCAmelCase   ,					return_tensors='''pt'''   ).to(lowerCAmelCase   )

										# forward pass
										with torch.no_grad():
																UpperCAmelCase         =			model(**lowerCAmelCase   )

										UpperCAmelCase         =			outputs.logits.detach().cpu()

										UpperCAmelCase         =			image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase   ,					target_sizes=[(50, 60)]   )
										UpperCAmelCase         =			torch.Size((50, 60)   )
										self.assertEqual(segmentation[0].shape   ,					lowerCAmelCase   )

										UpperCAmelCase         =			image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase   )
										UpperCAmelCase         =			torch.Size((32, 32)   )
										self.assertEqual(segmentation[0].shape   ,					lowerCAmelCase   )









'''simple docstring'''



import argparse

from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird
from transformers.utils import logging


logging.set_verbosity_info()


def    lowerCamelCase__   ( A     :    List[Any]   ,     A     :    int   ,     A     :    List[str]   ,     A     :    Optional[int]  ):




						'''simple docstring'''






						UpperCAmelCase         =			BigBirdConfig.from_json_file(A  )
						print(f"""Building PyTorch model from configuration: {config}"""  )

						if is_trivia_qa:
												UpperCAmelCase         =			BigBirdForQuestionAnswering(A  )
						else:
												UpperCAmelCase         =			BigBirdForPreTraining(A  )

						# Load weights from tf checkpoint
						load_tf_weights_in_big_bird(A   ,     A   ,     is_trivia_qa=A  )

						# Save pytorch-model
						print(f"""Save PyTorch model to {pytorch_dump_path}"""  )
						model.save_pretrained(A  )


if __name__ == "__main__":
	_lowercase    :    List[str]			     =  argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
	)
	parser.add_argument(
	    """--big_bird_config_file""",
	    default=None,
	    type=str,
	    required=True,
	    help=(
	        """The config json file corresponding to the pre-trained BERT model. \n"""
	        """This specifies the model architecture."""
	    ),
	)
	parser.add_argument(
	    """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
	)
	parser.add_argument(
	    """--is_trivia_qa""", action="""store_true""", help="""Whether to convert a model with a trivia_qa head."""
	)
	_lowercase    :    Any			     =  parser.parse_args()
	convert_tf_checkpoint_to_pytorch(
	    args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa
	)





