


"""simple docstring"""







import unittest

from transformers.testing_utils import is_torch_available, require_torch, tooslow

from ...generation.test_utils import torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    CpmAntConfig,
						    CpmAntForCausalLM,
						    CpmAntModel,
						    CpmAntTokenizer,
						)
@require_torch
class 				lowerCamelCase							:


							"""simple docstring"""






							def __init__(    self			:  List[Any]		,			lowerCamelCase_			:  List[Any]		,			lowerCamelCase_			:  List[str]=2		,			lowerCamelCase_			:  List[str]=8		,			lowerCamelCase_			:  Optional[Any]=True		,			lowerCamelCase_			:  int=False		,			lowerCamelCase_			:  Optional[int]=False		,			lowerCamelCase_			:  List[Any]=False		,			lowerCamelCase_			:  List[Any]=False		,			lowerCamelCase_			:  Tuple=99		,			lowerCamelCase_			:  Optional[int]=32		,			lowerCamelCase_			:  List[str]=3		,			lowerCamelCase_			:  Tuple=4		,			lowerCamelCase_			:  Tuple=37		,			lowerCamelCase_			:  Optional[Any]=32		,			lowerCamelCase_			:  Any=128		,			lowerCamelCase_			:  Union[str, Any]=8		,			lowerCamelCase_			:  Tuple=8		,			lowerCamelCase_			:  Optional[int]=8		,			lowerCamelCase_			:  str=1.0		,			lowerCamelCase_			:  str=True		,			):
													UpperCAmelCase__												=     parent
													UpperCAmelCase__												=     batch_size
													UpperCAmelCase__												=     seq_length
													UpperCAmelCase__												=     is_training
													UpperCAmelCase__												=     use_token_type_ids
													UpperCAmelCase__												=     use_input_mask
													UpperCAmelCase__												=     use_labels
													UpperCAmelCase__												=     use_mc_token_ids
													UpperCAmelCase__												=     vocab_size
													UpperCAmelCase__												=     hidden_size
													UpperCAmelCase__												=     num_hidden_layers
													UpperCAmelCase__												=     num_attention_heads
													UpperCAmelCase__												=     intermediate_size
													UpperCAmelCase__												=     num_buckets
													UpperCAmelCase__												=     max_distance
													UpperCAmelCase__												=     prompt_length
													UpperCAmelCase__												=     prompt_types
													UpperCAmelCase__												=     segment_types
													UpperCAmelCase__												=     init_std
													UpperCAmelCase__												=     return_dict






							def        lowerCAmelCase  (    self			:  Optional[Any]					):
													UpperCAmelCase__												=     {}
													UpperCAmelCase__												=     ids_tensor([self.batch_size, self.seq_length]		,			self.vocab_size					).type(torch.intaa					)
													UpperCAmelCase__												=     False

													UpperCAmelCase__												=     self.get_config()

													return (config, input_ids)






							def        lowerCAmelCase  (    self			:  int					):
													return CpmAntConfig(
													    vocab_size=self.vocab_size		,			hidden_size=self.hidden_size		,			num_hidden_layers=self.num_hidden_layers		,			num_attention_heads=self.num_attention_heads		,			dim_ff=self.intermediate_size		,			position_bias_num_buckets=self.num_buckets		,			position_bias_max_distance=self.max_distance		,			prompt_types=self.prompt_types		,			prompt_length=self.prompt_length		,			segment_types=self.segment_types		,			use_cache=lowerCamelCase_		,			init_std=self.init_std		,			return_dict=self.return_dict		,			)






							def        lowerCAmelCase  (    self			:  Dict		,			lowerCamelCase_			:  Optional[Any]		,			lowerCamelCase_			:  str		,			*lowerCamelCase_			:  str					):
													UpperCAmelCase__												=     CpmAntModel(config=lowerCamelCase_					)
													model.to(lowerCamelCase_					)
													model.eval()

													UpperCAmelCase__												=     model(**lowerCamelCase_					).last_hidden_state

													self.parent.assertEqual(hidden_states.shape		,			(self.batch_size, self.seq_length, config.hidden_size)					)






							def        lowerCAmelCase  (    self			:  Optional[Any]		,			lowerCamelCase_			:  Any		,			lowerCamelCase_			:  str		,			*lowerCamelCase_			:  Dict					):
													UpperCAmelCase__												=     CpmAntForCausalLM(lowerCamelCase_					)
													model.to(lowerCamelCase_					)
													UpperCAmelCase__												=     input_ids['''input_ids'''].to(lowerCamelCase_					)
													model.eval()

													UpperCAmelCase__												=     model(**lowerCamelCase_					)
													self.parent.assertEqual(
													    model_output.logits.shape		,			(self.batch_size, self.seq_length, config.vocab_size + config.prompt_types * config.prompt_length)		,			)






							def        lowerCAmelCase  (    self			:  Optional[int]					):
													UpperCAmelCase__						,					UpperCAmelCase__												=     self.prepare_config_and_inputs()
													return config, inputs_dict




@require_torch
class 				lowerCamelCase							(      __SCREAMING_SNAKE_CASE					,       __SCREAMING_SNAKE_CASE					,       unittest.TestCase			):


							"""simple docstring"""
							SCREAMING_SNAKE_CASE              =   (CpmAntModel, CpmAntForCausalLM) if is_torch_available() else ()
							SCREAMING_SNAKE_CASE              =   (
							    {"""feature-extraction""": CpmAntModel, """text-generation""": CpmAntForCausalLM} if is_torch_available() else {}
							)

							SCREAMING_SNAKE_CASE              =   False
							SCREAMING_SNAKE_CASE              =   False
							SCREAMING_SNAKE_CASE              =   False
							SCREAMING_SNAKE_CASE              =   False
							SCREAMING_SNAKE_CASE              =   False






							def        lowerCAmelCase  (    self			:  Dict					):
													UpperCAmelCase__												=     CpmAntModelTester(self					)
													UpperCAmelCase__												=     ConfigTester(self		,			config_class=lowerCamelCase_					)






							def        lowerCAmelCase  (    self			:  Dict					):
													self.config_tester.create_and_test_config_common_properties()
													self.config_tester.create_and_test_config_to_json_string()
													self.config_tester.create_and_test_config_to_json_file()
													self.config_tester.create_and_test_config_from_and_save_pretrained()
													self.config_tester.check_config_can_be_init_without_params()
													self.config_tester.check_config_arguments_init()






							def        lowerCAmelCase  (    self			:  int					):
													unittest.skip('''CPMAnt doesn\'t support input_embeds.'''					)(self.test_inputs_embeds					)






							def        lowerCAmelCase  (    self			:  Optional[int]					):
													unittest.skip(
													    '''CPMAnt doesn\'t support retain grad in hidden_states or attentions, because prompt management will peel off the output.hidden_states from graph.\
                 So is attentions. We strongly recommand you use loss to tune model.'''					)(self.test_retain_grad_hidden_states_attentions					)






							def        lowerCAmelCase  (    self			:  Union[str, Any]					):
													UpperCAmelCase__						,					UpperCAmelCase__												=     self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_cpmant_model(lowerCamelCase_		,			lowerCamelCase_					)






							def        lowerCAmelCase  (    self			:  List[Any]					):
													UpperCAmelCase__						,					UpperCAmelCase__												=     self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_lm_head_model(lowerCamelCase_		,			lowerCamelCase_					)




@require_torch
class 				lowerCamelCase							(      unittest.TestCase			):


							"""simple docstring"""






							@tooslow
							def        lowerCAmelCase  (    self			:  List[str]					):
													UpperCAmelCase__												=     '''今天天气真好！'''
													UpperCAmelCase__												=     '''openbmb/cpm-ant-10b'''
													UpperCAmelCase__												=     CpmAntModel.from_pretrained(lowerCamelCase_					)
													UpperCAmelCase__												=     CpmAntTokenizer.from_pretrained(lowerCamelCase_					)
													UpperCAmelCase__												=     tokenizer(lowerCamelCase_		,			return_tensors='''pt'''					)
													UpperCAmelCase__												=     model(**lowerCamelCase_					).last_hidden_state

													UpperCAmelCase__												=     torch.tensor(
													    [[[6.1708, 5.9244, 1.0835], [6.5207, 6.2893, -11.3324], [-1.0107, -0.0576, -5.9577]]]		,			)
													self.assertTrue(torch.allclose(hidden_states[:, :3, :3]		,			lowerCamelCase_		,			atol=1E-2					)					)




@require_torch
class 				lowerCamelCase							(      unittest.TestCase			):


							"""simple docstring"""






							@tooslow
							def        lowerCAmelCase  (    self			:  Union[str, Any]					):
													UpperCAmelCase__												=     '''今天天气真好！'''
													UpperCAmelCase__												=     '''openbmb/cpm-ant-10b'''
													UpperCAmelCase__												=     CpmAntForCausalLM.from_pretrained(lowerCamelCase_					)
													UpperCAmelCase__												=     CpmAntTokenizer.from_pretrained(lowerCamelCase_					)
													UpperCAmelCase__												=     tokenizer(lowerCamelCase_		,			return_tensors='''pt'''					)
													UpperCAmelCase__												=     model(**lowerCamelCase_					).logits

													UpperCAmelCase__												=     torch.tensor(
													    [[[-6.4267, -6.4083, -6.3958], [-5.8802, -5.9447, -5.7811], [-5.3896, -5.4820, -5.4295]]]		,			)
													self.assertTrue(torch.allclose(hidden_states[:, :3, :3]		,			lowerCamelCase_		,			atol=1E-2					)					)






							@tooslow
							def        lowerCAmelCase  (    self			:  Union[str, Any]					):
													UpperCAmelCase__												=     '''openbmb/cpm-ant-10b'''
													UpperCAmelCase__												=     CpmAntForCausalLM.from_pretrained(lowerCamelCase_					)
													UpperCAmelCase__												=     CpmAntTokenizer.from_pretrained(lowerCamelCase_					)
													UpperCAmelCase__												=     '''今天天气不错，'''
													UpperCAmelCase__												=     '''今天天气不错，阳光明媚，我和妈妈一起去超市买东西。\n在超市里，我看到了一个很好玩的玩具，它的名字叫“机器人”。它有一个圆圆的脑袋，两只圆圆的眼睛，还有一个圆圆的'''
													UpperCAmelCase__												=     tokenizer(lowerCamelCase_		,			return_tensors='''pt'''					)
													UpperCAmelCase__												=     model.generate(**lowerCamelCase_					)
													UpperCAmelCase__												=     tokenizer.batch_decode(lowerCamelCase_					)
													self.assertEqual(lowerCamelCase_		,			lowerCamelCase_					)






							@tooslow
							def        lowerCAmelCase  (    self			:  Optional[int]					):
													UpperCAmelCase__												=     '''openbmb/cpm-ant-10b'''
													UpperCAmelCase__												=     CpmAntForCausalLM.from_pretrained(lowerCamelCase_					)
													UpperCAmelCase__												=     CpmAntTokenizer.from_pretrained(lowerCamelCase_					)
													UpperCAmelCase__												=     ['''今天天气不错，''', '''新年快乐，万事如意！''']
													UpperCAmelCase__												=     [
													    '''今天天气不错，阳光明媚，我和妈妈一起去超市买东西。\n在超市里，我看到了一个很好玩的玩具，它的名字叫“机器人”。它有一个圆圆的脑袋，两只圆圆的眼睛，还有一个圆圆的''',
													    '''新年快乐，万事如意！在这辞旧迎新的美好时刻，我谨代表《农村新技术》杂志社全体同仁，向一直以来关心、支持《农村新技术》杂志发展的各级领导、各界朋友和广大读者致以最诚挚的''',
													]
													UpperCAmelCase__												=     tokenizer(lowerCamelCase_		,			return_tensors='''pt'''		,			padding=lowerCamelCase_					)
													UpperCAmelCase__												=     model.generate(**lowerCamelCase_					)
													UpperCAmelCase__												=     tokenizer.batch_decode(lowerCamelCase_					)
													self.assertEqual(lowerCamelCase_		,			lowerCamelCase_					)



"""simple docstring"""







import inspect
import json
import os
import tempfile
import unittest

from transformers.models.speech_to_text_a import SpeechaTextaTokenizer
from transformers.models.speech_to_text_a.tokenization_speech_to_text_a import VOCAB_FILES_NAMES

from ...test_tokenization_common import TokenizerTesterMixin
class 				lowerCamelCase							(      __SCREAMING_SNAKE_CASE					,       unittest.TestCase			):


							"""simple docstring"""
							SCREAMING_SNAKE_CASE              =   SpeechaTextaTokenizer
							SCREAMING_SNAKE_CASE              =   False






							def        lowerCAmelCase  (    self			:  Dict					):
													super().setUp()

													UpperCAmelCase__												=     '''<s> <pad> </s> <unk> here@@ a couple of@@ words for the he@@ re@@ vocab'''.split(''' '''					)
													UpperCAmelCase__												=     ['''he re</w> 123''', '''here a 1456''']
													UpperCAmelCase__												=     dict(zip(lowerCamelCase_		,			range(len(lowerCamelCase_					)					)					)					)

													UpperCAmelCase__												=     {'''pad_token''': '''<pad>''', '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>'''}

													UpperCAmelCase__												=     tempfile.mkdtemp()
													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'''		,			encoding='''utf-8'''					) as fp:
																			fp.write(json.dumps(lowerCamelCase_					) + '''\n'''					)

													with open(self.merges_file		,			'''w'''					) as fp:
																			fp.write('''\n'''.join(lowerCamelCase_					)					)






							def        lowerCAmelCase  (    self			:  Union[str, Any]					):
													UpperCAmelCase__												=     list(self.get_tokenizer().get_vocab().keys()					)

													self.assertEqual(vocab_keys[0]		,			'''<s>'''					)
													self.assertEqual(vocab_keys[1]		,			'''<pad>'''					)
													self.assertEqual(vocab_keys[-1]		,			'''vocab'''					)
													self.assertEqual(len(lowerCamelCase_					)		,			14					)






							def        lowerCAmelCase  (    self			:  Optional[Any]					):
													self.assertEqual(self.get_tokenizer().vocab_size		,			14					)






							def        lowerCAmelCase  (    self			:  Any					):
													UpperCAmelCase__												=     SpeechaTextaTokenizer.from_pretrained(self.tmpdirname					)

													# make sure @@ is correctly concatenated
													UpperCAmelCase__												=     [4, 6, 8, 7, 10]  # ["here@@", "couple", "words", "of@@", "the"]
													UpperCAmelCase__												=     tokenizer.decode(lowerCamelCase_					)

													self.assertTrue(output_string == '''herecouple words ofthe'''					)






							def        lowerCAmelCase  (    self			:  int					):
													UpperCAmelCase__												=     SpeechaTextaTokenizer.from_pretrained(self.tmpdirname					)

													with tempfile.TemporaryDirectory() as tmp_dirname:
																			tokenizer.save_pretrained(lowerCamelCase_					)
																			os.remove(os.path.join(lowerCamelCase_		,			'''merges.txt'''					)					)

																			# load tokenizer without merges file should not throw an error
																			UpperCAmelCase__												=     SpeechaTextaTokenizer.from_pretrained(lowerCamelCase_					)

													with tempfile.TemporaryDirectory() as tmp_dirname:
																			# save tokenizer and load again
																			tokenizer.save_pretrained(lowerCamelCase_					)
																			UpperCAmelCase__												=     SpeechaTextaTokenizer.from_pretrained(lowerCamelCase_					)

													self.assertIsNotNone(lowerCamelCase_					)






							def        lowerCAmelCase  (    self			:  int					):
													if not self.test_slow_tokenizer:
																			return

													UpperCAmelCase__												=     inspect.signature(self.tokenizer_class.__init__					)
													UpperCAmelCase__												=     self.get_tokenizer()

													for parameter_name, parameter in signature.parameters.items():
																			if parameter.default != inspect.Parameter.empty and parameter_name != "merges_file":
																									self.assertIn(lowerCamelCase_		,			tokenizer.init_kwargs					)