


"""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     A:

		"""simple docstring"""





		def __init__(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__=3_60_00				,							SCREAMING_SNAKE_CASE__=13				,							SCREAMING_SNAKE_CASE__=7				,							SCREAMING_SNAKE_CASE__=True				,							SCREAMING_SNAKE_CASE__=32				,							SCREAMING_SNAKE_CASE__=42				,							SCREAMING_SNAKE_CASE__=5				,							SCREAMING_SNAKE_CASE__=2				,							SCREAMING_SNAKE_CASE__=4				,							SCREAMING_SNAKE_CASE__=2				,							SCREAMING_SNAKE_CASE__=32				,							SCREAMING_SNAKE_CASE__=80				,							SCREAMING_SNAKE_CASE__=33				,							SCREAMING_SNAKE_CASE__=0.0				,							SCREAMING_SNAKE_CASE__=1E-6				,							SCREAMING_SNAKE_CASE__=1_00				,							SCREAMING_SNAKE_CASE__=0.0				,							)			->  str:

					"""simple docstring"""



					_UpperCamelCase				:Dict				    =  vocab_size
					_UpperCamelCase				:Union[str, Any]				    =  parent
					_UpperCamelCase				:int				    =  batch_size
					_UpperCamelCase				:List[Any]				    =  num_contexts
					# For common tests
					_UpperCamelCase				:List[Any]				    =  self.num_contexts
					_UpperCamelCase				:Optional[int]				    =  is_training
					_UpperCamelCase				:Union[str, Any]				    =  hidden_size
					_UpperCamelCase				:List[Any]				    =  num_ext_layers
					_UpperCamelCase				:Dict				    =  ext_size
					_UpperCamelCase				:Any				    =  num_hidden_layers
					_UpperCamelCase				:Optional[Any]				    =  num_attention_heads
					_UpperCamelCase				:int				    =  num_experts
					_UpperCamelCase				:Dict				    =  d_ff
					_UpperCamelCase				:List[str]				    =  d_ext
					_UpperCamelCase				:Tuple				    =  d_spout
					_UpperCamelCase				:Dict				    =  dropout_rate
					_UpperCamelCase				:List[str]				    =  layer_norm_epsilon
					_UpperCamelCase				:str				    =  expert_capacity
					_UpperCamelCase				:str				    =  router_jitter_noise
		def      _UpperCamelCase(   self      )			->  Any:

					"""simple docstring"""



					return GPTSanJapaneseConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
		def      _UpperCamelCase(   self      )			->  int:

					"""simple docstring"""



					_UpperCamelCase				:Union[str, Any]				    =  ids_tensor([self.batch_size, self.seq_length]				,							self.vocab_size      )

					_UpperCamelCase				:int				    =  self.get_config()

					return (config, input_ids)
		def      _UpperCamelCase(   self      )			->  Any:

					"""simple docstring"""



					_UpperCamelCase				:Optional[Any]				    =  ids_tensor([self.batch_size, self.seq_length]				,							self.vocab_size      )

					_UpperCamelCase				:Union[str, Any]				    =  self.get_config()

					return (config, {"input_ids": input_ids})
		def      _UpperCamelCase(   self      )			->  Optional[int]:

					"""simple docstring"""



					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      _UpperCamelCase(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							)			->  int:

					"""simple docstring"""



					_UpperCamelCase				:Tuple				    =  GPTSanJapaneseForConditionalGeneration(config=SCREAMING_SNAKE_CASE__      )
					model.to(SCREAMING_SNAKE_CASE__      )
					model.eval()
					_UpperCamelCase				:Optional[Any]				    =  model(
					    input_ids=SCREAMING_SNAKE_CASE__				,							)
					self.parent.assertIsNotNone(SCREAMING_SNAKE_CASE__      )






@require_torch
class     A(     lowerCamelCase__							,       lowerCamelCase__							,       unittest.TestCase		):

		"""simple docstring"""





		A         =       (GPTSanJapaneseModel,) if is_torch_available() else ()
		A         =       (
		    {
		        "conversational": GPTSanJapaneseForConditionalGeneration,
		        "feature-extraction": GPTSanJapaneseForConditionalGeneration,
		        "summarization": GPTSanJapaneseForConditionalGeneration,
		        "text2text-generation": GPTSanJapaneseForConditionalGeneration,
		        "translation": GPTSanJapaneseForConditionalGeneration,
		    }
		    if is_torch_available()
		    else {}
		)
		A         =       False
		A         =       False
		A         =       False
		A         =       False
		A         =       False
		A         =       False
		A         =       False
		A         =       False
		# The small GPTSAN_JAPANESE model needs higher percentages for CPU/MP tests
		A         =       [0.8, 0.9]
		def      _UpperCamelCase(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )			->  Any:

					"""simple docstring"""



					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      _UpperCamelCase(   self      )			->  Dict:

					"""simple docstring"""



					_UpperCamelCase				:Union[str, Any]				    =  GPTSanJapaneseTester(self      )
					_UpperCamelCase				:Union[str, Any]				    =  ConfigTester(self				,							config_class=SCREAMING_SNAKE_CASE__				,							d_model=37      )
		def      _UpperCamelCase(   self      )			->  Optional[int]:

					"""simple docstring"""



					GPTSanJapaneseConfig()
		def      _UpperCamelCase(   self      )			->  List[Any]:

					"""simple docstring"""



					_UpperCamelCase				:int				    =  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__      )
		@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      _UpperCamelCase(   self      )			->  Union[str, Any]:

					"""simple docstring"""



					super().test_model_parallelism()





		@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''      )
		def      _UpperCamelCase(   self      )			->  Optional[Any]:

					"""simple docstring"""



					pass






@require_torch
class     A(     lowerCamelCase__							,       lowerCamelCase__							,       unittest.TestCase		):

		"""simple docstring"""





		A         =       (GPTSanJapaneseForConditionalGeneration,) if is_torch_available() else ()
		A         =       False
		A         =       False
		A         =       False
		A         =       False
		A         =       False
		A         =       False
		# The small GPTSAN_JAPANESE model needs higher percentages for CPU/MP tests
		A         =       [0.8, 0.9]
		def      _UpperCamelCase(   self      )			->  Optional[int]:

					"""simple docstring"""



					_UpperCamelCase				:int				    =  GPTSanJapaneseTester(self      )
					_UpperCamelCase				:Dict				    =  ConfigTester(self				,							config_class=SCREAMING_SNAKE_CASE__				,							d_model=37      )
		def      _UpperCamelCase(   self      )			->  int:

					"""simple docstring"""



					GPTSanJapaneseConfig()
		def      _UpperCamelCase(   self      )			->  Tuple:

					"""simple docstring"""



					_UpperCamelCase				:Union[str, Any]				    =  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__      )
		@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      _UpperCamelCase(   self      )			->  Optional[int]:

					"""simple docstring"""



					super().test_model_parallelism()
		@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''      )
		def      _UpperCamelCase(   self      )			->  Any:

					"""simple docstring"""



					pass
		@slow
		def      _UpperCamelCase(   self      )			->  List[Any]:

					"""simple docstring"""



					_UpperCamelCase				:Optional[int]				    =  GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					_UpperCamelCase				:Optional[Any]				    =  GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					_UpperCamelCase				:Optional[int]				    =  tokenizer.encode('''武田信玄は'''				,							return_tensors='''pt'''      )
					_UpperCamelCase				:List[Any]				    =  model(SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:Optional[Any]				    =  outputs.logits.detach().cpu().numpy()
					# Output of original model created with mesh-tensoflow
					_UpperCamelCase				:Tuple				    =  [
					    # fmt: off
					    [-12.0_37_83_98_89_52_63_67, -12.4_33_06_15_99_73_14_45, -14.3_33_84_03_70_17_82_23, -12.4_50_34_59_93_04_19_92, -11.1_66_13_76_95_31_25,
					    -11.9_30_13_76_34_27_73_44, -10.6_59_74_04_47_99_80_47, -12.9_09_57_45_08_66_69_92, -13.2_41_04_30_90_82_03_12, -13.3_98_57_95_97_47_31_45,
					    -11.1_07_52_48_71_82_61_72, -12.3_68_59_41_69_61_67, -22.97_94_31_15_23_43_75, -10.4_81_06_76_57_47_07_03, -12.4_84_03_07_23_57_17_77,
					    -12.8_07_36_06_49_10_88_87, -14.7_69_70_00_50_35_40_04, -12.2_33_57_96_35_62_01_17, -13.4_28_14_54_08_63_03_71, -22.6_24_17_79_32_73_92_58],
					    [-7.5_1_1_1_4_9_8_8_3_2_7_0_2_6_4, -8.2_8_1_8_5_1_7_6_8_4_9_3_6_5_2, -7.9_4_3_1_2_7_1_5_5_3_0_3_9_5_5, -7.5_5_0_2_1_3_3_3_6_9_4_4_5_8, -6.4_9_8_6_9_9_6_6_5_0_6_9_5_8,
					    -7.5_8_6_7_9_6_2_8_3_7_2_1_9_2_4, -6.9_7_8_0_8_5_9_9_4_7_2_0_4_5_9, -7.8_3_9_1_4_5_1_8_3_5_6_3_2_3_2, -8.2_1_9_6_4_1_6_8_5_4_8_5_8_4, -8.6_9_5_0_9_1_2_4_7_5_5_8_5_9_4,
					    -6.7_0_6_9_1_0_6_1_0_1_9_8_9_7_5, -6.6_5_8_5_7_9_8_2_6_3_5_4_9_8_0_5, -19.5_65_69_86_23_65_72_27, -5.3_5_3_8_4_2_7_3_5_2_9_0_5_2_7, -8.3_5_0_6_8_6_0_7_3_3_0_3_2_2_3,
					    -8.0_3_9_3_8_8_6_5_6_6_1_6_2_1_1, -10.8_56_56_92_90_16_11_33, -7.7_5_1_5_4_4_4_7_5_5_5_5_4_2, -8.8_1_9_0_2_2_1_7_8_6_4_9_9_0_2, -19.51_53_27_45_36_13_28],
					    [-9.7_3_0_6_6_2_3_4_5_8_8_6_2_3, -10.2_23_92_27_29_49_21_88, -9.9_3_2_9_8_1_4_9_1_0_8_8_8_6_7, -11.8_57_83_67_23_32_76_37, -7.6_6_2_6_2_6_2_6_6_4_7_9_4_9_2,
					    -11.13_52_91_09_95_48_34, -7.7_6_5_0_9_7_6_1_8_1_0_3_0_2_7, -11.4_72_92_32_78_80_85_94, -9.5_4_3_1_4_9_9_4_8_1_2_0_1_1_7, -11.9_05_63_39_26_39_16_02,
					    -9.3_6_6_1_6_4_2_0_7_4_5_8_4_9_6, -11.5_73_42_81_53_99_17, -23.6_99_00_32_19_60_44_92, -9.4_2_9_5_9_0_2_2_5_2_1_9_7_2_7, -10.42_83_92_41_02_78_32,
					    -10.5_85_24_03_64_07_47_07, -10.94_77_19_57_39_74_61, -11.0_95_41_60_69_03_07_62, -10.3_90_24_06_69_25_04_88, -23.7_69_37_29_40_06_34_77],
					    [-9.7_2_8_2_6_5_7_6_2_3_2_9_1_0_2, -9.8_5_9_7_1_2_6_0_0_7_0_8_0_0_8, -10.09_72_92_90_00_85_45, -9.6_7_8_5_2_2_1_0_9_9_8_5_3_5_2, -6.8_7_9_5_1_9_9_3_9_4_2_2_6_0_7,
					    -9.6_8_4_8_7_5_4_8_8_2_8_1_2_5, -4.2_8_0_3_4_2_5_7_8_8_8_7_9_3_9_5, -10.0_18_91_42_22_71_72_85, -9.3_0_8_4_4_5_9_3_0_4_8_0_9_5_7, -10.63_39_45_46_50_87_89,
					    -8.0_8_3_6_4_6_7_7_4_2_9_1_9_9_2, -9.0_6_3_0_1_4_9_8_4_1_3_0_8_6, -21.9_04_26_63_57_42_18_75, -8.9_0_1_6_0_8_4_6_7_1_0_2_0_5, -8.8_4_1_8_7_6_0_2_9_9_6_8_2_6_2,
					    -11.8_56_71_99_70_70_31_25, -12.0_79_39_81_55_21_24_02, -11.2_33_75_32_04_34_57_03, -10.1_77_33_86_00_15_86_91, -21.87_25_66_22_31_44_53],
					    [-9.6_6_9_7_6_4_5_1_8_7_3_7_7_9_3, -9.6_1_4_1_9_8_6_8_4_6_9_2_3_8_3, -9.8_1_4_5_1_0_3_4_5_4_5_8_9_8_4, -9.9_9_6_5_0_1_9_2_2_6_0_7_4_2_2, -11.3_75_69_04_60_20_50_78,
					    -10.1_13_40_52_27_66_11_33, -10.5_46_86_73_70_60_54_69, -10.04_36_90_68_14_57_52, -10.9_07_80_92_57_50_73_24, -10.5_04_21_61_94_15_28_32,
					    -11.1_29_19_90_28_01_51_37, -10.1_51_12_40_00_54_93_16, -21.96_58_67_99_62_15_82, -9.0_8_6_3_4_9_4_8_7_3_0_4_6_8_8, -11.7_30_33_90_50_29_29_69,
					    -10.4_60_66_76_10_16_84_57, -10.2_98_04_99_26_75_78_12, -10.7_84_14_82_16_24_75_59, -10.8_40_69_34_73_81_59_18, -22.03_15_28_47_29_00_39],
					    # fmt: on
					]
					_UpperCamelCase				:Union[str, Any]				    =  np.array(SCREAMING_SNAKE_CASE__      ).flatten()
					_UpperCamelCase				:Union[str, Any]				    =  output_logits[0, :, :20].flatten()

					def check(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__=5E-4      ):
								return abs(a - b      ) < epsilon * max(abs(SCREAMING_SNAKE_CASE__      )				,							abs(SCREAMING_SNAKE_CASE__      )      )

					self.assertTrue(np.all([check(target[i]				,							predict[i]      ) for i in range(len(SCREAMING_SNAKE_CASE__      )      )]      )      )
		@slow
		def      _UpperCamelCase(   self      )			->  Any:

					"""simple docstring"""



					_UpperCamelCase				:Dict				    =  GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					_UpperCamelCase				:Optional[Any]				    =  GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					model.to(SCREAMING_SNAKE_CASE__      )

					# set deterministically
					_UpperCamelCase				:Dict				    =  GenerationConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					_UpperCamelCase				:List[str]				    =  1

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

					_UpperCamelCase				:Optional[Any]				    =  '''left'''
					_UpperCamelCase				:int				    =  tokenizer(SCREAMING_SNAKE_CASE__				,							return_tensors='''pt'''				,							padding=SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:Dict				    =  inputs['''input_ids'''].to(SCREAMING_SNAKE_CASE__      )

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

					_UpperCamelCase				:List[str]				    =  model.generate(
					    input_ids=SCREAMING_SNAKE_CASE__				,							attention_mask=inputs['''attention_mask'''].to(SCREAMING_SNAKE_CASE__      )				,							max_new_tokens=3				,							generation_config=SCREAMING_SNAKE_CASE__				,							)

					_UpperCamelCase				:Dict				    =  tokenizer(sentences[0]				,							return_tensors='''pt'''      ).input_ids.to(SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:Optional[int]				    =  model.generate(
					    input_ids=SCREAMING_SNAKE_CASE__				,							max_new_tokens=3				,							generation_config=SCREAMING_SNAKE_CASE__      )

					_UpperCamelCase				:Any				    =  tokenizer(sentences[1]				,							return_tensors='''pt'''      ).input_ids.to(SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:Tuple				    =  model.generate(input_ids=SCREAMING_SNAKE_CASE__				,							max_new_tokens=3				,							generation_config=SCREAMING_SNAKE_CASE__      )

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

					_UpperCamelCase				:List[Any]				    =  tokenizer.batch_decode(SCREAMING_SNAKE_CASE__				,							skip_special_tokens=SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:Union[str, Any]				    =  tokenizer.decode(output_non_padded[0]				,							skip_special_tokens=SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:List[str]				    =  tokenizer.decode(output_padded[0]				,							skip_special_tokens=SCREAMING_SNAKE_CASE__      )

					_UpperCamelCase				:Union[str, Any]				    =  [
					    '''甲斐なら武田と言うほど甲斐の武田''',
					    '''織田信長は、このような''',
					]
					self.assertListEqual(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )
					self.assertListEqual(SCREAMING_SNAKE_CASE__				,							[non_padded_sentence, padded_sentence]      )
		@tooslow
		def      _UpperCamelCase(   self      )			->  str:

					"""simple docstring"""



					_UpperCamelCase				:str				    =  GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					_UpperCamelCase				:Dict				    =  GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					# Output of original model created with mesh-tensoflow
					_UpperCamelCase				:str				    =  [
					    ('''武田信玄は''', 3_56_75),
					    ('''武田信玄は、''', 45),
					    ('''武田信玄は、この''', 29),
					    ('''武田信玄は、このよう''', 3_06_42),
					    ('''武田信玄は、このような''', 3_56_80),
					    ('''武田信玄は、このような「''', 86_40),
					    ('''武田信玄は、このような「武田''', 3_16_17),
					    ('''武田信玄は、このような「武田家''', 3_06_46),
					    ('''武田信玄は、このような「武田家の''', 3_16_17),
					    ('''武田信玄は、このような「武田家の家''', 3_13_81),
					]
					for input, output in target:
								_UpperCamelCase				:Any				    =  tokenizer.encode(SCREAMING_SNAKE_CASE__				,							return_tensors='''pt'''      )
								_UpperCamelCase				:Any				    =  model(SCREAMING_SNAKE_CASE__      )
								_UpperCamelCase				:Any				    =  outputs.logits.detach().cpu().numpy()[0]
								_UpperCamelCase				:Optional[int]				    =  np.argmax(output_logits[-1]      )
								self.assertEqual(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )
		@slow
		def      _UpperCamelCase(   self      )			->  Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase				:Tuple				    =  GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					_UpperCamelCase				:Any				    =  GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					model.to(SCREAMING_SNAKE_CASE__      )

					# set deterministically
					_UpperCamelCase				:Any				    =  GenerationConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					_UpperCamelCase				:Tuple				    =  1

					_UpperCamelCase				:Tuple				    =  '''武田信玄は、'''
					_UpperCamelCase				:Union[str, Any]				    =  tokenizer(SCREAMING_SNAKE_CASE__				,							return_tensors='''pt'''      ).input_ids.to(SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:Optional[Any]				    =  tokenizer([input_text, input_text]				,							return_tensors='''pt'''      ).input_ids.to(SCREAMING_SNAKE_CASE__      )

					# spout from uniform and one-hot
					_UpperCamelCase				:str				    =  [
					    # 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_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# 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				:int				    =  model.generate(
					    input_ids=SCREAMING_SNAKE_CASE__				,							spout=spouts[0]				,							max_new_tokens=20				,							generation_config=SCREAMING_SNAKE_CASE__				,							)

					_UpperCamelCase				:Any				    =  model.generate(
					    input_ids=SCREAMING_SNAKE_CASE__				,							spout=spouts[1]				,							max_new_tokens=20				,							generation_config=SCREAMING_SNAKE_CASE__				,							)

					_UpperCamelCase				:Optional[Any]				    =  model.generate(
					    input_ids=SCREAMING_SNAKE_CASE__				,							spout=SCREAMING_SNAKE_CASE__				,							max_new_tokens=20				,							generation_config=SCREAMING_SNAKE_CASE__				,							)

					_UpperCamelCase				:str				    =  tokenizer.decode(outputa[0]      )
					_UpperCamelCase				:Dict				    =  tokenizer.decode(outputa[0]      )
					_UpperCamelCase				:Optional[int]				    =  tokenizer.batch_decode(SCREAMING_SNAKE_CASE__      )

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





		@slow
		def      _UpperCamelCase(   self      )			->  Any:

					"""simple docstring"""



					_UpperCamelCase				:Any				    =  GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					_UpperCamelCase				:List[Any]				    =  GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					model.to(SCREAMING_SNAKE_CASE__      )

					# set deterministically
					_UpperCamelCase				:str				    =  GenerationConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''      )
					_UpperCamelCase				:int				    =  1

					_UpperCamelCase				:int				    =  '''武田信玄'''
					_UpperCamelCase				:List[str]				    =  '''織田信長'''
					_UpperCamelCase				:Optional[int]				    =  '''は、'''
					_UpperCamelCase				:Optional[int]				    =  '''が、'''
					_UpperCamelCase				:Tuple				    =  tokenizer(SCREAMING_SNAKE_CASE__				,							prefix_text=SCREAMING_SNAKE_CASE__				,							return_tensors='''pt'''      )
					_UpperCamelCase				:str				    =  tokenizer(SCREAMING_SNAKE_CASE__				,							prefix_text=SCREAMING_SNAKE_CASE__				,							return_tensors='''pt'''      )
					_UpperCamelCase				:List[str]				    =  tokenizer([[prefix_text_a, input_text_a], [prefix_text_a, input_text_a]]				,							return_tensors='''pt'''      )

					_UpperCamelCase				:Any				    =  model.generate(
					    input_ids=input_tok_a.input_ids.to(SCREAMING_SNAKE_CASE__      )				,							token_type_ids=input_tok_a.token_type_ids.to(SCREAMING_SNAKE_CASE__      )				,							max_new_tokens=20				,							generation_config=SCREAMING_SNAKE_CASE__				,							)

					_UpperCamelCase				:List[Any]				    =  model.generate(
					    input_ids=input_tok_a.input_ids.to(SCREAMING_SNAKE_CASE__      )				,							token_type_ids=input_tok_a.token_type_ids.to(SCREAMING_SNAKE_CASE__      )				,							max_new_tokens=20				,							generation_config=SCREAMING_SNAKE_CASE__				,							)

					_UpperCamelCase				:Optional[int]				    =  model.generate(
					    input_ids=input_tok_a.input_ids.to(SCREAMING_SNAKE_CASE__      )				,							token_type_ids=input_tok_a.token_type_ids.to(SCREAMING_SNAKE_CASE__      )				,							attention_mask=input_tok_a.attention_mask.to(SCREAMING_SNAKE_CASE__      )				,							max_new_tokens=20				,							generation_config=SCREAMING_SNAKE_CASE__				,							)

					_UpperCamelCase				:Tuple				    =  tokenizer.decode(outputa[0]      )
					_UpperCamelCase				:int				    =  tokenizer.decode(outputa[0]      )
					_UpperCamelCase				:List[str]				    =  tokenizer.batch_decode(SCREAMING_SNAKE_CASE__      )

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







"""simple docstring"""






import argparse

# utilities to import the model weights and config file
import os
import pickle as pkl

# PyTorch + new model classes
import torch
from torch import nn

from transformers import AutoTokenizer, MegaConfig, MegaForMaskedLM


# import the EncoderLayer class used to pretrain
# !! NOTE !! this requires the version of fairseq that is built when you install the Mega source
try:
					from fairseq.modules.mega_layer import MegaEncoderLayer
except ImportError:
					raise ImportError("""You need to install the version of fairseq from the Mega repo!""")






class     A(     nn.Module		):

		"""simple docstring"""





		def __init__(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )			->  Optional[int]:

					"""simple docstring"""



					super().__init__()
					_UpperCamelCase				:List[str]				    =  mega_args
					_UpperCamelCase				:Dict				    =  nn.Embedding(SCREAMING_SNAKE_CASE__				,							self.mega_args.encoder_embed_dim      )
					_UpperCamelCase				:Optional[Any]				    =  nn.ModuleList([MegaEncoderLayer(self.mega_args      ) for _ in range(SCREAMING_SNAKE_CASE__      )]      )
					_UpperCamelCase				:Tuple				    =  depth





		def      _UpperCamelCase(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__=True				,							SCREAMING_SNAKE_CASE__=0      )			->  Dict:

					"""simple docstring"""



					if batch_first:
								_UpperCamelCase				:Tuple				    =  input_ids.T

					# to make things more confusing, Mega expects the attention mask to
					# be (batch, time), but with values of 0 (normal token) and 1 (ignore token)
					# which is the opposite of what HF returns
					if ignore_mask_value == 0:
								_UpperCamelCase				:str				    =  1 - attention_mask

					# get token embeddings from IDs
					_UpperCamelCase				:Union[str, Any]				    =  self.embedding_layer(SCREAMING_SNAKE_CASE__      )

					# pass through the Mega layers
					# input is (time, batch, encoder dim) and output is the same
					for encoder in self.encoders:
								_UpperCamelCase				:Union[str, Any]				    =  encoder(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )

					# return according to the shape specified
					if batch_first:
								# (T, B, H) --> (B, T, H)
								return torch.transpose(SCREAMING_SNAKE_CASE__				,							0				,							1      )
					else:
								return embeds






class     A(     nn.Module		):

		"""simple docstring"""





		def __init__(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )			->  Any:

					"""simple docstring"""



					super().__init__()
					_UpperCamelCase				:Dict				    =  MegaLM(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:str				    =  nn.Linear(mega_args.encoder_embed_dim				,							SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:int				    =  nn.Dropout(p=0.1      )





		def      _UpperCamelCase(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__=True				,							SCREAMING_SNAKE_CASE__=0      )			->  int:

					"""simple docstring"""



					_UpperCamelCase				:List[Any]				    =  self.mega(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )
					return self.mlm_head(self.dropout(SCREAMING_SNAKE_CASE__      )      )





def 							A_					(   snake_case__					,				snake_case__					,				snake_case__		)				->     Union[str, Any]:
			with open(os.path.join(snake_case__					,				'''model_args.pkl'''		)					,				'''rb'''		) as f:
						_UpperCamelCase				:List[str]				    =  pkl.load(snake_case__		)

			# load the original encoder
			_UpperCamelCase				:Tuple				    =  OriginalMegaForMaskedLM(**snake_case__		).eval()

			# load its weights
			print(
			    '''Original Mega encoder:'''					,				original_mlm.mega.load_state_dict(
			        torch.load(os.path.join(snake_case__					,				'''encoder_weights.pt'''		)					,				map_location='''cpu'''		)		)					,				)
			print(
			    '''Original Mega MLM layer:'''					,				original_mlm.mlm_head.load_state_dict(
			        torch.load(os.path.join(snake_case__					,				'''mlm_head_weights.pt'''		)					,				map_location='''cpu'''		)		)					,				)

			# create a new config from the old one
			_UpperCamelCase				:Optional[int]				    =  MegaConfig(
			    num_hidden_layers=mega_original_args['''depth''']					,				vocab_size=mega_original_args['''vocab_size''']					,				hidden_size=mega_original_args['''mega_args'''].encoder_embed_dim					,				shared_representation_size=mega_original_args['''mega_args'''].encoder_z_dim					,				intermediate_size=mega_original_args['''mega_args'''].encoder_hidden_dim					,				ema_projection_size=mega_original_args['''mega_args'''].encoder_n_dim					,				dropout_prob=mega_original_args['''mega_args'''].dropout					,				attention_probs_dropout_prob=mega_original_args['''mega_args'''].attention_dropout					,				hidden_dropout_prob=mega_original_args['''mega_args'''].hidden_dropout					,				activation=mega_original_args['''mega_args'''].activation_fn					,				attention_activation=mega_original_args['''mega_args'''].attention_activation_fn					,				bidirectional=mega_original_args['''mega_args'''].bidirectional					,				use_chunking=mega_original_args['''mega_args'''].encoder_chunk_size > 0					,				chunk_size=mega_original_args['''mega_args'''].encoder_chunk_size					,				truncation=mega_original_args['''mega_args'''].truncation_length					,				normalization_type=mega_original_args['''mega_args'''].normalization_type					,				normalize_before_mega=snake_case__					,				norm_affine=snake_case__					,				use_feature_dropout=mega_original_args['''mega_args'''].feature_dropout					,				relative_positional_bias=mega_original_args['''mega_args'''].rel_pos_bias					,				max_positions=mega_original_args['''mega_args'''].max_source_positions					,				nffn_hidden_size=mega_original_args['''mega_args'''].encoder_ffn_embed_dim					,				normalize_before_ffn=mega_original_args['''mega_args'''].normalize_before					,				nffn_activation_dropout_prob=0.0					,				add_token_type_embeddings=snake_case__					,				add_lm_hidden_dense_layer=snake_case__					,				)

			_UpperCamelCase				:Optional[Any]				    =  MegaForMaskedLM(snake_case__		).eval()

			# the originl checkpoint just uses nn.Embedding for the word embeddings
			# we use a wrapper module for embeddings to add support for positional embeddings
			_UpperCamelCase				:Dict				    =  original_mlm.mega.embedding_layer.weight

			# modify the state dictionary of the original checkpoint to account for naming issues in the Hugging Face
			# ecosystem -- any names containing "beta" or "gamma" aren't safe to use and are renamed upon _load_pretrained,
			# also renaming previously confusing parameter names
			_UpperCamelCase				:Union[str, Any]				    =  original_mlm.mega.encoders.state_dict()
			_UpperCamelCase				:List[str]				    =  {}
			for module_name in original_state_dict.keys():
						_UpperCamelCase				:Any				    =  None
						# have to handle gamma, beta, and alpha differently due to their use
						# in multiple modules within the original repository;
						# beta is used in EMA, MovingAverageGatedAttention, and RotaryRelativePositionalBias, and must be renamed due to flax/tf weights
						# the EMA sublayer was renamed from "move" to "ema_gate" for readability, so that is also done here
						if "beta" in module_name:
									# EMA sub-layers were always called "move" in the original repo
									if "move.beta" in module_name:
												_UpperCamelCase				:List[Any]				    =  module_name.replace('''move.beta'''					,				'''ema_gate.ema_expansion_matrix'''		)
									elif "mega_layer.beta" in module_name:
												_UpperCamelCase				:List[str]				    =  module_name.replace('''beta'''					,				'''qk_bias'''		)
									else:
												_UpperCamelCase				:Union[str, Any]				    =  module_name.replace('''beta'''					,				'''b_param'''		)
        # beta is used in EMA and MovingAverageGatedAttention, and must be renamed due to flax/tf weights
						elif "gamma" in module_name:
									if "move.gamma" in module_name:
												_UpperCamelCase				:List[str]				    =  module_name.replace('''move.gamma'''					,				'''ema_gate.kernel_projection_matrix'''		)
									elif "mega_layer.gamma" in module_name:
												_UpperCamelCase				:str				    =  module_name.replace('''gamma'''					,				'''qk_weight'''		)
									else:
												_UpperCamelCase				:List[str]				    =  module_name.replace('''gamma'''					,				'''g_param'''		)
        # alpha is used in EMA and positional bias; renaming to improve readability
						elif "move.alpha" in module_name:
									_UpperCamelCase				:Optional[Any]				    =  module_name.replace('''move.alpha'''					,				'''ema_gate.decay_factor'''		)
						# delta is only used in EMA; renaming to improve readability
						elif "move.delta" in module_name:
									_UpperCamelCase				:Union[str, Any]				    =  module_name.replace('''move.delta'''					,				'''ema_gate.damping_factor'''		)
						# omega is only used in EMA; renaming to improve readability
						elif "omega" in module_name:
									_UpperCamelCase				:int				    =  module_name.replace('''move.omega'''					,				'''ema_gate.residual_weight'''		)

						if new_module_name:
									_UpperCamelCase				:List[Any]				    =  new_module_name

			if len(snake_case__		) != 0:
						print(f"Renaming these keys: {updated_keys.keys()}"		)
			else:
						print('''No need to rename state dict entries'''		)
			for old, new in updated_keys.items():
						_UpperCamelCase				:List[str]				    =  original_state_dict.pop(snake_case__		)

			# now attempt to load the state dictionary with updated names
			# note that we now call it `mega.layers` instead of `mega.encoders` due to hugging face style
			print('''HF Mega encoder:'''					,				hf_mlm.mega.layers.load_state_dict(snake_case__		)		)

			# load the MLM head weights directly
			print(
			    '''HF Mega MLM layer:'''					,				hf_mlm.mlm_head.load_state_dict(
			        torch.load(os.path.join(snake_case__					,				'''mlm_head_weights.pt'''		)					,				map_location='''cpu'''		)		)					,				)

			# test on a randomly generated input sequence
			_UpperCamelCase				:Dict				    =  torch.randint(0					,				hf_config.vocab_size					,				size=(4, 2_56)		)
			_UpperCamelCase				:Tuple				    =  torch.ones_like(snake_case__		)
			# mask a few tokens to make sure masking is applied appropriately :)
			_UpperCamelCase				:str				    =  0

			# run forward passes
			_UpperCamelCase				:str				    =  original_mlm(snake_case__					,				snake_case__					,				batch_first=snake_case__					,				ignore_mask_value=0		)
			_UpperCamelCase				:str				    =  hf_mlm(snake_case__					,				snake_case__		)[0]

			# print shapes and diff
			print(f"original output {original_output.shape}"		)
			print(f"hf output {hf_output.shape}"		)
			print(f"max diff: {(original_output - hf_output).max()}"		)  # 0.0
			_UpperCamelCase				:str				    =  torch.allclose(snake_case__					,				snake_case__					,				atol=1E-3		)

			if success:
						print('''Yay!'''		)
						hf_mlm.save_pretrained(snake_case__		)
			else:
						raise RuntimeError(f"Something's broken :(\nOriginal:\n{original_output}\n\nHF\n{hf_output}\n{hf_mlm}"		)

			if includes_tokenizer:
						print('''Transferring tokenizer'''		)
						_UpperCamelCase				:Optional[Any]				    =  AutoTokenizer.from_pretrained(snake_case__		)
						tokenizer.save_pretrained(snake_case__		)


if __name__ == "__main__":
					UpperCamelCase__							:Optional[int]       =  argparse.ArgumentParser()

					parser.add_argument(
					    """--pretrained_checkpoint_path""",
					    default=None,
					    type=str,
					    required=True,
					    help="""Point to the directory containing your model weights using the official Mega repo""",
					)

					parser.add_argument(
					    """--output_path""", default=None, type=str, required=True, help="""Location to save the Hugging Face version"""
					)

					parser.add_argument(
					    """--includes_tokenizer""",
					    action="""store_true""",
					    help="""Use this flag if there is a Hugging Face tokenizer in the original checkpoint repo""",
					)

					UpperCamelCase__							:Dict       =  parser.parse_args()

					convert_checkpoint_to_huggingface(args.pretrained_checkpoint_path, args.output_path, args.includes_tokenizer)

