"""simple docstring"""






import unittest

import numpy as np

from transformers import (
    GPTSanJapaneseConfig,
    GPTSanJapaneseForConditionalGeneration,
    GPTSanJapaneseModel,
    GPTSanJapaneseTokenizer,
    is_torch_available,
)
from transformers.generation import GenerationConfig
from transformers.testing_utils import require_torch, slow, tooslow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
class     snake_case	:




					"""simple docstring"""

					def __init__(    self       :     int   ,lowerCamelCase__       :     str   ,lowerCamelCase__       :     Optional[int]=36_000   ,lowerCamelCase__       :     int=13   ,lowerCamelCase__       :     Optional[int]=7   ,lowerCamelCase__       :     List[str]=True   ,lowerCamelCase__       :     Union[str, Any]=32   ,lowerCamelCase__       :     str=42   ,lowerCamelCase__       :     int=5   ,lowerCamelCase__       :     Dict=2   ,lowerCamelCase__       :     List[str]=4   ,lowerCamelCase__       :     Optional[int]=2   ,lowerCamelCase__       :     Tuple=32   ,lowerCamelCase__       :     Any=80   ,lowerCamelCase__       :     Optional[Any]=33   ,lowerCamelCase__       :     Dict=0.0   ,lowerCamelCase__       :     Any=1e-6   ,lowerCamelCase__       :     Tuple=100   ,lowerCamelCase__       :     int=0.0   ,):
									UpperCAmelCase__					=							vocab_size
									UpperCAmelCase__					=							parent
									UpperCAmelCase__					=							batch_size
									UpperCAmelCase__					=							num_contexts
									# For common tests
									UpperCAmelCase__					=							self.num_contexts
									UpperCAmelCase__					=							is_training
									UpperCAmelCase__					=							hidden_size
									UpperCAmelCase__					=							num_ext_layers
									UpperCAmelCase__					=							ext_size
									UpperCAmelCase__					=							num_hidden_layers
									UpperCAmelCase__					=							num_attention_heads
									UpperCAmelCase__					=							num_experts
									UpperCAmelCase__					=							d_ff
									UpperCAmelCase__					=							d_ext
									UpperCAmelCase__					=							d_spout
									UpperCAmelCase__					=							dropout_rate
									UpperCAmelCase__					=							layer_norm_epsilon
									UpperCAmelCase__					=							expert_capacity
									UpperCAmelCase__					=							router_jitter_noise







					def 		__lowerCAmelCase						(    self       :     List[Any]      ):
									return GPTSanJapaneseConfig.from_pretrained('Tanrei/GPTSAN-japanese'      )







					def 		__lowerCAmelCase						(    self       :     Dict      ):
									UpperCAmelCase__					=							ids_tensor([self.batch_size, self.seq_length]   ,self.vocab_size      )

									UpperCAmelCase__					=							self.get_config()

									return (config, input_ids)







					def 		__lowerCAmelCase						(    self       :     str      ):
									UpperCAmelCase__					=							ids_tensor([self.batch_size, self.seq_length]   ,self.vocab_size      )

									UpperCAmelCase__					=							self.get_config()

									return (config, {"input_ids": input_ids})







					def 		__lowerCAmelCase						(    self       :     Any      ):
									return GPTSanJapaneseConfig(
									    vocab_size=self.vocab_size   ,num_contexts=self.seq_length   ,d_model=self.hidden_size   ,d_ff=self.d_ff   ,d_ext=self.d_ext   ,d_spout=self.d_spout   ,num_switch_layers=self.num_hidden_layers - self.num_ext_layers   ,num_ext_layers=self.num_ext_layers   ,num_heads=self.num_attention_heads   ,num_experts=self.num_experts   ,expert_capacity=self.expert_capacity   ,dropout_rate=self.dropout_rate   ,layer_norm_epsilon=self.layer_norm_epsilon   ,router_jitter_noise=self.router_jitter_noise   ,)







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,lowerCamelCase__       :     Optional[Any]   ,lowerCamelCase__       :     Union[str, Any]   ,):
									UpperCAmelCase__					=							GPTSanJapaneseForConditionalGeneration(config=lowerCamelCase__      )
									model.to(lowerCamelCase__      )
									model.eval()
									UpperCAmelCase__					=							model(
									    input_ids=lowerCamelCase__   ,)
									self.parent.assertIsNotNone(lowerCamelCase__      )






@require_torch
class     snake_case	(			snake_case__				,   snake_case__				,   unittest.TestCase    ):




					"""simple docstring"""

					snake_case__       =			(GPTSanJapaneseModel,) if is_torch_available() else ()
					snake_case__       =			(
					    {
					        'conversational': GPTSanJapaneseForConditionalGeneration,
					        'feature-extraction': GPTSanJapaneseForConditionalGeneration,
					        'summarization': GPTSanJapaneseForConditionalGeneration,
					        'text2text-generation': GPTSanJapaneseForConditionalGeneration,
					        'translation': GPTSanJapaneseForConditionalGeneration,
					    }
					    if is_torch_available()
					    else {}
					)
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					# The small GPTSAN_JAPANESE model needs higher percentages for CPU/MP tests
					snake_case__       =			[0.8, 0.9]







					def 		__lowerCAmelCase						(    self       :     Optional[int]   ,lowerCamelCase__       :     List[str]   ,lowerCamelCase__       :     Union[str, Any]   ,lowerCamelCase__       :     Union[str, Any]   ,lowerCamelCase__       :     List[str]   ,lowerCamelCase__       :     int      ):
									if pipeline_test_casse_name == "SummarizationPipelineTests":
													# TODO: fix `_reorder_cache` is not implemented for this model
													return True
									elif pipeline_test_casse_name == "Text2TextGenerationPipelineTests":
													# TODO: check this.
													return True

									return False







					def 		__lowerCAmelCase						(    self       :     Optional[Any]      ):
									UpperCAmelCase__					=							GPTSanJapaneseTester(self      )
									UpperCAmelCase__					=							ConfigTester(self   ,config_class=lowerCamelCase__   ,d_model=37      )







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									GPTSanJapaneseConfig()







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									UpperCAmelCase__					=							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCamelCase__      )







					@unittest.skip(
					    reason='skip for now as the computed `max_memory` by `model_split_percents` in the test method will be changed inside `from_pretrained`'      )
					def 		__lowerCAmelCase						(    self       :     List[str]      ):
									super().test_model_parallelism()







					@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'      )
					def 		__lowerCAmelCase						(    self       :     List[str]      ):
									pass






@require_torch
class     snake_case	(			snake_case__				,   snake_case__				,   unittest.TestCase    ):




					"""simple docstring"""

					snake_case__       =			(GPTSanJapaneseForConditionalGeneration,) if is_torch_available() else ()
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					snake_case__       =			False
					# The small GPTSAN_JAPANESE model needs higher percentages for CPU/MP tests
					snake_case__       =			[0.8, 0.9]







					def 		__lowerCAmelCase						(    self       :     int      ):
									UpperCAmelCase__					=							GPTSanJapaneseTester(self      )
									UpperCAmelCase__					=							ConfigTester(self   ,config_class=lowerCamelCase__   ,d_model=37      )







					def 		__lowerCAmelCase						(    self       :     Optional[Any]      ):
									GPTSanJapaneseConfig()







					def 		__lowerCAmelCase						(    self       :     Optional[Any]      ):
									UpperCAmelCase__					=							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCamelCase__      )







					@unittest.skip(
					    reason='skip for now as the computed `max_memory` by `model_split_percents` in the test method will be changed inside `from_pretrained`'      )
					def 		__lowerCAmelCase						(    self       :     int      ):
									super().test_model_parallelism()







					@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'      )
					def 		__lowerCAmelCase						(    self       :     str      ):
									pass







					@slow
					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									UpperCAmelCase__					=							GPTSanJapaneseForConditionalGeneration.from_pretrained('Tanrei/GPTSAN-japanese'      )
									UpperCAmelCase__					=							GPTSanJapaneseTokenizer.from_pretrained('Tanrei/GPTSAN-japanese'      )
									UpperCAmelCase__					=							tokenizer.encode('武田信玄は'   ,return_tensors='pt'      )
									UpperCAmelCase__					=							model(lowerCamelCase__      )
									UpperCAmelCase__					=							outputs.logits.detach().cpu().numpy()
									# Output of original model created with mesh-tensoflow
									UpperCAmelCase__					=							[
									    # fmt: off
									    [-1_2.0_3_7_8_3_9_8_8_9_5_2_6_3_6_7, -1_2.4_3_3_0_6_1_5_9_9_7_3_1_4_4_5, -1_4.3_3_3_8_4_0_3_7_0_1_7_8_2_2_3, -1_2.4_5_0_3_4_5_9_9_3_0_4_1_9_9_2, -1_1.1_6_6_1_3_7_6_9_5_3_1_2_5,
									    -1_1.9_3_0_1_3_7_6_3_4_2_7_7_3_4_4, -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_0_1_6_8_4_5_7, -1_0.2_9_8_0_4_9_9_2_6_7_5_7_8_1_2, -1_0.7_8_4_1_4_8_2_1_6_2_4_7_5_5_9, -1_0.8_4_0_6_9_3_4_7_3_8_1_5_9_1_8, -2_2.0_3_1_5_2_8_4_7_2_9_0_0_3_9],
									    # fmt: on
									]
									UpperCAmelCase__					=							np.array(lowerCamelCase__      ).flatten()
									UpperCAmelCase__					=							output_logits[0, :, :20].flatten()

									def check(lowerCamelCase__       :     Union[str, Any]   ,lowerCamelCase__       :     Union[str, Any]   ,lowerCamelCase__       :     Union[str, Any]=5e-4      ):
													return abs(a - b      ) < epsilon * max(abs(lowerCamelCase__      )   ,abs(lowerCamelCase__      )      )

									self.assertTrue(np.all([check(target[i]   ,predict[i]      ) for i in range(len(lowerCamelCase__      )      )]      )      )







					@slow
					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									UpperCAmelCase__					=							GPTSanJapaneseForConditionalGeneration.from_pretrained('Tanrei/GPTSAN-japanese'      )
									UpperCAmelCase__					=							GPTSanJapaneseTokenizer.from_pretrained('Tanrei/GPTSAN-japanese'      )
									model.to(lowerCamelCase__      )

									# set deterministically
									UpperCAmelCase__					=							GenerationConfig.from_pretrained('Tanrei/GPTSAN-japanese'      )
									UpperCAmelCase__					=							1

									# use different length sentences to test batching
									UpperCAmelCase__					=							[
									    '甲斐なら武田と言うほど',
									    '織田信長は、',
									]

									UpperCAmelCase__					=							'left'
									UpperCAmelCase__					=							tokenizer(lowerCamelCase__   ,return_tensors='pt'   ,padding=lowerCamelCase__      )
									UpperCAmelCase__					=							inputs['input_ids'].to(lowerCamelCase__      )

									self.assertNotEqual(inputs['attention_mask'][0].numpy().tolist()   ,inputs['attention_mask'][1].numpy().tolist()      )

									UpperCAmelCase__					=							model.generate(
									    input_ids=lowerCamelCase__   ,attention_mask=inputs['attention_mask'].to(lowerCamelCase__      )   ,max_new_tokens=3   ,generation_config=lowerCamelCase__   ,)

									UpperCAmelCase__					=							tokenizer(sentences[0]   ,return_tensors='pt'      ).input_ids.to(lowerCamelCase__      )
									UpperCAmelCase__					=							model.generate(
									    input_ids=lowerCamelCase__   ,max_new_tokens=3   ,generation_config=lowerCamelCase__      )

									UpperCAmelCase__					=							tokenizer(sentences[1]   ,return_tensors='pt'      ).input_ids.to(lowerCamelCase__      )
									UpperCAmelCase__					=							model.generate(input_ids=lowerCamelCase__   ,max_new_tokens=3   ,generation_config=lowerCamelCase__      )

									self.assertNotEqual(inputs_non_padded.shape   ,inputs_padded.shape      )

									UpperCAmelCase__					=							tokenizer.batch_decode(lowerCamelCase__   ,skip_special_tokens=lowerCamelCase__      )
									UpperCAmelCase__					=							tokenizer.decode(output_non_padded[0]   ,skip_special_tokens=lowerCamelCase__      )
									UpperCAmelCase__					=							tokenizer.decode(output_padded[0]   ,skip_special_tokens=lowerCamelCase__      )

									UpperCAmelCase__					=							[
									    '甲斐なら武田と言うほど甲斐の武田',
									    '織田信長は、このような',
									]
									self.assertListEqual(lowerCamelCase__   ,lowerCamelCase__      )
									self.assertListEqual(lowerCamelCase__   ,[non_padded_sentence, padded_sentence]      )







					@tooslow
					def 		__lowerCAmelCase						(    self       :     Any      ):
									UpperCAmelCase__					=							GPTSanJapaneseForConditionalGeneration.from_pretrained('Tanrei/GPTSAN-japanese'      )
									UpperCAmelCase__					=							GPTSanJapaneseTokenizer.from_pretrained('Tanrei/GPTSAN-japanese'      )
									# Output of original model created with mesh-tensoflow
									UpperCAmelCase__					=							[
									    ('武田信玄は', 35_675),
									    ('武田信玄は、', 45),
									    ('武田信玄は、この', 29),
									    ('武田信玄は、このよう', 30_642),
									    ('武田信玄は、このような', 35_680),
									    ('武田信玄は、このような「', 8_640),
									    ('武田信玄は、このような「武田', 31_617),
									    ('武田信玄は、このような「武田家', 30_646),
									    ('武田信玄は、このような「武田家の', 31_617),
									    ('武田信玄は、このような「武田家の家', 31_381),
									]
									for input, output in target:
													UpperCAmelCase__					=							tokenizer.encode(lowerCamelCase__   ,return_tensors='pt'      )
													UpperCAmelCase__					=							model(lowerCamelCase__      )
													UpperCAmelCase__					=							outputs.logits.detach().cpu().numpy()[0]
													UpperCAmelCase__					=							np.argmax(output_logits[-1]      )
													self.assertEqual(lowerCamelCase__   ,lowerCamelCase__      )







					@slow
					def 		__lowerCAmelCase						(    self       :     Optional[Any]      ):
									UpperCAmelCase__					=							GPTSanJapaneseForConditionalGeneration.from_pretrained('Tanrei/GPTSAN-japanese'      )
									UpperCAmelCase__					=							GPTSanJapaneseTokenizer.from_pretrained('Tanrei/GPTSAN-japanese'      )
									model.to(lowerCamelCase__      )

									# set deterministically
									UpperCAmelCase__					=							GenerationConfig.from_pretrained('Tanrei/GPTSAN-japanese'      )
									UpperCAmelCase__					=							1

									UpperCAmelCase__					=							'武田信玄は、'
									UpperCAmelCase__					=							tokenizer(lowerCamelCase__   ,return_tensors='pt'      ).input_ids.to(lowerCamelCase__      )
									UpperCAmelCase__					=							tokenizer([input_text, input_text]   ,return_tensors='pt'      ).input_ids.to(lowerCamelCase__      )

									# spout from uniform and one-hot
									UpperCAmelCase__					=							[
									    # fmt: off
									    [0.8_7_8_8_2_2_0_8, 0.3_8_4_2_6_3_9_6, 0.3_3_2_2_0_2_4_8, 0.4_3_8_9_0_4_0_6, 0.1_6_5_6_2_2_5_2,
									    0.0_4_8_0_3_9_8_5, 0.2_1_1_5_7_2  , 0.2_3_1_8_8_4_7_3, 0.3_7_1_5_3_0_6_8, 0.7_8_3_6_3_7_7 ,
									    0.0_2_1_6_0_1_7_2, 0.3_8_7_6_1_7_1_9, 0.7_5_2_9_0_7_7_2, 0.9_0_1_9_8_8_5_7, 0.3_4_3_6_5_7_7_7,
									    0.6_4_1_6_8_1_6_9, 0.4_4_3_1_8_4_7_1, 0.1_4_5_7_5_7_4_6, 0.9_2_5_6_2_8_8_1, 0.4_0_8_1_2_1_4_8,
									    0.2_9_0_1_9_1_2_2, 0.8_8_8_6_1_5_9_9, 0.6_5_5_2_4_8_4_6, 0.4_3_5_6_3_4_5_6, 0.3_8_1_7_7_1_8_7,
									    0.7_0_8_3_2_9_6_5, 0.8_1_5_2_7_8_9_2, 0.6_8_8_3_2_8_1_2, 0.3_8_8_3_3_1_9_2, 0.4_5_6_1_5_2_2 ,
									    0.1_4_8_2_8_8_1_7, 0.4_7_2_4_8_2_1_3, 0.5_4_3_5_7_3_3_5, 0.8_2_0_0_9_5_6_6, 0.1_3_3_8_8_8_4 ,
									    0.0_2_7_5_5_4_1_7, 0.1_9_7_6_4_6_7_7, 0.2_4_2_2_0_8_4 , 0.0_4_7_5_7_6_7_4, 0.6_5_4_0_9_6_0_6,
									    0.0_8_2_4_5_8_9 , 0.0_3_3_0_4_3_8_3, 0.9_4_3_8_7_6_8_9, 0.9_8_7_6_4_5_0_9, 0.8_2_4_3_3_9_0_1,
									    0.2_7_6_4_6_7_4_1, 0.6_4_9_0_7_4_9_3, 0.7_6_0_0_9_4_0_6, 0.3_0_0_8_7_9_1_5, 0.1_7_9_0_4_6_8_9,
									    0.4_1_6_0_1_7_1_4, 0.6_7_0_4_6_3_9_8, 0.1_0_4_2_2_8_2_2, 0.0_8_4_4_7_3_7_4, 0.0_7_3_5_4_3_4_4,
									    0.6_1_4_2_3_5_6_5, 0.7_0_2_8_4_8_6_6, 0.7_5_3_2_3_3_3 , 0.1_9_7_2_0_3_8 , 0.2_9_5_7_5_6_5_9,
									    0.9_0_5_8_3_8_8_6, 0.2_9_2_6_5_3_0_7, 0.5_0_0_0_0_1_7_5, 0.7_0_4_0_7_6_5_5, 0.8_8_9_3_6_3  ,
									    0.8_1_9_0_4_4_1_8, 0.6_6_8_2_9_1_2_8, 0.6_4_4_6_8_8_1_5, 0.5_6_5_6_3_7_2_3, 0.8_5_6_0_1_8_7_5,
									    0.9_4_9_2_4_6_7_2, 0.0_0_1_6_6_7_6_2, 0.2_5_2_2_0_6_4_3, 0.7_4_5_4_0_2_1_9, 0.6_7_9_9_3_2_4_7,
									    0.1_5_4_9_6_7_5 , 0.3_9_3_8_5_3_5_2, 0.9_2_1_5_3_6_0_7, 0.6_3_7_4_5_9_3_1, 0.2_7_7_5_9_0_4_3,
									    0.8_4_7_0_2_2_9_5, 0.6_5_9_0_4_2_7_1, 0.5_8_6_7_6_6_1_4, 0.8_6_6_6_9_3_6 , 0.3_9_6_0_7_4_3_8,
									    0.7_9_9_5_4_9_8_3, 0.4_2_2_2_0_6_9_7, 0.3_9_6_5_0_3_8_1, 0.7_8_4_9_8_6_4 , 0.5_6_1_5_0_2_0_1,
									    0.1_5_6_7_8_9_2_5, 0.1_4_7_4_6_0_3_2, 0.3_4_5_4_2_1_1_4, 0.4_7_0_2_6_7_8_3, 0.1_1_9_5_6_4_8_9,
									    0.2_5_4_2_1_4_3_5, 0.3_3_7_8_8_9_0_1, 0.6_8_9_3_4_8_4_2, 0.3_6_4_2_4_6_8_5, 0.7_1_7_3_7_8_9_8,
									    0.3_8_9_8_3_4_4_9, 0.9_4_3_9_3_7_7_9, 0.3_9_5_7_5_5_8_8, 0.3_6_6_1_6_5_5_3, 0.8_7_1_0_4_6_6_5,
									    0.6_4_6_3_0_2_0_3, 0.2_2_5_1_6_9_0_5, 0.8_8_2_7_0_8_0_4, 0.1_5_0_3_1_3_3_8, 0.7_5_1_4_4_3_4_5,
									    0.4_6_4_5_9_0_2_5, 0.8_5_3_9_6_4_5_4, 0.8_6_3_5_5_6_4_3, 0.6_5_1_3_9_8_5_1, 0.7_0_2_6_6_0_6_1,
									    0.3_0_2_4_1_3_8_9, 0.8_1_0_5_6_4_9_7, 0.8_8_8_6_5_9_6_9, 0.3_8_7_7_3_8_0_7, 0.7_0_6_3_5_8_4_9,
									    0.9_0_7_1_8_4_5_9, 0.4_3_2_4_5_7_8_9, 0.2_8_0_0_0_6_5_4, 0.4_5_9_3_5_5_6_2, 0.0_8_7_7_3_5_1_9,
									    0.9_5_5_2_1_5_1 , 0.9_3_9_0_1_5_1_1, 0.2_2_4_8_9_2_8_8], # uniform
									    [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., 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.],
									    # fmt: on
									]

									UpperCAmelCase__					=							model.generate(
									    input_ids=lowerCamelCase__   ,spout=spouts[0]   ,max_new_tokens=20   ,generation_config=lowerCamelCase__   ,)

									UpperCAmelCase__					=							model.generate(
									    input_ids=lowerCamelCase__   ,spout=spouts[1]   ,max_new_tokens=20   ,generation_config=lowerCamelCase__   ,)

									UpperCAmelCase__					=							model.generate(
									    input_ids=lowerCamelCase__   ,spout=lowerCamelCase__   ,max_new_tokens=20   ,generation_config=lowerCamelCase__   ,)

									UpperCAmelCase__					=							tokenizer.decode(outputa[0]      )
									UpperCAmelCase__					=							tokenizer.decode(outputa[0]      )
									UpperCAmelCase__					=							tokenizer.batch_decode(lowerCamelCase__      )

									UpperCAmelCase__					=							[
									    '武田信玄は、武田氏の滅亡後、武田氏の居城であった甲斐武田氏の居城である',
									    '武田信玄は、武田家の滅亡を防ぐため、武田家の家臣である武田信虎を討',
									]
									self.assertListEqual(lowerCamelCase__   ,lowerCamelCase__      )
									self.assertListEqual(lowerCamelCase__   ,[outa_sentence, outa_sentence]      )







					@slow
					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									UpperCAmelCase__					=							GPTSanJapaneseForConditionalGeneration.from_pretrained('Tanrei/GPTSAN-japanese'      )
									UpperCAmelCase__					=							GPTSanJapaneseTokenizer.from_pretrained('Tanrei/GPTSAN-japanese'      )
									model.to(lowerCamelCase__      )

									# set deterministically
									UpperCAmelCase__					=							GenerationConfig.from_pretrained('Tanrei/GPTSAN-japanese'      )
									UpperCAmelCase__					=							1

									UpperCAmelCase__					=							'武田信玄'
									UpperCAmelCase__					=							'織田信長'
									UpperCAmelCase__					=							'は、'
									UpperCAmelCase__					=							'が、'
									UpperCAmelCase__					=							tokenizer(lowerCamelCase__   ,prefix_text=lowerCamelCase__   ,return_tensors='pt'      )
									UpperCAmelCase__					=							tokenizer(lowerCamelCase__   ,prefix_text=lowerCamelCase__   ,return_tensors='pt'      )
									UpperCAmelCase__					=							tokenizer([[prefix_text_a, input_text_a], [prefix_text_a, input_text_a]]   ,return_tensors='pt'      )

									UpperCAmelCase__					=							model.generate(
									    input_ids=input_tok_a.input_ids.to(lowerCamelCase__      )   ,token_type_ids=input_tok_a.token_type_ids.to(lowerCamelCase__      )   ,max_new_tokens=20   ,generation_config=lowerCamelCase__   ,)

									UpperCAmelCase__					=							model.generate(
									    input_ids=input_tok_a.input_ids.to(lowerCamelCase__      )   ,token_type_ids=input_tok_a.token_type_ids.to(lowerCamelCase__      )   ,max_new_tokens=20   ,generation_config=lowerCamelCase__   ,)

									UpperCAmelCase__					=							model.generate(
									    input_ids=input_tok_a.input_ids.to(lowerCamelCase__      )   ,token_type_ids=input_tok_a.token_type_ids.to(lowerCamelCase__      )   ,attention_mask=input_tok_a.attention_mask.to(lowerCamelCase__      )   ,max_new_tokens=20   ,generation_config=lowerCamelCase__   ,)

									UpperCAmelCase__					=							tokenizer.decode(outputa[0]      )
									UpperCAmelCase__					=							tokenizer.decode(outputa[0]      )
									UpperCAmelCase__					=							tokenizer.batch_decode(lowerCamelCase__      )

									UpperCAmelCase__					=							[
									    '武田信玄は、武田氏の祖である武田信虎を、その子・武田信友を擁して',
									    '織田信長が、織田信長の妻・お市の方を妻として迎えたという逸話が残',
									]
									self.assertListEqual(lowerCamelCase__   ,lowerCamelCase__      )
									self.assertListEqual(lowerCamelCase__   ,[outa_sentence, outa_sentence]      )



"""simple docstring"""






import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
						import torch


lowerCAmelCase__  :  Optional[Any]											=     logging.get_logger(__name__)
class     snake_case	:




					"""simple docstring"""

					def __init__(    self       :     Optional[Any]   ,lowerCamelCase__       :     Dict   ,lowerCamelCase__       :     Optional[Any]=21   ,lowerCamelCase__       :     str=[]   ,lowerCamelCase__       :     Any=None      ):
									UpperCAmelCase__					=							model
									UpperCAmelCase__					=							trace_batch_nums
									UpperCAmelCase__					=							abort_after_batch_num

									# keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence
									UpperCAmelCase__					=							collections.deque([]   ,lowerCamelCase__      )
									UpperCAmelCase__					=							[]
									UpperCAmelCase__					=							0
									UpperCAmelCase__					=							0
									UpperCAmelCase__					=							False
									UpperCAmelCase__					=							'                 '

									self.analyse_model()

									self.register_forward_hook()







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]   ,lowerCamelCase__       :     Tuple=None      ):
									if frame is not None:
													self.expand_frame(lowerCamelCase__      )
									self.frames.append('\n'.join(self.frame      )      )
									UpperCAmelCase__					=							[]  # start a new frame







					def 		__lowerCAmelCase						(    self       :     int   ,lowerCamelCase__       :     int      ):
									self.frame.append(lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     List[str]      ):
									print('\n'.join(self.frames      )      )
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Dict      ):
									print(f'''\nDetected inf/nan during batch_number={self.batch_number}'''      )
									print(f'''Last {len(self.frames      )} forward frames:'''      )
									print(f'''{"abs min":8} {"abs max":8} metadata'''      )
									print('\n'.join(self.frames      )      )
									print('\n\n'      )
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									# extract the fully qualified module names, to be able to report at run time. e.g.:
									# encoder.block.2.layer.0.SelfAttention.o
									#
									# for shared weights only the first shared module name will be registered
									UpperCAmelCase__					=							{m: name for name, m in self.model.named_modules()}
									# self.longest_module_name = max(len(v) for v in self.module_names.values())







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,lowerCamelCase__       :     int   ,lowerCamelCase__       :     List[Any]      ):
									if torch.is_tensor(lowerCamelCase__      ):
													self.expand_frame(get_abs_min_max(lowerCamelCase__   ,lowerCamelCase__      )      )
													if detect_overflow(lowerCamelCase__   ,lowerCamelCase__      ):
																	UpperCAmelCase__					=							True
									elif var is None:
													self.expand_frame(f'''{"None":>17} {ctx}'''      )
									else:
													self.expand_frame(f'''{"not a tensor":>17} {ctx}'''      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									self.expand_frame(f'''\n\n{self.prefix} *** Starting batch number={self.batch_number} ***'''      )
									self.expand_frame(f'''{"abs min":8} {"abs max":8} metadata'''      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									self.expand_frame(f'''{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n'''      )







					def 		__lowerCAmelCase						(    self       :     List[str]   ,lowerCamelCase__       :     List[str]   ,lowerCamelCase__       :     List[Any]   ,lowerCamelCase__       :     Optional[Any]      ):
									self.expand_frame(f'''{self.prefix} {self.module_names[module]} {module.__class__.__name__}'''      )

									# params
									for name, p in module.named_parameters(recurse=lowerCamelCase__      ):
													self.analyse_variable(lowerCamelCase__   ,lowerCamelCase__      )

									# inputs
									if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
													for i, x in enumerate(lowerCamelCase__      ):
																	self.analyse_variable(lowerCamelCase__   ,f'''input[{i}]'''      )
									else:
													self.analyse_variable(lowerCamelCase__   ,'input'      )

									# outputs
									if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
													for i, x in enumerate(lowerCamelCase__      ):
																	# possibly a tuple of tuples
																	if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
																					for j, y in enumerate(lowerCamelCase__      ):
																									self.analyse_variable(lowerCamelCase__   ,f'''output[{i}][{j}]'''      )
																	else:
																					self.analyse_variable(lowerCamelCase__   ,f'''output[{i}]'''      )
									else:
													self.analyse_variable(lowerCamelCase__   ,'output'      )

									self.save_frame()







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]      ):
									self.model.apply(self._register_forward_hook      )







					def 		__lowerCAmelCase						(    self       :     List[Any]   ,lowerCamelCase__       :     str      ):
									module.register_forward_hook(self.forward_hook      )







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,lowerCamelCase__       :     Any   ,lowerCamelCase__       :     str   ,lowerCamelCase__       :     Union[str, Any]      ):
									# - input is a tuple of packed inputs (could be non-Tensors)
									# - output could be a Tensor or a tuple of Tensors and non-Tensors

									UpperCAmelCase__					=							False

									UpperCAmelCase__					=							True if self.batch_number in self.trace_batch_nums else False
									if trace_mode:
													self.reset_saved_frames()

									if self.total_calls == 0:
													self.batch_start_frame()
									self.total_calls += 1

									# count batch numbers - the very first forward hook of the batch will be called when the
									# batch completes - i.e. it gets called very last - we know this batch has finished
									if module == self.model:
													self.batch_number += 1
													UpperCAmelCase__					=							True

									self.create_frame(lowerCamelCase__   ,lowerCamelCase__   ,lowerCamelCase__      )

									# if last_frame_of_batch:
									#     self.batch_end_frame()

									if trace_mode:
													self.trace_frames()

									if last_frame_of_batch:
													self.batch_start_frame()

									if self.detected_overflow and not trace_mode:
													self.dump_saved_frames()

													# now we can abort, as it's pointless to continue running
													raise ValueError(
													    'DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. '
													    'Please scroll up above this traceback to see the activation values prior to this event.'      )

									# abort after certain batch if requested to do so
									if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:
													raise ValueError(
													    f'''DebugUnderflowOverflow: aborting after {self.batch_number} batches due to'''
													    f''' `abort_after_batch_num={self.abort_after_batch_num}` arg'''      )






def   a_						( lowerCamelCase ,      lowerCamelCase	):
				UpperCAmelCase__					=							var.abs()
				return f'''{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'''



def   a_						( lowerCamelCase ,      lowerCamelCase	):
				UpperCAmelCase__					=							False
				if torch.isnan(lowerCamelCase	).any().item():
								UpperCAmelCase__					=							True
								print(f'''{ctx} has nans'''	)
				if torch.isinf(lowerCamelCase	).any().item():
								UpperCAmelCase__					=							True
								print(f'''{ctx} has infs'''	)

				# if needed to monitor large elements can enable the following
				if 0:  # and detected:
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0	)]
								if naaa.numel() > 0:
												print(f'''{ctx}:  n100={naaa.numel()}'''	)
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0_0	)]
								if naaaa.numel() > 0:
												print(f'''{ctx}: n1000={naaaa.numel()}'''	)
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0_0_0	)]
								if naaaaa.numel() > 0:
												print(f'''{ctx}: n10000={naaaaa.numel()}'''	)

				if 0:
								print(f'''min={var.min():9.2e} max={var.max():9.2e}'''	)

				if 0:
								print(f'''min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})'''	)

				return detected







class     snake_case	(			__UpperCAmelCase    ):




					"""simple docstring"""

					snake_case__       =			"underflow_overflow"
					snake_case__       =			"tpu_metrics_debug"



