
"""simple docstring"""





import os
import tempfile
import unittest

from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, 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 (
				    FlaubertForMultipleChoice,
				    FlaubertForQuestionAnswering,
				    FlaubertForQuestionAnsweringSimple,
				    FlaubertForSequenceClassification,
				    FlaubertForTokenClassification,
				    FlaubertModel,
				    FlaubertWithLMHeadModel,
				)
				from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST






class        _UpperCAmelCase(       lowerCamelCase      ):



		def __init__(   self							,						__a							,						__a=13							,						__a=7							,						__a=True							,						__a=True							,						__a=True							,						__a=True							,						__a=True							,						__a=False							,						__a=False							,						__a=False							,						__a=2							,						__a=99							,						__a=0							,						__a=32							,						__a=5							,						__a=4							,						__a=0.1							,						__a=0.1							,						__a=5_12							,						__a=12							,						__a=2							,						__a=0.02							,						__a=3							,						__a=4							,						__a="last"							,						__a=None							,						__a=None							,						)			->			List[str]:






							'''simple docstring'''
							_UpperCamelCase									=    parent
							_UpperCamelCase									=    batch_size
							_UpperCamelCase									=    seq_length
							_UpperCamelCase									=    is_training
							_UpperCamelCase									=    use_input_lengths
							_UpperCamelCase									=    use_token_type_ids
							_UpperCamelCase									=    use_labels
							_UpperCamelCase									=    gelu_activation
							_UpperCamelCase									=    sinusoidal_embeddings
							_UpperCamelCase									=    causal
							_UpperCamelCase									=    asm
							_UpperCamelCase									=    n_langs
							_UpperCamelCase									=    vocab_size
							_UpperCamelCase									=    n_special
							_UpperCamelCase									=    hidden_size
							_UpperCamelCase									=    num_hidden_layers
							_UpperCamelCase									=    num_attention_heads
							_UpperCamelCase									=    hidden_dropout_prob
							_UpperCamelCase									=    attention_probs_dropout_prob
							_UpperCamelCase									=    max_position_embeddings
							_UpperCamelCase									=    type_vocab_size
							_UpperCamelCase									=    type_sequence_label_size
							_UpperCamelCase									=    initializer_range
							_UpperCamelCase									=    num_labels
							_UpperCamelCase									=    num_choices
							_UpperCamelCase									=    summary_type
							_UpperCamelCase									=    use_proj
							_UpperCamelCase									=    scope



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






							'''simple docstring'''
							_UpperCamelCase									=    ids_tensor([self.batch_size, self.seq_length]							,						self.vocab_size)
							_UpperCamelCase									=    random_attention_mask([self.batch_size, self.seq_length])

							_UpperCamelCase									=    None
							if self.use_input_lengths:
												_UpperCamelCase									=    (
												    ids_tensor([self.batch_size]							,						vocab_size=2) + self.seq_length - 2
												)  # small variation of seq_length

							_UpperCamelCase									=    None
							if self.use_token_type_ids:
												_UpperCamelCase									=    ids_tensor([self.batch_size, self.seq_length]							,						self.n_langs)

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

							_UpperCamelCase									=    self.get_config()

							return (
							    config,
							    input_ids,
							    token_type_ids,
							    input_lengths,
							    sequence_labels,
							    token_labels,
							    is_impossible_labels,
							    choice_labels,
							    input_mask,
							)



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






							'''simple docstring'''
							return FlaubertConfig(
							    vocab_size=self.vocab_size							,						n_special=self.n_special							,						emb_dim=self.hidden_size							,						n_layers=self.num_hidden_layers							,						n_heads=self.num_attention_heads							,						dropout=self.hidden_dropout_prob							,						attention_dropout=self.attention_probs_dropout_prob							,						gelu_activation=self.gelu_activation							,						sinusoidal_embeddings=self.sinusoidal_embeddings							,						asm=self.asm							,						causal=self.causal							,						n_langs=self.n_langs							,						max_position_embeddings=self.max_position_embeddings							,						initializer_range=self.initializer_range							,						summary_type=self.summary_type							,						use_proj=self.use_proj							,						)



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






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertModel(config=__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase									=    model(__a							,						lengths=__a							,						langs=__a)
							_UpperCamelCase									=    model(__a							,						langs=__a)
							_UpperCamelCase									=    model(__a)
							self.parent.assertEqual(result.last_hidden_state.shape							,						(self.batch_size, self.seq_length, self.hidden_size))



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






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertWithLMHeadModel(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a							,						token_type_ids=__a							,						labels=__a)
							self.parent.assertEqual(result.loss.shape							,						())
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.seq_length, self.vocab_size))



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			Dict:






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertForQuestionAnsweringSimple(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a)

							_UpperCamelCase									=    model(__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 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			Tuple:






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertForQuestionAnswering(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a)

							_UpperCamelCase									=    model(
							    __a							,						start_positions=__a							,						end_positions=__a							,						cls_index=__a							,						is_impossible=__a							,						p_mask=__a							,						)

							_UpperCamelCase									=    model(
							    __a							,						start_positions=__a							,						end_positions=__a							,						cls_index=__a							,						is_impossible=__a							,						)

							((_UpperCamelCase)					,    )									=    result_with_labels.to_tuple()

							_UpperCamelCase									=    model(__a							,						start_positions=__a							,						end_positions=__a)

							((_UpperCamelCase)					,    )									=    result_with_labels.to_tuple()

							self.parent.assertEqual(result_with_labels.loss.shape							,						())
							self.parent.assertEqual(result.start_top_log_probs.shape							,						(self.batch_size, model.config.start_n_top))
							self.parent.assertEqual(result.start_top_index.shape							,						(self.batch_size, model.config.start_n_top))
							self.parent.assertEqual(
							    result.end_top_log_probs.shape							,						(self.batch_size, model.config.start_n_top * model.config.end_n_top))
							self.parent.assertEqual(
							    result.end_top_index.shape							,						(self.batch_size, model.config.start_n_top * model.config.end_n_top))
							self.parent.assertEqual(result.cls_logits.shape							,						(self.batch_size,))



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			Dict:






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertForSequenceClassification(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a)
							_UpperCamelCase									=    model(__a							,						labels=__a)

							self.parent.assertEqual(result.loss.shape							,						())
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.type_sequence_label_size))



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






							'''simple docstring'''
							_UpperCamelCase									=    self.num_labels
							_UpperCamelCase									=    FlaubertForTokenClassification(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a							,						attention_mask=__a							,						labels=__a)
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.seq_length, self.num_labels))



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






							'''simple docstring'''
							_UpperCamelCase									=    self.num_choices
							_UpperCamelCase									=    FlaubertForMultipleChoice(config=__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase									=    input_ids.unsqueeze(1).expand(-1							,						self.num_choices							,						-1).contiguous()
							_UpperCamelCase									=    token_type_ids.unsqueeze(1).expand(-1							,						self.num_choices							,						-1).contiguous()
							_UpperCamelCase									=    input_mask.unsqueeze(1).expand(-1							,						self.num_choices							,						-1).contiguous()
							_UpperCamelCase									=    model(
							    __a							,						attention_mask=__a							,						token_type_ids=__a							,						labels=__a							,						)
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.num_choices))




		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    self.prepare_config_and_inputs()
							(
							    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    
							)									=    config_and_inputs
							_UpperCamelCase									=    {
							    '''input_ids''': input_ids,
							    '''token_type_ids''': token_type_ids,
							    '''lengths''': input_lengths,
							    '''attention_mask''': input_mask,
							}
							return config, inputs_dict






@require_torch
class        _UpperCAmelCase(       lowerCamelCase ,	lowerCamelCase ,	unittest.TestCase      ):
		lowercase__         = (
		    (
		        FlaubertModel,
		        FlaubertWithLMHeadModel,
		        FlaubertForQuestionAnswering,
		        FlaubertForQuestionAnsweringSimple,
		        FlaubertForSequenceClassification,
		        FlaubertForTokenClassification,
		        FlaubertForMultipleChoice,
		    )
		    if is_torch_available()
		    else ()
		)
		lowercase__         = (
		    {
		        'feature-extraction': FlaubertModel,
		        'fill-mask': FlaubertWithLMHeadModel,
		        'question-answering': FlaubertForQuestionAnsweringSimple,
		        'text-classification': FlaubertForSequenceClassification,
		        'token-classification': FlaubertForTokenClassification,
		        'zero-shot': FlaubertForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)



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






							'''simple docstring'''
							if (
							    pipeline_test_casse_name == "QAPipelineTests"
							    and tokenizer_name is not None
							    and not tokenizer_name.endswith('''Fast''')
							):
												# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
												# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
												# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
												return True

							return False



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a=False)			->			Dict:






							'''simple docstring'''
							_UpperCamelCase									=    super()._prepare_for_class(__a							,						__a							,						return_labels=__a)

							if return_labels:
												if model_class.__name__ == "FlaubertForQuestionAnswering":
																	_UpperCamelCase									=    torch.zeros(
																	    self.model_tester.batch_size							,						dtype=torch.long							,						device=__a)
																	_UpperCamelCase									=    torch.zeros(
																	    self.model_tester.batch_size							,						dtype=torch.long							,						device=__a)

							return inputs_dict



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






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertModelTester(self)
							_UpperCamelCase									=    ConfigTester(self							,						config_class=__a							,						emb_dim=37)



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






							'''simple docstring'''
							self.config_tester.run_common_tests()



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






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_model(*__a)



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






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_lm_head(*__a)



		def 		UpperCAmelCase				(   self)			->			int:






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_simple_qa(*__a)



		def 		UpperCAmelCase				(   self)			->			Optional[int]:






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_qa(*__a)



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






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_sequence_classif(*__a)



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_token_classif(*__a)



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_multiple_choice(*__a)



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






							'''simple docstring'''
							for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												_UpperCamelCase									=    FlaubertModel.from_pretrained(__a)
												self.assertIsNotNone(__a)




		@slow
		@require_torch_gpu
		def 		UpperCAmelCase				(   self)			->			Union[str, Any]:






							'''simple docstring'''
							_UpperCamelCase					,    _UpperCamelCase									=    self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
												# FlauBertForMultipleChoice behaves incorrectly in JIT environments.
												if model_class == FlaubertForMultipleChoice:
																	return

												_UpperCamelCase									=    True
												_UpperCamelCase									=    model_class(config=__a)

												_UpperCamelCase									=    self._prepare_for_class(__a							,						__a)
												_UpperCamelCase									=    torch.jit.trace(
												    __a							,						(inputs_dict['''input_ids'''].to('''cpu'''), inputs_dict['''attention_mask'''].to('''cpu''')))

												with tempfile.TemporaryDirectory() as tmp:
																	torch.jit.save(__a							,						os.path.join(__a							,						'''traced_model.pt'''))
																	_UpperCamelCase									=    torch.jit.load(os.path.join(__a							,						'''traced_model.pt''')							,						map_location=__a)
																	loaded(inputs_dict['''input_ids'''].to(__a)							,						inputs_dict['''attention_mask'''].to(__a))






@require_torch
class        _UpperCAmelCase(       unittest.TestCase      ):



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






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertModel.from_pretrained('''flaubert/flaubert_base_cased''')
							_UpperCamelCase									=    torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]])
							with torch.no_grad():
												_UpperCamelCase									=    model(__a)[0]
							_UpperCamelCase									=    torch.Size((1, 11, 7_68))
							self.assertEqual(output.shape							,						__a)
							_UpperCamelCase									=    torch.tensor(
							    [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]])

							self.assertTrue(torch.allclose(output[:, :3, :3]							,						__a							,						atol=1e-4))














'''simple docstring'''



import argparse
import json
import re
from pathlib import Path

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

from transformers import (
    MobileNetVaConfig,
    MobileNetVaForImageClassification,
    MobileNetVaImageProcessor,
    load_tf_weights_in_mobilenet_va,
)
from transformers.utils import logging


logging.set_verbosity_info()
__UpperCamelCase   :							Tuple         =   logging.get_logger(__name__)



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						List[Any]     )	->      Optional[Any]:

   """simple docstring"""
   __a					  =     MobileNetVaConfig(layer_norm_eps=0.0_0_1     )

   if "_quant" in model_name:
      raise ValueError('Quantized models are not supported.'     )

   __a					  =     re.match(r'^mobilenet_v1_([^_]*)_([^_]*)$',       SCREAMING_SNAKE_CASE__     )
   if matches:
      __a					  =     float(matches[1]     )
      __a					  =     int(matches[2]     )

   # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of
   # the usual 1000. The first class (index 0) is "background".
   __a					  =     1001
   __a					  =     'imagenet-1k-id2label.json'
   __a					  =     'huggingface/label-files'
   __a					  =     json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       repo_type='dataset'     ),       'r'     )     )
   __a					  =     {int(SCREAMING_SNAKE_CASE__     ) + 1: v for k, v in idalabel.items()}
   __a					  =     'background'
   __a					  =     idalabel
   __a					  =     {v: k for k, v in idalabel.items()}

   return config



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

   """simple docstring"""
   __a					  =     'http://images.cocodataset.org/val2017/000000039769.jpg'
   __a					  =     Image.open(requests.get(SCREAMING_SNAKE_CASE__,       stream=SCREAMING_SNAKE_CASE__     ).raw     )
   return im



@torch.no_grad()
def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						int,       SCREAMING_SNAKE_CASE__:						Union[str, Any],       SCREAMING_SNAKE_CASE__:						Optional[int],       SCREAMING_SNAKE_CASE__:						str=False     )	->      int:

   """simple docstring"""
   __a					  =     get_mobilenet_va_config(SCREAMING_SNAKE_CASE__     )

   # Load 🤗 model
   __a					  =     MobileNetVaForImageClassification(SCREAMING_SNAKE_CASE__     ).eval()

   # Load weights from TensorFlow checkpoint
   load_tf_weights_in_mobilenet_va(SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__     )

   # Check outputs on an image, prepared by MobileNetV1ImageProcessor
   __a					  =     MobileNetVaImageProcessor(
       crop_size={'width': config.image_size, 'height': config.image_size},       size={'shortest_edge': config.image_size + 32},       )
   __a					  =     image_processor(images=prepare_img(),       return_tensors='pt'     )
   __a					  =     model(**SCREAMING_SNAKE_CASE__     )
   __a					  =     outputs.logits

   assert logits.shape == (1, 1001)

   if model_name == "mobilenet_v1_1.0_224":
      __a					  =     torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5]     )
   elif model_name == "mobilenet_v1_0.75_192":
      __a					  =     torch.tensor([-3.9_4_4_0, -2.3_1_4_1, -0.3_3_3_3]     )
   else:
      __a					  =     None

   if expected_logits is not None:
      assert torch.allclose(logits[0, :3],       SCREAMING_SNAKE_CASE__,       atol=1e-4     )

   Path(SCREAMING_SNAKE_CASE__     ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__     )
   print(f"""Saving model {model_name} to {pytorch_dump_folder_path}"""     )
   model.save_pretrained(SCREAMING_SNAKE_CASE__     )
   print(f"""Saving image processor to {pytorch_dump_folder_path}"""     )
   image_processor.save_pretrained(SCREAMING_SNAKE_CASE__     )

   if push_to_hub:
      print('Pushing to the hub...'     )
      __a					  =     'google/' + model_name
      image_processor.push_to_hub(SCREAMING_SNAKE_CASE__     )
      model.push_to_hub(SCREAMING_SNAKE_CASE__     )


if __name__ == "__main__":
 __UpperCamelCase   :							Any         =   argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     """--model_name""",
     default="""mobilenet_v1_1.0_224""",
     type=str,
     help="""Name of the MobileNetV1 model you'd like to convert. Should in the form 'mobilenet_v1_<depth>_<size>'.""",
 )
 parser.add_argument(
     """--checkpoint_path""", required=True, type=str, help="""Path to the original TensorFlow checkpoint (.ckpt file)."""
 )
 parser.add_argument(
     """--pytorch_dump_folder_path""", required=True, 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."""
 )

 __UpperCamelCase   :							Any         =   parser.parse_args()
 convert_movilevit_checkpoint(
     args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
 )