

'''simple docstring'''






import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/text-classification/requirements.txt''')

lowerCAmelCase__      		=			logging.getLogger(__name__)






@dataclass
class     lowercase_			:




  """simple docstring"""




  SCREAMING_SNAKE_CASE					:						Optional[int]           =    field(
      default=1_2_8       , metadata={
          'help': (
              'The maximum total input sequence length after tokenization. Sequences longer '
              'than this will be truncated, sequences shorter will be padded.'
          )
      }       , )
  SCREAMING_SNAKE_CASE					:						bool           =    field(
      default=lowerCamelCase__       , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'}   )
  SCREAMING_SNAKE_CASE					:						bool           =    field(
      default=lowerCamelCase__       , metadata={
          'help': (
              'Whether to pad all samples to `max_seq_length`. '
              'If False, will pad the samples dynamically when batching to the maximum length in the batch.'
          )
      }       , )
  SCREAMING_SNAKE_CASE					:						Optional[int]           =    field(
      default=lowerCamelCase__       , metadata={
          'help': (
              'For debugging purposes or quicker training, truncate the number of training examples to this '
              'value if set.'
          )
      }       , )
  SCREAMING_SNAKE_CASE					:						Optional[int]           =    field(
      default=lowerCamelCase__       , metadata={
          'help': (
              'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
              'value if set.'
          )
      }       , )
  SCREAMING_SNAKE_CASE					:						Optional[int]           =    field(
      default=lowerCamelCase__       , metadata={
          'help': (
              'For debugging purposes or quicker training, truncate the number of prediction examples to this '
              'value if set.'
          )
      }       , )






@dataclass
class     lowercase_			:




  """simple docstring"""




  SCREAMING_SNAKE_CASE					:						str           =    field(
      default=lowerCamelCase__       , metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}   )
  SCREAMING_SNAKE_CASE					:						str           =    field(
      default=lowerCamelCase__       , metadata={'help': 'Evaluation language. Also train language if `train_language` is set to None.'}   )
  SCREAMING_SNAKE_CASE					:						Optional[str]           =    field(
      default=lowerCamelCase__       , metadata={'help': 'Train language if it is different from the evaluation language.'}   )
  SCREAMING_SNAKE_CASE					:						Optional[str]           =    field(
      default=lowerCamelCase__       , metadata={'help': 'Pretrained config name or path if not the same as model_name'}   )
  SCREAMING_SNAKE_CASE					:						Optional[str]           =    field(
      default=lowerCamelCase__       , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}   )
  SCREAMING_SNAKE_CASE					:						Optional[str]           =    field(
      default=lowerCamelCase__       , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}       , )
  SCREAMING_SNAKE_CASE					:						Optional[bool]           =    field(
      default=lowerCamelCase__       , metadata={'help': 'arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()'}       , )
  SCREAMING_SNAKE_CASE					:						bool           =    field(
      default=lowerCamelCase__       , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'}       , )
  SCREAMING_SNAKE_CASE					:						str           =    field(
      default='main'       , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}       , )
  SCREAMING_SNAKE_CASE					:						bool           =    field(
      default=lowerCamelCase__       , metadata={
          'help': (
              'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
              'with private models).'
          )
      }       , )
  SCREAMING_SNAKE_CASE					:						bool           =    field(
      default=lowerCamelCase__       , metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'}       , )


def 	_A  (					):






 """simple docstring"""



 __lowercase													=				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)   )
 __lowercase						,			__lowercase						,			__lowercase													=				parser.parse_args_into_dataclasses()

 # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
 # information sent is the one passed as arguments along with your Python/PyTorch versions.
 send_example_telemetry('''run_xnli'''  ,       A__   )

 # Setup logging
 logging.basicConfig(
     format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''  ,       datefmt='''%m/%d/%Y %H:%M:%S'''  ,       handlers=[logging.StreamHandler(sys.stdout   )]  ,       )

 if training_args.should_log:
  # The default of training_args.log_level is passive, so we set log level at info here to have that default.
  transformers.utils.logging.set_verbosity_info()

 __lowercase													=				training_args.get_process_log_level()
 logger.setLevel(A__   )
 datasets.utils.logging.set_verbosity(A__   )
 transformers.utils.logging.set_verbosity(A__   )
 transformers.utils.logging.enable_default_handler()
 transformers.utils.logging.enable_explicit_format()

 # Log on each process the small summary:
 logger.warning(
     F"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
     + F"distributed training: {bool(training_args.local_rank != -1   )}, 16-bits training: {training_args.fpaa}"   )
 logger.info(F"Training/evaluation parameters {training_args}"   )

 # Detecting last checkpoint.
 __lowercase													=				None
 if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
  __lowercase													=				get_last_checkpoint(training_args.output_dir   )
  if last_checkpoint is None and len(os.listdir(training_args.output_dir   )   ) > 0:
   raise ValueError(
       F"Output directory ({training_args.output_dir}) already exists and is not empty. "
       '''Use --overwrite_output_dir to overcome.'''   )
  elif last_checkpoint is not None:
   logger.info(
       F"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
       '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''   )

    # Set seed before initializing model.
 set_seed(training_args.seed   )

 # In distributed training, the load_dataset function guarantees that only one local process can concurrently
 # download the dataset.
 # Downloading and loading xnli dataset from the hub.
 if training_args.do_train:
  if model_args.train_language is None:
   __lowercase													=				load_dataset(
       '''xnli'''  ,       model_args.language  ,       split='''train'''  ,       cache_dir=model_args.cache_dir  ,       use_auth_token=True if model_args.use_auth_token else None  ,       )
  else:
   __lowercase													=				load_dataset(
       '''xnli'''  ,       model_args.train_language  ,       split='''train'''  ,       cache_dir=model_args.cache_dir  ,       use_auth_token=True if model_args.use_auth_token else None  ,       )
  __lowercase													=				train_dataset.features['''label'''].names

 if training_args.do_eval:
  __lowercase													=				load_dataset(
      '''xnli'''  ,       model_args.language  ,       split='''validation'''  ,       cache_dir=model_args.cache_dir  ,       use_auth_token=True if model_args.use_auth_token else None  ,       )
  __lowercase													=				eval_dataset.features['''label'''].names

 if training_args.do_predict:
  __lowercase													=				load_dataset(
      '''xnli'''  ,       model_args.language  ,       split='''test'''  ,       cache_dir=model_args.cache_dir  ,       use_auth_token=True if model_args.use_auth_token else None  ,       )
  __lowercase													=				predict_dataset.features['''label'''].names

 # Labels
 __lowercase													=				len(A__   )

 # Load pretrained model and tokenizer
 # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.
 __lowercase													=				AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path  ,       num_labels=A__  ,       idalabel={str(A__   ): label for i, label in enumerate(A__   )}  ,       labelaid={label: i for i, label in enumerate(A__   )}  ,       finetuning_task='''xnli'''  ,       cache_dir=model_args.cache_dir  ,       revision=model_args.model_revision  ,       use_auth_token=True if model_args.use_auth_token else None  ,       )
 __lowercase													=				AutoTokenizer.from_pretrained(
     model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path  ,       do_lower_case=model_args.do_lower_case  ,       cache_dir=model_args.cache_dir  ,       use_fast=model_args.use_fast_tokenizer  ,       revision=model_args.model_revision  ,       use_auth_token=True if model_args.use_auth_token else None  ,       )
 __lowercase													=				AutoModelForSequenceClassification.from_pretrained(
     model_args.model_name_or_path  ,       from_tf=bool('''.ckpt''' in model_args.model_name_or_path   )  ,       config=A__  ,       cache_dir=model_args.cache_dir  ,       revision=model_args.model_revision  ,       use_auth_token=True if model_args.use_auth_token else None  ,       ignore_mismatched_sizes=model_args.ignore_mismatched_sizes  ,       )

 # Preprocessing the datasets
 # Padding strategy
 if data_args.pad_to_max_length:
  __lowercase													=				'''max_length'''
 else:
  # We will pad later, dynamically at batch creation, to the max sequence length in each batch
  __lowercase													=				False

 def preprocess_function(A__   ):
  # Tokenize the texts
  return tokenizer(
      examples['''premise''']  ,       examples['''hypothesis''']  ,       padding=A__  ,       max_length=data_args.max_seq_length  ,       truncation=A__  ,       )

 if training_args.do_train:
  if data_args.max_train_samples is not None:
   __lowercase													=				min(len(A__   )  ,       data_args.max_train_samples   )
   __lowercase													=				train_dataset.select(range(A__   )   )
  with training_args.main_process_first(desc='''train dataset map pre-processing'''   ):
   __lowercase													=				train_dataset.map(
       A__  ,       batched=A__  ,       load_from_cache_file=not data_args.overwrite_cache  ,       desc='''Running tokenizer on train dataset'''  ,       )
  # Log a few random samples from the training set:
  for index in random.sample(range(len(A__   )   )  ,       3   ):
   logger.info(F"Sample {index} of the training set: {train_dataset[index]}."   )

 if training_args.do_eval:
  if data_args.max_eval_samples is not None:
   __lowercase													=				min(len(A__   )  ,       data_args.max_eval_samples   )
   __lowercase													=				eval_dataset.select(range(A__   )   )
  with training_args.main_process_first(desc='''validation dataset map pre-processing'''   ):
   __lowercase													=				eval_dataset.map(
       A__  ,       batched=A__  ,       load_from_cache_file=not data_args.overwrite_cache  ,       desc='''Running tokenizer on validation dataset'''  ,       )

 if training_args.do_predict:
  if data_args.max_predict_samples is not None:
   __lowercase													=				min(len(A__   )  ,       data_args.max_predict_samples   )
   __lowercase													=				predict_dataset.select(range(A__   )   )
  with training_args.main_process_first(desc='''prediction dataset map pre-processing'''   ):
   __lowercase													=				predict_dataset.map(
       A__  ,       batched=A__  ,       load_from_cache_file=not data_args.overwrite_cache  ,       desc='''Running tokenizer on prediction dataset'''  ,       )

    # Get the metric function
 __lowercase													=				evaluate.load('''xnli'''   )

 # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
 # predictions and label_ids field) and has to return a dictionary string to float.
 def compute_metrics(A__   ):
  __lowercase													=				p.predictions[0] if isinstance(p.predictions  ,       A__   ) else p.predictions
  __lowercase													=				np.argmax(A__  ,       axis=1   )
  return metric.compute(predictions=A__  ,       references=p.label_ids   )

 # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
 if data_args.pad_to_max_length:
  __lowercase													=				default_data_collator
 elif training_args.fpaa:
  __lowercase													=				DataCollatorWithPadding(A__  ,       pad_to_multiple_of=8   )
 else:
  __lowercase													=				None

 # Initialize our Trainer
 __lowercase													=				Trainer(
     model=A__  ,       args=A__  ,       train_dataset=train_dataset if training_args.do_train else None  ,       eval_dataset=eval_dataset if training_args.do_eval else None  ,       compute_metrics=A__  ,       tokenizer=A__  ,       data_collator=A__  ,       )

 # Training
 if training_args.do_train:
  __lowercase													=				None
  if training_args.resume_from_checkpoint is not None:
   __lowercase													=				training_args.resume_from_checkpoint
  elif last_checkpoint is not None:
   __lowercase													=				last_checkpoint
  __lowercase													=				trainer.train(resume_from_checkpoint=A__   )
  __lowercase													=				train_result.metrics
  __lowercase													=				(
      data_args.max_train_samples if data_args.max_train_samples is not None else len(A__   )
  )
  __lowercase													=				min(A__  ,       len(A__   )   )

  trainer.save_model()  # Saves the tokenizer too for easy upload

  trainer.log_metrics('''train'''  ,       A__   )
  trainer.save_metrics('''train'''  ,       A__   )
  trainer.save_state()

 # Evaluation
 if training_args.do_eval:
  logger.info('''*** Evaluate ***'''   )
  __lowercase													=				trainer.evaluate(eval_dataset=A__   )

  __lowercase													=				data_args.max_eval_samples if data_args.max_eval_samples is not None else len(A__   )
  __lowercase													=				min(A__  ,       len(A__   )   )

  trainer.log_metrics('''eval'''  ,       A__   )
  trainer.save_metrics('''eval'''  ,       A__   )

 # Prediction
 if training_args.do_predict:
  logger.info('''*** Predict ***'''   )
  __lowercase						,			__lowercase						,			__lowercase													=				trainer.predict(A__  ,       metric_key_prefix='''predict'''   )

  __lowercase													=				(
      data_args.max_predict_samples if data_args.max_predict_samples is not None else len(A__   )
  )
  __lowercase													=				min(A__  ,       len(A__   )   )

  trainer.log_metrics('''predict'''  ,       A__   )
  trainer.save_metrics('''predict'''  ,       A__   )

  __lowercase													=				np.argmax(A__  ,       axis=1   )
  __lowercase													=				os.path.join(training_args.output_dir  ,       '''predictions.txt'''   )
  if trainer.is_world_process_zero():
   with open(A__  ,       '''w'''   ) as writer:
    writer.write('''index\tprediction\n'''   )
    for index, item in enumerate(A__   ):
     __lowercase													=				label_list[item]
     writer.write(F"{index}\t{item}\n"   )


if __name__ == "__main__":
 main()




'''simple docstring'''






import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import require_keras_nlp, require_tf, slow


if is_tf_available():
 import tensorflow as tf

if is_keras_nlp_available():
 from transformers.models.gpta import TFGPTaTokenizer


lowerCAmelCase__      		=			['''gpt2''']
lowerCAmelCase__      		=			'''gpt2'''

if is_tf_available():






 class     lowercase_			(tf.Module   ):




   """simple docstring"""




   def __init__(   self     :  List[str]      ,lowercase__     :  Tuple    ):
    super().__init__()
    __lowercase													=				tokenizer
    __lowercase													=				AutoConfig.from_pretrained(lowercase__    )
    __lowercase													=				TFGPTaLMHeadModel.from_config(lowercase__    )






   @tf.function(input_signature=(tf.TensorSpec((None,)      ,tf.string      ,name='''text'''    ),)    )
   def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]      ,lowercase__     :  Dict    ):
    __lowercase													=				self.tokenizer(lowercase__    )
    __lowercase													=				tokenized['''input_ids'''].to_tensor()

    __lowercase													=				tf.cast(input_ids_dense > 0      ,tf.intaa    )
    # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])

    __lowercase													=				self.model(input_ids=lowercase__      ,attention_mask=lowercase__    )['''logits''']

    return outputs






@require_tf
@require_keras_nlp
class     lowercase_			(unittest.TestCase   ):




  """simple docstring"""




  def       SCREAMING_SNAKE_CASE   (   self     :  List[Any]    ):
   super().setUp()

   __lowercase													=				[GPTaTokenizer.from_pretrained(lowercase__    ) for checkpoint in (TOKENIZER_CHECKPOINTS)]
   __lowercase													=				[TFGPTaTokenizer.from_pretrained(lowercase__    ) for checkpoint in TOKENIZER_CHECKPOINTS]
   assert len(self.tokenizers    ) == len(self.tf_tokenizers    )

   __lowercase													=				[
       '''This is a straightforward English test sentence.''',
       '''This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.''',
       '''Now we\'re going to add some Chinese: 一 二 三 一二三''',
       '''And some much more rare Chinese: 齉 堃 齉堃''',
       '''Je vais aussi écrire en français pour tester les accents''',
       '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
   ]
   __lowercase													=				list(zip(self.test_sentences      ,self.test_sentences[::-1]    )    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   for tokenizer, tf_tokenizer in zip(self.tokenizers      ,self.tf_tokenizers    ):
    for test_inputs in self.test_sentences:
     __lowercase													=				tokenizer([test_inputs]      ,return_tensors='''tf'''    )
     __lowercase													=				tf_tokenizer([test_inputs]    )

     for key in python_outputs.keys():
      # convert them to numpy to avoid messing with ragged tensors
      __lowercase													=				python_outputs[key].numpy()
      __lowercase													=				tf_outputs[key].numpy()

      self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape    )    )
      self.assertTrue(tf.reduce_all(tf.cast(lowercase__      ,tf.intaa    ) == tf_outputs_values    )    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  Union[str, Any]    ):
   for tf_tokenizer in self.tf_tokenizers:
    __lowercase													=				tf.function(lowercase__    )
    for test_inputs in self.test_sentences:
     __lowercase													=				tf.constant(lowercase__    )
     __lowercase													=				compiled_tokenizer(lowercase__    )
     __lowercase													=				tf_tokenizer(lowercase__    )

     for key in eager_outputs.keys():
      self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]    )    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  str    ):
   for tf_tokenizer in self.tf_tokenizers:
    __lowercase													=				ModelToSave(tokenizer=lowercase__    )
    __lowercase													=				tf.convert_to_tensor([self.test_sentences[0]]    )
    __lowercase													=				model.serving(lowercase__    )  # Build model with some sample inputs
    with TemporaryDirectory() as tempdir:
     __lowercase													=				Path(lowercase__    ) / '''saved.model'''
     tf.saved_model.save(lowercase__      ,lowercase__      ,signatures={'''serving_default''': model.serving}    )
     __lowercase													=				tf.saved_model.load(lowercase__    )
    __lowercase													=				loaded_model.signatures['''serving_default'''](lowercase__    )['''output_0''']
    # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
    self.assertTrue(tf.reduce_all(out == loaded_output    )    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  Union[str, Any]    ):
   for tf_tokenizer in self.tf_tokenizers:
    __lowercase													=				tf.convert_to_tensor([self.test_sentences[0]]    )
    __lowercase													=				tf_tokenizer(lowercase__    )  # Build model with some sample inputs

    __lowercase													=				tf_tokenizer.get_config()
    __lowercase													=				TFGPTaTokenizer.from_config(lowercase__    )
    __lowercase													=				model_from_config(lowercase__    )

    for key in from_config_output.keys():
     self.assertTrue(tf.reduce_all(from_config_output[key] == out[key]    )    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   for tf_tokenizer in self.tf_tokenizers:
    # for the test to run
    __lowercase													=				1_2_3_1_2_3

    for max_length in [3, 5, 1_0_2_4]:
     __lowercase													=				tf.convert_to_tensor([self.test_sentences[0]]    )
     __lowercase													=				tf_tokenizer(lowercase__      ,max_length=lowercase__    )

     __lowercase													=				out['''input_ids'''].numpy().shape[1]

     assert out_length == max_length

