




'''simple docstring'''






import unittest

from transformers import PegasusConfig, PegasusTokenizer, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
      import os

      # The slow tests are often failing with OOM error on GPU
      # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
      # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
      A_			      =		"platform"
      import jax
      import jax.numpy as jnp
      import numpy as np

      from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel






@require_flax
class        lowercase_      :
     A_											=			PegasusConfig
     A_											=			{}
     A_											=			'''gelu'''





     def __init__(     self     :					Optional[int]     ,							__lowerCamelCase     :					Optional[Any]     ,							__lowerCamelCase     :					Dict=13     ,							__lowerCamelCase     :					Dict=7     ,							__lowerCamelCase     :					Any=True     ,							__lowerCamelCase     :					Tuple=False     ,							__lowerCamelCase     :					int=99     ,							__lowerCamelCase     :					Tuple=32     ,							__lowerCamelCase     :					Union[str, Any]=5     ,							__lowerCamelCase     :					Dict=4     ,							__lowerCamelCase     :					Any=37     ,							__lowerCamelCase     :					int=0.1     ,							__lowerCamelCase     :					str=0.1     ,							__lowerCamelCase     :					Optional[Any]=20     ,							__lowerCamelCase     :					int=2     ,							__lowerCamelCase     :					str=1     ,							__lowerCamelCase     :					Any=0     ,							):
           snake_case__       :   List[str]	      =    parent
           snake_case__       :   Any	      =    batch_size
           snake_case__       :   int	      =    seq_length
           snake_case__       :   List[str]	      =    is_training
           snake_case__       :   Any	      =    use_labels
           snake_case__       :   Tuple	      =    vocab_size
           snake_case__       :   List[str]	      =    hidden_size
           snake_case__       :   Union[str, Any]	      =    num_hidden_layers
           snake_case__       :   Optional[Any]	      =    num_attention_heads
           snake_case__       :   int	      =    intermediate_size

           snake_case__       :   Tuple	      =    hidden_dropout_prob
           snake_case__       :   Dict	      =    attention_probs_dropout_prob
           snake_case__       :   int	      =    max_position_embeddings
           snake_case__       :   int	      =    eos_token_id
           snake_case__       :   Tuple	      =    pad_token_id
           snake_case__       :   List[Any]	      =    bos_token_id





     def 			_lowerCAmelCase      (     self     :					Any			):
           snake_case__       :   int	      =    ids_tensor([self.batch_size, self.seq_length - 1]     ,							self.vocab_size			).clip(3     ,							self.vocab_size			)
           snake_case__       :   Union[str, Any]	      =    np.expand_dims(np.array([self.eos_token_id] * self.batch_size			)     ,							1			)
           snake_case__       :   Dict	      =    np.concatenate([input_ids, eos_tensor]     ,							axis=1			)

           snake_case__       :   Optional[int]	      =    ids_tensor([self.batch_size, self.seq_length]     ,							self.vocab_size			)

           snake_case__       :   Union[str, Any]	      =    self.config_cls(
               vocab_size=self.vocab_size     ,							d_model=self.hidden_size     ,							encoder_layers=self.num_hidden_layers     ,							decoder_layers=self.num_hidden_layers     ,							encoder_attention_heads=self.num_attention_heads     ,							decoder_attention_heads=self.num_attention_heads     ,							encoder_ffn_dim=self.intermediate_size     ,							decoder_ffn_dim=self.intermediate_size     ,							dropout=self.hidden_dropout_prob     ,							attention_dropout=self.attention_probs_dropout_prob     ,							max_position_embeddings=self.max_position_embeddings     ,							eos_token_ids=[2]     ,							bos_token_id=self.bos_token_id     ,							pad_token_id=self.pad_token_id     ,							decoder_start_token_id=self.pad_token_id     ,							**self.config_updates     ,							)
           snake_case__       :   str	      =    prepare_pegasus_inputs_dict(__lowerCAmelCase     ,							__lowerCAmelCase     ,							__lowerCAmelCase			)
           return config, inputs_dict





     def 			_lowerCAmelCase      (     self     :					int     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					int     ,							__lowerCamelCase     :					Optional[Any]			):
           snake_case__       :   Optional[int]	      =    20
           snake_case__       :   Optional[Any]	      =    model_class_name(__lowerCAmelCase			)

           snake_case__       :   List[str]	      =    model.encode(inputs_dict['input_ids']			)

           snake_case__      ,							snake_case__       :   List[str]	      =    (
               inputs_dict['decoder_input_ids'],
               inputs_dict['decoder_attention_mask'],
           )

           snake_case__       :   Optional[int]	      =    model.init_cache(decoder_input_ids.shape[0]     ,							__lowerCAmelCase     ,							__lowerCAmelCase			)
           snake_case__       :   Any	      =    jnp.ones((decoder_input_ids.shape[0], max_decoder_length)     ,							dtype='i4'			)

           snake_case__       :   int	      =    jnp.broadcast_to(
               jnp.arange(decoder_input_ids.shape[-1] - 1			)[None, :]     ,							(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)     ,							)
           snake_case__       :   Union[str, Any]	      =    model.decode(
               decoder_input_ids[:, :-1]     ,							__lowerCAmelCase     ,							decoder_attention_mask=__lowerCAmelCase     ,							past_key_values=__lowerCAmelCase     ,							decoder_position_ids=__lowerCAmelCase     ,							)

           snake_case__       :   Union[str, Any]	      =    jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]     ,							dtype='i4'			)
           snake_case__       :   Optional[int]	      =    model.decode(
               decoder_input_ids[:, -1:]     ,							__lowerCAmelCase     ,							decoder_attention_mask=__lowerCAmelCase     ,							past_key_values=outputs_cache.past_key_values     ,							decoder_position_ids=__lowerCAmelCase     ,							)

           snake_case__       :   Tuple	      =    model.decode(__lowerCAmelCase     ,							__lowerCAmelCase			)

           snake_case__       :   Any	      =    np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])			)			)
           self.parent.assertTrue(diff < 1E-3     ,							msg=F"Max diff is {diff}"			)





     def 			_lowerCAmelCase      (     self     :					str     ,							__lowerCamelCase     :					Dict     ,							__lowerCamelCase     :					Tuple     ,							__lowerCamelCase     :					int			):
           snake_case__       :   Tuple	      =    20
           snake_case__       :   Tuple	      =    model_class_name(__lowerCAmelCase			)

           snake_case__       :   Tuple	      =    model.encode(inputs_dict['input_ids']			)

           snake_case__      ,							snake_case__       :   Tuple	      =    (
               inputs_dict['decoder_input_ids'],
               inputs_dict['decoder_attention_mask'],
           )

           snake_case__       :   Dict	      =    jnp.concatenate(
               [
                   decoder_attention_mask,
                   jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])			),
               ]     ,							axis=-1     ,							)

           snake_case__       :   Optional[Any]	      =    model.init_cache(decoder_input_ids.shape[0]     ,							__lowerCAmelCase     ,							__lowerCAmelCase			)
           snake_case__       :   Any	      =    jnp.broadcast_to(
               jnp.arange(decoder_input_ids.shape[-1] - 1			)[None, :]     ,							(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)     ,							)

           snake_case__       :   int	      =    model.decode(
               decoder_input_ids[:, :-1]     ,							__lowerCAmelCase     ,							decoder_attention_mask=__lowerCAmelCase     ,							past_key_values=__lowerCAmelCase     ,							decoder_position_ids=__lowerCAmelCase     ,							)
           snake_case__       :   List[str]	      =    jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]     ,							dtype='i4'			)
           snake_case__       :   List[Any]	      =    model.decode(
               decoder_input_ids[:, -1:]     ,							__lowerCAmelCase     ,							past_key_values=outputs_cache.past_key_values     ,							decoder_attention_mask=__lowerCAmelCase     ,							decoder_position_ids=__lowerCAmelCase     ,							)

           snake_case__       :   str	      =    model.decode(__lowerCAmelCase     ,							__lowerCAmelCase     ,							decoder_attention_mask=__lowerCAmelCase			)

           snake_case__       :   Dict	      =    np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])			)			)
           self.parent.assertTrue(diff < 1E-3     ,							msg=F"Max diff is {diff}"			)






def 		UpperCamelCase__      (		__SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE=None				,      __SCREAMING_SNAKE_CASE=None				,      )    ->   Any:
      if attention_mask is None:
            snake_case__       :   Union[str, Any]	      =    np.not_equal(__SCREAMING_SNAKE_CASE				,      config.pad_token_id		).astype(np.inta		)
      if decoder_attention_mask is None:
            snake_case__       :   str	      =    np.concatenate(
                [
                    np.ones(decoder_input_ids[:, :1].shape				,      dtype=np.inta		),
                    np.not_equal(decoder_input_ids[:, 1:]				,      config.pad_token_id		).astype(np.inta		),
                ]				,      axis=-1				,      )
      return {
          "input_ids": input_ids,
          "decoder_input_ids": decoder_input_ids,
          "attention_mask": attention_mask,
          "decoder_attention_mask": decoder_attention_mask,
      }






@require_flax
class        lowercase_      (						UpperCAmelCase__						,       unittest.TestCase							):
     A_											=			(
         (
             FlaxPegasusForConditionalGeneration,
             FlaxPegasusModel,
         )
         if is_flax_available()
         else ()
     )
     A_											=			(FlaxPegasusForConditionalGeneration,) if is_flax_available() else ()
     A_											=			True
     A_											=			False
     A_											=			False
     A_											=			False





     def 			_lowerCAmelCase      (     self     :					List[str]			):
           snake_case__       :   Optional[int]	      =    FlaxPegasusModelTester(self			)
           snake_case__       :   Dict	      =    ConfigTester(self     ,							config_class=__lowerCAmelCase			)





     def 			_lowerCAmelCase      (     self     :					Any			):
           self.config_tester.run_common_tests()





     def 			_lowerCAmelCase      (     self     :					int			):
           snake_case__      ,							snake_case__       :   Tuple	      =    self.model_tester.prepare_config_and_inputs_for_common()
           for model_class in self.all_model_classes:
                 self.model_tester.check_use_cache_forward(__lowerCAmelCase     ,							__lowerCAmelCase     ,							__lowerCAmelCase			)





     def 			_lowerCAmelCase      (     self     :					List[str]			):
           snake_case__      ,							snake_case__       :   List[Any]	      =    self.model_tester.prepare_config_and_inputs_for_common()
           for model_class in self.all_model_classes:
                 self.model_tester.check_use_cache_forward_with_attn_mask(__lowerCAmelCase     ,							__lowerCAmelCase     ,							__lowerCAmelCase			)





     def 			_lowerCAmelCase      (     self     :					List[str]			):
           snake_case__      ,							snake_case__       :   str	      =    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 with self.subTest(model_class.__name__			):
                       snake_case__       :   Tuple	      =    self._prepare_for_class(__lowerCAmelCase     ,							__lowerCAmelCase			)
                       snake_case__       :   List[Any]	      =    model_class(__lowerCAmelCase			)

                       @jax.jit
                       def encode_jitted(__lowerCamelCase     :					str     ,							__lowerCamelCase     :					List[Any]=None     ,							**__lowerCamelCase     :					Union[str, Any]			):
                             return model.encode(input_ids=__lowerCAmelCase     ,							attention_mask=__lowerCAmelCase			)

                       with self.subTest('JIT Enabled'			):
                             snake_case__       :   str	      =    encode_jitted(**__lowerCAmelCase			).to_tuple()

                       with self.subTest('JIT Disabled'			):
                             with jax.disable_jit():
                                   snake_case__       :   Optional[Any]	      =    encode_jitted(**__lowerCAmelCase			).to_tuple()

                       self.assertEqual(len(__lowerCAmelCase			)     ,							len(__lowerCAmelCase			)			)
                       for jitted_output, output in zip(__lowerCAmelCase     ,							__lowerCAmelCase			):
                             self.assertEqual(jitted_output.shape     ,							output.shape			)





     def 			_lowerCAmelCase      (     self     :					Optional[int]			):
           snake_case__      ,							snake_case__       :   Optional[Any]	      =    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 with self.subTest(model_class.__name__			):
                       snake_case__       :   Optional[Any]	      =    model_class(__lowerCAmelCase			)
                       snake_case__       :   str	      =    model.encode(inputs_dict['input_ids']     ,							inputs_dict['attention_mask']			)

                       snake_case__       :   Optional[int]	      =    {
                           'decoder_input_ids': inputs_dict['decoder_input_ids'],
                           'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
                           'encoder_outputs': encoder_outputs,
                       }

                       @jax.jit
                       def decode_jitted(__lowerCamelCase     :					Union[str, Any]     ,							__lowerCamelCase     :					Dict     ,							__lowerCamelCase     :					List[str]			):
                             return model.decode(
                                 decoder_input_ids=__lowerCAmelCase     ,							decoder_attention_mask=__lowerCAmelCase     ,							encoder_outputs=__lowerCAmelCase     ,							)

                       with self.subTest('JIT Enabled'			):
                             snake_case__       :   Union[str, Any]	      =    decode_jitted(**__lowerCAmelCase			).to_tuple()

                       with self.subTest('JIT Disabled'			):
                             with jax.disable_jit():
                                   snake_case__       :   Tuple	      =    decode_jitted(**__lowerCAmelCase			).to_tuple()

                       self.assertEqual(len(__lowerCAmelCase			)     ,							len(__lowerCAmelCase			)			)
                       for jitted_output, output in zip(__lowerCAmelCase     ,							__lowerCAmelCase			):
                             self.assertEqual(jitted_output.shape     ,							output.shape			)





     @slow
     def 			_lowerCAmelCase      (     self     :					int			):
           for model_class_name in self.all_model_classes:
                 snake_case__       :   int	      =    model_class_name.from_pretrained('google/pegasus-large'     ,							from_pt=__lowerCAmelCase			)
                 snake_case__       :   Union[str, Any]	      =    np.ones((1, 1)			)
                 snake_case__       :   Tuple	      =    model(__lowerCAmelCase			)
                 self.assertIsNotNone(__lowerCAmelCase			)





     @slow
     def 			_lowerCAmelCase      (     self     :					Optional[Any]			):
           snake_case__       :   List[Any]	      =    FlaxPegasusForConditionalGeneration.from_pretrained('google/pegasus-xsum'			)
           snake_case__       :   Dict	      =    PegasusTokenizer.from_pretrained('google/pegasus-xsum'			)

           snake_case__       :   List[Any]	      =    [
               ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.',
               ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ',
           ]

           snake_case__       :   Union[str, Any]	      =    [
               'California\'s largest electricity provider has turned off power to hundreds of thousands of customers.',
               'Pop group N-Dubz have revealed they were surprised to get four nominations for this year\'s Mobo Awards.',
           ]

           snake_case__       :   Any	      =    tokenizer(__lowerCAmelCase     ,							return_tensors='np'     ,							truncation=__lowerCAmelCase     ,							max_length=512     ,							padding=__lowerCAmelCase			)
           snake_case__       :   List[str]	      =    model.generate(**__lowerCAmelCase     ,							num_beams=2			).sequences
           snake_case__       :   Dict	      =    tokenizer.batch_decode(__lowerCAmelCase     ,							skip_special_tokens=__lowerCAmelCase			)
           assert tgt_text == decoded






'''simple docstring'''


import argparse

import requests
import torch
from PIL import Image

from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel
def 						lowerCamelCase__   (				a							):
						# vision encoder
						if "img_encoder.pos_embed" in name:
												__snake_case						 =   name.replace('img_encoder.pos_embed'    ,	'vision_model.embeddings.position_embeddings'							)
						if "img_encoder.patch_embed.proj" in name:
												__snake_case						 =   name.replace('img_encoder.patch_embed.proj'    ,	'vision_model.embeddings.patch_embeddings.projection'							)
						if "img_encoder.patch_embed.norm" in name:
												__snake_case						 =   name.replace('img_encoder.patch_embed.norm'    ,	'vision_model.embeddings.layernorm'							)
						if "img_encoder.layers" in name:
												__snake_case						 =   name.replace('img_encoder.layers'    ,	'vision_model.encoder.stages'							)
						if "blocks" in name and "res" not in name:
												__snake_case						 =   name.replace('blocks'    ,	'layers'							)
						if "attn" in name and "pre_assign" not in name:
												__snake_case						 =   name.replace('attn'    ,	'self_attn'							)
						if "proj" in name and "self_attn" in name and "text" not in name:
												__snake_case						 =   name.replace('proj'    ,	'out_proj'							)
						if "pre_assign_attn.attn.proj" in name:
												__snake_case						 =   name.replace('pre_assign_attn.attn.proj'    ,	'pre_assign_attn.attn.out_proj'							)
						if "norm1" in name:
												__snake_case						 =   name.replace('norm1'    ,	'layer_norm1'							)
						if "norm2" in name and "pre_assign" not in name:
												__snake_case						 =   name.replace('norm2'    ,	'layer_norm2'							)
						if "img_encoder.norm" in name:
												__snake_case						 =   name.replace('img_encoder.norm'    ,	'vision_model.layernorm'							)
						# text encoder
						if "text_encoder.token_embedding" in name:
												__snake_case						 =   name.replace('text_encoder.token_embedding'    ,	'text_model.embeddings.token_embedding'							)
						if "text_encoder.positional_embedding" in name:
												__snake_case						 =   name.replace('text_encoder.positional_embedding'    ,	'text_model.embeddings.position_embedding.weight'							)
						if "text_encoder.transformer.resblocks." in name:
												__snake_case						 =   name.replace('text_encoder.transformer.resblocks.'    ,	'text_model.encoder.layers.'							)
						if "ln_1" in name:
												__snake_case						 =   name.replace('ln_1'    ,	'layer_norm1'							)
						if "ln_2" in name:
												__snake_case						 =   name.replace('ln_2'    ,	'layer_norm2'							)
						if "c_fc" in name:
												__snake_case						 =   name.replace('c_fc'    ,	'fc1'							)
						if "c_proj" in name:
												__snake_case						 =   name.replace('c_proj'    ,	'fc2'							)
						if "text_encoder" in name:
												__snake_case						 =   name.replace('text_encoder'    ,	'text_model'							)
						if "ln_final" in name:
												__snake_case						 =   name.replace('ln_final'    ,	'final_layer_norm'							)
						# projection layers
						if "img_projector.linear_hidden." in name:
												__snake_case						 =   name.replace('img_projector.linear_hidden.'    ,	'visual_projection.'							)
						if "img_projector.linear_out." in name:
												__snake_case						 =   name.replace('img_projector.linear_out.'    ,	'visual_projection.3.'							)
						if "text_projector.linear_hidden" in name:
												__snake_case						 =   name.replace('text_projector.linear_hidden'    ,	'text_projection'							)
						if "text_projector.linear_out" in name:
												__snake_case						 =   name.replace('text_projector.linear_out'    ,	'text_projection.3'							)

						return name
def 						lowerCamelCase__   (				a    ,	a							):
						for key in orig_state_dict.copy().keys():
												__snake_case						 =   orig_state_dict.pop(a							)

												if "qkv" in key:
																		# weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment:
																		# we need to split them up into separate matrices/vectors
																		__snake_case						 =   key.split('.'							)
																		__snake_case ,       __snake_case						 =   int(key_split[2]							), int(key_split[4]							)
																		__snake_case						 =   config.vision_config.hidden_size
																		if "weight" in key:
																								__snake_case						 =   val[:dim, :]
																								__snake_case						 =   val[dim : dim * 2, :]
																								__snake_case						 =   val[-dim:, :]
																		else:
																								__snake_case						 =   val[:dim]
																								__snake_case						 =   val[dim : dim * 2]
																								__snake_case						 =   val[-dim:]
												elif "in_proj" in key:
																		# weights and biases of the key, value and query projections of text encoder's attention layers require special treatment:
																		# we need to split them up into separate matrices/vectors
																		__snake_case						 =   key.split('.'							)
																		__snake_case						 =   int(key_split[3]							)
																		__snake_case						 =   config.text_config.hidden_size
																		if "weight" in key:
																								__snake_case						 =   val[:dim, :]
																								__snake_case						 =   val[
																								    dim : dim * 2, :
																								]
																								__snake_case						 =   val[-dim:, :]
																		else:
																								__snake_case						 =   val[:dim]
																								__snake_case						 =   val[dim : dim * 2]
																								__snake_case						 =   val[-dim:]
												else:
																		__snake_case						 =   rename_key(a							)
																		# squeeze if necessary
																		if (
																		    "text_projection.0" in new_name
																		    or "text_projection.3" in new_name
																		    or "visual_projection.0" in new_name
																		    or "visual_projection.3" in new_name
																		):
																								__snake_case						 =   val.squeeze_()
																		else:
																								__snake_case						 =   val

						return orig_state_dict
def 						lowerCamelCase__   (				):
						__snake_case						 =   'http://images.cocodataset.org/val2017/000000039769.jpg'
						__snake_case						 =   Image.open(requests.get(a    ,	stream=a							).raw							)
						return im
@torch.no_grad()
def 						lowerCamelCase__   (				a    ,	a    ,	a="groupvit-gcc-yfcc"    ,	a=False							):
						__snake_case						 =   GroupViTConfig()
						__snake_case						 =   GroupViTModel(a							).eval()

						__snake_case						 =   torch.load(a    ,	map_location='cpu'							)['model']
						__snake_case						 =   convert_state_dict(a    ,	a							)
						__snake_case ,       __snake_case						 =   model.load_state_dict(a    ,	strict=a							)
						assert missing_keys == ["text_model.embeddings.position_ids"]
						assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(a							) == 0)

						# verify result
						__snake_case						 =   CLIPProcessor.from_pretrained('openai/clip-vit-base-patch32'							)
						__snake_case						 =   prepare_img()
						__snake_case						 =   processor(text=['a photo of a cat', 'a photo of a dog']    ,	images=a    ,	padding=a    ,	return_tensors='pt'							)

						with torch.no_grad():
												__snake_case						 =   model(**a							)

						if model_name == "groupvit-gcc-yfcc":
												__snake_case						 =   torch.tensor([[13.3_523, 6.3_629]]							)
						elif model_name == "groupvit-gcc-redcaps":
												__snake_case						 =   torch.tensor([[16.1_873, 8.6_230]]							)
						else:
												raise ValueError(f'Model name {model_name} not supported.'							)
						assert torch.allclose(outputs.logits_per_image    ,	a    ,	atol=1E-3							)

						processor.save_pretrained(a							)
						model.save_pretrained(a							)
						print('Successfully saved processor and model to'    ,	a							)

						if push_to_hub:
												print('Pushing to the hub...'							)
												processor.push_to_hub(a    ,	organization='nielsr'							)
												model.push_to_hub(a    ,	organization='nielsr'							)


if __name__ == "__main__":
	_lowercase  =			argparse.ArgumentParser()
	parser.add_argument(
	    """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to dump the processor and PyTorch model."""
	)
	parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to GroupViT checkpoint""")
	parser.add_argument(
	    """--model_name""",
	    default="""groupvit-gccy-fcc""",
	    type=str,
	    help="""Name of the model. Expecting either 'groupvit-gcc-yfcc' or 'groupvit-gcc-redcaps'""",
	)
	parser.add_argument(
	    """--push_to_hub""",
	    action="""store_true""",
	    help="""Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.""",
	)
	_lowercase  =			parser.parse_args()

	convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)

