





import argparse

import torch
from torch import nn

from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Tuple			)   ->							Optional[int]:




		'''simple docstring'''
		lowercase__					:      Optional[int]      =		[
		    'encoder.version',
		    'decoder.version',
		    'model.encoder.version',
		    'model.decoder.version',
		    'decoder.output_projection.weight',
		    '_float_tensor',
		    'encoder.embed_positions._float_tensor',
		    'decoder.embed_positions._float_tensor',
		]
		for k in ignore_keys:
				state_dict.pop(__A   ,    __A			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[Any]			)   ->							Union[str, Any]:




		'''simple docstring'''
		lowercase__					:      int      =		list(s_dict.keys()			)
		for key in keys:
				if "transformer_layers" in key:
						lowercase__					:      Dict      =		s_dict.pop(__A			)
				elif "subsample" in key:
						lowercase__					:      List[Any]      =		s_dict.pop(__A			)


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : List[Any]			)   ->							Dict:




		'''simple docstring'''
		lowercase__   ,				lowercase__					:      List[Any]      =		emb.weight.shape
		lowercase__					:      List[str]      =		nn.Linear(__A   ,    __A   ,    bias=__A			)
		lowercase__					:      Optional[Any]      =		emb.weight.data
		return lin_layer


def       SCREAMING_SNAKE_CASE__  (       _lowercase     : Any   ,    _lowercase     : int			)   ->							Tuple:




		'''simple docstring'''
		lowercase__					:      str      =		torch.load(__A   ,    map_location='cpu'			)
		lowercase__					:      Any      =		mam_aaa['args']
		lowercase__					:      List[Any]      =		mam_aaa['model']
		lowercase__					:      List[Any]      =		state_dict['decoder.output_projection.weight']

		remove_ignore_keys_(__A			)
		rename_keys(__A			)

		lowercase__					:      Union[str, Any]      =		state_dict['decoder.embed_tokens.weight'].shape[0]

		lowercase__					:      int      =		args.share_decoder_input_output_embed

		lowercase__					:      List[str]      =		[int(__A			) for i in args.conv_kernel_sizes.split(','			)]
		lowercase__					:      List[str]      =		SpeechaTextConfig(
		    vocab_size=__A   ,    max_source_positions=args.max_source_positions   ,    max_target_positions=args.max_target_positions   ,    encoder_layers=args.encoder_layers   ,    decoder_layers=args.decoder_layers   ,    encoder_attention_heads=args.encoder_attention_heads   ,    decoder_attention_heads=args.decoder_attention_heads   ,    encoder_ffn_dim=args.encoder_ffn_embed_dim   ,    decoder_ffn_dim=args.decoder_ffn_embed_dim   ,    d_model=args.encoder_embed_dim   ,    dropout=args.dropout   ,    attention_dropout=args.attention_dropout   ,    activation_dropout=args.activation_dropout   ,    activation_function='relu'   ,    num_conv_layers=len(__A			)   ,    conv_channels=args.conv_channels   ,    conv_kernel_sizes=__A   ,    input_feat_per_channel=args.input_feat_per_channel   ,    input_channels=args.input_channels   ,    tie_word_embeddings=__A   ,    num_beams=5   ,    max_length=200   ,    use_cache=__A   ,    decoder_start_token_id=2   ,    early_stopping=__A   ,    )

		lowercase__					:      List[Any]      =		SpeechaTextForConditionalGeneration(__A			)
		lowercase__   ,				lowercase__					:      Optional[int]      =		model.model.load_state_dict(__A   ,    strict=__A			)
		if len(__A			) > 0 and not set(__A			) <= {
		    "encoder.embed_positions.weights",
		    "decoder.embed_positions.weights",
		}:
				raise ValueError(
				    'Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights`  are allowed to be missing,'
				    f""" but all the following weights are missing {missing}"""			)

		if tie_embeds:
				lowercase__					:      List[Any]      =		make_linear_from_emb(model.model.decoder.embed_tokens			)
		else:
				lowercase__					:      Optional[int]      =		lm_head_weights

		model.save_pretrained(__A			)


if __name__ == "__main__":
			__UpperCamelCase:	str = argparse.ArgumentParser()
			# Required parameters
			parser.add_argument("""--fairseq_path""", type=str, help="""Path to the fairseq model (.pt) file.""")
			parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
			__UpperCamelCase:	Optional[Any] = parser.parse_args()
			convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)





import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
    from PIL import Image

    from transformers import CLIPImageProcessor, CLIPProcessor

@require_vision
class     __snake_case    (				unittest.TestCase  ):
       """simple docstring"""







       def 			a		(		self   )      ->							Optional[int]:






              """simple docstring"""


              __snake_case       	=							tempfile.mkdtemp()

              # fmt: off
              __snake_case       	=							["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""]
              # fmt: on
              __snake_case       	=							dict(zip(_UpperCamelCase      , range(len(_UpperCamelCase   )   )   )   )
              __snake_case       	=							["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""]
              __snake_case       	=							{"""unk_token""": """<unk>"""}

              __snake_case       	=							os.path.join(self.tmpdirname      , VOCAB_FILES_NAMES["""vocab_file"""]   )
              __snake_case       	=							os.path.join(self.tmpdirname      , VOCAB_FILES_NAMES["""merges_file"""]   )
              with open(self.vocab_file      , """w"""      , encoding="""utf-8"""   ) as fp:
                     fp.write(json.dumps(_UpperCamelCase   ) + """\n"""   )
              with open(self.merges_file      , """w"""      , encoding="""utf-8"""   ) as fp:
                     fp.write("""\n""".join(_UpperCamelCase   )   )

              __snake_case       	=							{
                  """do_resize""": True,
                  """size""": 20,
                  """do_center_crop""": True,
                  """crop_size""": 18,
                  """do_normalize""": True,
                  """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073],
                  """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711],
              }
              __snake_case       	=							os.path.join(self.tmpdirname      , _UpperCamelCase   )
              with open(self.image_processor_file      , """w"""      , encoding="""utf-8"""   ) as fp:
                     json.dump(_UpperCamelCase      , _UpperCamelCase   )


       def 			a		(		self      , **_UpperCamelCase   )      ->							Optional[int]:






              """simple docstring"""


              return CLIPTokenizer.from_pretrained(self.tmpdirname      , **_UpperCamelCase   )


       def 			a		(		self      , **_UpperCamelCase   )      ->							Union[str, Any]:






              """simple docstring"""


              return CLIPTokenizerFast.from_pretrained(self.tmpdirname      , **_UpperCamelCase   )


       def 			a		(		self      , **_UpperCamelCase   )      ->							List[str]:






              """simple docstring"""


              return CLIPImageProcessor.from_pretrained(self.tmpdirname      , **_UpperCamelCase   )


       def 			a		(		self   )      ->							int:






              """simple docstring"""


              shutil.rmtree(self.tmpdirname   )


       def 			a		(		self   )      ->							Optional[Any]:






              """simple docstring"""


              __snake_case       	=							[np.random.randint(2_55      , size=(3, 30, 4_00)      , dtype=np.uinta   )]

              __snake_case       	=							[Image.fromarray(np.moveaxis(_UpperCamelCase      , 0      , -1   )   ) for x in image_inputs]

              return image_inputs


       def 			a		(		self   )      ->							List[Any]:






              """simple docstring"""


              __snake_case       	=							self.get_tokenizer()
              __snake_case       	=							self.get_rust_tokenizer()
              __snake_case       	=							self.get_image_processor()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )
              processor_slow.save_pretrained(self.tmpdirname   )
              __snake_case       	=							CLIPProcessor.from_pretrained(self.tmpdirname      , use_fast=_UpperCamelCase   )

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )
              processor_fast.save_pretrained(self.tmpdirname   )
              __snake_case       	=							CLIPProcessor.from_pretrained(self.tmpdirname   )

              self.assertEqual(processor_slow.tokenizer.get_vocab()      , tokenizer_slow.get_vocab()   )
              self.assertEqual(processor_fast.tokenizer.get_vocab()      , tokenizer_fast.get_vocab()   )
              self.assertEqual(tokenizer_slow.get_vocab()      , tokenizer_fast.get_vocab()   )
              self.assertIsInstance(processor_slow.tokenizer      , _UpperCamelCase   )
              self.assertIsInstance(processor_fast.tokenizer      , _UpperCamelCase   )

              self.assertEqual(processor_slow.image_processor.to_json_string()      , image_processor.to_json_string()   )
              self.assertEqual(processor_fast.image_processor.to_json_string()      , image_processor.to_json_string()   )
              self.assertIsInstance(processor_slow.image_processor      , _UpperCamelCase   )
              self.assertIsInstance(processor_fast.image_processor      , _UpperCamelCase   )


       def 			a		(		self   )      ->							List[str]:






              """simple docstring"""


              __snake_case       	=							CLIPProcessor(tokenizer=self.get_tokenizer()      , image_processor=self.get_image_processor()   )
              processor.save_pretrained(self.tmpdirname   )

              __snake_case       	=							self.get_tokenizer(bos_token="""(BOS)"""      , eos_token="""(EOS)"""   )
              __snake_case       	=							self.get_image_processor(do_normalize=_UpperCamelCase      , padding_value=1.0   )

              __snake_case       	=							CLIPProcessor.from_pretrained(
                  self.tmpdirname      , bos_token="""(BOS)"""      , eos_token="""(EOS)"""      , do_normalize=_UpperCamelCase      , padding_value=1.0   )

              self.assertEqual(processor.tokenizer.get_vocab()      , tokenizer_add_kwargs.get_vocab()   )
              self.assertIsInstance(processor.tokenizer      , _UpperCamelCase   )

              self.assertEqual(processor.image_processor.to_json_string()      , image_processor_add_kwargs.to_json_string()   )
              self.assertIsInstance(processor.image_processor      , _UpperCamelCase   )


       def 			a		(		self   )      ->							Any:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							self.prepare_image_inputs()

              __snake_case       	=							image_processor(_UpperCamelCase      , return_tensors="""np"""   )
              __snake_case       	=							processor(images=_UpperCamelCase      , return_tensors="""np"""   )

              for key in input_image_proc.keys():
                     self.assertAlmostEqual(input_image_proc[key].sum()      , input_processor[key].sum()      , delta=1E-2   )


       def 			a		(		self   )      ->							str:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							"""lower newer"""

              __snake_case       	=							processor(text=_UpperCamelCase   )

              __snake_case       	=							tokenizer(_UpperCamelCase   )

              for key in encoded_tok.keys():
                     self.assertListEqual(encoded_tok[key]      , encoded_processor[key]   )


       def 			a		(		self   )      ->							str:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							"""lower newer"""
              __snake_case       	=							self.prepare_image_inputs()

              __snake_case       	=							processor(text=_UpperCamelCase      , images=_UpperCamelCase   )

              self.assertListEqual(list(inputs.keys()   )      , ["""input_ids""", """attention_mask""", """pixel_values"""]   )

              # test if it raises when no input is passed
              with pytest.raises(_UpperCamelCase   ):
                     processor()


       def 			a		(		self   )      ->							Any:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

              __snake_case       	=							processor.batch_decode(_UpperCamelCase   )
              __snake_case       	=							tokenizer.batch_decode(_UpperCamelCase   )

              self.assertListEqual(_UpperCamelCase      , _UpperCamelCase   )






       def 			a		(		self   )      ->							int:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							"""lower newer"""
              __snake_case       	=							self.prepare_image_inputs()

              __snake_case       	=							processor(text=_UpperCamelCase      , images=_UpperCamelCase   )

              self.assertListEqual(list(inputs.keys()   )      , processor.model_input_names   )

