






import argparse

import torch

from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert
from transformers.utils import logging


logging.set_verbosity_info()

def      lowerCAmelCase__	(    _a       :			Union[str, Any]  ,      _a       :			str  ,      _a       :			Tuple    ):
		# Initialise PyTorch model
		snake_case_				:							Optional[int]						 =       RemBertConfig.from_json_file(_a    )
		print("Building PyTorch model from configuration: {}".format(str(_a    )    )    )
		snake_case_				:							Optional[Any]						 =       RemBertModel(_a    )

		# Load weights from tf checkpoint
		load_tf_weights_in_rembert(_a  ,      _a  ,      _a    )

		# Save pytorch-model
		print("Save PyTorch model to {}".format(_a    )    )
		torch.save(model.state_dict()  ,      _a    )


if __name__ == "__main__":
							lowercase  :							Optional[Any]			  =    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(
							    '''--rembert_config_file''',
							    default=None,
							    type=str,
							    required=True,
							    help=(
							        '''The config json file corresponding to the pre-trained RemBERT 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.'''
							)
							lowercase  :							str			  =    parser.parse_args()
							convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)








import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


lowercase  :							Optional[Any]			  =    logging.getLogger(__name__)




@dataclass(frozen=SCREAMING_SNAKE_CASE__					)
class 		UpperCAmelCase_						:


						'''simple docstring'''




						A     :   str
						A     :   str
						A     :   Optional[str]						=					None
						A     :   Optional[str]						=					None
						A     :   Optional[str]						=					None




@dataclass(frozen=SCREAMING_SNAKE_CASE__					)
class 		UpperCAmelCase_						:


						'''simple docstring'''




						A     :   List[int]
						A     :   Optional[List[int]]						=					None
						A     :   Optional[List[int]]						=					None
						A     :   Optional[Union[int, float]]						=					None
						A     :   Optional[int]						=					None


if is_torch_available():
							import torch
							from torch.utils.data import Dataset




							class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


													'''simple docstring'''




													A     :   List[InputFeatures]






													def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE=False		,				_SCREAMING_SNAKE_CASE = False		,				) ->				Union[str, Any]:
															snake_case_				:							str						 =       hans_processors[task]()

															snake_case_				:							Tuple						 =       os.path.join(
															    _SCREAMING_SNAKE_CASE		,				"cached_{}_{}_{}_{}".format(
															        "dev" if evaluate else "train"		,				tokenizer.__class__.__name__		,				str(_SCREAMING_SNAKE_CASE				)		,				_SCREAMING_SNAKE_CASE		,				)		,				)
															snake_case_				:							Dict						 =       processor.get_labels()
															if tokenizer.__class__ in (
															    RobertaTokenizer,
															    RobertaTokenizerFast,
															    XLMRobertaTokenizer,
															    BartTokenizer,
															    BartTokenizerFast,
															):
																	# HACK(label indices are swapped in RoBERTa pretrained model)
																	snake_case_ ,       snake_case_				:							Any						 =       label_list[2], label_list[1]
															snake_case_				:							Tuple						 =       label_list

															# Make sure only the first process in distributed training processes the dataset,
															# and the others will use the cache.
															snake_case_				:							Dict						 =       cached_features_file + ".lock"
															with FileLock(_SCREAMING_SNAKE_CASE				):
																	if os.path.exists(_SCREAMING_SNAKE_CASE				) and not overwrite_cache:
																			logger.info(f'''Loading features from cached file {cached_features_file}'''				)
																			snake_case_				:							Dict						 =       torch.load(_SCREAMING_SNAKE_CASE				)
																	else:
																			logger.info(f'''Creating features from dataset file at {data_dir}'''				)

																			snake_case_				:							Any						 =       (
																			    processor.get_dev_examples(_SCREAMING_SNAKE_CASE				) if evaluate else processor.get_train_examples(_SCREAMING_SNAKE_CASE				)
																			)

																			logger.info("Training examples: %s"		,				len(_SCREAMING_SNAKE_CASE				)				)
																			snake_case_				:							Union[str, Any]						 =       hans_convert_examples_to_features(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)
																			logger.info("Saving features into cached file %s"		,				_SCREAMING_SNAKE_CASE				)
																			torch.save(self.features		,				_SCREAMING_SNAKE_CASE				)






													def __len__(	self				) ->				Tuple:
															return len(self.features				)






													def __getitem__(	self		,				_SCREAMING_SNAKE_CASE				) ->				InputFeatures:
															return self.features[i]






													def       _lowerCAmelCase       (	self				) ->				Dict:
															return self.label_list


if is_tf_available():
							import tensorflow as tf




							class 		UpperCAmelCase_						:


													'''simple docstring'''




													A     :   List[InputFeatures]






													def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = 128		,				_SCREAMING_SNAKE_CASE=False		,				_SCREAMING_SNAKE_CASE = False		,				) ->				Optional[int]:
															snake_case_				:							Tuple						 =       hans_processors[task]()
															snake_case_				:							Dict						 =       processor.get_labels()
															if tokenizer.__class__ in (
															    RobertaTokenizer,
															    RobertaTokenizerFast,
															    XLMRobertaTokenizer,
															    BartTokenizer,
															    BartTokenizerFast,
															):
																	# HACK(label indices are swapped in RoBERTa pretrained model)
																	snake_case_ ,       snake_case_				:							List[str]						 =       label_list[2], label_list[1]
															snake_case_				:							Dict						 =       label_list

															snake_case_				:							int						 =       processor.get_dev_examples(_SCREAMING_SNAKE_CASE				) if evaluate else processor.get_train_examples(_SCREAMING_SNAKE_CASE				)
															snake_case_				:							str						 =       hans_convert_examples_to_features(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)

															def gen():
																	for ex_index, ex in tqdm.tqdm(enumerate(self.features				)		,				desc="convert examples to features"				):
																			if ex_index % 1_0000 == 0:
																					logger.info("Writing example %d of %d" % (ex_index, len(_SCREAMING_SNAKE_CASE				))				)

																			yield (
																			    {
																			        "example_id": 0,
																			        "input_ids": ex.input_ids,
																			        "attention_mask": ex.attention_mask,
																			        "token_type_ids": ex.token_type_ids,
																			    },
																			    ex.label,
																			)

															snake_case_				:							List[Any]						 =       tf.data.Dataset.from_generator(
															    _SCREAMING_SNAKE_CASE		,				(
															        {
															            "example_id": tf.intaa,
															            "input_ids": tf.intaa,
															            "attention_mask": tf.intaa,
															            "token_type_ids": tf.intaa,
															        },
															        tf.intaa,
															    )		,				(
															        {
															            "example_id": tf.TensorShape([]				),
															            "input_ids": tf.TensorShape([None, None]				),
															            "attention_mask": tf.TensorShape([None, None]				),
															            "token_type_ids": tf.TensorShape([None, None]				),
															        },
															        tf.TensorShape([]				),
															    )		,				)






													def       _lowerCAmelCase       (	self				) ->				int:
															return self.dataset






													def __len__(	self				) ->				int:
															return len(self.features				)






													def __getitem__(	self		,				_SCREAMING_SNAKE_CASE				) ->				InputFeatures:
															return self.features[i]






													def       _lowerCAmelCase       (	self				) ->				Dict:
															return self.label_list




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				int:
								return self._create_examples(self._read_tsv(os.path.join(_SCREAMING_SNAKE_CASE		,				"heuristics_train_set.txt"				)				)		,				"train"				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[Any]:
								return self._create_examples(self._read_tsv(os.path.join(_SCREAMING_SNAKE_CASE		,				"heuristics_evaluation_set.txt"				)				)		,				"dev"				)






						def       _lowerCAmelCase       (	self				) ->				Dict:
								return ["contradiction", "entailment", "neutral"]






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
								snake_case_				:							Optional[Any]						 =       []
								for i, line in enumerate(_SCREAMING_SNAKE_CASE				):
										if i == 0:
												continue
										snake_case_				:							List[Any]						 =       "%s-%s" % (set_type, line[0])
										snake_case_				:							int						 =       line[5]
										snake_case_				:							str						 =       line[6]
										snake_case_				:							Any						 =       line[7][2:] if line[7].startswith("ex"				) else line[7]
										snake_case_				:							Dict						 =       line[0]
										examples.append(InputExample(guid=_SCREAMING_SNAKE_CASE		,				text_a=_SCREAMING_SNAKE_CASE		,				text_b=_SCREAMING_SNAKE_CASE		,				label=_SCREAMING_SNAKE_CASE		,				pairID=_SCREAMING_SNAKE_CASE				)				)
								return examples




def      lowerCAmelCase__	(    _a       :			List[InputExample]  ,      _a       :			List[str]  ,      _a       :			int  ,      _a       :			PreTrainedTokenizer  ,      ):
		snake_case_				:							Optional[Any]						 =       {label: i for i, label in enumerate(_a    )}

		snake_case_				:							Optional[Any]						 =       []
		for ex_index, example in tqdm.tqdm(enumerate(_a    )  ,      desc="convert examples to features"    ):
				if ex_index % 1_00_00 == 0:
						logger.info("Writing example %d" % (ex_index)    )

				snake_case_				:							Optional[Any]						 =       tokenizer(
				    example.text_a  ,      example.text_b  ,      add_special_tokens=_a  ,      max_length=_a  ,      padding="max_length"  ,      truncation=_a  ,      return_overflowing_tokens=_a  ,      )

				snake_case_				:							Dict						 =       label_map[example.label] if example.label in label_map else 0

				snake_case_				:							Optional[Any]						 =       int(example.pairID    )

				features.append(InputFeatures(**_a  ,      label=_a  ,      pairID=_a    )    )

		for i, example in enumerate(examples[:5]    ):
				logger.info("*** Example ***"    )
				logger.info(F'''guid: {example}'''    )
				logger.info(F'''features: {features[i]}'''    )

		return features


lowercase  :							List[str]			  =    {
    '''hans''': 3,
}

lowercase  :							int			  =    {
    '''hans''': HansProcessor,
}
