






import argparse
from copy import deepcopy

import numpy as np
from datasets import ClassLabel, DatasetDict, load_dataset
from evaluate import load

from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    set_seed,
)






def     _snake_case    ():
   UpperCamelCase_									=     argparse.ArgumentParser()
   parser.add_argument('--model_ckpt'    ,      type=__lowercase    ,      default='microsoft/unixcoder-base-nine')
   parser.add_argument('--num_epochs'    ,      type=__lowercase    ,      default=5)
   parser.add_argument('--batch_size'    ,      type=__lowercase    ,      default=6)
   parser.add_argument('--gradient_accumulation_steps'    ,      type=__lowercase    ,      default=1)
   parser.add_argument('--freeze'    ,      type=__lowercase    ,      default=__lowercase)
   parser.add_argument('--learning_rate'    ,      type=__lowercase    ,      default=5e-4)
   parser.add_argument('--seed'    ,      type=__lowercase    ,      default=0)
   parser.add_argument('--lr_scheduler_type'    ,      type=__lowercase    ,      default='cosine')
   parser.add_argument('--num_warmup_steps'    ,      type=__lowercase    ,      default=10)
   parser.add_argument('--weight_decay'    ,      type=__lowercase    ,      default=0.01)
   parser.add_argument('--output_dir'    ,      type=__lowercase    ,      default='./results')
   return parser.parse_args()


snake_case__      :	List[Any]       	=      load("""accuracy""")






def     _snake_case    (__lowercase):
   UpperCamelCase_		,      UpperCamelCase_									=     eval_pred
   UpperCamelCase_									=     np.argmax(__lowercase    ,      axis=1)
   return metric.compute(predictions=__lowercase    ,      references=__lowercase)


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase )			-> None:
     super().__init__()
     UpperCamelCase_									=     trainer




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		**_UpperCAmelCase )			-> Dict:
     if control.should_evaluate:
        UpperCamelCase_									=     deepcopy(_UpperCAmelCase )
        self._trainer.evaluate(eval_dataset=self._trainer.train_dataset		,		metric_key_prefix='train' )
        return control_copy






def     _snake_case    ():
   UpperCamelCase_									=     get_args()
   set_seed(args.seed)

   UpperCamelCase_									=     load_dataset('codeparrot/codecomplex'    ,      split='train')
   UpperCamelCase_									=     dataset.train_test_split(test_size=0.2)
   UpperCamelCase_									=     train_test['test'].train_test_split(test_size=0.5)
   UpperCamelCase_									=     DatasetDict(
       {
           'train': train_test['train'],
           'test': test_validation['train'],
           'valid': test_validation['test'],
       })

   print('Loading tokenizer and model')
   UpperCamelCase_									=     AutoTokenizer.from_pretrained(args.model_ckpt)
   UpperCamelCase_									=     tokenizer.eos_token
   UpperCamelCase_									=     AutoModelForSequenceClassification.from_pretrained(args.model_ckpt    ,      num_labels=7)
   UpperCamelCase_									=     model.config.eos_token_id

   if args.freeze:
      for param in model.roberta.parameters():
         UpperCamelCase_									=     False

   UpperCamelCase_									=     ClassLabel(num_classes=7    ,      names=list(set(train_test_validation['train']['complexity'])))

   def tokenize(__lowercase):
      UpperCamelCase_									=     tokenizer(example['src']    ,      truncation=__lowercase    ,      max_length=1024)
      UpperCamelCase_									=     labels.straint(example['complexity'])
      return {
          "input_ids": inputs["input_ids"],
          "attention_mask": inputs["attention_mask"],
          "label": label,
      }

   UpperCamelCase_									=     train_test_validation.map(
       __lowercase    ,      batched=__lowercase    ,      remove_columns=train_test_validation['train'].column_names    ,      )
   UpperCamelCase_									=     DataCollatorWithPadding(tokenizer=__lowercase)

   UpperCamelCase_									=     TrainingArguments(
       output_dir=args.output_dir    ,      learning_rate=args.learning_rate    ,      lr_scheduler_type=args.lr_scheduler_type    ,      evaluation_strategy='epoch'    ,      save_strategy='epoch'    ,      logging_strategy='epoch'    ,      per_device_train_batch_size=args.batch_size    ,      per_device_eval_batch_size=args.batch_size    ,      num_train_epochs=args.num_epochs    ,      gradient_accumulation_steps=args.gradient_accumulation_steps    ,      weight_decay=0.01    ,      metric_for_best_model='accuracy'    ,      run_name='complexity-java'    ,      report_to='wandb'    ,      )

   UpperCamelCase_									=     Trainer(
       model=__lowercase    ,      args=__lowercase    ,      train_dataset=tokenized_datasets['train']    ,      eval_dataset=tokenized_datasets['valid']    ,      tokenizer=__lowercase    ,      data_collator=__lowercase    ,      compute_metrics=__lowercase    ,      )

   print('Training...')
   trainer.add_callback(CustomCallback(__lowercase))
   trainer.train()


if __name__ == "__main__":
 main()













import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_realm import RealmTokenizer


snake_case__      :	List[str]       	=      logging.get_logger(__name__)

snake_case__      :	Optional[int]       	=      {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

snake_case__      :	Optional[Any]       	=      {
    """vocab_file""": {
        """google/realm-cc-news-pretrained-embedder""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt"""
        ),
        """google/realm-cc-news-pretrained-encoder""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt"""
        ),
        """google/realm-cc-news-pretrained-scorer""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt"""
        ),
        """google/realm-cc-news-pretrained-openqa""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt"""
        ),
        """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt""",
        """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt""",
        """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt""",
        """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt""",
    },
    """tokenizer_file""": {
        """google/realm-cc-news-pretrained-embedder""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont"""
        ),
        """google/realm-cc-news-pretrained-encoder""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json"""
        ),
        """google/realm-cc-news-pretrained-scorer""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json"""
        ),
        """google/realm-cc-news-pretrained-openqa""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json"""
        ),
        """google/realm-orqa-nq-openqa""": (
            """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json"""
        ),
        """google/realm-orqa-nq-reader""": (
            """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json"""
        ),
        """google/realm-orqa-wq-openqa""": (
            """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json"""
        ),
        """google/realm-orqa-wq-reader""": (
            """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json"""
        ),
    },
}

snake_case__      :	List[str]       	=      {
    """google/realm-cc-news-pretrained-embedder""": 5_1_2,
    """google/realm-cc-news-pretrained-encoder""": 5_1_2,
    """google/realm-cc-news-pretrained-scorer""": 5_1_2,
    """google/realm-cc-news-pretrained-openqa""": 5_1_2,
    """google/realm-orqa-nq-openqa""": 5_1_2,
    """google/realm-orqa-nq-reader""": 5_1_2,
    """google/realm-orqa-wq-openqa""": 5_1_2,
    """google/realm-orqa-wq-reader""": 5_1_2,
}

snake_case__      :	Tuple       	=      {
    """google/realm-cc-news-pretrained-embedder""": {"""do_lower_case""": True},
    """google/realm-cc-news-pretrained-encoder""": {"""do_lower_case""": True},
    """google/realm-cc-news-pretrained-scorer""": {"""do_lower_case""": True},
    """google/realm-cc-news-pretrained-openqa""": {"""do_lower_case""": True},
    """google/realm-orqa-nq-openqa""": {"""do_lower_case""": True},
    """google/realm-orqa-nq-reader""": {"""do_lower_case""": True},
    """google/realm-orqa-wq-openqa""": {"""do_lower_case""": True},
    """google/realm-orqa-wq-reader""": {"""do_lower_case""": True},
}


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   VOCAB_FILES_NAMES
  A_						=   PRETRAINED_VOCAB_FILES_MAP
  A_						=   PRETRAINED_INIT_CONFIGURATION
  A_						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  A_						=   RealmTokenizer




  def __init__(     self		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=True		,		_UpperCAmelCase="[UNK]"		,		_UpperCAmelCase="[SEP]"		,		_UpperCAmelCase="[PAD]"		,		_UpperCAmelCase="[CLS]"		,		_UpperCAmelCase="[MASK]"		,		_UpperCAmelCase=True		,		_UpperCAmelCase=None		,		**_UpperCAmelCase		,		)			-> Optional[Any]:
     super().__init__(
         _UpperCAmelCase		,		tokenizer_file=_UpperCAmelCase		,		do_lower_case=_UpperCAmelCase		,		unk_token=_UpperCAmelCase		,		sep_token=_UpperCAmelCase		,		pad_token=_UpperCAmelCase		,		cls_token=_UpperCAmelCase		,		mask_token=_UpperCAmelCase		,		tokenize_chinese_chars=_UpperCAmelCase		,		strip_accents=_UpperCAmelCase		,		**_UpperCAmelCase		,		)

     UpperCamelCase_									=     json.loads(self.backend_tokenizer.normalizer.__getstate__() )
     if (
         normalizer_state.get('lowercase'		,		_UpperCAmelCase ) != do_lower_case
         or normalizer_state.get('strip_accents'		,		_UpperCAmelCase ) != strip_accents
         or normalizer_state.get('handle_chinese_chars'		,		_UpperCAmelCase ) != tokenize_chinese_chars
     ):
        UpperCamelCase_									=     getattr(_UpperCAmelCase		,		normalizer_state.pop('type' ) )
        UpperCamelCase_									=     do_lower_case
        UpperCamelCase_									=     strip_accents
        UpperCamelCase_									=     tokenize_chinese_chars
        UpperCamelCase_									=     normalizer_class(**_UpperCAmelCase )

     UpperCamelCase_									=     do_lower_case




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		**_UpperCAmelCase )			-> List[Any]:
     UpperCamelCase_									=     PaddingStrategy.MAX_LENGTH

     UpperCamelCase_									=     text
     UpperCamelCase_									=     kwargs.pop('text_pair'		,		_UpperCAmelCase )
     UpperCamelCase_									=     kwargs.pop('return_tensors'		,		_UpperCAmelCase )

     UpperCamelCase_									=     {
         'input_ids': [],
         'attention_mask': [],
         'token_type_ids': [],
     }

     for idx, candidate_text in enumerate(_UpperCAmelCase ):
        if batch_text_pair is not None:
           UpperCamelCase_									=     batch_text_pair[idx]
        else:
           UpperCamelCase_									=     None

        UpperCamelCase_									=     super().__call__(_UpperCAmelCase		,		_UpperCAmelCase		,		return_tensors=_UpperCAmelCase		,		**_UpperCAmelCase )

        UpperCamelCase_									=     encoded_candidates.get('input_ids' )
        UpperCamelCase_									=     encoded_candidates.get('attention_mask' )
        UpperCamelCase_									=     encoded_candidates.get('token_type_ids' )

        if encoded_input_ids is not None:
           output_data["input_ids"].append(_UpperCAmelCase )
        if encoded_attention_mask is not None:
           output_data["attention_mask"].append(_UpperCAmelCase )
        if encoded_token_type_ids is not None:
           output_data["token_type_ids"].append(_UpperCAmelCase )

     UpperCamelCase_									=     {key: item for key, item in output_data.items() if len(_UpperCAmelCase ) != 0}

     return BatchEncoding(_UpperCAmelCase		,		tensor_type=_UpperCAmelCase )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase=None )			-> Union[str, Any]:
     UpperCamelCase_									=     [self.cls_token_id] + token_ids_a + [self.sep_token_id]

     if token_ids_a:
        output += token_ids_a + [self.sep_token_id]

     return output




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = None )			-> List[int]:
     UpperCamelCase_									=     [self.sep_token_id]
     UpperCamelCase_									=     [self.cls_token_id]
     if token_ids_a is None:
        return len(cls + token_ids_a + sep ) * [0]
     return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = None )			-> Tuple[str]:
     UpperCamelCase_									=     self._tokenizer.model.save(_UpperCAmelCase		,		name=_UpperCAmelCase )
     return tuple(_UpperCAmelCase )





