




'''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 	SCREAMING_SNAKE_CASE_		:



 def __init__(	self ,		A ,		A=36000 ,		A=13 ,		A=7 ,		A=True ,		A=32 ,		A=42 ,		A=5 ,		A=2 ,		A=4 ,		A=2 ,		A=32 ,		A=80 ,		A=33 ,		A=0.0 ,		A=1E-6 ,		A=100 ,		A=0.0 ,		):






        '''simple docstring'''




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



 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        return GPTSanJapaneseConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''			)



 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




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

        lowercase	:		str    =   self.get_config()

        return (config, input_ids)



 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        lowercase	:		Tuple    =   ids_tensor([self.batch_size, self.seq_length] ,		self.vocab_size			)

        lowercase	:		Optional[int]    =   self.get_config()

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



 def  SCREAMING_SNAKE_CASE(	self			):






        '''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  SCREAMING_SNAKE_CASE(	self ,		A ,		A ,		):






        '''simple docstring'''




        lowercase	:		Tuple    =   GPTSanJapaneseForConditionalGeneration(config=A			)
        model.to(A			)
        model.eval()
        lowercase	:		Union[str, Any]    =   model(
            input_ids=A ,		)
        self.parent.assertIsNotNone(A			)






@require_torch
class 	SCREAMING_SNAKE_CASE_		(							lowerCamelCase_		,  lowerCamelCase_		,  unittest.TestCase					):
 __snake_case						:  Any       =   (GPTSanJapaneseModel,) if is_torch_available() else ()
 __snake_case						:  List[str]       =   (
     {
         "conversational": GPTSanJapaneseForConditionalGeneration,
         "feature-extraction": GPTSanJapaneseForConditionalGeneration,
         "summarization": GPTSanJapaneseForConditionalGeneration,
         "text2text-generation": GPTSanJapaneseForConditionalGeneration,
         "translation": GPTSanJapaneseForConditionalGeneration,
     }
     if is_torch_available()
     else {}
 )
 __snake_case						:  List[Any]       =   False
 __snake_case						:  int       =   False
 __snake_case						:  Tuple       =   False
 __snake_case						:  Tuple       =   False
 __snake_case						:  Any       =   False
 __snake_case						:  List[Any]       =   False
 __snake_case						:  Tuple       =   False
 __snake_case						:  Optional[int]       =   False
 # The small GPTSAN_JAPANESE model needs higher percentages for CPU/MP tests
 __snake_case						:  Any       =   [0.8, 0.9]



 def  SCREAMING_SNAKE_CASE(	self ,		A ,		A ,		A ,		A ,		A			):






        '''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  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        lowercase	:		Union[str, Any]    =   GPTSanJapaneseTester(self			)
        lowercase	:		Dict    =   ConfigTester(self ,		config_class=A ,		d_model=37			)



 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        GPTSanJapaneseConfig()



 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        lowercase	:		Any    =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A			)



 @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  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        super().test_model_parallelism()





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






        '''simple docstring'''




        pass






@require_torch
class 	SCREAMING_SNAKE_CASE_		(							lowerCamelCase_		,  lowerCamelCase_		,  unittest.TestCase					):
 __snake_case						:  Tuple       =   (GPTSanJapaneseForConditionalGeneration,) if is_torch_available() else ()
 __snake_case						:  str       =   False
 __snake_case						:  Any       =   False
 __snake_case						:  str       =   False
 __snake_case						:  Union[str, Any]       =   False
 __snake_case						:  Dict       =   False
 __snake_case						:  List[Any]       =   False
 # The small GPTSAN_JAPANESE model needs higher percentages for CPU/MP tests
 __snake_case						:  Tuple       =   [0.8, 0.9]



 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        lowercase	:		Tuple    =   GPTSanJapaneseTester(self			)
        lowercase	:		Any    =   ConfigTester(self ,		config_class=A ,		d_model=37			)



 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        GPTSanJapaneseConfig()



 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        lowercase	:		Optional[Any]    =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A			)



 @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  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        super().test_model_parallelism()



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






        '''simple docstring'''




        pass



 @slow
 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        lowercase	:		Union[str, Any]    =   GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''			)
        lowercase	:		int    =   GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''			)
        lowercase	:		Any    =   tokenizer.encode('''武田信玄は''' ,		return_tensors='''pt'''			)
        lowercase	:		int    =   model(A			)
        lowercase	:		List[str]    =   outputs.logits.detach().cpu().numpy()
        # Output of original model created with mesh-tensoflow
        lowercase	:		Tuple    =   [
            # 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_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8_4_7_2_9_0_0_3_9],
            # fmt: on
        ]
        lowercase	:		int    =   np.array(A			).flatten()
        lowercase	:		Optional[Any]    =   output_logits[0, :, :20].flatten()

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

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



 @slow
 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        lowercase	:		str    =   GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''			)
        lowercase	:		Any    =   GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''			)
        model.to(A			)

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

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

        lowercase	:		List[Any]    =   '''left'''
        lowercase	:		Any    =   tokenizer(A ,		return_tensors='''pt''' ,		padding=A			)
        lowercase	:		Tuple    =   inputs['''input_ids'''].to(A			)

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

        lowercase	:		Optional[int]    =   model.generate(
            input_ids=A ,		attention_mask=inputs['''attention_mask'''].to(A			) ,		max_new_tokens=3 ,		generation_config=A ,		)

        lowercase	:		List[str]    =   tokenizer(sentences[0] ,		return_tensors='''pt'''			).input_ids.to(A			)
        lowercase	:		Optional[int]    =   model.generate(
            input_ids=A ,		max_new_tokens=3 ,		generation_config=A			)

        lowercase	:		List[Any]    =   tokenizer(sentences[1] ,		return_tensors='''pt'''			).input_ids.to(A			)
        lowercase	:		Any    =   model.generate(input_ids=A ,		max_new_tokens=3 ,		generation_config=A			)

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

        lowercase	:		List[Any]    =   tokenizer.batch_decode(A ,		skip_special_tokens=A			)
        lowercase	:		Any    =   tokenizer.decode(output_non_padded[0] ,		skip_special_tokens=A			)
        lowercase	:		int    =   tokenizer.decode(output_padded[0] ,		skip_special_tokens=A			)

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



 @tooslow
 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        lowercase	:		Any    =   GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''			)
        lowercase	:		str    =   GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''			)
        # Output of original model created with mesh-tensoflow
        lowercase	:		Tuple    =   [
            ('''武田信玄は''', 35675),
            ('''武田信玄は、''', 45),
            ('''武田信玄は、この''', 29),
            ('''武田信玄は、このよう''', 30642),
            ('''武田信玄は、このような''', 35680),
            ('''武田信玄は、このような「''', 8640),
            ('''武田信玄は、このような「武田''', 31617),
            ('''武田信玄は、このような「武田家''', 30646),
            ('''武田信玄は、このような「武田家の''', 31617),
            ('''武田信玄は、このような「武田家の家''', 31381),
        ]
        for input, output in target:
               lowercase	:		List[str]    =   tokenizer.encode(A ,		return_tensors='''pt'''			)
               lowercase	:		Dict    =   model(A			)
               lowercase	:		Union[str, Any]    =   outputs.logits.detach().cpu().numpy()[0]
               lowercase	:		Optional[Any]    =   np.argmax(output_logits[-1]			)
               self.assertEqual(A ,		A			)



 @slow
 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




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

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

        lowercase	:		str    =   '''武田信玄は、'''
        lowercase	:		str    =   tokenizer(A ,		return_tensors='''pt'''			).input_ids.to(A			)
        lowercase	:		int    =   tokenizer([input_text, input_text] ,		return_tensors='''pt'''			).input_ids.to(A			)

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

        lowercase	:		str    =   model.generate(
            input_ids=A ,		spout=spouts[1] ,		max_new_tokens=20 ,		generation_config=A ,		)

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

        lowercase	:		int    =   tokenizer.decode(outputa[0]			)
        lowercase	:		Tuple    =   tokenizer.decode(outputa[0]			)
        lowercase	:		int    =   tokenizer.batch_decode(A			)

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





 @slow
 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        lowercase	:		Optional[Any]    =   GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''			)
        lowercase	:		Tuple    =   GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''			)
        model.to(A			)

        # set deterministically
        lowercase	:		str    =   GenerationConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''			)
        lowercase	:		Optional[int]    =   1

        lowercase	:		Dict    =   '''武田信玄'''
        lowercase	:		List[Any]    =   '''織田信長'''
        lowercase	:		Optional[int]    =   '''は、'''
        lowercase	:		List[Any]    =   '''が、'''
        lowercase	:		int    =   tokenizer(A ,		prefix_text=A ,		return_tensors='''pt'''			)
        lowercase	:		Optional[Any]    =   tokenizer(A ,		prefix_text=A ,		return_tensors='''pt'''			)
        lowercase	:		Optional[Any]    =   tokenizer([[prefix_text_a, input_text_a], [prefix_text_a, input_text_a]] ,		return_tensors='''pt'''			)

        lowercase	:		Dict    =   model.generate(
            input_ids=input_tok_a.input_ids.to(A			) ,		token_type_ids=input_tok_a.token_type_ids.to(A			) ,		max_new_tokens=20 ,		generation_config=A ,		)

        lowercase	:		Optional[int]    =   model.generate(
            input_ids=input_tok_a.input_ids.to(A			) ,		token_type_ids=input_tok_a.token_type_ids.to(A			) ,		max_new_tokens=20 ,		generation_config=A ,		)

        lowercase	:		str    =   model.generate(
            input_ids=input_tok_a.input_ids.to(A			) ,		token_type_ids=input_tok_a.token_type_ids.to(A			) ,		attention_mask=input_tok_a.attention_mask.to(A			) ,		max_new_tokens=20 ,		generation_config=A ,		)

        lowercase	:		Optional[int]    =   tokenizer.decode(outputa[0]			)
        lowercase	:		int    =   tokenizer.decode(outputa[0]			)
        lowercase	:		Optional[Any]    =   tokenizer.batch_decode(A			)

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










'''simple docstring'''






import argparse
import collections

import jax
import jax.numpy as jnp
import torch
import torch.nn as nn
from clip.model import CLIP
from flax.training import checkpoints
from huggingface_hub import Repository

from transformers import (
    CLIPTokenizer,
    OwlViTConfig,
    OwlViTForObjectDetection,
    OwlViTImageProcessor,
    OwlViTModel,
    OwlViTProcessor,
)


lowercase						:   Any      						=							{
    '''vit_b32''': {
        '''embed_dim''': 512,
        '''image_resolution''': 768,
        '''context_length''': 16,
        '''vocab_size''': 49408,
        '''vision_layers''': 12,
        '''vision_width''': 768,
        '''vision_patch_size''': 32,
        '''transformer_width''': 512,
        '''transformer_heads''': 8,
        '''transformer_layers''': 12,
    },
    '''vit_b16''': {
        '''embed_dim''': 512,
        '''image_resolution''': 768,
        '''context_length''': 16,
        '''vocab_size''': 49408,
        '''vision_layers''': 12,
        '''vision_width''': 768,
        '''vision_patch_size''': 16,
        '''transformer_width''': 512,
        '''transformer_heads''': 8,
        '''transformer_layers''': 12,
    },
    '''vit_l14''': {
        '''embed_dim''': 768,
        '''image_resolution''': 840,
        '''context_length''': 16,
        '''vocab_size''': 49408,
        '''vision_layers''': 24,
        '''vision_width''': 1024,
        '''vision_patch_size''': 14,
        '''transformer_width''': 768,
        '''transformer_heads''': 12,
        '''transformer_layers''': 12,
    },
}




def 		a_(			lowerCamelCase ,					lowerCamelCase="" ,					lowerCamelCase="/"   )					->str:






       '''simple docstring'''




       lowercase	:		List[Any]    =   []

       for k, v in params.items():
              lowercase	:		int    =   parent_key + sep + k if parent_key else k

              if isinstance(lowerCamelCase ,					collections.MutableMapping   ):
                     items.extend(flatten_nested_dict(lowerCamelCase ,					lowerCamelCase ,					sep=lowerCamelCase   ).items()   )
              else:
                     items.append((new_key, v)   )
       return dict(lowerCamelCase   )




def 		a_(			lowerCamelCase   )					->Optional[Any]:






       '''simple docstring'''




       return jax.tree_util.tree_map(lambda lowerCamelCase   : x.astype(jnp.floataa   ) if x.dtype == jnp.bfloataa else x ,					lowerCamelCase   )




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->Dict:






       '''simple docstring'''




       lowercase,  lowercase,  lowercase	:		Optional[Any]    =   pt_attn_layer.in_proj_weight.chunk(3 ,					dim=0   )
       lowercase,  lowercase,  lowercase	:		Optional[int]    =   pt_attn_layer.in_proj_bias.chunk(3 ,					dim=0   )

       lowercase	:		Union[str, Any]    =   pt_attn_layer.out_proj.weight
       lowercase	:		Tuple    =   pt_attn_layer.out_proj.bias

       lowercase	:		int    =   q_proj
       lowercase	:		Optional[Any]    =   q_proj_bias

       lowercase	:		str    =   k_proj
       lowercase	:		List[Any]    =   k_proj_bias

       lowercase	:		Dict    =   v_proj
       lowercase	:		List[str]    =   v_proj_bias

       lowercase	:		Optional[int]    =   out_proj_weights
       lowercase	:		Tuple    =   out_proj_bias




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->List[str]:






       '''simple docstring'''




       copy_linear(hf_mlp.fca ,					pt_mlp.c_fc   )
       copy_linear(hf_mlp.fca ,					pt_mlp.c_proj   )




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->Any:






       '''simple docstring'''




       lowercase	:		List[str]    =   pt_linear.weight
       lowercase	:		Tuple    =   pt_linear.bias




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->str:






       '''simple docstring'''




       copy_linear(hf_layer.layer_norma ,					pt_layer.ln_a   )
       copy_linear(hf_layer.layer_norma ,					pt_layer.ln_a   )

       # copy MLP
       copy_mlp(hf_layer.mlp ,					pt_layer.mlp   )

       # copy attn
       copy_attn_layer(hf_layer.self_attn ,					pt_layer.attn   )




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->List[Any]:






       '''simple docstring'''




       for hf_layer, pt_layer in zip(lowerCamelCase ,					lowerCamelCase   ):
              copy_layer(lowerCamelCase ,					lowerCamelCase   )




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->Dict:






       '''simple docstring'''




       lowercase	:		List[str]    =   pt_model.token_embedding.weight
       lowercase	:		Optional[int]    =   pt_model.positional_embedding

       # copy layer norm
       copy_linear(hf_encoder.final_layer_norm ,					pt_model.ln_final   )

       # copy hidden layers
       copy_layers(hf_encoder.encoder.layers ,					pt_model.transformer.resblocks   )




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->Tuple:






       '''simple docstring'''




       lowercase	:		List[str]    =   pt_model.text_projection.data.T

       # copy text encoder
       copy_encoder(hf_model.text_model ,					lowerCamelCase   )




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->str:






       '''simple docstring'''




       lowercase	:		List[str]    =   pt_model.visual.proj.data.T

       # copy layer norms
       copy_linear(hf_model.vision_model.pre_layernorm ,					pt_model.visual.ln_pre   )
       copy_linear(hf_model.vision_model.post_layernorm ,					pt_model.visual.ln_post   )

       # copy embeds
       lowercase	:		Union[str, Any]    =   pt_model.visual.conva.weight.data
       lowercase	:		int    =   pt_model.visual.class_embedding
       lowercase	:		str    =   pt_model.visual.positional_embedding.data

       # copy encoder
       copy_layers(hf_model.vision_model.encoder.layers ,					pt_model.visual.transformer.resblocks   )




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->List[Any]:






       '''simple docstring'''




       lowercase	:		Dict    =   flatten_nested_dict(flax_params['''backbone''']['''merged_class_token''']   )

       lowercase	:		Union[str, Any]    =   torch.from_numpy(flax_class_token_params['''scale''']   )
       lowercase	:		List[str]    =   torch.from_numpy(flax_class_token_params['''bias''']   )
       lowercase	:		Tuple    =   nn.Parameter(lowerCamelCase   )
       lowercase	:		Union[str, Any]    =   nn.Parameter(lowerCamelCase   )




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->List[Any]:






       '''simple docstring'''




       lowercase	:		Optional[int]    =   hf_model.state_dict()
       lowercase	:		Dict    =   {}

       # Rename class prediction head flax params to pytorch HF
       lowercase	:		Dict    =   flatten_nested_dict(flax_params['''class_head''']   )

       for flax_key, v in flax_class_params.items():
              lowercase	:		List[str]    =   flax_key.replace('''/''' ,					'''.'''   )
              lowercase	:		Tuple    =   torch_key.replace('''.kernel''' ,					'''.weight'''   )
              lowercase	:		Dict    =   torch_key.replace('''Dense_0''' ,					'''dense0'''   )
              lowercase	:		Optional[int]    =   '''class_head.''' + torch_key

              if "weight" in torch_key and v.ndim == 2:
                     lowercase	:		Optional[int]    =   v.T

              lowercase	:		Optional[int]    =   nn.Parameter(torch.from_numpy(lowerCamelCase   )   )

       # Rename box prediction box flax params to pytorch HF
       lowercase	:		Optional[Any]    =   flatten_nested_dict(flax_params['''obj_box_head''']   )

       for flax_key, v in flax_box_params.items():
              lowercase	:		Dict    =   flax_key.replace('''/''' ,					'''.'''   )
              lowercase	:		Union[str, Any]    =   torch_key.replace('''.kernel''' ,					'''.weight'''   )
              lowercase	:		int    =   torch_key.replace('''_''' ,					''''''   ).lower()
              lowercase	:		Union[str, Any]    =   '''box_head.''' + torch_key

              if "weight" in torch_key and v.ndim == 2:
                     lowercase	:		Tuple    =   v.T

              lowercase	:		Tuple    =   nn.Parameter(torch.from_numpy(lowerCamelCase   )   )

       # Copy flax params to PyTorch params
       for name, param in new_params.items():
              if name in pt_params.keys():
                     pt_params[name].copy_(lowerCamelCase   )




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->Dict:






       '''simple docstring'''




       for k, v in flax_attn_params.items():
              if k.startswith('''transformer'''   ):
                     lowercase	:		Optional[Any]    =   k.replace('''transformer.resblocks''' ,					'''text_model.encoder.layers'''   )
              else:
                     lowercase	:		Optional[Any]    =   k.replace('''visual.transformer.resblocks''' ,					'''vision_model.encoder.layers'''   )

              lowercase	:		Optional[Any]    =   torch_key.replace('''attn''' ,					'''self_attn'''   )
              lowercase	:		Optional[int]    =   torch_key.replace('''key''' ,					'''k_proj'''   )
              lowercase	:		Dict    =   torch_key.replace('''value''' ,					'''v_proj'''   )
              lowercase	:		List[Any]    =   torch_key.replace('''query''' ,					'''q_proj'''   )
              lowercase	:		Any    =   torch_key.replace('''out''' ,					'''out_proj'''   )

              if "bias" in torch_key and v.ndim == 2:
                     lowercase	:		str    =   v.shape[0] * v.shape[1]
                     lowercase	:		List[str]    =   v.reshape(lowerCamelCase   )

              if "weight" in torch_key and "out" in torch_key:
                     lowercase	:		Union[str, Any]    =   (v.shape[0] * v.shape[1], v.shape[2])
                     lowercase	:		Union[str, Any]    =   v.reshape(lowerCamelCase   ).T

              if "weight" in torch_key and "out" not in torch_key:
                     lowercase	:		Optional[int]    =   (v.shape[0], v.shape[1] * v.shape[2])
                     lowercase	:		List[Any]    =   v.reshape(lowerCamelCase   ).T

              # Copy flax CLIP attn params to HF PyTorch params
              lowercase	:		List[str]    =   torch.from_numpy(lowerCamelCase   )
              hf_backbone.state_dict()[torch_key].copy_(lowerCamelCase   )




def 		a_(			lowerCamelCase   )					->Any:






       '''simple docstring'''




       lowercase	:		Union[str, Any]    =   {}
       lowercase	:		Union[str, Any]    =   []

       for k, v in params.items():
              if "attn." in k:
                     lowercase	:		Union[str, Any]    =   k[: k.rindex('''attn.'''   ) + 5]
                     if base in processed_attn_layers:
                            continue

                     processed_attn_layers.append(lowerCamelCase   )
                     lowercase	:		Dict    =   params[base + '''out.weight'''].shape[-1]
                     lowercase	:		Union[str, Any]    =   params[base + '''out.weight'''].reshape(lowerCamelCase ,					lowerCamelCase   ).T
                     lowercase	:		List[str]    =   params[base + '''out.bias''']
              else:
                     lowercase	:		Dict    =   v
       return new_params




def 		a_(			lowerCamelCase ,					lowerCamelCase   )					->Dict:






       '''simple docstring'''




       lowercase	:		Tuple    =   CLIP(**lowerCamelCase   )
       torch_model.eval()
       lowercase	:		Any    =   torch_model.state_dict()

       lowercase	:		List[Any]    =   flatten_nested_dict(flax_params['''backbone''']['''clip''']   )
       lowercase	:		str    =   {}

       for flax_key, v in flax_clip_params.items():
              lowercase	:		int    =   flax_key.replace('''/''' ,					'''.'''   )
              lowercase	:		Optional[int]    =   torch_key.replace('''text.token_embedding.embedding''' ,					'''token_embedding.kernel'''   )

              if (
                  torch_key.startswith('''text.transformer'''   )
                  or torch_key.startswith('''text.text_projection'''   )
                  or torch_key.startswith('''text.ln_final'''   )
                  or torch_key.startswith('''text.positional_embedding'''   )
              ):
                     lowercase	:		int    =   torch_key[5:]

              lowercase	:		List[Any]    =   torch_key.replace('''text_projection.kernel''' ,					'''text_projection'''   )
              lowercase	:		Any    =   torch_key.replace('''visual.proj.kernel''' ,					'''visual.proj'''   )
              lowercase	:		Union[str, Any]    =   torch_key.replace('''.scale''' ,					'''.weight'''   )
              lowercase	:		Optional[Any]    =   torch_key.replace('''.kernel''' ,					'''.weight'''   )

              if "conv" in torch_key or "downsample.0.weight" in torch_key:
                     lowercase	:		List[str]    =   v.transpose(3 ,					2 ,					0 ,					1   )

              elif "weight" in torch_key and v.ndim == 2 and "embedding" not in torch_key:
                     # Fully connected layers are transposed, embeddings are not
                     lowercase	:		Union[str, Any]    =   v.T

              lowercase	:		str    =   v

       lowercase	:		Tuple    =   _convert_attn_layers(lowerCamelCase   )
       new_torch_params.update(lowerCamelCase   )
       lowercase	:		Union[str, Any]    =   {}

       # Copy flax CLIP backbone params to PyTorch params
       for name, param in new_torch_params.items():
              if name in torch_clip_params.keys():
                     lowercase	:		Any    =   torch.from_numpy(new_torch_params[name]   )
                     torch_clip_params[name].copy_(lowerCamelCase   )
              else:
                     lowercase	:		Optional[int]    =   param

       return torch_clip_params, torch_model, attn_params




@torch.no_grad()
def 		a_(			lowerCamelCase ,					lowerCamelCase ,					lowerCamelCase ,					lowerCamelCase ,					lowerCamelCase=None   )					->Tuple:






       '''simple docstring'''




       lowercase	:		List[str]    =   Repository(lowerCamelCase ,					clone_from=f"""google/{pytorch_dump_folder_path}"""   )
       repo.git_pull()

       if config_path is not None:
              lowercase	:		Any    =   OwlViTConfig.from_pretrained(lowerCamelCase   )
       else:
              lowercase	:		Optional[int]    =   OwlViTConfig()

       lowercase	:		Any    =   OwlViTModel(lowerCamelCase   ).eval()
       lowercase	:		str    =   OwlViTForObjectDetection(lowerCamelCase   ).eval()

       copy_text_model_and_projection(lowerCamelCase ,					lowerCamelCase   )
       copy_vision_model_and_projection(lowerCamelCase ,					lowerCamelCase   )
       lowercase	:		Any    =   pt_backbone.logit_scale
       copy_flax_attn_params(lowerCamelCase ,					lowerCamelCase   )

       lowercase	:		Optional[Any]    =   hf_backbone
       copy_class_merge_token(lowerCamelCase ,					lowerCamelCase   )
       copy_class_box_heads(lowerCamelCase ,					lowerCamelCase   )

       # Save HF model
       hf_model.save_pretrained(repo.local_dir   )

       # Initialize image processor
       lowercase	:		List[Any]    =   OwlViTImageProcessor(
           size=config.vision_config.image_size ,					crop_size=config.vision_config.image_size   )
       # Initialize tokenizer
       lowercase	:		str    =   CLIPTokenizer.from_pretrained('''openai/clip-vit-base-patch32''' ,					pad_token='''!''' ,					model_max_length=16   )

       # Initialize processor
       lowercase	:		Tuple    =   OwlViTProcessor(image_processor=lowerCamelCase ,					tokenizer=lowerCamelCase   )
       image_processor.save_pretrained(repo.local_dir   )
       processor.save_pretrained(repo.local_dir   )

       repo.git_add()
       repo.git_commit('''Upload model and processor'''   )
       repo.git_push()


if __name__ == "__main__":
      lowercase						:   Optional[Any]      						=							argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          '''--owlvit_version''',
          default=None,
          type=str,
          required=True,
          help='''OWL-ViT model name [clip_b16, clip_b32, clip_l14].''',
      )
      parser.add_argument(
          '''--owlvit_checkpoint''', default=None, type=str, required=True, help='''Path to flax model checkpoint.'''
      )
      parser.add_argument('''--hf_config''', default=None, type=str, required=True, help='''Path to HF model config.''')
      parser.add_argument(
          '''--pytorch_dump_folder_path''', default='''hf_model''', type=str, help='''Path to the output PyTorch model.'''
      )
      lowercase						:   Optional[int]      						=							parser.parse_args()

      # Initialize PyToch clip model
      lowercase						:   Any      						=							args.owlvit_version
      if model_name == "clip_b16":
            lowercase						:   Tuple      						=							CONFIGS['''vit_b16''']
      elif model_name == "clip_b32":
            lowercase						:   int      						=							CONFIGS['''vit_b32''']
      elif model_name == "clip_l14":
            lowercase						:   Any      						=							CONFIGS['''vit_l14''']

      # Load from checkpoint and convert params to float-32
      lowercase						:   List[str]      						=							checkpoints.restore_checkpoint(args.owlvit_checkpoint, target=None)['''optimizer''']['''target''']
      lowercase						:   str      						=							jax.tree_util.tree_map(lambda x: x.astype(jnp.floataa) if x.dtype == jnp.bfloataa else x, variables)
      del variables

      # Convert CLIP backbone
      lowercase						,						lowercase						,						lowercase						:   Optional[int]      						=							convert_clip_backbone(flax_params, torch_config)

      convert_owlvit_checkpoint(clip_pt, flax_params, attn_params, args.pytorch_dump_folder_path, args.hf_config)




