





import unittest

from cer import CER


UpperCAmelCase__  :	str     =CER()

class 					__A   (  unittest.TestCase			):


				def _snake_case				(						self							):
								lowerCamelCase		       =["""White House"""]
								lowerCamelCase		       =["""white house"""]
								# S = 2, D = 0, I = 0, N = 11, CER = 2 / 11
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.1_8_1_8_1_8_1_8_1_8							) < 1E-6							)


				def _snake_case				(						self							):
								lowerCamelCase		       =["""were wolf"""]
								lowerCamelCase		       =["""werewolf"""]
								# S = 0, D = 0, I = 1, N = 9, CER = 1 / 9
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.1_1_1_1_1_1_1							) < 1E-6							)

								lowerCamelCase		       =["""werewolf"""]
								lowerCamelCase		       =["""weae     wolf"""]
								# S = 1, D = 1, I = 0, N = 8, CER = 0.25
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.2_5							) < 1E-6							)

								# consecutive whitespaces case 1
								lowerCamelCase		       =["""were wolf"""]
								lowerCamelCase		       =["""were               wolf"""]
								# S = 0, D = 0, I = 0, N = 9, CER = 0
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.0							) < 1E-6							)

								# consecutive whitespaces case 2
								lowerCamelCase		       =["""were   wolf"""]
								lowerCamelCase		       =["""were               wolf"""]
								# S = 0, D = 0, I = 0, N = 9, CER = 0
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.0							) < 1E-6							)


				def _snake_case				(						self							):
								lowerCamelCase		       =["""werewolf"""]
								lowerCamelCase		       =["""weaewolf"""]
								# S = 1, D = 0, I = 0, N = 8, CER = 0.125
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.1_2_5							) < 1E-6							)


				def _snake_case				(						self							):
								lowerCamelCase		       =["""werewolf"""]
								lowerCamelCase		       =["""wereawolf"""]
								# S = 0, D = 1, I = 0, N = 8, CER = 0.125
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.1_2_5							) < 1E-6							)


				def _snake_case				(						self							):
								lowerCamelCase		       =["""werewolf"""]
								lowerCamelCase		       =["""wereolf"""]
								# S = 0, D = 0, I = 1, N = 8, CER = 0.125
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.1_2_5							) < 1E-6							)


				def _snake_case				(						self							):
								lowerCamelCase		       =["""werewolf"""]
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertEqual(UpperCAmelCase_      ,       0.0							)


				def _snake_case				(						self							):
								lowerCamelCase		       =["""werewolf""", """I am your father"""]
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertEqual(UpperCAmelCase_      ,       0.0							)

								lowerCamelCase		       =["""werewolf""", """I am your father""", """doge"""]
								lowerCamelCase		       =["""werxwolf""", """I       am your father""", """doge"""]
								# S = 1, D = 0, I = 0, N = 28, CER = 1 / 28
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.0_3_5_7_1_4_2_8							) < 1E-6							)


				def _snake_case				(						self							):
								lowerCamelCase		       =["""My hovercraft""", """is full of eels"""]
								lowerCamelCase		       =["""My hovercraft is full""", """ of eels"""]
								# S = 0, D = 0, I = 2, N = 28, CER = 2 / 28
								# whitespace at the front of " of eels" will be strip during preporcessing
								# so need to insert 2 whitespaces
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_      ,       concatenate_texts=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.0_7_1_4_2_8							) < 1E-6							)


				def _snake_case				(						self							):
								lowerCamelCase		       =["""我能吞下玻璃而不伤身体"""]
								lowerCamelCase		       =[""" 能吞虾玻璃而 不霜身体啦"""]
								# S = 3, D = 2, I = 0, N = 11, CER = 5 / 11
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.4_5_4_5_4_5_4_5_4_5							) < 1E-6							)

								lowerCamelCase		       =["""我能吞下玻璃""", """而不伤身体"""]
								lowerCamelCase		       =["""我    能 吞 下 玻 璃""", """而不伤身体"""]
								# S = 0, D = 5, I = 0, N = 11, CER = 5 / 11
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertTrue(abs(char_error_rate - 0.4_5_4_5_4_5_4_5_4_5_4_5							) < 1E-6							)

								lowerCamelCase		       =["""我能吞下玻璃而不伤身体"""]
								lowerCamelCase		       =cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)
								self.assertFalse(UpperCAmelCase_      ,       0.0							)


				def _snake_case				(						self							):
								lowerCamelCase		       =[""""""]
								lowerCamelCase		       =["""Hypothesis"""]
								with self.assertRaises(UpperCAmelCase_							):
												cer.compute(predictions=UpperCAmelCase_      ,       references=UpperCAmelCase_							)


if __name__ == "__main__":
							unittest.main()












from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


UpperCAmelCase__  :	str     =logging.get_logger(__name__)

UpperCAmelCase__  :	Optional[int]     ={
    '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/config.json''',
    '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/config.json''',
    '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/config.json''',
    '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/config.json''',
    '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/config.json''',
}

class 					__A   (  a			):
				__A            = """gpt2"""
				__A            = ["""past_key_values"""]
				__A            = {
				    """hidden_size""": """n_embd""",
				    """max_position_embeddings""": """n_positions""",
				    """num_attention_heads""": """n_head""",
				    """num_hidden_layers""": """n_layer""",
				}


				def __init__(						self      ,       UpperCAmelCase_=50257      ,       UpperCAmelCase_=1024      ,       UpperCAmelCase_=768      ,       UpperCAmelCase_=12      ,       UpperCAmelCase_=12      ,       UpperCAmelCase_=None      ,       UpperCAmelCase_="gelu_new"      ,       UpperCAmelCase_=0.1      ,       UpperCAmelCase_=0.1      ,       UpperCAmelCase_=0.1      ,       UpperCAmelCase_=1E-5      ,       UpperCAmelCase_=0.0_2      ,       UpperCAmelCase_="cls_index"      ,       UpperCAmelCase_=True      ,       UpperCAmelCase_=None      ,       UpperCAmelCase_=True      ,       UpperCAmelCase_=0.1      ,       UpperCAmelCase_=True      ,       UpperCAmelCase_=True      ,       UpperCAmelCase_=50256      ,       UpperCAmelCase_=50256      ,       UpperCAmelCase_=False      ,       UpperCAmelCase_=False      ,       **UpperCAmelCase_      ,       ):
								lowerCamelCase		       =vocab_size
								lowerCamelCase		       =n_positions
								lowerCamelCase		       =n_embd
								lowerCamelCase		       =n_layer
								lowerCamelCase		       =n_head
								lowerCamelCase		       =n_inner
								lowerCamelCase		       =activation_function
								lowerCamelCase		       =resid_pdrop
								lowerCamelCase		       =embd_pdrop
								lowerCamelCase		       =attn_pdrop
								lowerCamelCase		       =layer_norm_epsilon
								lowerCamelCase		       =initializer_range
								lowerCamelCase		       =summary_type
								lowerCamelCase		       =summary_use_proj
								lowerCamelCase		       =summary_activation
								lowerCamelCase		       =summary_first_dropout
								lowerCamelCase		       =summary_proj_to_labels
								lowerCamelCase		       =scale_attn_weights
								lowerCamelCase		       =use_cache
								lowerCamelCase		       =scale_attn_by_inverse_layer_idx
								lowerCamelCase		       =reorder_and_upcast_attn

								lowerCamelCase		       =bos_token_id
								lowerCamelCase		       =eos_token_id

								super().__init__(bos_token_id=UpperCAmelCase_      ,       eos_token_id=UpperCAmelCase_      ,       **UpperCAmelCase_							)




class 					__A   (  a			):


				def __init__(						self      ,       UpperCAmelCase_      ,       UpperCAmelCase_ = "default"      ,       UpperCAmelCase_ = None      ,       UpperCAmelCase_ = False      ,       ):
								super().__init__(UpperCAmelCase_      ,       task=UpperCAmelCase_      ,       patching_specs=UpperCAmelCase_      ,       use_past=UpperCAmelCase_							)
								if not getattr(self._config      ,       """pad_token_id"""      ,       UpperCAmelCase_							):
												# TODO: how to do that better?
												lowerCamelCase		       =0


				@property
				def _snake_case				(						self							):
								lowerCamelCase		       =OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}							)
								if self.use_past:
												self.fill_with_past_key_values_(UpperCAmelCase_      ,       direction="""inputs"""							)
												lowerCamelCase		       ={0: """batch""", 1: """past_sequence + sequence"""}
								else:
												lowerCamelCase		       ={0: """batch""", 1: """sequence"""}

								return common_inputs


				@property
				def _snake_case				(						self							):
								return self._config.n_layer


				@property
				def _snake_case				(						self							):
								return self._config.n_head


				def _snake_case				(						self      ,       UpperCAmelCase_      ,       UpperCAmelCase_ = -1      ,       UpperCAmelCase_ = -1      ,       UpperCAmelCase_ = False      ,       UpperCAmelCase_ = None      ,       ):
								lowerCamelCase		       =super(UpperCAmelCase_      ,       self							).generate_dummy_inputs(
								    UpperCAmelCase_      ,       batch_size=UpperCAmelCase_      ,       seq_length=UpperCAmelCase_      ,       is_pair=UpperCAmelCase_      ,       framework=UpperCAmelCase_							)

								# We need to order the input in the way they appears in the forward()
								lowerCamelCase		       =OrderedDict({"""input_ids""": common_inputs["""input_ids"""]}							)

								# Need to add the past_keys
								if self.use_past:
												if not is_torch_available():
																raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""							)
												else:
																import torch

																lowerCamelCase       ,     lowerCamelCase		       =common_inputs["""input_ids"""].shape
																# Not using the same length for past_key_values
																lowerCamelCase		       =seqlen + 2
																lowerCamelCase		       =(
																    batch,
																    self.num_attention_heads,
																    past_key_values_length,
																    self._config.hidden_size // self.num_attention_heads,
																)
																lowerCamelCase		       =[
																    (torch.zeros(UpperCAmelCase_							), torch.zeros(UpperCAmelCase_							)) for _ in range(self.num_layers							)
																]

								lowerCamelCase		       =common_inputs["""attention_mask"""]
								if self.use_past:
												lowerCamelCase		       =ordered_inputs["""attention_mask"""].dtype
												lowerCamelCase		       =torch.cat(
												    [ordered_inputs["""attention_mask"""], torch.ones(UpperCAmelCase_      ,       UpperCAmelCase_      ,       dtype=UpperCAmelCase_							)]      ,       dim=1							)

								return ordered_inputs


				@property
				def _snake_case				(						self							):
								return 13





