



'''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 				a  (     )       ->	List[Any]:
		snake_case__	     ='https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png'
		snake_case__	     =Image.open(requests.get(UpperCamelCase_      ,					stream=UpperCamelCase_			).raw			).convert('RGB'			)

		return image






def 				a  (     UpperCamelCase_    :    Optional[Any]			)       ->	Union[str, Any]:
		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 				a  (     UpperCamelCase_    :    Dict      ,					UpperCamelCase_    :    List[Any]      ,					UpperCamelCase_    :    Optional[Any]			)       ->	List[str]:
		snake_case__	     =dct.pop(UpperCamelCase_			)
		snake_case__	     =val






def 				a  (     UpperCamelCase_    :    Any      ,					UpperCamelCase_    :    Dict			)       ->	Any:
		for i in range(config.vision_config.num_hidden_layers			):
				# read in original q and v biases
				snake_case__	     =state_dict.pop(f"""visual_encoder.blocks.{i}.attn.q_bias"""			)
				snake_case__	     =state_dict.pop(f"""visual_encoder.blocks.{i}.attn.v_bias"""			)

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






def 				a  (     UpperCamelCase_    :    Dict      ,					UpperCamelCase_    :    Union[str, Any]			)       ->	str:
		snake_case__	     =364 if 'coco' in model_name else 224
		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:
				snake_case__	     =OPTConfig.from_pretrained('facebook/opt-2.7b'      ,					eos_token_id=UpperCamelCase_			).to_dict()
		elif "opt-6.7b" in model_name:
				snake_case__	     =OPTConfig.from_pretrained('facebook/opt-6.7b'      ,					eos_token_id=UpperCamelCase_			).to_dict()
		elif "t5-xl" in model_name:
				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:
				snake_case__	     =TaConfig.from_pretrained('google/flan-t5-xxl'      ,					dense_act_fn='gelu'      ,					bos_token_id=1			).to_dict()

		snake_case__	     =BlipaConfig(vision_config=UpperCamelCase_      ,					text_config=UpperCamelCase_			)

		return config, image_size






@torch.no_grad()
def 				a  (     UpperCamelCase_    :    Dict      ,					UpperCamelCase_    :    Optional[int]=None      ,					UpperCamelCase_    :    Union[str, Any]=False			)       ->	List[str]:
		snake_case__	     =(
		    AutoTokenizer.from_pretrained('facebook/opt-2.7b'			)
		    if 'opt' in model_name
		    else AutoTokenizer.from_pretrained('google/flan-t5-xl'			)
		)
		snake_case__	     =tokenizer('\n'      ,					add_special_tokens=UpperCamelCase_			).input_ids[0]
		snake_case__     ,	snake_case__	     =get_blipa_config(UpperCamelCase_      ,					eos_token_id=UpperCamelCase_			)

		snake_case__	     =BlipaForConditionalGeneration(UpperCamelCase_			).eval()

		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'),
		}

		snake_case__     ,	snake_case__	     =model_name_to_original[model_name]

		# load original model
		print('Loading original model...'			)
		snake_case__	     ='cuda' if torch.cuda.is_available() else 'cpu'
		snake_case__     ,	snake_case__     ,	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
		snake_case__	     =original_model.state_dict()
		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():
				snake_case__	     =state_dict.pop(UpperCamelCase_			)
				if key.startswith('Qformer.bert'			):
						snake_case__	     =key.replace('Qformer.bert'      ,					'qformer'			)
				if "attention.self" in key:
						snake_case__	     =key.replace('self'      ,					'attention'			)
				if "opt_proj" in key:
						snake_case__	     =key.replace('opt_proj'      ,					'language_projection'			)
				if "t5_proj" in key:
						snake_case__	     =key.replace('t5_proj'      ,					'language_projection'			)
				if key.startswith('opt'			):
						snake_case__	     =key.replace('opt'      ,					'language'			)
				if key.startswith('t5'			):
						snake_case__	     =key.replace('t5'      ,					'language'			)
				snake_case__	     =val

		# read in qv biases
		read_in_q_v_bias(UpperCamelCase_      ,					UpperCamelCase_			)

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

		snake_case__	     =load_demo_image()
		snake_case__	     =vis_processors['eval'](UpperCamelCase_			).unsqueeze(0			).to(UpperCamelCase_			)
		snake_case__	     =tokenizer(['\n']      ,					return_tensors='pt'			).input_ids.to(UpperCamelCase_			)

		# create processor
		snake_case__	     =BlipImageProcessor(
		    size={'height': image_size, 'width': image_size}      ,					image_mean=UpperCamelCase_      ,					image_std=UpperCamelCase_			)
		snake_case__	     =BlipaProcessor(image_processor=UpperCamelCase_      ,					tokenizer=UpperCamelCase_			)
		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:
						snake_case__	     =original_model({'image': original_pixel_values, 'text_input': ['']}			).logits
						snake_case__	     =hf_model(UpperCamelCase_      ,					UpperCamelCase_			).logits
				else:
						snake_case__	     =original_model(
						    {'image': original_pixel_values, 'text_input': ['\n'], 'text_output': ['\n']}			).logits
						snake_case__	     =input_ids.masked_fill(input_ids == tokenizer.pad_token_id      ,					-100			)
						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":
				snake_case__	     =torch.tensor(
				    [[-4_1.5_8_5_0, -4.4_4_4_0, -8.9_9_2_2], [-4_7.4_3_2_2, -5.9_1_4_3, -1.7_3_4_0]]      ,					device=UpperCamelCase_			)
				assert torch.allclose(logits[0, :3, :3]      ,					UpperCamelCase_      ,					atol=1e-4			)
		elif model_name == "blip2-flan-t5-xl-coco":
				snake_case__	     =torch.tensor(
				    [[-5_7.0_1_0_9, -9.8_9_6_7, -1_2.6_2_8_0], [-6_8.6_5_7_8, -1_2.7_1_9_1, -1_0.5_0_6_5]]      ,					device=UpperCamelCase_			)
		else:
				# cast to same type
				snake_case__	     =logits.dtype
				assert torch.allclose(original_logits.to(UpperCamelCase_			)      ,					UpperCamelCase_      ,					atol=1e-2			)
		print('Looks ok!'			)

		print('Generating a caption...'			)
		snake_case__	     =''
		snake_case__	     =tokenizer(UpperCamelCase_      ,					return_tensors='pt'			).input_ids.to(UpperCamelCase_			)

		snake_case__	     =original_model.generate({'image': original_pixel_values}			)
		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_			)
		snake_case__	     =input_ids.shape[1]
		snake_case__	     =processor.batch_decode(outputs[:, prompt_length:]      ,					skip_special_tokens=UpperCamelCase_			)
		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__":
			SCREAMING_SNAKE_CASE__     :						Dict	=  argparse.ArgumentParser()
			SCREAMING_SNAKE_CASE__     :						Union[str, Any]	=  [
			    '''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''',
			)

			SCREAMING_SNAKE_CASE__     :						Optional[int]	=  parser.parse_args()

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









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






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






			def 						_lowercase  (     self						)							->							Dict:
					snake_case__	     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

					snake_case__	     =self.get_config()

					return config, pixel_values, labels






			def 						_lowercase  (     self						)							->							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 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =FocalNetModel(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

					snake_case__	     =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
					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 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Optional[int]:
					snake_case__	     =FocalNetBackbone(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

					# 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
					snake_case__	     =None
					snake_case__	     =FocalNetBackbone(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

					# 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 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Any:
					snake_case__	     =FocalNetForMaskedImageModeling(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(
					    result.reconstruction.shape					,   (self.batch_size, self.num_channels, self.image_size, self.image_size)						)

					# test greyscale images
					snake_case__	     =1
					snake_case__	     =FocalNetForMaskedImageModeling(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

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






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Tuple:
					snake_case__	     =self.type_sequence_label_size
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase					,   labels=_UpperCAmelCase						)
					self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)						)

					# test greyscale images
					snake_case__	     =1
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

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






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__	     =self.prepare_config_and_inputs()

					snake_case__     ,	snake_case__     ,	snake_case__	     =config_and_inputs
					snake_case__	     ={'pixel_values': pixel_values}
					return config, inputs_dict





@require_torch
class 							a__( snake_case__   ,      snake_case__   ,      unittest.TestCase     ):
			a_	: str									=      (
			    (
			        FocalNetModel,
			        FocalNetForImageClassification,
			        FocalNetForMaskedImageModeling,
			        FocalNetBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			a_	: Union[str, Any]									=      (
			    {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
			    if is_torch_available()
			    else {}
			)
			a_	: Dict									=      False

			a_	: Any									=      False
			a_	: List[str]									=      False
			a_	: List[Any]									=      False
			a_	: Optional[Any]									=      False






			def 						_lowercase  (     self						)							->							Optional[int]:
					snake_case__	     =FocalNetModelTester(self						)
					snake_case__	     =ConfigTester(self					,   config_class=_UpperCAmelCase					,   embed_dim=37					,   has_text_modality=_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					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 						_lowercase  (     self						)							->							str:
					return






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Union[str, Any]:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase						)






			@unittest.skip(reason='FocalNet does not use inputs_embeds'						)
			def 						_lowercase  (     self						)							->							str:
					pass






			@unittest.skip(reason='FocalNet does not use feedforward chunking'						)
			def 						_lowercase  (     self						)							->							int:
					pass






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

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






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

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

							snake_case__	     =['pixel_values']
							self.assertListEqual(arg_names[:1]					,   _UpperCAmelCase						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =model_class(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					with torch.no_grad():
							snake_case__	     =model(**self._prepare_for_class(_UpperCAmelCase					,   _UpperCAmelCase						)						)

					snake_case__	     =outputs.hidden_states

					snake_case__	     =getattr(
					    self.model_tester					,   'expected_num_hidden_layers'					,   len(self.model_tester.depths						) + 1						)
					self.assertEqual(len(_UpperCAmelCase						)					,   _UpperCAmelCase						)

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

					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]					,   )

					snake_case__	     =outputs.reshaped_hidden_states
					self.assertEqual(len(_UpperCAmelCase						)					,   _UpperCAmelCase						)

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






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					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]:
							snake_case__	     =True
							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)

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

							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()
					snake_case__	     =3

					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)
					)
					snake_case__	     =(
					    config.patch_size
					    if isinstance(config.patch_size					,   collections.abc.Iterable						)
					    else (config.patch_size, config.patch_size)
					)

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

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

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






			@slow
			def 						_lowercase  (     self						)							->							Optional[Any]:
					for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case__	     =FocalNetModel.from_pretrained(_UpperCAmelCase						)
							self.assertIsNotNone(_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							int:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__	     =_config_zero_init(_UpperCAmelCase						)
					for model_class in self.all_model_classes:
							snake_case__	     =model_class(config=_UpperCAmelCase						)
							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 							a__( unittest.TestCase     ):






			@cached_property
			def 						_lowercase  (     self						)							->							Any:
					# TODO update organization
					return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'						) if is_vision_available() else None






			@slow
			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'						).to(_UpperCAmelCase						)
					snake_case__	     =self.default_image_processor

					snake_case__	     =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
					snake_case__	     =image_processor(images=_UpperCAmelCase					,   return_tensors='pt'						).to(_UpperCAmelCase						)

					# forward pass
					with torch.no_grad():
							snake_case__	     =model(**_UpperCAmelCase						)

					# verify the logits
					snake_case__	     =torch.Size((1, 1000)						)
					self.assertEqual(outputs.logits.shape					,   _UpperCAmelCase						)
					snake_case__	     =torch.tensor([0.2_166, -0.4_368, 0.2_191]						).to(_UpperCAmelCase						)
					self.assertTrue(torch.allclose(outputs.logits[0, :3]					,   _UpperCAmelCase					,   atol=1E-4						)						)
					self.assertTrue(outputs.logits.argmax(dim=-1						).item()					,   281						)





@require_torch
class 							a__( snake_case__   ,      unittest.TestCase     ):
			a_	: int									=      (FocalNetBackbone,) if is_torch_available() else ()
			a_	: Any									=      FocalNetConfig

			a_	: int									=      False






			def 						_lowercase  (     self						)							->							Optional[int]:
					snake_case__	     =FocalNetModelTester(self						)




