





import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory

from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
    convert,
    ensure_valid_input,
    generate_identified_filename,
    infer_shapes,
    quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow





class      lowercase__    :







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       return None





class      lowercase__    :







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       return None





class      lowercase__    (							unittest.TestCase  ):
  __UpperCamelCase	     =  [
      # (model_name, model_kwargs)
      ("""bert-base-cased""", {}),
      ("""gpt2""", {"""use_cache""": False}),  # We don't support exporting GPT2 past keys anymore
  ]







  @require_tf
  @slow
  def 	UpperCAmelCase__		(	self						):
       for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
            self._test_export(_lowercase    ,						"""tf"""    ,						12    ,						**_lowercase						)







  @require_torch
  @slow
  def 	UpperCAmelCase__		(	self						):
       for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
            self._test_export(_lowercase    ,						"""pt"""    ,						12    ,						**_lowercase						)







  @require_torch
  @slow
  def 	UpperCAmelCase__		(	self						):
       from transformers import BertModel

       lowerCAmelCase_					:       Tuple    =		["""[UNK]""", """[SEP]""", """[CLS]""", """[PAD]""", """[MASK]""", """some""", """other""", """words"""]
       with NamedTemporaryFile(mode="""w+t"""						) as vocab_file:
            vocab_file.write("""\n""".join(_lowercase						)						)
            vocab_file.flush()
            lowerCAmelCase_					:       List[str]    =		BertTokenizerFast(vocab_file.name						)

       with TemporaryDirectory() as bert_save_dir:
            lowerCAmelCase_					:       List[str]    =		BertModel(BertConfig(vocab_size=len(_lowercase						)						)						)
            model.save_pretrained(_lowercase						)
            self._test_export(_lowercase    ,						"""pt"""    ,						12    ,						_lowercase						)







  @require_tf
  @slow
  def 	UpperCAmelCase__		(	self						):
       for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
            lowerCAmelCase_					:       str    =		self._test_export(_lowercase    ,						"""tf"""    ,						12    ,						**_lowercase						)
            lowerCAmelCase_					:       List[Any]    =		quantize(Path(_lowercase						)						)

            # Ensure the actual quantized model is not bigger than the original one
            if quantized_path.stat().st_size >= Path(_lowercase						).stat().st_size:
                 self.fail("""Quantized model is bigger than initial ONNX model"""						)







  @require_torch
  @slow
  def 	UpperCAmelCase__		(	self						):
       for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
            lowerCAmelCase_					:       List[Any]    =		self._test_export(_lowercase    ,						"""pt"""    ,						12    ,						**_lowercase						)
            lowerCAmelCase_					:       Optional[int]    =		quantize(_lowercase						)

            # Ensure the actual quantized model is not bigger than the original one
            if quantized_path.stat().st_size >= Path(_lowercase						).stat().st_size:
                 self.fail("""Quantized model is bigger than initial ONNX model"""						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase=None    ,						**_lowercase						):
       try:
            # Compute path
            with TemporaryDirectory() as tempdir:
                 lowerCAmelCase_					:       Optional[int]    =		Path(_lowercase						).joinpath("""model.onnx"""						)

            # Remove folder if exists
            if path.parent.exists():
                 path.parent.rmdir()

            # Export
            convert(_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						**_lowercase						)

            return path
       except Exception as e:
            self.fail(_lowercase						)







  @require_torch
  @require_tokenizers
  @slow
  def 	UpperCAmelCase__		(	self						):
       from transformers import BertModel

       lowerCAmelCase_					:       List[Any]    =		BertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random"""						)						)
       lowerCAmelCase_					:       str    =		BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random"""						)
       self._test_infer_dynamic_axis(_lowercase    ,						_lowercase    ,						"""pt"""						)







  @require_tf
  @require_tokenizers
  @slow
  def 	UpperCAmelCase__		(	self						):
       from transformers import TFBertModel

       lowerCAmelCase_					:       str    =		TFBertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random"""						)						)
       lowerCAmelCase_					:       Any    =		BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random"""						)
       self._test_infer_dynamic_axis(_lowercase    ,						_lowercase    ,						"""tf"""						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       List[Any]    =		FeatureExtractionPipeline(_lowercase    ,						_lowercase						)

       lowerCAmelCase_					:       Union[str, Any]    =		["""input_ids""", """token_type_ids""", """attention_mask""", """output_0""", """output_1"""]
       lowerCAmelCase_   ,  lowerCAmelCase_   ,  lowerCAmelCase_   ,  lowerCAmelCase_					:       List[Any]    =		infer_shapes(_lowercase    ,						_lowercase						)

       # Assert all variables are present
       self.assertEqual(len(_lowercase						)    ,						len(_lowercase						)						)
       self.assertTrue(all(var_name in shapes for var_name in variable_names						)						)
       self.assertSequenceEqual(variable_names[:3]    ,						_lowercase						)
       self.assertSequenceEqual(variable_names[3:]    ,						_lowercase						)

       # Assert inputs are {0: batch, 1: sequence}
       for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
            self.assertDictEqual(shapes[var_name]    ,						{0: """batch""", 1: """sequence"""}						)

       # Assert outputs are {0: batch, 1: sequence} and {0: batch}
       self.assertDictEqual(shapes["""output_0"""]    ,						{0: """batch""", 1: """sequence"""}						)
       self.assertDictEqual(shapes["""output_1"""]    ,						{0: """batch"""}						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Optional[int]    =		["""input_ids""", """attention_mask""", """token_type_ids"""]
       lowerCAmelCase_					:       List[str]    =		{"""input_ids""": [1, 2, 3, 4], """attention_mask""": [0, 0, 0, 0], """token_type_ids""": [1, 1, 1, 1]}
       lowerCAmelCase_   ,  lowerCAmelCase_					:       Optional[int]    =		ensure_valid_input(FuncContiguousArgs()    ,						_lowercase    ,						_lowercase						)

       # Should have exactly the same number of args (all are valid)
       self.assertEqual(len(_lowercase						)    ,						3						)

       # Should have exactly the same input names
       self.assertEqual(set(_lowercase						)    ,						set(_lowercase						)						)

       # Parameter should be reordered according to their respective place in the function:
       # (input_ids, token_type_ids, attention_mask)
       self.assertEqual(_lowercase    ,						(tokens["""input_ids"""], tokens["""token_type_ids"""], tokens["""attention_mask"""])						)

       # Generated args are interleaved with another args (for instance parameter "past" in GPT2)
       lowerCAmelCase_   ,  lowerCAmelCase_					:       str    =		ensure_valid_input(FuncNonContiguousArgs()    ,						_lowercase    ,						_lowercase						)

       # Should have exactly the one arg (all before the one not provided "some_other_args")
       self.assertEqual(len(_lowercase						)    ,						1						)
       self.assertEqual(len(_lowercase						)    ,						1						)

       # Should have only "input_ids"
       self.assertEqual(inputs_args[0]    ,						tokens["""input_ids"""]						)
       self.assertEqual(ordered_input_names[0]    ,						"""input_ids"""						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Tuple    =		generate_identified_filename(Path("""/home/something/my_fake_model.onnx"""						)    ,						"""-test"""						)
       self.assertEqual("""/home/something/my_fake_model-test.onnx"""    ,						generated.as_posix()						)







import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


UpperCAmelCase_					:   str 							=						logging.get_logger(__name__)





@dataclass
class      lowercase__    :
  __UpperCamelCase	     =  field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()  )}  )
  __UpperCamelCase	     =  field(
      metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}  )
  __UpperCamelCase	     =  field(
      default=128     ,					metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }     ,					)
  __UpperCamelCase	     =  field(
      default=__A     ,					metadata={"""help""": """Overwrite the cached training and evaluation sets"""}  )







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       List[str]    =		self.task_name.lower()





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  """train"""
  __UpperCamelCase	     =  """dev"""
  __UpperCamelCase	     =  """test"""





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  42
  __UpperCamelCase	     =  42
  __UpperCamelCase	     =  42







  def __init__(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase = None    ,						_lowercase = Split.train    ,						_lowercase = None    ,						):
       warnings.warn(
           """This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """
           """library. You can have a look at this example script for pointers: """
           """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py"""    ,						_lowercase    ,						)
       lowerCAmelCase_					:       Any    =		args
       lowerCAmelCase_					:       List[str]    =		glue_processors[args.task_name]()
       lowerCAmelCase_					:       Tuple    =		glue_output_modes[args.task_name]
       if isinstance(_lowercase    ,						_lowercase						):
            try:
                 lowerCAmelCase_					:       Dict    =		Split[mode]
            except KeyError:
                 raise KeyError("""mode is not a valid split name"""						)
        # Load data features from cache or dataset file
       lowerCAmelCase_					:       Optional[int]    =		os.path.join(
           cache_dir if cache_dir is not None else args.data_dir    ,						F'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}'    ,						)
       lowerCAmelCase_					:       List[str]    =		self.processor.get_labels()
       if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
           "RobertaTokenizer",
           "RobertaTokenizerFast",
           "XLMRobertaTokenizer",
           "BartTokenizer",
           "BartTokenizerFast",
       ):
            # HACK(label indices are swapped in RoBERTa pretrained model)
            lowerCAmelCase_   ,  lowerCAmelCase_					:       List[str]    =		label_list[2], label_list[1]
       lowerCAmelCase_					:       int    =		label_list

       # Make sure only the first process in distributed training processes the dataset,
       # and the others will use the cache.
       lowerCAmelCase_					:       Optional[int]    =		cached_features_file + """.lock"""
       with FileLock(_lowercase						):
            if os.path.exists(_lowercase						) and not args.overwrite_cache:
                 lowerCAmelCase_					:       Dict    =		time.time()
                 lowerCAmelCase_					:       str    =		torch.load(_lowercase						)
                 logger.info(
                     F'Loading features from cached file {cached_features_file} [took %.3f s]'    ,						time.time() - start						)
            else:
                 logger.info(F'Creating features from dataset file at {args.data_dir}'						)

                 if mode == Split.dev:
                      lowerCAmelCase_					:       List[Any]    =		self.processor.get_dev_examples(args.data_dir						)
                 elif mode == Split.test:
                      lowerCAmelCase_					:       Dict    =		self.processor.get_test_examples(args.data_dir						)
                 else:
                      lowerCAmelCase_					:       List[str]    =		self.processor.get_train_examples(args.data_dir						)
                 if limit_length is not None:
                      lowerCAmelCase_					:       Optional[int]    =		examples[:limit_length]
                 lowerCAmelCase_					:       Any    =		glue_convert_examples_to_features(
                     _lowercase    ,						_lowercase    ,						max_length=args.max_seq_length    ,						label_list=_lowercase    ,						output_mode=self.output_mode    ,						)
                 lowerCAmelCase_					:       str    =		time.time()
                 torch.save(self.features    ,						_lowercase						)
                 # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                 logger.info(
                     F'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'						)







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







  def __getitem__(	self    ,						_lowercase						):
       return self.features[i]







  def 	UpperCAmelCase__		(	self						):
       return self.label_list
