





import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_lowerCamelCase   				=			logging.get_logger(__name__)

_lowerCamelCase   				=			{
    'nvidia/segformer-b0-finetuned-ade-512-512': (
        'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json'
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}




class   UpperCamelCase_       (     UpperCamelCase__    ):
							lowerCamelCase_           =					"segformer"


							def __init__(							self    :Optional[int]							,				__A    :List[Any]=3							,				__A    :Optional[Any]=4							,				__A    :int=[2, 2, 2, 2]							,				__A    :Union[str, Any]=[8, 4, 2, 1]							,				__A    :Optional[int]=[32, 64, 160, 256]							,				__A    :int=[7, 3, 3, 3]							,				__A    :Tuple=[4, 2, 2, 2]							,				__A    :str=[1, 2, 5, 8]							,				__A    :Union[str, Any]=[4, 4, 4, 4]							,				__A    :Any="gelu"							,				__A    :List[str]=0.0							,				__A    :List[Any]=0.0							,				__A    :Any=0.1							,				__A    :Optional[int]=0.0_2							,				__A    :List[Any]=0.1							,				__A    :int=1E-6							,				__A    :int=256							,				__A    :Dict=255							,				**__A    :Any							,				)   ->   List[Any]:



									"""simple docstring"""



									super().__init__(**__A		)

									if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
											warnings.warn(
											    """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be"""
											    """ removed, as the behaviour will default to that of reshape_last_stage = True."""							,				__A							,				)

									SCREAMING_SNAKE_CASE__			=      num_channels
									SCREAMING_SNAKE_CASE__			=      num_encoder_blocks
									SCREAMING_SNAKE_CASE__			=      depths
									SCREAMING_SNAKE_CASE__			=      sr_ratios
									SCREAMING_SNAKE_CASE__			=      hidden_sizes
									SCREAMING_SNAKE_CASE__			=      patch_sizes
									SCREAMING_SNAKE_CASE__			=      strides
									SCREAMING_SNAKE_CASE__			=      mlp_ratios
									SCREAMING_SNAKE_CASE__			=      num_attention_heads
									SCREAMING_SNAKE_CASE__			=      hidden_act
									SCREAMING_SNAKE_CASE__			=      hidden_dropout_prob
									SCREAMING_SNAKE_CASE__			=      attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE__			=      classifier_dropout_prob
									SCREAMING_SNAKE_CASE__			=      initializer_range
									SCREAMING_SNAKE_CASE__			=      drop_path_rate
									SCREAMING_SNAKE_CASE__			=      layer_norm_eps
									SCREAMING_SNAKE_CASE__			=      decoder_hidden_size
									SCREAMING_SNAKE_CASE__			=      kwargs.get("""reshape_last_stage"""							,				__A		)
									SCREAMING_SNAKE_CASE__			=      semantic_loss_ignore_index




class   UpperCamelCase_       (     UpperCamelCase__    ):
							lowerCamelCase_           =					version.parse("1.11"    )


							@property
							def      _snake_case  (							self    :Union[str, Any]		)   ->   Mapping[str, Mapping[int, str]]:



									"""simple docstring"""



									return OrderedDict(
									    [
									        ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
									    ]		)


							@property
							def      _snake_case  (							self    :Optional[Any]		)   ->   float:



									"""simple docstring"""



									return 1E-4


							@property
							def      _snake_case  (							self    :str		)   ->   int:



									"""simple docstring"""



									return 12






import argparse
import os
import pickle
import sys

import torch

from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
_lowerCamelCase   				=			data_utils.TransfoXLTokenizer
_lowerCamelCase   				=			data_utils.TransfoXLCorpus
_lowerCamelCase   				=			data_utils
_lowerCamelCase   				=			data_utils






def 				SCREAMING_SNAKE_CASE__							(       UpperCamelCase__:							Dict					,   UpperCamelCase__:							Any					,   UpperCamelCase__:							Any					,   UpperCamelCase__:							Tuple    ):
		if transfo_xl_dataset_file:
				# Convert a pre-processed corpus (see original TensorFlow repo)
				with open(UpperCamelCase__					,   """rb"""    ) as fp:
						SCREAMING_SNAKE_CASE__			=      pickle.load(UpperCamelCase__					,   encoding="""latin1"""    )
				# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
				SCREAMING_SNAKE_CASE__			=      pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""]
				print(f'''Save vocabulary to {pytorch_vocab_dump_path}'''    )
				SCREAMING_SNAKE_CASE__			=      corpus.vocab.__dict__
				torch.save(UpperCamelCase__					,   UpperCamelCase__    )

				SCREAMING_SNAKE_CASE__			=      corpus.__dict__
				corpus_dict_no_vocab.pop("""vocab"""					,   UpperCamelCase__    )
				SCREAMING_SNAKE_CASE__			=      pytorch_dump_folder_path + """/""" + CORPUS_NAME
				print(f'''Save dataset to {pytorch_dataset_dump_path}'''    )
				torch.save(UpperCamelCase__					,   UpperCamelCase__    )

		if tf_checkpoint_path:
				# Convert a pre-trained TensorFlow model
				SCREAMING_SNAKE_CASE__			=      os.path.abspath(UpperCamelCase__    )
				SCREAMING_SNAKE_CASE__			=      os.path.abspath(UpperCamelCase__    )

				print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.'''    )
				# Initialise PyTorch model
				if transfo_xl_config_file == "":
						SCREAMING_SNAKE_CASE__			=      TransfoXLConfig()
				else:
						SCREAMING_SNAKE_CASE__			=      TransfoXLConfig.from_json_file(UpperCamelCase__    )
				print(f'''Building PyTorch model from configuration: {config}'''    )
				SCREAMING_SNAKE_CASE__			=      TransfoXLLMHeadModel(UpperCamelCase__    )

				SCREAMING_SNAKE_CASE__			=      load_tf_weights_in_transfo_xl(UpperCamelCase__					,   UpperCamelCase__					,   UpperCamelCase__    )
				# Save pytorch-model
				SCREAMING_SNAKE_CASE__			=      os.path.join(UpperCamelCase__					,   UpperCamelCase__    )
				SCREAMING_SNAKE_CASE__			=      os.path.join(UpperCamelCase__					,   UpperCamelCase__    )
				print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__    )}'''    )
				torch.save(model.state_dict()					,   UpperCamelCase__    )
				print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__    )}'''    )
				with open(UpperCamelCase__					,   """w"""					,   encoding="""utf-8"""    ) as f:
						f.write(config.to_json_string()    )


if __name__ == "__main__":
	_lowerCamelCase   				=			argparse.ArgumentParser()
	parser.add_argument(
	    '--pytorch_dump_folder_path',
	    default=None,
	    type=str,
	    required=True,
	    help='Path to the folder to store the PyTorch model or dataset/vocab.',
	)
	parser.add_argument(
	    '--tf_checkpoint_path',
	    default='',
	    type=str,
	    help='An optional path to a TensorFlow checkpoint path to be converted.',
	)
	parser.add_argument(
	    '--transfo_xl_config_file',
	    default='',
	    type=str,
	    help=(
	        'An optional config json file corresponding to the pre-trained BERT model. \n'
	        'This specifies the model architecture.'
	    ),
	)
	parser.add_argument(
	    '--transfo_xl_dataset_file',
	    default='',
	    type=str,
	    help='An optional dataset file to be converted in a vocabulary.',
	)
	_lowerCamelCase   				=			parser.parse_args()
	convert_transfo_xl_checkpoint_to_pytorch(
	    args.tf_checkpoint_path,
	    args.transfo_xl_config_file,
	    args.pytorch_dump_folder_path,
	    args.transfo_xl_dataset_file,
	)