


"""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 _lowerCAmelCase    (				snake_case_     ):







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

       '''simple docstring'''




       snake_case   :				Dict				 =   self.config_class(**self.inputs_dict						)
       self.parent.assertTrue(hasattr(UpperCamelCase__						,     "width_multiplier"						)						)







class _lowerCAmelCase    :







   def __init__(     self						,     UpperCamelCase__						,     UpperCamelCase__=13						,     UpperCamelCase__=64						,     UpperCamelCase__=2						,     UpperCamelCase__=3						,     UpperCamelCase__="swish"						,     UpperCamelCase__=3						,     UpperCamelCase__=32						,     UpperCamelCase__=0.1						,     UpperCamelCase__=0.02						,     UpperCamelCase__=True						,     UpperCamelCase__=True						,     UpperCamelCase__=10						,     UpperCamelCase__=None						,     UpperCamelCase__=0.25						,     UpperCamelCase__=0.0						,     UpperCamelCase__=0.0						,     )     ->		Any:

       '''simple docstring'''




       snake_case   :				str				 =   parent
       snake_case   :				Dict				 =   batch_size
       snake_case   :				Union[str, Any]				 =   image_size
       snake_case   :				Union[str, Any]				 =   patch_size
       snake_case   :				Tuple				 =   num_channels
       snake_case   :				Union[str, Any]				 =   make_divisible(512 * width_multiplier						,     divisor=8						)
       snake_case   :				int				 =   hidden_act
       snake_case   :				List[Any]				 =   conv_kernel_size
       snake_case   :				Optional[Any]				 =   output_stride
       snake_case   :				str				 =   classifier_dropout_prob
       snake_case   :				int				 =   use_labels
       snake_case   :				int				 =   is_training
       snake_case   :				str				 =   num_labels
       snake_case   :				List[Any]				 =   initializer_range
       snake_case   :				List[Any]				 =   scope
       snake_case   :				List[str]				 =   width_multiplier
       snake_case   :				str				 =   ffn_dropout
       snake_case   :				Dict				 =   attn_dropout







   def 			lowerCamelCase		(     self						)     ->		str:

       '''simple docstring'''




       snake_case   :				int				 =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       snake_case   :				Dict				 =   None
       snake_case   :				List[Any]				 =   None
       if self.use_labels:
           snake_case   :				str				 =   ids_tensor([self.batch_size]						,     self.num_labels						)
           snake_case   :				Tuple				 =   ids_tensor([self.batch_size, self.image_size, self.image_size]						,     self.num_labels						)

       snake_case   :				Any				 =   self.get_config()

       return config, pixel_values, labels, pixel_labels







   def 			lowerCamelCase		(     self						)     ->		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 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)     ->		Dict:

       '''simple docstring'''




       snake_case   :				Tuple				 =   MobileViTVaModel(config=UpperCamelCase__						)
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case   :				Dict				 =   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,
           )						,     )







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)     ->		str:

       '''simple docstring'''




       snake_case   :				Any				 =   self.num_labels
       snake_case   :				List[Any]				 =   MobileViTVaForImageClassification(UpperCamelCase__						)
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case   :				Any				 =   model(UpperCamelCase__						,     labels=UpperCamelCase__						)
       self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.num_labels)						)







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)     ->		Optional[Any]:

       '''simple docstring'''




       snake_case   :				Any				 =   self.num_labels
       snake_case   :				Optional[Any]				 =   MobileViTVaForSemanticSegmentation(UpperCamelCase__						)
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case   :				Dict				 =   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,
           )						,     )
       snake_case   :				List[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						)     ->		Optional[Any]:

       '''simple docstring'''




       snake_case   :				Optional[Any]				 =   self.prepare_config_and_inputs()
       snake_case ,snake_case ,snake_case ,snake_case   :				Optional[int]				 =   config_and_inputs
       snake_case   :				str				 =   {"pixel_values": pixel_values}
       return config, inputs_dict







@require_torch
class _lowerCAmelCase    (				snake_case_   ,							snake_case_   ,							unittest.TestCase     ):
   __UpperCAmelCase			:	Tuple							  =  (
       (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )

   __UpperCAmelCase			:	Dict							  =  (
       {
           '''feature-extraction''': MobileViTVaModel,
           '''image-classification''': MobileViTVaForImageClassification,
           '''image-segmentation''': MobileViTVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __UpperCAmelCase			:	str							  =  False
   __UpperCAmelCase			:	Dict							  =  False
   __UpperCAmelCase			:	Optional[Any]							  =  False
   __UpperCAmelCase			:	List[str]							  =  False







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

       '''simple docstring'''




       snake_case   :				Tuple				 =   MobileViTVaModelTester(self						)
       snake_case   :				Optional[int]				 =   MobileViTVaConfigTester(self						,     config_class=UpperCamelCase__						,     has_text_modality=UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Dict:

       '''simple docstring'''




       self.config_tester.run_common_tests()







   @unittest.skip(reason="MobileViTV2 does not use inputs_embeds"						)
   def 			lowerCamelCase		(     self						)     ->		Dict:

       '''simple docstring'''




       pass







   @unittest.skip(reason="MobileViTV2 does not support input and output embeddings"						)
   def 			lowerCamelCase		(     self						)     ->		Any:

       '''simple docstring'''




       pass







   @unittest.skip(reason="MobileViTV2 does not output attentions"						)
   def 			lowerCamelCase		(     self						)     ->		int:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       pass







   @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."						)
   def 			lowerCamelCase		(     self						)     ->		Optional[int]:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       snake_case ,snake_case   :				Union[str, Any]				 =   self.model_tester.prepare_config_and_inputs_for_common()

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

           snake_case   :				Tuple				 =   ["pixel_values"]
           self.assertListEqual(arg_names[:1]						,     UpperCamelCase__						)







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

       '''simple docstring'''




       snake_case   :				List[str]				 =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







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

       '''simple docstring'''




       def check_hidden_states_output(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						):
           snake_case   :				List[Any]				 =   model_class(UpperCamelCase__						)
           model.to(UpperCamelCase__						)
           model.eval()

           with torch.no_grad():
               snake_case   :				Union[str, Any]				 =   model(**self._prepare_for_class(UpperCamelCase__						,     UpperCamelCase__						)						)

           snake_case   :				str				 =   outputs.hidden_states

           snake_case   :				List[Any]				 =   5
           self.assertEqual(len(UpperCamelCase__						)						,     UpperCamelCase__						)

           # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
           # with the width and height being successively divided by 2.
           snake_case   :				str				 =   2
           for i in range(len(UpperCamelCase__						)						):
               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						)

       snake_case ,snake_case   :				Dict				 =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           snake_case   :				str				 =   True
           check_hidden_states_output(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)

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

           check_hidden_states_output(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)







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

       '''simple docstring'''




       snake_case   :				Dict				 =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__						)







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

       '''simple docstring'''




       snake_case   :				Any				 =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__						)







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

       '''simple docstring'''




       for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case   :				Tuple				 =   MobileViTVaModel.from_pretrained(UpperCamelCase__						)
           self.assertIsNotNone(UpperCamelCase__						)







def   __lowerCAmelCase						(						)     ->						Dict:


    """simple docstring"""





    snake_case   :				List[Any]				 =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
    return image







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







   @cached_property
   def 			lowerCamelCase		(     self						)     ->		str:

       '''simple docstring'''




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







   @slow
   def 			lowerCamelCase		(     self						)     ->		Any:

       '''simple docstring'''




       snake_case   :				List[Any]				 =   MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"						).to(
           UpperCamelCase__						)

       snake_case   :				Optional[int]				 =   self.default_image_processor
       snake_case   :				int				 =   prepare_img()
       snake_case   :				Tuple				 =   image_processor(images=UpperCamelCase__						,     return_tensors="pt"						).to(UpperCamelCase__						)

       # forward pass
       with torch.no_grad():
           snake_case   :				str				 =   model(**UpperCamelCase__						)

       # verify the logits
       snake_case   :				int				 =   torch.Size((1, 1000)						)
       self.assertEqual(outputs.logits.shape						,     UpperCamelCase__						)

       snake_case   :				Union[str, Any]				 =   torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]						).to(UpperCamelCase__						)

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







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

       '''simple docstring'''




       snake_case   :				Optional[Any]				 =   MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"						)
       snake_case   :				Dict				 =   model.to(UpperCamelCase__						)

       snake_case   :				Optional[Any]				 =   MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"						)

       snake_case   :				Optional[int]				 =   prepare_img()
       snake_case   :				str				 =   image_processor(images=UpperCamelCase__						,     return_tensors="pt"						).to(UpperCamelCase__						)

       # forward pass
       with torch.no_grad():
           snake_case   :				Union[str, Any]				 =   model(**UpperCamelCase__						)
       snake_case   :				str				 =   outputs.logits

       # verify the logits
       snake_case   :				int				 =   torch.Size((1, 21, 32, 32)						)
       self.assertEqual(logits.shape						,     UpperCamelCase__						)

       snake_case   :				Optional[Any]				 =   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=UpperCamelCase__						,     )

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







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

       '''simple docstring'''




       snake_case   :				str				 =   MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"						)
       snake_case   :				int				 =   model.to(UpperCamelCase__						)

       snake_case   :				int				 =   MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"						)

       snake_case   :				Tuple				 =   prepare_img()
       snake_case   :				List[str]				 =   image_processor(images=UpperCamelCase__						,     return_tensors="pt"						).to(UpperCamelCase__						)

       # forward pass
       with torch.no_grad():
           snake_case   :				Optional[int]				 =   model(**UpperCamelCase__						)

       snake_case   :				List[str]				 =   outputs.logits.detach().cpu()

       snake_case   :				Tuple				 =   image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__						,     target_sizes=[(50, 60)]						)
       snake_case   :				Dict				 =   torch.Size((50, 60)						)
       self.assertEqual(segmentation[0].shape						,     UpperCamelCase__						)

       snake_case   :				Optional[Any]				 =   image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__						)
       snake_case   :				Dict				 =   torch.Size((32, 32)						)
       self.assertEqual(segmentation[0].shape						,     UpperCamelCase__						)









"""simple docstring"""



import argparse
import re

from flax.traverse_util import flatten_dict, unflatten_dict
from tax import checkpoints

from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration
from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model
from transformers.utils import logging


logging.set_verbosity_info()


# should not include what is already done by the `from_pt` argument
__snake_case             =   {
    """/attention/""": """/0/SelfAttention/""",
    """/self_attention/""": """/0/SelfAttention/""",
    """/encoder_decoder_attention/""": """/1/EncDecAttention/""",
    """value""": """v""",
    """query""": """q""",
    """key""": """k""",
    """out""": """o""",
    """pre_self_attention_layer_norm""": """0/layer_norm""",
    """pre_cross_attention_layer_norm""": """1/layer_norm""",
    """pre_attention_layer_norm""": """0/layer_norm""",  # previously 1, but seems wrong
    """token_embedder""": """shared""",
    """encoder_norm""": """final_layer_norm""",
    """decoder_norm""": """final_layer_norm""",
    """relpos_bias/rel_embedding""": """block/0/layer/0/SelfAttention/relative_attention_bias/weight""",
    """router/router_weights/w/""": """router/classifier/""",
    """roer/roer_weights/w/""": """router/classifier/""",
    """logits_dense""": """lm_head""",
}







def   __lowerCAmelCase						(						lowercase  :  Optional[int]			)     ->						List[str]:


    """simple docstring"""





    snake_case   :				Optional[Any]				 =   list(s_dict.keys()			)
    for key in keys:
        snake_case   :				Any				 =   R".*/layers_(\d+)"
        snake_case   :				Tuple				 =   key
        if re.match(lowercase						,							lowercase			):
            snake_case   :				List[str]				 =   re.sub(R"layers_(\d+)"						,							R"block/\1/layer"						,							lowercase			)

        snake_case   :				Union[str, Any]				 =   R"(encoder|decoder)\/"

        if re.match(lowercase						,							lowercase			):
            snake_case   :				Any				 =   re.match(lowercase						,							lowercase			).groups()
            if groups[0] == "encoder":
                snake_case   :				Union[str, Any]				 =   re.sub(R"/mlp/"						,							R"/1/mlp/"						,							lowercase			)
                snake_case   :				int				 =   re.sub(R"/pre_mlp_layer_norm/"						,							R"/1/layer_norm/"						,							lowercase			)

            elif groups[0] == "decoder":
                snake_case   :				str				 =   re.sub(R"/mlp/"						,							R"/2/mlp/"						,							lowercase			)
                snake_case   :				List[str]				 =   re.sub(R"/pre_mlp_layer_norm/"						,							R"/2/layer_norm/"						,							lowercase			)

        # 2. Convert other classic mappings
        for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items():
            if old_key in new_key:
                snake_case   :				int				 =   new_key.replace(lowercase						,							lowercase			)

        print(F'{key} -> {new_key}'			)
        snake_case   :				Optional[Any]				 =   s_dict.pop(lowercase			)

    if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict:
        snake_case   :				int				 =   s_dict[
            "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight"
        ].T
    if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict:
        snake_case   :				Optional[Any]				 =   s_dict[
            "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight"
        ].T

    # 3. Take extra care of the EXPERTS layer
    for key in list(s_dict.keys()			):
        if "expert" in key:
            snake_case   :				Tuple				 =   s_dict[key].shape[0]
            snake_case   :				int				 =   s_dict[key]
            for idx in range(lowercase			):
                snake_case   :				List[str]				 =   expert_weihts[idx]
                print(F'{key} -> {key.replace("expert/"						,							"nested fstring"			)}'			)

            s_dict.pop(lowercase			)

    return s_dict


__snake_case             =   {
    """NUM_ENCODER_LAYERS""": """num_layers""",
    """NUM_DECODER_LAYERS""": """num_decoder_layers""",
    """NUM_HEADS""": """num_heads""",
    """HEAD_DIM""": """d_kv""",
    """EMBED_DIM""": """d_model""",
    """MLP_DIM""": """d_ff""",
    """NUM_SELECTED_EXPERTS""": """num_selected_experts""",
    """NUM_ENCODER_SPARSE_LAYERS""": """num_sparse_encoder_layers""",
    """NUM_DECODER_SPARSE_LAYERS""": """num_sparse_decoder_layers""",
    """dense.MlpBlock.activations""": """feed_forward_proj""",
}







def   __lowerCAmelCase						(						lowercase  :  Dict						,							lowercase  :  Optional[Any]			)     ->						int:


    """simple docstring"""





    import regex as re

    with open(lowercase						,							"r"			) as f:
        snake_case   :				List[str]				 =   f.read()

    snake_case   :				Tuple				 =   re.findall(R"(.*) = ([0-9.]*)"						,							lowercase			)
    snake_case   :				Any				 =   {}
    for param, value in regex_match:
        if param in GIN_TO_CONFIG_MAPPING and value != "":
            snake_case   :				Tuple				 =   float(lowercase			) if "." in value else int(lowercase			)

    snake_case   :				List[str]				 =   re.findall(R"(.*activations) = \(\'(.*)\',\)"						,							lowercase			)[0]
    snake_case   :				List[Any]				 =   str(activation[1]			)

    snake_case   :				Optional[Any]				 =   num_experts
    snake_case   :				List[Any]				 =   SwitchTransformersConfig(**lowercase			)
    return config







def   __lowerCAmelCase						(						lowercase  :  Tuple						,							lowercase  :  Tuple						,							lowercase  :  Union[str, Any]=None						,							lowercase  :  Any="./"						,							lowercase  :  int=8			)     ->						Dict:


    """simple docstring"""





    print(F'Loading flax weights from : {flax_checkpoint_path}'			)
    snake_case   :				Union[str, Any]				 =   checkpoints.load_tax_checkpoint(lowercase			)

    if gin_file is not None:
        snake_case   :				List[str]				 =   convert_gin_to_config(lowercase						,							lowercase			)
    else:
        snake_case   :				str				 =   SwitchTransformersConfig.from_pretrained(lowercase			)

    snake_case   :				Any				 =   SwitchTransformersForConditionalGeneration(lowercase			)

    snake_case   :				Optional[Any]				 =   flax_params["target"]
    snake_case   :				Optional[int]				 =   flatten_dict(lowercase						,							sep="/"			)
    snake_case   :				Optional[Any]				 =   rename_keys(lowercase			)
    snake_case   :				List[str]				 =   unflatten_dict(lowercase						,							sep="/"			)

    # Load the flax params in the PT model
    load_flax_weights_in_pytorch_model(lowercase						,							lowercase			)

    print(F'Save PyTorch model to {pytorch_dump_path}'			)
    pt_model.save_pretrained(lowercase			)


if __name__ == "__main__":
  __snake_case             =   argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      """--switch_t5x_checkpoint_path""",
      default=None,
      type=str,
      required=True,
      help=(
          """The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the"""
          """ model architecture. If not provided, a `gin_file` has to be provided."""
      ),
  )
  parser.add_argument(
      """--gin_file""",
      default=None,
      type=str,
      required=False,
      help="""Path to the gin config file. If not provided, a `config_file` has to be passed   """,
  )
  parser.add_argument(
      """--config_name""", default=None, type=str, required=False, help="""Config name of SwitchTransformers model."""
  )
  parser.add_argument(
      """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output pytorch model."""
  )
  parser.add_argument("""--num_experts""", default=8, type=int, required=False, help="""Number of experts""")
  __snake_case             =   parser.parse_args()
  convert_flax_checkpoint_to_pytorch(
      args.switch_tax_checkpoint_path,
      args.config_name,
      args.gin_file,
      args.pytorch_dump_folder_path,
      args.num_experts,
  )





