





'''simple docstring'''

import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
   import torch_xla.core.xla_model as xm
   import torch_xla.debug.metrics as met
class 							__lowerCAmelCase	(       __magic_name__					):






       """simple docstring"""





       def __init__(				self  :						Optional[Any]			,					*lowerCAmelCase__  :						Union[str, Any]			,					lowerCAmelCase__  :						Any=None			,					lowerCAmelCase__  :						Tuple=None			,					**lowerCAmelCase__  :						Any	)       ->	List[str]:

            '''simple docstring'''




            super().__init__(*lowerCAmelCase__			,					**lowerCAmelCase__	)
            _UpperCamelCase							       =			eval_examples
            _UpperCamelCase							       =			post_process_function





       def snake_case__		(				self  :						List[Any]			,					lowerCAmelCase__  :						Tuple=None			,					lowerCAmelCase__  :						Any=None			,					lowerCAmelCase__  :						str=None			,					lowerCAmelCase__  :						str = "eval"	)       ->	Union[str, Any]:

            '''simple docstring'''




            _UpperCamelCase							       =			self.eval_dataset if eval_dataset is None else eval_dataset
            _UpperCamelCase							       =			self.get_eval_dataloader(lowerCAmelCase__	)
            _UpperCamelCase							       =			self.eval_examples if eval_examples is None else eval_examples

            # Temporarily disable metric computation, we will do it in the loop here.
            _UpperCamelCase							       =			self.compute_metrics
            _UpperCamelCase							       =			None
            _UpperCamelCase							       =			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
            _UpperCamelCase							       =			time.time()
            try:
                 _UpperCamelCase							       =			eval_loop(
                     lowerCAmelCase__			,					description='''Evaluation'''			,					prediction_loss_only=True if compute_metrics is None else None			,					ignore_keys=lowerCAmelCase__			,					metric_key_prefix=lowerCAmelCase__			,					)
            finally:
                 _UpperCamelCase							       =			compute_metrics
            _UpperCamelCase							       =			self.args.eval_batch_size * self.args.world_size
            if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
                 start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""]
            output.metrics.update(
                speed_metrics(
                    lowerCAmelCase__			,					lowerCAmelCase__			,					num_samples=output.num_samples			,					num_steps=math.ceil(output.num_samples / total_batch_size	)			,					)	)
            if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
                 # Only the main node write the results by default
                 _UpperCamelCase							       =			self.post_process_function(lowerCAmelCase__			,					lowerCAmelCase__			,					output.predictions	)
                 _UpperCamelCase							       =			self.compute_metrics(lowerCAmelCase__	)

                 # Prefix all keys with metric_key_prefix + '_'
                 for key in list(metrics.keys()	):
                      if not key.startswith(f"""{metric_key_prefix}_"""	):
                           _UpperCamelCase							       =			metrics.pop(lowerCAmelCase__	)
                 metrics.update(output.metrics	)
            else:
                 _UpperCamelCase							       =			output.metrics

            if self.args.should_log:
                 # Only the main node log the results by default
                 self.log(lowerCAmelCase__	)

            if self.args.tpu_metrics_debug or self.args.debug:
                 # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
                 xm.master_print(met.metrics_report()	)

            _UpperCamelCase							       =			self.callback_handler.on_evaluate(self.args			,					self.state			,					self.control			,					lowerCAmelCase__	)
            return metrics







       def snake_case__		(				self  :						Dict			,					lowerCAmelCase__  :						Optional[Any]			,					lowerCAmelCase__  :						Optional[int]			,					lowerCAmelCase__  :						int=None			,					lowerCAmelCase__  :						str = "test"	)       ->	str:

            '''simple docstring'''




            _UpperCamelCase							       =			self.get_test_dataloader(lowerCAmelCase__	)

            # Temporarily disable metric computation, we will do it in the loop here.
            _UpperCamelCase							       =			self.compute_metrics
            _UpperCamelCase							       =			None
            _UpperCamelCase							       =			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
            _UpperCamelCase							       =			time.time()
            try:
                 _UpperCamelCase							       =			eval_loop(
                     lowerCAmelCase__			,					description='''Prediction'''			,					prediction_loss_only=True if compute_metrics is None else None			,					ignore_keys=lowerCAmelCase__			,					metric_key_prefix=lowerCAmelCase__			,					)
            finally:
                 _UpperCamelCase							       =			compute_metrics
            _UpperCamelCase							       =			self.args.eval_batch_size * self.args.world_size
            if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
                 start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""]
            output.metrics.update(
                speed_metrics(
                    lowerCAmelCase__			,					lowerCAmelCase__			,					num_samples=output.num_samples			,					num_steps=math.ceil(output.num_samples / total_batch_size	)			,					)	)

            if self.post_process_function is None or self.compute_metrics is None:
                 return output

            _UpperCamelCase							       =			self.post_process_function(lowerCAmelCase__			,					lowerCAmelCase__			,					output.predictions			,					'''predict'''	)
            _UpperCamelCase							       =			self.compute_metrics(lowerCAmelCase__	)

            # Prefix all keys with metric_key_prefix + '_'
            for key in list(metrics.keys()	):
                 if not key.startswith(f"""{metric_key_prefix}_"""	):
                      _UpperCamelCase							       =			metrics.pop(lowerCAmelCase__	)
            metrics.update(output.metrics	)
            return PredictionOutput(predictions=predictions.predictions			,					label_ids=predictions.label_ids			,					metrics=lowerCAmelCase__	)










'''simple docstring'''

import json
import os
import unittest

from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast
from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class 							__lowerCAmelCase	(       __magic_name__		,		unittest.TestCase					):






       """simple docstring"""
       _snake_case      :	int									=       OpenAIGPTTokenizer
       _snake_case      :	Tuple									=       OpenAIGPTTokenizerFast
       _snake_case      :	Union[str, Any]									=       True
       _snake_case      :	Optional[int]									=       False





       def snake_case__		(				self  :						Dict	)       ->	List[Any]:

            '''simple docstring'''




            super().setUp()

            # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
            _UpperCamelCase							       =			[
                '''l''',
                '''o''',
                '''w''',
                '''e''',
                '''r''',
                '''s''',
                '''t''',
                '''i''',
                '''d''',
                '''n''',
                '''w</w>''',
                '''r</w>''',
                '''t</w>''',
                '''lo''',
                '''low''',
                '''er</w>''',
                '''low</w>''',
                '''lowest</w>''',
                '''newer</w>''',
                '''wider</w>''',
                '''<unk>''',
            ]
            _UpperCamelCase							       =			dict(zip(lowerCAmelCase__			,					range(len(lowerCAmelCase__	)	)	)	)
            _UpperCamelCase							       =			['''#version: 0.2''', '''l o''', '''lo w''', '''e r</w>''', '''''']

            _UpperCamelCase							       =			os.path.join(self.tmpdirname			,					VOCAB_FILES_NAMES['''vocab_file''']	)
            _UpperCamelCase							       =			os.path.join(self.tmpdirname			,					VOCAB_FILES_NAMES['''merges_file''']	)
            with open(self.vocab_file			,					'''w'''	) as fp:
                 fp.write(json.dumps(lowerCAmelCase__	)	)
            with open(self.merges_file			,					'''w'''	) as fp:
                 fp.write('''\n'''.join(lowerCAmelCase__	)	)





       def snake_case__		(				self  :						Tuple			,					lowerCAmelCase__  :						List[str]	)       ->	Optional[Any]:

            '''simple docstring'''




            return "lower newer", "lower newer"





       def snake_case__		(				self  :						Tuple	)       ->	Union[str, Any]:

            '''simple docstring'''




            _UpperCamelCase							       =			OpenAIGPTTokenizer(self.vocab_file			,					self.merges_file	)

            _UpperCamelCase							       =			'''lower'''
            _UpperCamelCase							       =			['''low''', '''er</w>''']
            _UpperCamelCase							       =			tokenizer.tokenize(lowerCAmelCase__	)
            self.assertListEqual(lowerCAmelCase__			,					lowerCAmelCase__	)

            _UpperCamelCase							       =			tokens + ['''<unk>''']
            _UpperCamelCase							       =			[14, 15, 20]
            self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase__	)			,					lowerCAmelCase__	)





       def snake_case__		(				self  :						Union[str, Any]			,					lowerCAmelCase__  :						Tuple=15	)       ->	Union[str, Any]:

            '''simple docstring'''




            for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                 with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""	):
                      _UpperCamelCase							       =			self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__			,					**lowerCAmelCase__	)

                      # Simple input
                      _UpperCamelCase							       =			'''This is a simple input'''
                      _UpperCamelCase							       =			['''This is a simple input 1''', '''This is a simple input 2''']
                      _UpperCamelCase							       =			('''This is a simple input''', '''This is a pair''')
                      _UpperCamelCase							       =			[
                          ('''This is a simple input 1''', '''This is a simple input 2'''),
                          ('''This is a simple pair 1''', '''This is a simple pair 2'''),
                      ]

                      # Simple input tests
                      self.assertRaises(lowerCAmelCase__			,					tokenizer_r.encode			,					lowerCAmelCase__			,					max_length=lowerCAmelCase__			,					padding='''max_length'''	)

                      # Simple input
                      self.assertRaises(lowerCAmelCase__			,					tokenizer_r.encode_plus			,					lowerCAmelCase__			,					max_length=lowerCAmelCase__			,					padding='''max_length'''	)

                      # Simple input
                      self.assertRaises(
                          lowerCAmelCase__			,					tokenizer_r.batch_encode_plus			,					lowerCAmelCase__			,					max_length=lowerCAmelCase__			,					padding='''max_length'''			,					)

                      # Pair input
                      self.assertRaises(lowerCAmelCase__			,					tokenizer_r.encode			,					lowerCAmelCase__			,					max_length=lowerCAmelCase__			,					padding='''max_length'''	)

                      # Pair input
                      self.assertRaises(lowerCAmelCase__			,					tokenizer_r.encode_plus			,					lowerCAmelCase__			,					max_length=lowerCAmelCase__			,					padding='''max_length'''	)

                      # Pair input
                      self.assertRaises(
                          lowerCAmelCase__			,					tokenizer_r.batch_encode_plus			,					lowerCAmelCase__			,					max_length=lowerCAmelCase__			,					padding='''max_length'''			,					)







       def snake_case__		(				self  :						Tuple	)       ->	Optional[Any]:

            '''simple docstring'''




            pass

@require_ftfy
@require_spacy
@require_tokenizers
class 							__lowerCAmelCase	(       __magic_name__					):






       """simple docstring"""
       pass



