






import argparse
import logging
import pickle
from collections import Counter


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
_a      	=  logging.getLogger(__name__)

if __name__ == "__main__":
		_a      	=  argparse.ArgumentParser(
		    description='''Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)'''
		)
		parser.add_argument(
		    '''--data_file''', type=str, default='''data/dump.bert-base-uncased.pickle''', help='''The binarized dataset.'''
		)
		parser.add_argument(
		    '''--token_counts_dump''', type=str, default='''data/token_counts.bert-base-uncased.pickle''', help='''The dump file.'''
		)
		parser.add_argument('''--vocab_size''', default=30522, type=int)
		_a      	=  parser.parse_args()

		logger.info(F'''Loading data from {args.data_file}''')
		with open(args.data_file, '''rb''') as fp:
				_a      	=  pickle.load(fp)

		logger.info('''Counting occurrences for MLM.''')
		_a      	=  Counter()
		for tk_ids in data:
				counter.update(tk_ids)
		_a      	=  [0] * args.vocab_size
		for k, v in counter.items():
				_a      	=  v

		logger.info(F'''Dump to {args.token_counts_dump}''')
		with open(args.token_counts_dump, '''wb''') as handle:
				pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)

'''simple docstring'''





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,
)


SCREAMING_SNAKE_CASE_:     str  =logging.getLogger(__name__)




@dataclass(frozen=UpperCamelCase__	)
class        __A      :
    a__       :						str
    a__       :						str
    a__       :						Optional[str]          =  None
    a__       :						Optional[str]          =  None
    a__       :						Optional[str]          =  None




@dataclass(frozen=UpperCamelCase__	)
class        __A      :
    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        __A      ( UpperCamelCase__	):
        a__       :						List[InputFeatures]



        def __init__(self    :    Any   ,			__a    :    str   ,			__a    :    PreTrainedTokenizer   ,			__a    :    str   ,			__a    :    Optional[int] = None   ,			__a    :    Dict=False   ,			__a    :    bool = False   ,			):
             UpperCAmelCase_           =   hans_processors[task]()

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

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

                       UpperCAmelCase_           =   (
                           processor.get_dev_examples(__a ) if evaluate else processor.get_train_examples(__a )
                       )

                       logger.info("Training examples: %s"   ,			len(__a ) )
                       UpperCAmelCase_           =   hans_convert_examples_to_features(__a   ,			__a   ,			__a   ,			__a )
                       logger.info("Saving features into cached file %s"   ,			__a )
                       torch.save(self.features   ,			__a )



        def __len__(self    :    List[Any] ):
             return len(self.features )



        def __getitem__(self    :    Any   ,			__a    :    Optional[Any] ):
             return self.features[i]






        def 					_lowercase						(self    :    Union[str, Any] ):
             return self.label_list


if is_tf_available():
    import tensorflow as tf




    class        __A      :
        a__       :						List[InputFeatures]



        def __init__(self    :    Union[str, Any]   ,			__a    :    str   ,			__a    :    PreTrainedTokenizer   ,			__a    :    str   ,			__a    :    Optional[int] = 128   ,			__a    :    Any=False   ,			__a    :    bool = False   ,			):
             UpperCAmelCase_           =   hans_processors[task]()
             UpperCAmelCase_           =   processor.get_labels()
             if tokenizer.__class__ in (
                 RobertaTokenizer,
                 RobertaTokenizerFast,
                 XLMRobertaTokenizer,
                 BartTokenizer,
                 BartTokenizerFast,
             ):
                  # HACK(label indices are swapped in RoBERTa pretrained model)
                  UpperCAmelCase_    , UpperCAmelCase_           =   label_list[2], label_list[1]
             UpperCAmelCase_           =   label_list

             UpperCAmelCase_           =   processor.get_dev_examples(__a ) if evaluate else processor.get_train_examples(__a )
             UpperCAmelCase_           =   hans_convert_examples_to_features(__a   ,			__a   ,			__a   ,			__a )

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

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

             UpperCAmelCase_           =   tf.data.Dataset.from_generator(
                 __a   ,			(
                     {
                         "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 					_lowercase						(self    :    int ):
             return self.dataset



        def __len__(self    :    Any ):
             return len(self.features )



        def __getitem__(self    :    int   ,			__a    :    Union[str, Any] ):
             return self.features[i]






        def 					_lowercase						(self    :    int ):
             return self.label_list




class        __A      ( UpperCamelCase__	):



    def 					_lowercase						(self    :    List[Any]   ,			__a    :    Dict ):
         return self._create_examples(self._read_tsv(os.path.join(__a   ,			"heuristics_train_set.txt" ) )   ,			"train" )



    def 					_lowercase						(self    :    Any   ,			__a    :    List[Any] ):
         return self._create_examples(self._read_tsv(os.path.join(__a   ,			"heuristics_evaluation_set.txt" ) )   ,			"dev" )



    def 					_lowercase						(self    :    Any ):
         return ["contradiction", "entailment", "neutral"]






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





def 	lowerCAmelCase_				(					snake_case_       : List[InputExample]					,    snake_case_       : List[str]					,    snake_case_       : int					,    snake_case_       : PreTrainedTokenizer					,    )    ->      Optional[Any]:


     '''simple docstring'''




     UpperCAmelCase_           =   {label: i for i, label in enumerate(snake_case_			)}

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

          UpperCAmelCase_           =   tokenizer(
              example.text_a					,    example.text_b					,    add_special_tokens=snake_case_					,    max_length=snake_case_					,    padding="max_length"					,    truncation=snake_case_					,    return_overflowing_tokens=snake_case_					,    )

          UpperCAmelCase_           =   label_map[example.label] if example.label in label_map else 0

          UpperCAmelCase_           =   int(example.pairID			)

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

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

     return features


SCREAMING_SNAKE_CASE_:     int  ={
    'hans': 3,
}






SCREAMING_SNAKE_CASE_:     Any  ={
    'hans': HansProcessor,
}




