

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







						def __init__(self  ,				UpperCAmelCase_  ,				UpperCAmelCase_=3_6_0_0_0  ,				UpperCAmelCase_=1_3  ,				UpperCAmelCase_=7  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_=3_2  ,				UpperCAmelCase_=4_2  ,				UpperCAmelCase_=5  ,				UpperCAmelCase_=2  ,				UpperCAmelCase_=4  ,				UpperCAmelCase_=2  ,				UpperCAmelCase_=3_2  ,				UpperCAmelCase_=8_0  ,				UpperCAmelCase_=3_3  ,				UpperCAmelCase_=0.0  ,				UpperCAmelCase_=1e-6  ,				UpperCAmelCase_=1_0_0  ,				UpperCAmelCase_=0.0  ,				)      ->    int:
											__lowercase        =      vocab_size
											__lowercase        =      parent
											__lowercase        =      batch_size
											__lowercase        =      num_contexts
											# For common tests
											__lowercase        =      self.num_contexts
											__lowercase        =      is_training
											__lowercase        =      hidden_size
											__lowercase        =      num_ext_layers
											__lowercase        =      ext_size
											__lowercase        =      num_hidden_layers
											__lowercase        =      num_attention_heads
											__lowercase        =      num_experts
											__lowercase        =      d_ff
											__lowercase        =      d_ext
											__lowercase        =      d_spout
											__lowercase        =      dropout_rate
											__lowercase        =      layer_norm_epsilon
											__lowercase        =      expert_capacity
											__lowercase        =      router_jitter_noise







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







						def 							_UpperCamelCase     (self				)      ->    str:
											__lowercase        =      ids_tensor([self.batch_size, self.seq_length]  ,				self.vocab_size				)

											__lowercase        =      self.get_config()

											return (config, input_ids)







						def 							_UpperCamelCase     (self				)      ->    str:
											__lowercase        =      ids_tensor([self.batch_size, self.seq_length]  ,				self.vocab_size				)

											__lowercase        =      self.get_config()

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







						def 							_UpperCamelCase     (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 							_UpperCamelCase     (self  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				)      ->    int:
											__lowercase        =      GPTSanJapaneseForConditionalGeneration(config=UpperCAmelCase_				)
											model.to(UpperCAmelCase_				)
											model.eval()
											__lowercase        =      model(
											    input_ids=UpperCAmelCase_  ,				)
											self.parent.assertIsNotNone(UpperCAmelCase_				)



@require_torch
class       _snake_case  (    UpperCamelCase    ,      UpperCamelCase    ,      unittest.TestCase							):
						__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 							_UpperCamelCase     (self  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_				)      ->    Tuple:
											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				)      ->    Any:
											__lowercase        =      GPTSanJapaneseTester(self				)
											__lowercase        =      ConfigTester(self  ,				config_class=UpperCAmelCase_  ,				d_model=3_7				)







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







						def 							_UpperCamelCase     (self				)      ->    str:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*UpperCAmelCase_				)







						@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]:
											super().test_model_parallelism()







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



@require_torch
class       _snake_case  (    UpperCamelCase    ,      UpperCamelCase    ,      unittest.TestCase							):
						__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 							_UpperCamelCase     (self				)      ->    List[Any]:
											__lowercase        =      GPTSanJapaneseTester(self				)
											__lowercase        =      ConfigTester(self  ,				config_class=UpperCAmelCase_  ,				d_model=3_7				)







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







						def 							_UpperCamelCase     (self				)      ->    Tuple:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*UpperCAmelCase_				)







						@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				)      ->    str:
											super().test_model_parallelism()







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







						@slow
						def 							_UpperCamelCase     (self				)      ->    int:
											__lowercase        =      GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											__lowercase        =      GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											__lowercase        =      tokenizer.encode('''武田信玄は'''  ,				return_tensors='''pt'''				)
											__lowercase        =      model(UpperCAmelCase_				)
											__lowercase        =      outputs.logits.detach().cpu().numpy()
											# Output of original model created with mesh-tensoflow
											__lowercase        =      [
											    # 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, -1_0.6_5_9_7_4_0_4_4_7_9_9_8_0_4_7, -1_2.9_0_9_5_7_4_5_0_8_6_6_6_9_9_2, -1_3.2_4_1_0_4_3_0_9_0_8_2_0_3_1_2, -1_3.3_9_8_5_7_9_5_9_7_4_7_3_1_4_5,
											    -1_1.1_0_7_5_2_4_8_7_1_8_2_6_1_7_2, -1_2.3_6_8_5_9_4_1_6_9_6_1_6_7, -2_2.9_7_9_4_3_1_1_5_2_3_4_3_7_5, -1_0.4_8_1_0_6_7_6_5_7_4_7_0_7_0_3, -1_2.4_8_4_0_3_0_7_2_3_5_7_1_7_7_7,
											    -1_2.8_0_7_3_6_0_6_4_9_1_0_8_8_8_7, -1_4.7_6_9_7_0_0_0_5_0_3_5_4_0_0_4, -1_2.2_3_3_5_7_9_6_3_5_6_2_0_1_1_7, -1_3.4_2_8_1_4_5_4_0_8_6_3_0_3_7_1, -2_2.6_2_4_1_7_7_9_3_2_7_3_9_2_5_8],
											    [-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, -1_9.5_6_5_6_9_8_6_2_3_6_5_7_2_2_7, -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, -1_0.8_5_6_5_6_9_2_9_0_1_6_1_1_3_3, -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, -1_9.5_1_5_3_2_7_4_5_3_6_1_3_2_8],
											    [-9.7_3_0_6_6_2_3_4_5_8_8_6_2_3, -1_0.2_2_3_9_2_2_7_2_9_4_9_2_1_8_8, -9.9_3_2_9_8_1_4_9_1_0_8_8_8_6_7, -1_1.8_5_7_8_3_6_7_2_3_3_2_7_6_3_7, -7.6_6_2_6_2_6_2_6_6_4_7_9_4_9_2,
											    -1_1.1_3_5_2_9_1_0_9_9_5_4_8_3_4, -7.7_6_5_0_9_7_6_1_8_1_0_3_0_2_7, -1_1.4_7_2_9_2_3_2_7_8_8_0_8_5_9_4, -9.5_4_3_1_4_9_9_4_8_1_2_0_1_1_7, -1_1.9_0_5_6_3_3_9_2_6_3_9_1_6_0_2,
											    -9.3_6_6_1_6_4_2_0_7_4_5_8_4_9_6, -1_1.5_7_3_4_2_8_1_5_3_9_9_1_7, -2_3.6_9_9_0_0_3_2_1_9_6_0_4_4_9_2, -9.4_2_9_5_9_0_2_2_5_2_1_9_7_2_7, -1_0.4_2_8_3_9_2_4_1_0_2_7_8_3_2,
											    -1_0.5_8_5_2_4_0_3_6_4_0_7_4_7_0_7, -1_0.9_4_7_7_1_9_5_7_3_9_7_4_6_1, -1_1.0_9_5_4_1_6_0_6_9_0_3_0_7_6_2, -1_0.3_9_0_2_4_0_6_6_9_2_5_0_4_8_8, -2_3.7_6_9_3_7_2_9_4_0_0_6_3_4_7_7],
											    [-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, -1_0.0_9_7_2_9_2_9_0_0_0_8_5_4_5, -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, -1_0.0_1_8_9_1_4_2_2_2_7_1_7_2_8_5, -9.3_0_8_4_4_5_9_3_0_4_8_0_9_5_7, -1_0.6_3_3_9_4_5_4_6_5_0_8_7_8_9,
											    -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, -2_1.9_0_4_2_6_6_3_5_7_4_2_1_8_7_5, -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,
											    -1_1.8_5_6_7_1_9_9_7_0_7_0_3_1_2_5, -1_2.0_7_9_3_9_8_1_5_5_2_1_2_4_0_2, -1_1.2_3_3_7_5_3_2_0_4_3_4_5_7_0_3, -1_0.1_7_7_3_3_8_6_0_0_1_5_8_6_9_1, -2_1.8_7_2_5_6_6_2_2_3_1_4_4_5_3],
											    [-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, -1_1.3_7_5_6_9_0_4_6_0_2_0_5_0_7_8,
											    -1_0.1_1_3_4_0_5_2_2_7_6_6_1_1_3_3, -1_0.5_4_6_8_6_7_3_7_0_6_0_5_4_6_9, -1_0.0_4_3_6_9_0_6_8_1_4_5_7_5_2, -1_0.9_0_7_8_0_9_2_5_7_5_0_7_3_2_4, -1_0.5_0_4_2_1_6_1_9_4_1_5_2_8_3_2,
											    -1_1.1_2_9_1_9_9_0_2_8_0_1_5_1_3_7, -1_0.1_5_1_1_2_4_0_0_0_5_4_9_3_1_6, -2_1.9_6_5_8_6_7_9_9_6_2_1_5_8_2, -9.0_8_6_3_4_9_4_8_7_3_0_4_6_8_8, -1_1.7_3_0_3_3_9_0_5_0_2_9_2_9_6_9,
											    -1_0.4_6_0_6_6_7_6_1_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
											]
											__lowercase        =      np.array(UpperCAmelCase_				).flatten()
											__lowercase        =      output_logits[0, :, :2_0].flatten()

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

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







						@slow
						def 							_UpperCamelCase     (self				)      ->    Tuple:
											__lowercase        =      GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											__lowercase        =      GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											model.to(UpperCAmelCase_				)

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

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

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

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

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

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

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

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

											__lowercase        =      tokenizer.batch_decode(UpperCAmelCase_  ,				skip_special_tokens=UpperCAmelCase_				)
											__lowercase        =      tokenizer.decode(output_non_padded[0]  ,				skip_special_tokens=UpperCAmelCase_				)
											__lowercase        =      tokenizer.decode(output_padded[0]  ,				skip_special_tokens=UpperCAmelCase_				)

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







						@tooslow
						def 							_UpperCamelCase     (self				)      ->    Optional[Any]:
											__lowercase        =      GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											__lowercase        =      GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											# Output of original model created with mesh-tensoflow
											__lowercase        =      [
											    ('''武田信玄は''', 3_5_6_7_5),
											    ('''武田信玄は、''', 4_5),
											    ('''武田信玄は、この''', 2_9),
											    ('''武田信玄は、このよう''', 3_0_6_4_2),
											    ('''武田信玄は、このような''', 3_5_6_8_0),
											    ('''武田信玄は、このような「''', 8_6_4_0),
											    ('''武田信玄は、このような「武田''', 3_1_6_1_7),
											    ('''武田信玄は、このような「武田家''', 3_0_6_4_6),
											    ('''武田信玄は、このような「武田家の''', 3_1_6_1_7),
											    ('''武田信玄は、このような「武田家の家''', 3_1_3_8_1),
											]
											for input, output in target:
																__lowercase        =      tokenizer.encode(UpperCAmelCase_  ,				return_tensors='''pt'''				)
																__lowercase        =      model(UpperCAmelCase_				)
																__lowercase        =      outputs.logits.detach().cpu().numpy()[0]
																__lowercase        =      np.argmax(output_logits[-1]				)
																self.assertEqual(UpperCAmelCase_  ,				UpperCAmelCase_				)







						@slow
						def 							_UpperCamelCase     (self				)      ->    List[Any]:
											__lowercase        =      GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											__lowercase        =      GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											model.to(UpperCAmelCase_				)

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

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

											# spout from uniform and one-hot
											__lowercase        =      [
											    # 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
											]

											__lowercase        =      model.generate(
											    input_ids=UpperCAmelCase_  ,				spout=spouts[0]  ,				max_new_tokens=2_0  ,				generation_config=UpperCAmelCase_  ,				)

											__lowercase        =      model.generate(
											    input_ids=UpperCAmelCase_  ,				spout=spouts[1]  ,				max_new_tokens=2_0  ,				generation_config=UpperCAmelCase_  ,				)

											__lowercase        =      model.generate(
											    input_ids=UpperCAmelCase_  ,				spout=UpperCAmelCase_  ,				max_new_tokens=2_0  ,				generation_config=UpperCAmelCase_  ,				)

											__lowercase        =      tokenizer.decode(outputa[0]				)
											__lowercase        =      tokenizer.decode(outputa[0]				)
											__lowercase        =      tokenizer.batch_decode(UpperCAmelCase_				)

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







						@slow
						def 							_UpperCamelCase     (self				)      ->    Optional[Any]:
											__lowercase        =      GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											__lowercase        =      GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''				)
											model.to(UpperCAmelCase_				)

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

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

											__lowercase        =      model.generate(
											    input_ids=input_tok_a.input_ids.to(UpperCAmelCase_				)  ,				token_type_ids=input_tok_a.token_type_ids.to(UpperCAmelCase_				)  ,				max_new_tokens=2_0  ,				generation_config=UpperCAmelCase_  ,				)

											__lowercase        =      model.generate(
											    input_ids=input_tok_a.input_ids.to(UpperCAmelCase_				)  ,				token_type_ids=input_tok_a.token_type_ids.to(UpperCAmelCase_				)  ,				max_new_tokens=2_0  ,				generation_config=UpperCAmelCase_  ,				)

											__lowercase        =      model.generate(
											    input_ids=input_tok_a.input_ids.to(UpperCAmelCase_				)  ,				token_type_ids=input_tok_a.token_type_ids.to(UpperCAmelCase_				)  ,				attention_mask=input_tok_a.attention_mask.to(UpperCAmelCase_				)  ,				max_new_tokens=2_0  ,				generation_config=UpperCAmelCase_  ,				)

											__lowercase        =      tokenizer.decode(outputa[0]				)
											__lowercase        =      tokenizer.decode(outputa[0]				)
											__lowercase        =      tokenizer.batch_decode(UpperCAmelCase_				)

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





"""simple docstring"""

import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

# Register SEW's fairseq modules
from sew_asapp import tasks  # noqa: F401

from transformers import (
    SEWDConfig,
    SEWDForCTC,
    SEWDModel,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
    logging,
)


logging.set_verbosity_info()
a__			:						int							=			logging.get_logger(__name__)

a__			:						Union[str, Any]							=			{
    """post_extract_proj""": """feature_projection""",
    """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""",
    """attention.self.query_proj""": """encoder.encoder.layer.*.attention.self.query_proj""",
    """attention.self.key_proj""": """encoder.encoder.layer.*.attention.self.key_proj""",
    """attention.self.value_proj""": """encoder.encoder.layer.*.attention.self.value_proj""",
    """attention.output.dense""": """encoder.encoder.layer.*.attention.output.dense""",
    """attention.output.LayerNorm""": """encoder.encoder.layer.*.attention.output.LayerNorm""",
    """intermediate.dense""": """encoder.encoder.layer.*.intermediate.dense""",
    """output.dense""": """encoder.encoder.layer.*.output.dense""",
    """output.LayerNorm""": """encoder.encoder.layer.*.output.LayerNorm""",
    """encoder.encoder.rel_embeddings""": """encoder.encoder.rel_embeddings""",
    """encoder.encoder.LayerNorm""": """encoder.encoder.LayerNorm""",
    """encoder.upsample.0""": """encoder.upsample.projection""",
    """encoder.layer_norm""": """encoder.layer_norm""",
    """w2v_model.layer_norm""": """layer_norm""",
    """w2v_encoder.proj""": """lm_head""",
    """mask_emb""": """masked_spec_embed""",
}





def 					__UpperCamelCase (     a__:			str			,						a__:			Any			,						a__:			Dict			,						a__:			List[str]			,						a__:			str      )					->      str:




					"""simple docstring"""



					for attribute in key.split('''.'''      ):
										__lowercase        =      getattr(a__			,						a__      )

					if weight_type is not None:
										__lowercase        =      getattr(a__			,						a__      ).shape
					else:
										__lowercase        =      hf_pointer.shape

					assert hf_shape == value.shape, (
					    f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
					    f''' {value.shape} for {full_name}'''
					)

					if weight_type == "weight":
										__lowercase        =      value
					elif weight_type == "weight_g":
										__lowercase        =      value
					elif weight_type == "weight_v":
										__lowercase        =      value
					elif weight_type == "bias":
										__lowercase        =      value
					else:
										__lowercase        =      value

					logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'''      )





def 					__UpperCamelCase (     a__:			Union[str, Any]			,						a__:			Optional[int]			,						a__:			Optional[Any]      )					->      Any:




					"""simple docstring"""



					__lowercase        =      []
					__lowercase        =      fairseq_model.state_dict()

					__lowercase        =      hf_model.sew_d.feature_extractor if is_finetuned else hf_model.feature_extractor

					for name, value in fairseq_dict.items():
										__lowercase        =      False
										if "conv_layers" in name:
															load_conv_layer(
															    a__			,						a__			,						a__			,						a__			,						hf_model.config.feat_extract_norm == '''group'''			,						)
															__lowercase        =      True
										else:
															for key, mapped_key in MAPPING.items():
																				__lowercase        =      '''sew_d.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key

																				if key in name or key.split('''w2v_model.'''      )[-1] == name.split('''.'''      )[0]:
																									__lowercase        =      True
																									if "*" in mapped_key:
																														__lowercase        =      name.split(a__      )[0].split('''.'''      )[-2]
																														if not layer_index.isnumeric():
																																			continue
																														__lowercase        =      mapped_key.replace('''*'''			,						a__      )
																									if "weight_g" in name:
																														__lowercase        =      '''weight_g'''
																									elif "weight_v" in name:
																														__lowercase        =      '''weight_v'''
																									elif "weight" in name:
																														__lowercase        =      '''weight'''
																									elif "bias" in name:
																														__lowercase        =      '''bias'''
																									else:
																														__lowercase        =      None
																									set_recursively(a__			,						a__			,						a__			,						a__			,						a__      )
																				continue
										if not is_used:
															unused_weights.append(a__      )

					logger.warning(f'''Unused weights: {unused_weights}'''      )





def 					__UpperCamelCase (     a__:			Optional[Any]			,						a__:			int			,						a__:			List[Any]			,						a__:			int			,						a__:			List[str]      )					->      Optional[Any]:




					"""simple docstring"""



					__lowercase        =      full_name.split('''conv_layers.'''      )[-1]
					__lowercase        =      name.split('''.'''      )
					__lowercase        =      int(items[0]      )
					__lowercase        =      int(items[1]      )

					if type_id == 0:
										if "bias" in name:
															assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
															    f'''{full_name} has size {value.shape}, but'''
															    f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
															)
															__lowercase        =      value
															logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''      )
										elif "weight" in name:
															assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
															    f'''{full_name} has size {value.shape}, but'''
															    f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
															)
															__lowercase        =      value
															logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''      )
					elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
										if "bias" in name:
															assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
															    f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
															    " found."
															)
															__lowercase        =      value
															logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''      )
										elif "weight" in name:
															assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
															    f'''{full_name} has size {value.shape}, but'''
															    f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
															)
															__lowercase        =      value
															logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''      )
					else:
										unused_weights.append(a__      )





def 					__UpperCamelCase (     a__:			Optional[Any]			,						a__:			List[str]      )					->      List[str]:




					"""simple docstring"""



					__lowercase        =      SEWDConfig()
					if is_finetuned:
										__lowercase        =      model.wav_encoder.wav_model.cfg
					else:
										__lowercase        =      model.cfg

					__lowercase        =      fs_config.conv_bias
					__lowercase        =      eval(fs_config.conv_feature_layers      )
					__lowercase        =      [x[0] for x in conv_layers]
					__lowercase        =      [x[1] for x in conv_layers]
					__lowercase        =      [x[2] for x in conv_layers]
					__lowercase        =      '''gelu'''
					__lowercase        =      '''layer''' if fs_config.extractor_mode == '''layer_norm''' else '''group'''
					__lowercase        =      0.0
					__lowercase        =      fs_config.activation_fn.name
					__lowercase        =      fs_config.encoder_embed_dim
					__lowercase        =      0.02
					__lowercase        =      fs_config.encoder_ffn_embed_dim
					__lowercase        =      1e-5
					__lowercase        =      fs_config.encoder_layerdrop
					__lowercase        =      fs_config.encoder_attention_heads
					__lowercase        =      fs_config.conv_pos_groups
					__lowercase        =      fs_config.conv_pos
					__lowercase        =      len(a__      )
					__lowercase        =      fs_config.encoder_layers
					__lowercase        =      fs_config.squeeze_factor
					# DeBERTa-specific parameters:
					__lowercase        =      fs_config.max_position_embeddings
					__lowercase        =      fs_config.position_buckets
					__lowercase        =      fs_config.share_att_key
					__lowercase        =      fs_config.relative_attention
					__lowercase        =      fs_config.position_biased_input
					__lowercase        =      tuple(fs_config.pos_att_type.split('''|'''      )      )
					__lowercase        =      fs_config.norm_rel_ebd

					# take care of any params that are overridden by the Wav2VecCtc model
					if is_finetuned:
										__lowercase        =      model.cfg
										__lowercase        =      fs_config.final_dropout
										__lowercase        =      fs_config.layerdrop
					__lowercase        =      fs_config.activation_dropout
					__lowercase        =      fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
					__lowercase        =      fs_config.attention_dropout
					__lowercase        =      fs_config.dropout_input
					__lowercase        =      fs_config.dropout
					__lowercase        =      fs_config.mask_channel_length
					__lowercase        =      fs_config.mask_channel_prob
					__lowercase        =      fs_config.mask_length
					__lowercase        =      fs_config.mask_prob

					__lowercase        =      '''Wav2Vec2FeatureExtractor'''
					__lowercase        =      '''Wav2Vec2CTCTokenizer'''

					return config





@torch.no_grad()
def 					__UpperCamelCase (     a__:			str			,						a__:			str			,						a__:			Optional[int]=None			,						a__:			str=None			,						a__:			Union[str, Any]=True      )					->      List[Any]:




					"""simple docstring"""



					if is_finetuned:
										__lowercase    ,			__lowercase    ,			__lowercase        =      fairseq.checkpoint_utils.load_model_ensemble_and_task(
										    [checkpoint_path]			,						arg_overrides={'''data''': '''/'''.join(dict_path.split('''/'''      )[:-1]      )}      )
					else:
										__lowercase    ,			__lowercase    ,			__lowercase        =      fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]      )

					if config_path is not None:
										__lowercase        =      SEWDConfig.from_pretrained(a__      )
					else:
										__lowercase        =      convert_config(model[0]			,						a__      )
					__lowercase        =      model[0].eval()

					__lowercase        =      True if config.feat_extract_norm == '''layer''' else False
					__lowercase        =      WavaVecaFeatureExtractor(
					    feature_size=1			,						sampling_rate=1_60_00			,						padding_value=0			,						do_normalize=a__			,						return_attention_mask=a__			,						)

					if is_finetuned:
										if dict_path:
															__lowercase        =      Dictionary.load(a__      )

															# important change bos & pad token id since CTC symbol is <pad> and
															# not <s> as in fairseq
															__lowercase        =      target_dict.pad_index
															__lowercase        =      target_dict.bos_index
															__lowercase        =      target_dict.pad_index
															__lowercase        =      target_dict.bos_index
															__lowercase        =      target_dict.eos_index
															__lowercase        =      len(target_dict.symbols      )
															__lowercase        =      os.path.join(a__			,						'''vocab.json'''      )
															if not os.path.isdir(a__      ):
																				logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(a__      )      )
																				return
															os.makedirs(a__			,						exist_ok=a__      )
															with open(a__			,						'''w'''			,						encoding='''utf-8'''      ) as vocab_handle:
																				json.dump(target_dict.indices			,						a__      )
															__lowercase        =      WavaVecaCTCTokenizer(
															    a__			,						unk_token=target_dict.unk_word			,						pad_token=target_dict.pad_word			,						bos_token=target_dict.bos_word			,						eos_token=target_dict.eos_word			,						word_delimiter_token='''|'''			,						do_lower_case=a__			,						)
															__lowercase        =      WavaVecaProcessor(feature_extractor=a__			,						tokenizer=a__      )
															processor.save_pretrained(a__      )

										__lowercase        =      SEWDForCTC(a__      )
					else:
										__lowercase        =      SEWDModel(a__      )
										feature_extractor.save_pretrained(a__      )

					recursively_load_weights(a__			,						a__			,						a__      )

					hf_model.save_pretrained(a__      )


if __name__ == "__main__":
							a__			:						Optional[Any]							=			argparse.ArgumentParser()
							parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
							parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""")
							parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""")
							parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
							parser.add_argument(
							    """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
							)
							a__			:						Union[str, Any]							=			parser.parse_args()
							convert_sew_checkpoint(
							    args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned
							)


