



'''simple docstring'''





import unittest

from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


_lowerCAmelCase      						=	get_tests_dir('''fixtures/test_sentencepiece.model''')






@require_sentencepiece
@require_tokenizers
class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_						, unittest.TestCase     ):
  '''simple docstring'''




  __lowercase							:      Union[str, Any]				=      XLNetTokenizer
  __lowercase							:      List[Any]				=      XLNetTokenizerFast
  __lowercase							:      List[str]				=      True
  __lowercase							:      str				=      True




  def 							UpperCAmelCase_	(    self      )    ->		int:
      super().setUp()

      # We have a SentencePiece fixture for testing
      lowerCAmelCase__ :  Optional[int]							      =					XLNetTokenizer(__UpperCAmelCase  ,keep_accents=__UpperCAmelCase      )
      tokenizer.sanitize_special_tokens()
      tokenizer.save_pretrained(self.tmpdirname      )




  def 							UpperCAmelCase_	(    self      )    ->		Optional[Any]:
      lowerCAmelCase__ :  List[Any]							      =					"""<s>"""
      lowerCAmelCase__ :  Optional[int]							      =					1

      self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase      )  ,__UpperCAmelCase      )
      self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase      )  ,__UpperCAmelCase      )




  def 							UpperCAmelCase_	(    self      )    ->		Dict:
      lowerCAmelCase__ :  Optional[int]							      =					list(self.get_tokenizer().get_vocab().keys()      )

      self.assertEqual(vocab_keys[0]  ,"""<unk>"""      )
      self.assertEqual(vocab_keys[1]  ,"""<s>"""      )
      self.assertEqual(vocab_keys[-1]  ,"""<eod>"""      )
      self.assertEqual(len(__UpperCAmelCase      )  ,1006      )




  def 							UpperCAmelCase_	(    self      )    ->		Dict:
      self.assertEqual(self.get_tokenizer().vocab_size  ,1000      )




  def 							UpperCAmelCase_	(    self      )    ->		Optional[Any]:
      lowerCAmelCase__ :  Tuple							      =					XLNetTokenizer(__UpperCAmelCase  ,keep_accents=__UpperCAmelCase      )

      lowerCAmelCase__ :  List[str]							      =					tokenizer.tokenize("""This is a test"""      )
      self.assertListEqual(__UpperCAmelCase  ,["""▁This""", """▁is""", """▁a""", """▁t""", """est"""]      )

      self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase      )  ,[285, 46, 10, 170, 382]      )

      lowerCAmelCase__ :  Tuple							      =					tokenizer.tokenize("""I was born in 92000, and this is falsé."""      )
      self.assertListEqual(
          __UpperCAmelCase  ,[
              SPIECE_UNDERLINE + """I""",
              SPIECE_UNDERLINE + """was""",
              SPIECE_UNDERLINE + """b""",
              """or""",
              """n""",
              SPIECE_UNDERLINE + """in""",
              SPIECE_UNDERLINE + """""",
              """9""",
              """2""",
              """0""",
              """0""",
              """0""",
              """,""",
              SPIECE_UNDERLINE + """and""",
              SPIECE_UNDERLINE + """this""",
              SPIECE_UNDERLINE + """is""",
              SPIECE_UNDERLINE + """f""",
              """al""",
              """s""",
              """é""",
              """.""",
          ]  ,)
      lowerCAmelCase__ :  List[Any]							      =					tokenizer.convert_tokens_to_ids(__UpperCAmelCase      )
      self.assertListEqual(__UpperCAmelCase  ,[8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4]      )

      lowerCAmelCase__ :  List[Any]							      =					tokenizer.convert_ids_to_tokens(__UpperCAmelCase      )
      self.assertListEqual(
          __UpperCAmelCase  ,[
              SPIECE_UNDERLINE + """I""",
              SPIECE_UNDERLINE + """was""",
              SPIECE_UNDERLINE + """b""",
              """or""",
              """n""",
              SPIECE_UNDERLINE + """in""",
              SPIECE_UNDERLINE + """""",
              """<unk>""",
              """2""",
              """0""",
              """0""",
              """0""",
              """,""",
              SPIECE_UNDERLINE + """and""",
              SPIECE_UNDERLINE + """this""",
              SPIECE_UNDERLINE + """is""",
              SPIECE_UNDERLINE + """f""",
              """al""",
              """s""",
              """<unk>""",
              """.""",
          ]  ,)




  def 							UpperCAmelCase_	(    self      )    ->		Optional[int]:
      lowerCAmelCase__ :  Optional[Any]							      =					XLNetTokenizer(__UpperCAmelCase  ,do_lower_case=__UpperCAmelCase      )
      lowerCAmelCase__ :  Optional[int]							      =					tokenizer.tokenize("""I was born in 92000, and this is falsé."""      )
      self.assertListEqual(
          __UpperCAmelCase  ,[
              SPIECE_UNDERLINE + """""",
              """i""",
              SPIECE_UNDERLINE + """was""",
              SPIECE_UNDERLINE + """b""",
              """or""",
              """n""",
              SPIECE_UNDERLINE + """in""",
              SPIECE_UNDERLINE + """""",
              """9""",
              """2""",
              """0""",
              """0""",
              """0""",
              """,""",
              SPIECE_UNDERLINE + """and""",
              SPIECE_UNDERLINE + """this""",
              SPIECE_UNDERLINE + """is""",
              SPIECE_UNDERLINE + """f""",
              """al""",
              """se""",
              """.""",
          ]  ,)
      self.assertListEqual(tokenizer.tokenize("""H\u00E9llo"""      )  ,["""▁he""", """ll""", """o"""]      )




  def 							UpperCAmelCase_	(    self      )    ->		Optional[int]:
      lowerCAmelCase__ :  Dict							      =					XLNetTokenizer(__UpperCAmelCase  ,do_lower_case=__UpperCAmelCase      )
      lowerCAmelCase__ :  Optional[Any]							      =					tokenizer.tokenize("""I was born in 92000, and this is falsé."""      )
      self.assertListEqual(
          __UpperCAmelCase  ,[
              SPIECE_UNDERLINE + """I""",
              SPIECE_UNDERLINE + """was""",
              SPIECE_UNDERLINE + """b""",
              """or""",
              """n""",
              SPIECE_UNDERLINE + """in""",
              SPIECE_UNDERLINE + """""",
              """9""",
              """2""",
              """0""",
              """0""",
              """0""",
              """,""",
              SPIECE_UNDERLINE + """and""",
              SPIECE_UNDERLINE + """this""",
              SPIECE_UNDERLINE + """is""",
              SPIECE_UNDERLINE + """f""",
              """al""",
              """se""",
              """.""",
          ]  ,)




  @slow
  def 							UpperCAmelCase_	(    self      )    ->		Union[str, Any]:
      lowerCAmelCase__ :  Tuple							      =					XLNetTokenizer.from_pretrained("""xlnet-base-cased"""      )

      lowerCAmelCase__ :  int							      =					tokenizer.encode("""sequence builders"""  ,add_special_tokens=__UpperCAmelCase      )
      lowerCAmelCase__ :  Dict							      =					tokenizer.encode("""multi-sequence build"""  ,add_special_tokens=__UpperCAmelCase      )

      lowerCAmelCase__ :  Dict							      =					tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase      )
      lowerCAmelCase__ :  Any							      =					tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase  ,__UpperCAmelCase      )

      assert encoded_sentence == text + [4, 3]
      assert encoded_pair == text + [4] + text_a + [4, 3]






  @slow
  def 							UpperCAmelCase_	(    self      )    ->		int:
      # fmt: off
      lowerCAmelCase__ :  Optional[Any]							      =					{"""input_ids""": [[17, 2_1442, 270, 17, 10, 1_4645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 2_2018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 1_4431, 13, 5500, 11, 1176, 580, 13, 1_6819, 4797, 23, 17, 10, 1_7135, 658, 19, 457, 7932, 13, 184, 19, 3154, 1_7135, 6468, 19, 1404, 1_2269, 19, 4229, 5356, 1_6264, 46, 19, 17, 2_0545, 1_0395, 9, 9, 9, 11, 28, 6421, 9531, 2_0729, 17, 10, 353, 1_7022, 11, 21, 6421, 9531, 1_6949, 17, 10, 1_1509, 753, 11, 33, 95, 2421, 7385, 956, 1_4431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 2_4738, 19, 1_3203, 658, 218, 787, 21, 430, 1_8482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 2_2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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}  # noqa: E501
      # fmt: on

      self.tokenizer_integration_test_util(
          expected_encoding=__UpperCAmelCase  ,model_name="""xlnet-base-cased"""  ,revision="""c841166438c31ec7ca9a106dee7bb312b73ae511"""  ,)







'''simple docstring'''





import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized, parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
 from sagemaker import Session, TrainingJobAnalytics
 from sagemaker.huggingface import HuggingFace






@pytest.mark.skipif(
    literal_eval(os.getenv('''TEST_SAGEMAKER'''						, '''False'''     )     ) is not True						, reason='''Skipping test because should only be run when releasing minor transformers version'''						, )
@pytest.mark.usefixtures('''sm_env'''     )
@parameterized_class(
    [
        {
            '''framework''': '''pytorch''',
            '''script''': '''run_glue.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.p3.16xlarge''',
            '''results''': {'''train_runtime''': 6_5_0, '''eval_accuracy''': 0.7, '''eval_loss''': 0.6},
        },
        {
            '''framework''': '''pytorch''',
            '''script''': '''run_ddp.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.p3.16xlarge''',
            '''results''': {'''train_runtime''': 6_0_0, '''eval_accuracy''': 0.7, '''eval_loss''': 0.6},
        },
        {
            '''framework''': '''tensorflow''',
            '''script''': '''run_tf_dist.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.p3.16xlarge''',
            '''results''': {'''train_runtime''': 6_0_0, '''eval_accuracy''': 0.6, '''eval_loss''': 0.7},
        },
    ]     )
class        lowerCAmelCase_(				unittest.TestCase     ):
  '''simple docstring'''




  def 							UpperCAmelCase_	(    self      )    ->		Optional[Any]:
      if self.framework == "pytorch":
          subprocess.run(
              F"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split()  ,encoding="""utf-8"""  ,check=__UpperCAmelCase  ,)
      assert hasattr(self  ,"""env"""      )




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Optional[Any]:
      lowerCAmelCase__ :  Optional[int]							      =					F"""{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}"""
      # distributed data settings
      lowerCAmelCase__ :  Any							      =					{"""smdistributed""": {"""dataparallel""": {"""enabled""": True}}} if self.script != """run_ddp.py""" else None

      # creates estimator
      return HuggingFace(
          entry_point=self.script  ,source_dir=self.env.test_path  ,role=self.env.role  ,image_uri=self.env.image_uri  ,base_job_name=__UpperCAmelCase  ,instance_count=__UpperCAmelCase  ,instance_type=self.instance_type  ,debugger_hook_config=__UpperCAmelCase  ,hyperparameters={**self.env.distributed_hyperparameters, """model_name_or_path""": self.model_name_or_path}  ,metric_definitions=self.env.metric_definitions  ,distribution=__UpperCAmelCase  ,py_version="""py36"""  ,)




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Optional[Any]:
      TrainingJobAnalytics(__UpperCAmelCase      ).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv"""      )






  @parameterized.expand([(2,)]      )
  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Any:
      # create estimator
      lowerCAmelCase__ :  List[Any]							      =					self.create_estimator(__UpperCAmelCase      )

      # run training
      estimator.fit()

      # result dataframe
      lowerCAmelCase__ :  Any							      =					TrainingJobAnalytics(estimator.latest_training_job.name      ).dataframe()

      # extract kpis
      lowerCAmelCase__ :  int							      =					list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""]      )
      lowerCAmelCase__ :  List[Any]							      =					list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""]      )
      # get train time from SageMaker job, this includes starting, preprocessing, stopping
      lowerCAmelCase__ :  List[str]							      =					(
          Session().describe_training_job(estimator.latest_training_job.name      ).get("""TrainingTimeInSeconds"""  ,99_9999      )
      )

      # assert kpis
      assert train_runtime <= self.results["train_runtime"]
      assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy      )
      assert all(t <= self.results["""eval_loss"""] for t in eval_loss      )

      # dump tests result into json file to share in PR
      with open(F"""{estimator.latest_training_job.name}.json"""  ,"""w"""      ) as outfile:
          json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss}  ,__UpperCAmelCase      )


