"""simple docstring"""






import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import (
						    FocalNetBackbone,
						    FocalNetForImageClassification,
						    FocalNetForMaskedImageModeling,
						    FocalNetModel,
						)
						from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor

class lowerCamelCase		:






					'''simple docstring'''


					def __init__(						self			:				Union[str, Any]   , _snake_case			:				int   , _snake_case			:				Union[str, Any]=13   , _snake_case			:				str=32   , _snake_case			:				int=2   , _snake_case			:				str=3   , _snake_case			:				List[str]=16   , _snake_case			:				Optional[int]=[32, 64, 128]   , _snake_case			:				str=[1, 2, 1]   , _snake_case			:				List[str]=[2, 2, 4]   , _snake_case			:				Tuple=2   , _snake_case			:				Tuple=2.0   , _snake_case			:				Dict=True   , _snake_case			:				Any=0.0   , _snake_case			:				Dict=0.0   , _snake_case			:				Any=0.1   , _snake_case			:				Optional[int]="gelu"   , _snake_case			:				str=False   , _snake_case			:				Union[str, Any]=True   , _snake_case			:				Any=0.02   , _snake_case			:				int=1e-5   , _snake_case			:				List[str]=True   , _snake_case			:				Any=None   , _snake_case			:				Tuple=True   , _snake_case			:				List[str]=10   , _snake_case			:				Union[str, Any]=8   , _snake_case			:				Dict=["stage1", "stage2"]   , _snake_case			:				int=[1, 2]   , )							->       Any:
									SCREAMING_SNAKE_CASE__		  =				parent
									SCREAMING_SNAKE_CASE__		  =				batch_size
									SCREAMING_SNAKE_CASE__		  =				image_size
									SCREAMING_SNAKE_CASE__		  =				patch_size
									SCREAMING_SNAKE_CASE__		  =				num_channels
									SCREAMING_SNAKE_CASE__		  =				embed_dim
									SCREAMING_SNAKE_CASE__		  =				hidden_sizes
									SCREAMING_SNAKE_CASE__		  =				depths
									SCREAMING_SNAKE_CASE__		  =				num_heads
									SCREAMING_SNAKE_CASE__		  =				window_size
									SCREAMING_SNAKE_CASE__		  =				mlp_ratio
									SCREAMING_SNAKE_CASE__		  =				qkv_bias
									SCREAMING_SNAKE_CASE__		  =				hidden_dropout_prob
									SCREAMING_SNAKE_CASE__		  =				attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE__		  =				drop_path_rate
									SCREAMING_SNAKE_CASE__		  =				hidden_act
									SCREAMING_SNAKE_CASE__		  =				use_absolute_embeddings
									SCREAMING_SNAKE_CASE__		  =				patch_norm
									SCREAMING_SNAKE_CASE__		  =				layer_norm_eps
									SCREAMING_SNAKE_CASE__		  =				initializer_range
									SCREAMING_SNAKE_CASE__		  =				is_training
									SCREAMING_SNAKE_CASE__		  =				scope
									SCREAMING_SNAKE_CASE__		  =				use_labels
									SCREAMING_SNAKE_CASE__		  =				type_sequence_label_size
									SCREAMING_SNAKE_CASE__		  =				encoder_stride
									SCREAMING_SNAKE_CASE__		  =				out_features
									SCREAMING_SNAKE_CASE__		  =				out_indices



					def 			lowerCAmelCase_					(						self			:				Any		)							->       int:
									SCREAMING_SNAKE_CASE__		  =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

									SCREAMING_SNAKE_CASE__		  =				None
									if self.use_labels:
													SCREAMING_SNAKE_CASE__		  =				ids_tensor([self.batch_size]   , self.type_sequence_label_size		)

									SCREAMING_SNAKE_CASE__		  =				self.get_config()

									return config, pixel_values, labels



					def 			lowerCAmelCase_					(						self			:				Any		)							->       Union[str, Any]:
									return FocalNetConfig(
									    image_size=self.image_size   , patch_size=self.patch_size   , num_channels=self.num_channels   , embed_dim=self.embed_dim   , hidden_sizes=self.hidden_sizes   , depths=self.depths   , num_heads=self.num_heads   , window_size=self.window_size   , mlp_ratio=self.mlp_ratio   , qkv_bias=self.qkv_bias   , hidden_dropout_prob=self.hidden_dropout_prob   , attention_probs_dropout_prob=self.attention_probs_dropout_prob   , drop_path_rate=self.drop_path_rate   , hidden_act=self.hidden_act   , use_absolute_embeddings=self.use_absolute_embeddings   , path_norm=self.patch_norm   , layer_norm_eps=self.layer_norm_eps   , initializer_range=self.initializer_range   , encoder_stride=self.encoder_stride   , out_features=self.out_features   , out_indices=self.out_indices   , )



					def 			lowerCAmelCase_					(						self			:				List[str]   , _snake_case			:				List[Any]   , _snake_case			:				Any   , _snake_case			:				Tuple		)							->       Union[str, Any]:
									SCREAMING_SNAKE_CASE__		  =				FocalNetModel(config=_snake_case		)
									model.to(_snake_case		)
									model.eval()
									SCREAMING_SNAKE_CASE__		  =				model(_snake_case		)

									SCREAMING_SNAKE_CASE__		  =				((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths		) - 1))
									SCREAMING_SNAKE_CASE__		  =				int(config.embed_dim * 2 ** (len(config.depths		) - 1)		)

									self.parent.assertEqual(result.last_hidden_state.shape   , (self.batch_size, expected_seq_len, expected_dim)		)



					def 			lowerCAmelCase_					(						self			:				Union[str, Any]   , _snake_case			:				Union[str, Any]   , _snake_case			:				Tuple   , _snake_case			:				Dict		)							->       int:
									SCREAMING_SNAKE_CASE__		  =				FocalNetBackbone(config=_snake_case		)
									model.to(_snake_case		)
									model.eval()
									SCREAMING_SNAKE_CASE__		  =				model(_snake_case		)

									# verify feature maps
									self.parent.assertEqual(len(result.feature_maps		)   , len(config.out_features		)		)
									self.parent.assertListEqual(list(result.feature_maps[0].shape		)   , [self.batch_size, self.image_size, 8, 8]		)

									# verify channels
									self.parent.assertEqual(len(model.channels		)   , len(config.out_features		)		)
									self.parent.assertListEqual(model.channels   , config.hidden_sizes[:-1]		)

									# verify backbone works with out_features=None
									SCREAMING_SNAKE_CASE__		  =				None
									SCREAMING_SNAKE_CASE__		  =				FocalNetBackbone(config=_snake_case		)
									model.to(_snake_case		)
									model.eval()
									SCREAMING_SNAKE_CASE__		  =				model(_snake_case		)

									# verify feature maps
									self.parent.assertEqual(len(result.feature_maps		)   , 1		)
									self.parent.assertListEqual(list(result.feature_maps[0].shape		)   , [self.batch_size, self.image_size * 2, 4, 4]		)

									# verify channels
									self.parent.assertEqual(len(model.channels		)   , 1		)
									self.parent.assertListEqual(model.channels   , [config.hidden_sizes[-1]]		)



					def 			lowerCAmelCase_					(						self			:				Optional[Any]   , _snake_case			:				Tuple   , _snake_case			:				Any   , _snake_case			:				Any		)							->       List[str]:
									SCREAMING_SNAKE_CASE__		  =				FocalNetForMaskedImageModeling(config=_snake_case		)
									model.to(_snake_case		)
									model.eval()
									SCREAMING_SNAKE_CASE__		  =				model(_snake_case		)
									self.parent.assertEqual(
									    result.reconstruction.shape   , (self.batch_size, self.num_channels, self.image_size, self.image_size)		)

									# test greyscale images
									SCREAMING_SNAKE_CASE__		  =				1
									SCREAMING_SNAKE_CASE__		  =				FocalNetForMaskedImageModeling(_snake_case		)
									model.to(_snake_case		)
									model.eval()

									SCREAMING_SNAKE_CASE__		  =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
									SCREAMING_SNAKE_CASE__		  =				model(_snake_case		)
									self.parent.assertEqual(result.reconstruction.shape   , (self.batch_size, 1, self.image_size, self.image_size)		)



					def 			lowerCAmelCase_					(						self			:				str   , _snake_case			:				str   , _snake_case			:				Dict   , _snake_case			:				Optional[int]		)							->       Optional[Any]:
									SCREAMING_SNAKE_CASE__		  =				self.type_sequence_label_size
									SCREAMING_SNAKE_CASE__		  =				FocalNetForImageClassification(_snake_case		)
									model.to(_snake_case		)
									model.eval()
									SCREAMING_SNAKE_CASE__		  =				model(_snake_case   , labels=_snake_case		)
									self.parent.assertEqual(result.logits.shape   , (self.batch_size, self.type_sequence_label_size)		)

									# test greyscale images
									SCREAMING_SNAKE_CASE__		  =				1
									SCREAMING_SNAKE_CASE__		  =				FocalNetForImageClassification(_snake_case		)
									model.to(_snake_case		)
									model.eval()

									SCREAMING_SNAKE_CASE__		  =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
									SCREAMING_SNAKE_CASE__		  =				model(_snake_case		)
									self.parent.assertEqual(result.logits.shape   , (self.batch_size, self.type_sequence_label_size)		)



					def 			lowerCAmelCase_					(						self			:				Union[str, Any]		)							->       str:
									SCREAMING_SNAKE_CASE__		  =				self.prepare_config_and_inputs()

									SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				config_and_inputs
									SCREAMING_SNAKE_CASE__		  =				{"pixel_values": pixel_values}
									return config, inputs_dict



@require_torch
class lowerCamelCase		(_SCREAMING_SNAKE_CASE    ,    _SCREAMING_SNAKE_CASE    ,    unittest.TestCase      ):






					'''simple docstring'''


					a   	=		(
					    (
					        FocalNetModel,
					        FocalNetForImageClassification,
					        FocalNetForMaskedImageModeling,
					        FocalNetBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					a   	=		(
					    {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification}
					    if is_torch_available()
					    else {}
					)
					a   	=		False

					a   	=		False
					a   	=		False
					a   	=		False
					a   	=		False



					def 			lowerCAmelCase_					(						self			:				Tuple		)							->       Optional[Any]:
									SCREAMING_SNAKE_CASE__		  =				FocalNetModelTester(self		)
									SCREAMING_SNAKE_CASE__		  =				ConfigTester(self   , config_class=_snake_case   , embed_dim=37   , has_text_modality=_snake_case		)



					def 			lowerCAmelCase_					(						self			:				Union[str, Any]		)							->       List[str]:
									self.create_and_test_config_common_properties()
									self.config_tester.create_and_test_config_to_json_string()
									self.config_tester.create_and_test_config_to_json_file()
									self.config_tester.create_and_test_config_from_and_save_pretrained()
									self.config_tester.create_and_test_config_with_num_labels()
									self.config_tester.check_config_can_be_init_without_params()
									self.config_tester.check_config_arguments_init()



					def 			lowerCAmelCase_					(						self			:				List[str]		)							->       str:
									return



					def 			lowerCAmelCase_					(						self			:				Any		)							->       int:
									SCREAMING_SNAKE_CASE__		  =				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_snake_case		)



					def 			lowerCAmelCase_					(						self			:				int		)							->       Optional[int]:
									SCREAMING_SNAKE_CASE__		  =				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_backbone(*_snake_case		)



					def 			lowerCAmelCase_					(						self			:				Union[str, Any]		)							->       List[Any]:
									SCREAMING_SNAKE_CASE__		  =				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_image_modeling(*_snake_case		)



					def 			lowerCAmelCase_					(						self			:				Optional[Any]		)							->       str:
									SCREAMING_SNAKE_CASE__		  =				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_snake_case		)



					@unittest.skip(reason="FocalNet does not use inputs_embeds"		)
					def 			lowerCAmelCase_					(						self			:				Dict		)							->       Tuple:
									pass



					@unittest.skip(reason="FocalNet does not use feedforward chunking"		)
					def 			lowerCAmelCase_					(						self			:				Optional[Any]		)							->       Any:
									pass



					def 			lowerCAmelCase_					(						self			:				Tuple		)							->       Any:
									SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes[:-1]:
													SCREAMING_SNAKE_CASE__		  =				model_class(_snake_case		)
													self.assertIsInstance(model.get_input_embeddings()   , (nn.Module)		)
													SCREAMING_SNAKE_CASE__		  =				model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_snake_case   , nn.Linear		)		)



					def 			lowerCAmelCase_					(						self			:				Union[str, Any]		)							->       Tuple:
									SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes[:-1]:
													SCREAMING_SNAKE_CASE__		  =				model_class(_snake_case		)
													SCREAMING_SNAKE_CASE__		  =				inspect.signature(model.forward		)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													SCREAMING_SNAKE_CASE__		  =				[*signature.parameters.keys()]

													SCREAMING_SNAKE_CASE__		  =				["pixel_values"]
													self.assertListEqual(arg_names[:1]   , _snake_case		)



					def 			lowerCAmelCase_					(						self			:				Union[str, Any]   , _snake_case			:				Union[str, Any]   , _snake_case			:				List[str]   , _snake_case			:				Optional[int]   , _snake_case			:				Optional[Any]		)							->       Optional[Any]:
									SCREAMING_SNAKE_CASE__		  =				model_class(_snake_case		)
									model.to(_snake_case		)
									model.eval()

									with torch.no_grad():
													SCREAMING_SNAKE_CASE__		  =				model(**self._prepare_for_class(_snake_case   , _snake_case		)		)

									SCREAMING_SNAKE_CASE__		  =				outputs.hidden_states

									SCREAMING_SNAKE_CASE__		  =				getattr(
									    self.model_tester   , "expected_num_hidden_layers"   , len(self.model_tester.depths		) + 1		)
									self.assertEqual(len(_snake_case		)   , _snake_case		)

									# FocalNet has a different seq_length
									SCREAMING_SNAKE_CASE__		  =				(
									    config.patch_size
									    if isinstance(config.patch_size   , collections.abc.Iterable		)
									    else (config.patch_size, config.patch_size)
									)

									SCREAMING_SNAKE_CASE__		  =				(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

									self.assertListEqual(
									    list(hidden_states[0].shape[-2:]		)   , [num_patches, self.model_tester.embed_dim]   , )

									SCREAMING_SNAKE_CASE__		  =				outputs.reshaped_hidden_states
									self.assertEqual(len(_snake_case		)   , _snake_case		)

									SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				reshaped_hidden_states[0].shape
									SCREAMING_SNAKE_CASE__		  =				(
									    reshaped_hidden_states[0].view(_snake_case   , _snake_case   , height * width		).permute(0   , 2   , 1		)
									)
									self.assertListEqual(
									    list(reshaped_hidden_states.shape[-2:]		)   , [num_patches, self.model_tester.embed_dim]   , )



					def 			lowerCAmelCase_					(						self			:				Optional[int]		)							->       Dict:
									SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				self.model_tester.prepare_config_and_inputs_for_common()

									SCREAMING_SNAKE_CASE__		  =				(
									    self.model_tester.image_size
									    if isinstance(self.model_tester.image_size   , collections.abc.Iterable		)
									    else (self.model_tester.image_size, self.model_tester.image_size)
									)

									for model_class in self.all_model_classes[:-1]:
													SCREAMING_SNAKE_CASE__		  =				True
													self.check_hidden_states_output(_snake_case   , _snake_case   , _snake_case   , _snake_case		)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													SCREAMING_SNAKE_CASE__		  =				True

													self.check_hidden_states_output(_snake_case   , _snake_case   , _snake_case   , _snake_case		)



					def 			lowerCAmelCase_					(						self			:				List[Any]		)							->       Dict:
									SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				self.model_tester.prepare_config_and_inputs_for_common()
									SCREAMING_SNAKE_CASE__		  =				3

									SCREAMING_SNAKE_CASE__		  =				(
									    self.model_tester.image_size
									    if isinstance(self.model_tester.image_size   , collections.abc.Iterable		)
									    else (self.model_tester.image_size, self.model_tester.image_size)
									)
									SCREAMING_SNAKE_CASE__		  =				(
									    config.patch_size
									    if isinstance(config.patch_size   , collections.abc.Iterable		)
									    else (config.patch_size, config.patch_size)
									)

									SCREAMING_SNAKE_CASE__		  =				image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
									SCREAMING_SNAKE_CASE__		  =				image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

									for model_class in self.all_model_classes[:-1]:
													SCREAMING_SNAKE_CASE__		  =				True
													self.check_hidden_states_output(_snake_case   , _snake_case   , _snake_case   , (padded_height, padded_width)		)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													SCREAMING_SNAKE_CASE__		  =				True
													self.check_hidden_states_output(_snake_case   , _snake_case   , _snake_case   , (padded_height, padded_width)		)



					@slow
					def 			lowerCAmelCase_					(						self			:				int		)							->       Union[str, Any]:
									for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													SCREAMING_SNAKE_CASE__		  =				FocalNetModel.from_pretrained(_snake_case		)
													self.assertIsNotNone(_snake_case		)



					def 			lowerCAmelCase_					(						self			:				Union[str, Any]		)							->       int:
									SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				self.model_tester.prepare_config_and_inputs_for_common()

									SCREAMING_SNAKE_CASE__		  =				_config_zero_init(_snake_case		)
									for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE__		  =				model_class(config=_snake_case		)
													for name, param in model.named_parameters():
																	if "embeddings" not in name and param.requires_grad:
																					self.assertIn(
																					    ((param.data.mean() * 1e9).round() / 1e9).item()   , [0.0, 1.0]   , msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""   , )



@require_vision
@require_torch
class lowerCamelCase		(unittest.TestCase      ):






					'''simple docstring'''


					@cached_property
					def 			lowerCAmelCase_					(						self			:				Tuple		)							->       str:
									# TODO update organization
									return AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny"		) if is_vision_available() else None



					@slow
					def 			lowerCAmelCase_					(						self			:				Tuple		)							->       List[str]:
									SCREAMING_SNAKE_CASE__		  =				FocalNetForImageClassification.from_pretrained("microsoft/focalnet-tiny"		).to(_snake_case		)
									SCREAMING_SNAKE_CASE__		  =				self.default_image_processor

									SCREAMING_SNAKE_CASE__		  =				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
									SCREAMING_SNAKE_CASE__		  =				image_processor(images=_snake_case   , return_tensors="pt"		).to(_snake_case		)

									# forward pass
									with torch.no_grad():
													SCREAMING_SNAKE_CASE__		  =				model(**_snake_case		)

									# verify the logits
									SCREAMING_SNAKE_CASE__		  =				torch.Size((1, 1000)		)
									self.assertEqual(outputs.logits.shape   , _snake_case		)
									SCREAMING_SNAKE_CASE__		  =				torch.tensor([0.2166, -0.4368, 0.2191]		).to(_snake_case		)
									self.assertTrue(torch.allclose(outputs.logits[0, :3]   , _snake_case   , atol=1e-4		)		)
									self.assertTrue(outputs.logits.argmax(dim=-1		).item()   , 281		)



@require_torch
class lowerCamelCase		(_SCREAMING_SNAKE_CASE    ,    unittest.TestCase      ):






					'''simple docstring'''


					a   	=		(FocalNetBackbone,) if is_torch_available() else ()
					a   	=		FocalNetConfig

					a   	=		False



					def 			lowerCAmelCase_					(						self			:				Dict		)							->       Any:
									SCREAMING_SNAKE_CASE__		  =				FocalNetModelTester(self		)





"""simple docstring"""






import argparse

import requests
import torch

# pip3 install salesforce-lavis
# I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis
from lavis.models import load_model_and_preprocess
from PIL import Image

from transformers import (
    AutoTokenizer,
    BlipaConfig,
    BlipaForConditionalGeneration,
    BlipaProcessor,
    BlipaVisionConfig,
    BlipImageProcessor,
    OPTConfig,
    TaConfig,
)
from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD




def 						SCREAMING_SNAKE_CASE					(  )							->   List[str]:
				SCREAMING_SNAKE_CASE__		  =				"https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png"
				SCREAMING_SNAKE_CASE__		  =				Image.open(requests.get(__UpperCAmelCase  ,					stream=__UpperCAmelCase       ).raw       ).convert("RGB"       )

				return image




def 						SCREAMING_SNAKE_CASE					(  __UpperCAmelCase       )							->   int:
				SCREAMING_SNAKE_CASE__		  =				[]
				# fmt: off

				# vision encoder
				rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding")       )
				rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding")       )
				rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight")       )
				rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias")       )
				rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight")       )
				rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias")       )

				for i in range(config.vision_config.num_hidden_layers       ):
								rename_keys.append((F"""visual_encoder.blocks.{i}.norm1.weight""", F"""vision_model.encoder.layers.{i}.layer_norm1.weight""")       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.norm1.bias""", F"""vision_model.encoder.layers.{i}.layer_norm1.bias""")       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.norm2.weight""", F"""vision_model.encoder.layers.{i}.layer_norm2.weight""")       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.norm2.bias""", F"""vision_model.encoder.layers.{i}.layer_norm2.bias""")       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.attn.qkv.weight""", F"""vision_model.encoder.layers.{i}.self_attn.qkv.weight""")       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.attn.proj.weight""", F"""vision_model.encoder.layers.{i}.self_attn.projection.weight""",)       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.attn.proj.bias""", F"""vision_model.encoder.layers.{i}.self_attn.projection.bias""")       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc1.weight""", F"""vision_model.encoder.layers.{i}.mlp.fc1.weight""")       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc1.bias""", F"""vision_model.encoder.layers.{i}.mlp.fc1.bias""")       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc2.weight""", F"""vision_model.encoder.layers.{i}.mlp.fc2.weight""")       )
								rename_keys.append((F"""visual_encoder.blocks.{i}.mlp.fc2.bias""", F"""vision_model.encoder.layers.{i}.mlp.fc2.bias""")       )

				# QFormer
				rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.layernorm.weight")       )
				rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.layernorm.bias")       )

				# fmt: on
				return rename_keys




def 						SCREAMING_SNAKE_CASE					(  __UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase       )							->   int:
				SCREAMING_SNAKE_CASE__		  =				dct.pop(__UpperCAmelCase       )
				SCREAMING_SNAKE_CASE__		  =				val




def 						SCREAMING_SNAKE_CASE					(  __UpperCAmelCase  ,					__UpperCAmelCase       )							->   Dict:
				for i in range(config.vision_config.num_hidden_layers       ):
								# read in original q and v biases
								SCREAMING_SNAKE_CASE__		  =				state_dict.pop(F"""visual_encoder.blocks.{i}.attn.q_bias"""       )
								SCREAMING_SNAKE_CASE__		  =				state_dict.pop(F"""visual_encoder.blocks.{i}.attn.v_bias"""       )

								# next, set bias in the state dict
								SCREAMING_SNAKE_CASE__		  =				torch.cat((q_bias, torch.zeros_like(__UpperCAmelCase  ,					requires_grad=__UpperCAmelCase       ), v_bias)       )
								SCREAMING_SNAKE_CASE__		  =				qkv_bias




def 						SCREAMING_SNAKE_CASE					(  __UpperCAmelCase  ,					__UpperCAmelCase       )							->   Tuple:
				SCREAMING_SNAKE_CASE__		  =				364 if "coco" in model_name else 224
				SCREAMING_SNAKE_CASE__		  =				BlipaVisionConfig(image_size=__UpperCAmelCase       ).to_dict()

				# make sure the models have proper bos_token_id and eos_token_id set (important for generation)
				# seems like flan-T5 models don't have bos_token_id properly set?
				if "opt-2.7b" in model_name:
								SCREAMING_SNAKE_CASE__		  =				OPTConfig.from_pretrained("facebook/opt-2.7b"  ,					eos_token_id=__UpperCAmelCase       ).to_dict()
				elif "opt-6.7b" in model_name:
								SCREAMING_SNAKE_CASE__		  =				OPTConfig.from_pretrained("facebook/opt-6.7b"  ,					eos_token_id=__UpperCAmelCase       ).to_dict()
				elif "t5-xl" in model_name:
								SCREAMING_SNAKE_CASE__		  =				TaConfig.from_pretrained("google/flan-t5-xl"  ,					dense_act_fn="gelu"  ,					bos_token_id=1       ).to_dict()
				elif "t5-xxl" in model_name:
								SCREAMING_SNAKE_CASE__		  =				TaConfig.from_pretrained("google/flan-t5-xxl"  ,					dense_act_fn="gelu"  ,					bos_token_id=1       ).to_dict()

				SCREAMING_SNAKE_CASE__		  =				BlipaConfig(vision_config=__UpperCAmelCase  ,					text_config=__UpperCAmelCase       )

				return config, image_size




@torch.no_grad()
def 						SCREAMING_SNAKE_CASE					(  __UpperCAmelCase  ,					__UpperCAmelCase=None  ,					__UpperCAmelCase=False       )							->   List[str]:
				SCREAMING_SNAKE_CASE__		  =				(
				    AutoTokenizer.from_pretrained("facebook/opt-2.7b"       )
				    if "opt" in model_name
				    else AutoTokenizer.from_pretrained("google/flan-t5-xl"       )
				)
				SCREAMING_SNAKE_CASE__		  =				tokenizer("\n"  ,					add_special_tokens=__UpperCAmelCase       ).input_ids[0]
				SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				get_blipa_config(__UpperCAmelCase  ,					eos_token_id=__UpperCAmelCase       )

				SCREAMING_SNAKE_CASE__		  =				BlipaForConditionalGeneration(__UpperCAmelCase       ).eval()

				SCREAMING_SNAKE_CASE__		  =				{
				    "blip2-opt-2.7b": ("blip2_opt", "pretrain_opt2.7b"),
				    "blip2-opt-6.7b": ("blip2_opt", "pretrain_opt6.7b"),
				    "blip2-opt-2.7b-coco": ("blip2_opt", "caption_coco_opt2.7b"),
				    "blip2-opt-6.7b-coco": ("blip2_opt", "caption_coco_opt6.7b"),
				    "blip2-flan-t5-xl": ("blip2_t5", "pretrain_flant5xl"),
				    "blip2-flan-t5-xl-coco": ("blip2_t5", "caption_coco_flant5xl"),
				    "blip2-flan-t5-xxl": ("blip2_t5", "pretrain_flant5xxl"),
				}

				SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				model_name_to_original[model_name]

				# load original model
				print("Loading original model..."       )
				SCREAMING_SNAKE_CASE__		  =				"cuda" if torch.cuda.is_available() else "cpu"
				SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				load_model_and_preprocess(
				    name=__UpperCAmelCase  ,					model_type=__UpperCAmelCase  ,					is_eval=__UpperCAmelCase  ,					device=__UpperCAmelCase       )
				original_model.eval()
				print("Done!"       )

				# update state dict keys
				SCREAMING_SNAKE_CASE__		  =				original_model.state_dict()
				SCREAMING_SNAKE_CASE__		  =				create_rename_keys(__UpperCAmelCase       )
				for src, dest in rename_keys:
								rename_key(__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase       )

				# some keys can be renamed efficiently
				for key, val in state_dict.copy().items():
								SCREAMING_SNAKE_CASE__		  =				state_dict.pop(__UpperCAmelCase       )
								if key.startswith("Qformer.bert"       ):
												SCREAMING_SNAKE_CASE__		  =				key.replace("Qformer.bert"  ,					"qformer"       )
								if "attention.self" in key:
												SCREAMING_SNAKE_CASE__		  =				key.replace("self"  ,					"attention"       )
								if "opt_proj" in key:
												SCREAMING_SNAKE_CASE__		  =				key.replace("opt_proj"  ,					"language_projection"       )
								if "t5_proj" in key:
												SCREAMING_SNAKE_CASE__		  =				key.replace("t5_proj"  ,					"language_projection"       )
								if key.startswith("opt"       ):
												SCREAMING_SNAKE_CASE__		  =				key.replace("opt"  ,					"language"       )
								if key.startswith("t5"       ):
												SCREAMING_SNAKE_CASE__		  =				key.replace("t5"  ,					"language"       )
								SCREAMING_SNAKE_CASE__		  =				val

				# read in qv biases
				read_in_q_v_bias(__UpperCAmelCase  ,					__UpperCAmelCase       )

				SCREAMING_SNAKE_CASE__  ,       SCREAMING_SNAKE_CASE__		  =				hf_model.load_state_dict(__UpperCAmelCase  ,					strict=__UpperCAmelCase       )
				assert len(__UpperCAmelCase       ) == 0
				assert unexpected_keys == ["qformer.embeddings.position_ids"]

				SCREAMING_SNAKE_CASE__		  =				load_demo_image()
				SCREAMING_SNAKE_CASE__		  =				vis_processors["eval"](__UpperCAmelCase       ).unsqueeze(0       ).to(__UpperCAmelCase       )
				SCREAMING_SNAKE_CASE__		  =				tokenizer(["\n"]  ,					return_tensors="pt"       ).input_ids.to(__UpperCAmelCase       )

				# create processor
				SCREAMING_SNAKE_CASE__		  =				BlipImageProcessor(
				    size={"height": image_size, "width": image_size}  ,					image_mean=__UpperCAmelCase  ,					image_std=__UpperCAmelCase       )
				SCREAMING_SNAKE_CASE__		  =				BlipaProcessor(image_processor=__UpperCAmelCase  ,					tokenizer=__UpperCAmelCase       )
				SCREAMING_SNAKE_CASE__		  =				processor(images=__UpperCAmelCase  ,					return_tensors="pt"       ).pixel_values.to(__UpperCAmelCase       )

				# make sure processor creates exact same pixel values
				assert torch.allclose(__UpperCAmelCase  ,					__UpperCAmelCase       )

				original_model.to(__UpperCAmelCase       )
				hf_model.to(__UpperCAmelCase       )
				with torch.no_grad():
								if "opt" in model_name:
												SCREAMING_SNAKE_CASE__		  =				original_model({"image": original_pixel_values, "text_input": [""]}       ).logits
												SCREAMING_SNAKE_CASE__		  =				hf_model(__UpperCAmelCase  ,					__UpperCAmelCase       ).logits
								else:
												SCREAMING_SNAKE_CASE__		  =				original_model(
												    {"image": original_pixel_values, "text_input": ["\n"], "text_output": ["\n"]}       ).logits
												SCREAMING_SNAKE_CASE__		  =				input_ids.masked_fill(input_ids == tokenizer.pad_token_id  ,					-100       )
												SCREAMING_SNAKE_CASE__		  =				hf_model(__UpperCAmelCase  ,					__UpperCAmelCase  ,					labels=__UpperCAmelCase       ).logits

				assert original_logits.shape == logits.shape
				print("First values of original logits:"  ,					original_logits[0, :3, :3]       )
				print("First values of HF logits:"  ,					logits[0, :3, :3]       )

				# assert values
				if model_name == "blip2-flan-t5-xl":
								SCREAMING_SNAKE_CASE__		  =				torch.tensor(
								    [[-41.5_850, -4.4_440, -8.9_922], [-47.4_322, -5.9_143, -1.7_340]]  ,					device=__UpperCAmelCase       )
								assert torch.allclose(logits[0, :3, :3]  ,					__UpperCAmelCase  ,					atol=1e-4       )
				elif model_name == "blip2-flan-t5-xl-coco":
								SCREAMING_SNAKE_CASE__		  =				torch.tensor(
								    [[-57.0_109, -9.8_967, -12.6_280], [-68.6_578, -12.7_191, -10.5_065]]  ,					device=__UpperCAmelCase       )
				else:
								# cast to same type
								SCREAMING_SNAKE_CASE__		  =				logits.dtype
								assert torch.allclose(original_logits.to(__UpperCAmelCase       )  ,					__UpperCAmelCase  ,					atol=1e-2       )
				print("Looks ok!"       )

				print("Generating a caption..."       )
				SCREAMING_SNAKE_CASE__		  =				""
				SCREAMING_SNAKE_CASE__		  =				tokenizer(__UpperCAmelCase  ,					return_tensors="pt"       ).input_ids.to(__UpperCAmelCase       )

				SCREAMING_SNAKE_CASE__		  =				original_model.generate({"image": original_pixel_values}       )
				SCREAMING_SNAKE_CASE__		  =				hf_model.generate(
				    __UpperCAmelCase  ,					__UpperCAmelCase  ,					do_sample=__UpperCAmelCase  ,					num_beams=5  ,					max_length=30  ,					min_length=1  ,					top_p=0.9  ,					repetition_penalty=1.0  ,					length_penalty=1.0  ,					temperature=1  ,					)
				print("Original generation:"  ,					__UpperCAmelCase       )
				SCREAMING_SNAKE_CASE__		  =				input_ids.shape[1]
				SCREAMING_SNAKE_CASE__		  =				processor.batch_decode(outputs[:, prompt_length:]  ,					skip_special_tokens=__UpperCAmelCase       )
				SCREAMING_SNAKE_CASE__		  =				[text.strip() for text in output_text]
				print("HF generation:"  ,					__UpperCAmelCase       )

				if pytorch_dump_folder_path is not None:
								processor.save_pretrained(__UpperCAmelCase       )
								hf_model.save_pretrained(__UpperCAmelCase       )

				if push_to_hub:
								processor.push_to_hub(F"""nielsr/{model_name}"""       )
								hf_model.push_to_hub(F"""nielsr/{model_name}"""       )


if __name__ == "__main__":
						_A   					=    argparse.ArgumentParser()
						_A   					=    [
						    'blip2-opt-2.7b',
						    'blip2-opt-6.7b',
						    'blip2-opt-2.7b-coco',
						    'blip2-opt-6.7b-coco',
						    'blip2-flan-t5-xl',
						    'blip2-flan-t5-xl-coco',
						    'blip2-flan-t5-xxl',
						]
						parser.add_argument(
						    '--model_name',
						    default='blip2-opt-2.7b',
						    choices=choices,
						    type=str,
						    help='Path to hf config.json of model to convert',
						)
						parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
						parser.add_argument(
						    '--push_to_hub',
						    action='store_true',
						    help='Whether to push the model and processor to the hub after converting',
						)

						_A   					=    parser.parse_args()

						convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)




