






from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


snake_case__      :	Any       	=      logging.get_logger(__name__)

snake_case__      :	List[str]       	=      {
    """EleutherAI/gpt-j-6B""": """https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json""",
    # See all GPT-J models at https://huggingface.co/models?filter=gpt_j
}


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """gptj"""
  A_						=   {
      """max_position_embeddings""": """n_positions""",
      """hidden_size""": """n_embd""",
      """num_attention_heads""": """n_head""",
      """num_hidden_layers""": """n_layer""",
  }




  def __init__(     self		,		_UpperCAmelCase=50400		,		_UpperCAmelCase=2048		,		_UpperCAmelCase=4096		,		_UpperCAmelCase=28		,		_UpperCAmelCase=16		,		_UpperCAmelCase=64		,		_UpperCAmelCase=None		,		_UpperCAmelCase="gelu_new"		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=1e-5		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=True		,		_UpperCAmelCase=50256		,		_UpperCAmelCase=50256		,		_UpperCAmelCase=False		,		**_UpperCAmelCase		,		)			-> Optional[int]:
     UpperCamelCase_									=     vocab_size
     UpperCamelCase_									=     n_positions
     UpperCamelCase_									=     n_embd
     UpperCamelCase_									=     n_layer
     UpperCamelCase_									=     n_head
     UpperCamelCase_									=     n_inner
     UpperCamelCase_									=     rotary_dim
     UpperCamelCase_									=     activation_function
     UpperCamelCase_									=     resid_pdrop
     UpperCamelCase_									=     embd_pdrop
     UpperCamelCase_									=     attn_pdrop
     UpperCamelCase_									=     layer_norm_epsilon
     UpperCamelCase_									=     initializer_range
     UpperCamelCase_									=     use_cache

     UpperCamelCase_									=     bos_token_id
     UpperCamelCase_									=     eos_token_id

     super().__init__(
         bos_token_id=_UpperCAmelCase		,		eos_token_id=_UpperCAmelCase		,		tie_word_embeddings=_UpperCAmelCase		,		**_UpperCAmelCase )



class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase = "default"		,		_UpperCAmelCase = None		,		_UpperCAmelCase = False		,		)			-> Union[str, Any]:
     super().__init__(_UpperCAmelCase		,		task=_UpperCAmelCase		,		patching_specs=_UpperCAmelCase		,		use_past=_UpperCAmelCase )
     if not getattr(self._config		,		'pad_token_id'		,		_UpperCAmelCase ):
        # TODO: how to do that better?
        UpperCamelCase_									=     0




  @property
  def    _UpperCAmelCase     (     self )			-> Mapping[str, Mapping[int, str]]:
     UpperCamelCase_									=     OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} )
     if self.use_past:
        self.fill_with_past_key_values_(_UpperCAmelCase		,		direction='inputs' )
        UpperCamelCase_									=     {0: 'batch', 1: 'past_sequence + sequence'}
     else:
        UpperCamelCase_									=     {0: 'batch', 1: 'sequence'}

     return common_inputs




  @property
  def    _UpperCAmelCase     (     self )			-> int:
     return self._config.n_layer




  @property
  def    _UpperCAmelCase     (     self )			-> int:
     return self._config.n_head




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = False		,		_UpperCAmelCase = None		,		)			-> Mapping[str, Any]:
     UpperCamelCase_									=     super(_UpperCAmelCase		,		self ).generate_dummy_inputs(
         _UpperCAmelCase		,		batch_size=_UpperCAmelCase		,		seq_length=_UpperCAmelCase		,		is_pair=_UpperCAmelCase		,		framework=_UpperCAmelCase )

     # We need to order the input in the way they appears in the forward()
     UpperCamelCase_									=     OrderedDict({'input_ids': common_inputs['input_ids']} )

     # Need to add the past_keys
     if self.use_past:
        if not is_torch_available():
           raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' )
        else:
           import torch

           UpperCamelCase_		,      UpperCamelCase_									=     common_inputs['input_ids'].shape
           # Not using the same length for past_key_values
           UpperCamelCase_									=     seqlen + 2
           UpperCamelCase_									=     (
               batch,
               self.num_attention_heads,
               past_key_values_length,
               self._config.hidden_size // self.num_attention_heads,
           )
           UpperCamelCase_									=     [
               (torch.zeros(_UpperCAmelCase ), torch.zeros(_UpperCAmelCase )) for _ in range(self.num_layers )
           ]

     UpperCamelCase_									=     common_inputs['attention_mask']
     if self.use_past:
        UpperCamelCase_									=     ordered_inputs['attention_mask'].dtype
        UpperCamelCase_									=     torch.cat(
            [ordered_inputs['attention_mask'], torch.ones(_UpperCAmelCase		,		_UpperCAmelCase		,		dtype=_UpperCAmelCase )]		,		dim=1 )

     return ordered_inputs




  @property
  def    _UpperCAmelCase     (     self )			-> int:
     return 13













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


snake_case__      :	str       	=      logging.getLogger(__name__)


@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None




@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None
  A_						=   None


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


 class 						_a       (  UpperCAmelCase__    ):






   """simple docstring"""





   A_						=   42




   def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		_UpperCAmelCase=False		,		_UpperCAmelCase = False		,		)			-> Any:
      UpperCamelCase_									=     hans_processors[task]()

      UpperCamelCase_									=     os.path.join(
          _UpperCAmelCase		,		'cached_{}_{}_{}_{}'.format(
              'dev' if evaluate else 'train'		,		tokenizer.__class__.__name__		,		str(_UpperCAmelCase )		,		_UpperCAmelCase		,		)		,		)
      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(_UpperCAmelCase ):
         if os.path.exists(_UpperCAmelCase ) and not overwrite_cache:
            logger.info(f"""Loading features from cached file {cached_features_file}""" )
            UpperCamelCase_									=     torch.load(_UpperCAmelCase )
         else:
            logger.info(f"""Creating features from dataset file at {data_dir}""" )

            UpperCamelCase_									=     (
                processor.get_dev_examples(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
            )

            logger.info('Training examples: %s'		,		len(_UpperCAmelCase ) )
            UpperCamelCase_									=     hans_convert_examples_to_features(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )
            logger.info('Saving features into cached file %s'		,		_UpperCAmelCase )
            torch.save(self.features		,		_UpperCAmelCase )




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




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




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


if is_tf_available():
 import tensorflow as tf


 class 						_a       :






   """simple docstring"""





   A_						=   42




   def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = 128		,		_UpperCAmelCase=False		,		_UpperCAmelCase = False		,		)			-> int:
      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(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
      UpperCamelCase_									=     hans_convert_examples_to_features(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )

      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(_UpperCAmelCase )) )

            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(
          _UpperCAmelCase		,		(
              {
                  '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    _UpperCAmelCase     (     self )			-> List[str]:
      return self.dataset




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




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




   def    _UpperCAmelCase     (     self )			-> int:
      return self.label_list


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Tuple:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_train_set.txt' ) )		,		'train' )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Dict:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_evaluation_set.txt' ) )		,		'dev' )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     return ["contradiction", "entailment", "neutral"]




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[str]:
     UpperCamelCase_									=     []
     for i, line in enumerate(_UpperCAmelCase ):
        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=_UpperCAmelCase		,		text_a=_UpperCAmelCase		,		text_b=_UpperCAmelCase		,		label=_UpperCAmelCase		,		pairID=_UpperCAmelCase ) )
     return examples






def     _snake_case    (__lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase    ,      ):
   UpperCamelCase_									=     {label: i for i, label in enumerate(__lowercase)}

   UpperCamelCase_									=     []
   for ex_index, example in tqdm.tqdm(enumerate(__lowercase)    ,      desc='convert examples to features'):
      if ex_index % 10000 == 0:
         logger.info('Writing example %d' % (ex_index))

      UpperCamelCase_									=     tokenizer(
          example.text_a    ,      example.text_b    ,      add_special_tokens=__lowercase    ,      max_length=__lowercase    ,      padding='max_length'    ,      truncation=__lowercase    ,      return_overflowing_tokens=__lowercase    ,      )

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

      UpperCamelCase_									=     int(example.pairID)

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

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

   return features


snake_case__      :	List[str]       	=      {
    """hans""": 3,
}

snake_case__      :	Union[str, Any]       	=      {
    """hans""": HansProcessor,
}





