



'''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_float32 (there's also the fix_lavis branch)
# also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml
# same for Vicuna-13b
from lavis.models import load_model_and_preprocess
from PIL import Image

from transformers import (
    AutoTokenizer,
    BlipImageProcessor,
    InstructBlipConfig,
    InstructBlipForConditionalGeneration,
    InstructBlipProcessor,
    InstructBlipQFormerConfig,
    InstructBlipVisionConfig,
    LlamaConfig,
    LlamaTokenizerFast,
    TaConfig,
    TaTokenizerFast,
)
from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD




def        lowerCamelCase  (				):





    '''simple docstring'''


    lowercase__		       =						"https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg"
    lowercase__		       =						Image.open(requests.get(_snake_case     ,stream=_snake_case       ).raw       ).convert("RGB"       )

    return image




def        lowerCamelCase  (				_snake_case  :						Union[str, Any]       ):





    '''simple docstring'''


    lowercase__		       =						[]
    # 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.embeddings.layernorm.weight")       )
    rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.embeddings.layernorm.bias")       )

    # fmt: on
    return rename_keys




def        lowerCamelCase  (				_snake_case  :						List[str]     ,_snake_case  :						int     ,_snake_case  :						List[str]       ):





    '''simple docstring'''


    lowercase__		       =						dct.pop(_snake_case       )
    lowercase__		       =						val




def        lowerCamelCase  (				_snake_case  :						str     ,_snake_case  :						List[Any]       ):





    '''simple docstring'''


    for i in range(config.vision_config.num_hidden_layers       ):
        # read in original q and v biases
        lowercase__		       =						state_dict.pop(f'''visual_encoder.blocks.{i}.attn.q_bias'''       )
        lowercase__		       =						state_dict.pop(f'''visual_encoder.blocks.{i}.attn.v_bias'''       )

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




def        lowerCamelCase  (				_snake_case  :						List[str]       ):





    '''simple docstring'''


    lowercase__		       =						364 if "coco" in model_name else 224
    lowercase__		       =						InstructBlipVisionConfig(image_size=_snake_case       ).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 "t5-xl" in model_name:
        lowercase__		       =						TaConfig.from_pretrained("google/flan-t5-xl"     ,dense_act_fn="gelu"     ,bos_token_id=1       ).to_dict()
    elif "t5-xxl" in model_name:
        lowercase__		       =						TaConfig.from_pretrained("google/flan-t5-xxl"     ,dense_act_fn="gelu"     ,bos_token_id=1       ).to_dict()
    elif "vicuna-7b" in model_name:
        lowercase__		       =						LlamaConfig.from_pretrained("decapoda-research/llama-7b-hf"     ,vocab_size=32_001       ).to_dict()
    elif "vicuna-13b" in model_name:
        lowercase__		       =						LlamaConfig.from_pretrained("decapoda-research/llama-13b-hf"     ,vocab_size=32_001       ).to_dict()
    else:
        raise ValueError("Model name not supported"       )

    # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1
    lowercase__		       =						InstructBlipQFormerConfig(vocab_size=30_523       ).to_dict()
    lowercase__		       =						InstructBlipConfig(vision_config=_snake_case     ,text_config=_snake_case     ,qformer_config=_snake_case       )

    return config, image_size




@torch.no_grad()
def        lowerCamelCase  (				_snake_case  :						List[str]     ,_snake_case  :						Optional[Any]=None     ,_snake_case  :						Optional[int]=False       ):





    '''simple docstring'''


    lowercase__		       =						AutoTokenizer.from_pretrained("bert-base-uncased"     ,truncation_side="left"       )
    qformer_tokenizer.add_special_tokens({"bos_token": "[DEC]"}       )

    if "t5" in model_name:
        lowercase__		       =						TaTokenizerFast.from_pretrained("google/flan-t5-xl"     ,truncation_side="left"       )
    elif "vicuna" in model_name:
        # the following was used in the original implementation:
        # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left")
        # tokenizer.add_special_tokens({"pad_token": "[PAD]"})
        # tokenizer.add_special_tokens({"bos_token": "</s>"})
        # tokenizer.add_special_tokens({"eos_token": "</s>"})
        # tokenizer.add_special_tokens({"unk_token": "</s>"})
        lowercase__		       =						LlamaTokenizerFast.from_pretrained(
            "huggyllama/llama-7b"     ,truncation_side="left"     ,bos_token="</s>"     ,unk_token="</s>"       )
        tokenizer.add_special_tokens({"pad_token": "[PAD]"}       )

    lowercase__       ,       lowercase__		       =						get_blipa_config(_snake_case       )
    lowercase__		       =						InstructBlipForConditionalGeneration(_snake_case       ).eval()

    lowercase__		       =						{
        "instructblip-vicuna-7b": ("blip2_vicuna_instruct", "vicuna7b"),
        "instructblip-vicuna-13b": ("blip2_vicuna_instruct", "vicuna13b"),
        "instructblip-flan-t5-xl": ("blip2_t5_instruct", "flant5xl"),
        "instructblip-flan-t5-xxl": ("blip2_t5_instruct", "flant5xxl"),
    }

    lowercase__       ,       lowercase__		       =						model_name_to_original[model_name]

    # load original model
    print("Loading original model..."       )
    lowercase__		       =						"cuda:1" if torch.cuda.is_available() else "cpu"
    lowercase__		       =						"cuda:2" if torch.cuda.is_available() else "cpu"
    lowercase__       ,       lowercase__       ,       lowercase__		       =						load_model_and_preprocess(
        name=_snake_case     ,model_type=_snake_case     ,is_eval=_snake_case     ,device=_snake_case       )
    original_model.eval()
    print("Done!"       )

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

    # some keys can be renamed efficiently
    for key, val in state_dict.copy().items():
        lowercase__		       =						state_dict.pop(_snake_case       )
        if key.startswith("Qformer.bert"       ):
            lowercase__		       =						key.replace("Qformer.bert"     ,"qformer"       )
        if "attention.self" in key:
            lowercase__		       =						key.replace("self"     ,"attention"       )
        if "llm_proj" in key:
            lowercase__		       =						key.replace("llm_proj"     ,"language_projection"       )
        if "t5_proj" in key:
            lowercase__		       =						key.replace("t5_proj"     ,"language_projection"       )
        if key.startswith("llm_model"       ):
            lowercase__		       =						key.replace("llm_model"     ,"language_model"       )
        if key.startswith("t5"       ):
            lowercase__		       =						key.replace("t5"     ,"language"       )
        lowercase__		       =						val

    # read in qv biases
    read_in_q_v_bias(_snake_case     ,_snake_case       )

    # note: weights get loaded in torch.float32 by default
    hf_model.load_state_dict(_snake_case     ,strict=_snake_case       )

    lowercase__		       =						load_demo_image()
    lowercase__		       =						"What is unusual about this image?"

    # create processor
    lowercase__		       =						BlipImageProcessor(
        size={"height": image_size, "width": image_size}     ,image_mean=_snake_case     ,image_std=_snake_case       )
    lowercase__		       =						InstructBlipProcessor(
        image_processor=_snake_case     ,tokenizer=_snake_case     ,qformer_tokenizer=_snake_case     ,)
    lowercase__		       =						processor(images=_snake_case     ,text=_snake_case     ,return_tensors="pt"       ).to(_snake_case       )

    # make sure processor creates exact same pixel values
    lowercase__		       =						vis_processors["eval"](_snake_case       ).unsqueeze(0       ).to(_snake_case       )
    lowercase__		       =						inputs.pixel_values
    assert torch.allclose(original_pixel_values.to(pixel_values.device       )     ,_snake_case       )

    original_model.to(_snake_case       )
    hf_model.to(_snake_case       )
    with torch.no_grad():
        if "vicuna" in model_name:
            lowercase__		       =						original_model({"image": original_pixel_values, "text_input": [prompt]}       ).logits
            lowercase__		       =						hf_model(**_snake_case       ).logits
        else:
            lowercase__		       =						original_model(
                {"image": original_pixel_values, "text_input": [prompt], "text_output": ["\n"]}       ).logits
            lowercase__		       =						tokenizer("\n"     ,return_tensors="pt"       ).input_ids.to(_snake_case       )
            lowercase__		       =						label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id     ,-100       )
            lowercase__		       =						hf_model(**_snake_case     ,labels=_snake_case       ).logits

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

    # assert values
    assert original_logits.shape == logits.shape
    lowercase__		       =						1e-4 if "vicuna" in model_name else 1e-5
    assert torch.allclose(original_logits.to(logits.device       )     ,_snake_case     ,atol=_snake_case       )
    print("Looks ok!"       )

    print("Generating with original model..."       )
    lowercase__		       =						original_model.generate({"image": original_pixel_values, "prompt": prompt}     ,num_beams=5       )

    # important: we need to cast the weights of the HF model to the appropriate type
    print("Generating with HF model..."       )
    lowercase__		       =						hf_model.generate(
        **_snake_case     ,do_sample=_snake_case     ,num_beams=5     ,max_length=256     ,min_length=1     ,top_p=0.9     ,repetition_penalty=1.5     ,length_penalty=1.0     ,temperature=1     ,)
    if "vicuna" in model_name:
        # convert output id 0 to 2 (eos_token_id)
        # TODO add this in the generate method?
        lowercase__		       =						2
    print("Original generation:"     ,_snake_case       )
    lowercase__		       =						processor.batch_decode(_snake_case     ,skip_special_tokens=_snake_case       )
    lowercase__		       =						[text.strip() for text in output_text]
    print("HF generation:"     ,_snake_case       )

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

    if push_to_hub:
        processor.push_to_hub(f'''Salesforce/{model_name}'''       )
        hf_model.push_to_hub(f'''Salesforce/{model_name}'''       )


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE__      					=     argparse.ArgumentParser()
 SCREAMING_SNAKE_CASE__      					=     [
     "instructblip-vicuna-7b",
     "instructblip-vicuna-13b",
     "instructblip-flan-t5-xl",
     "instructblip-flan-t5-xxl",
 ]
 parser.add_argument(
     "--model_name",
     default="instructblip-flan-t5-xl",
     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__      					=     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 				snake_case :



       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]     ,)  ->							Dict:
           lowercase__		       =						parent
           lowercase__		       =						batch_size
           lowercase__		       =						image_size
           lowercase__		       =						patch_size
           lowercase__		       =						num_channels
           lowercase__		       =						embed_dim
           lowercase__		       =						hidden_sizes
           lowercase__		       =						depths
           lowercase__		       =						num_heads
           lowercase__		       =						window_size
           lowercase__		       =						mlp_ratio
           lowercase__		       =						qkv_bias
           lowercase__		       =						hidden_dropout_prob
           lowercase__		       =						attention_probs_dropout_prob
           lowercase__		       =						drop_path_rate
           lowercase__		       =						hidden_act
           lowercase__		       =						use_absolute_embeddings
           lowercase__		       =						patch_norm
           lowercase__		       =						layer_norm_eps
           lowercase__		       =						initializer_range
           lowercase__		       =						is_training
           lowercase__		       =						scope
           lowercase__		       =						use_labels
           lowercase__		       =						type_sequence_label_size
           lowercase__		       =						encoder_stride
           lowercase__		       =						out_features
           lowercase__		       =						out_indices



       def 							_a      (				self      )  ->							int:
           lowercase__		       =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

           lowercase__		       =						self.get_config()

           return config, pixel_values, labels



       def 							_a      (				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 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							str:
           lowercase__		       =						FocalNetModel(config=UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_      )

           lowercase__		       =						((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths      ) - 1))
           lowercase__		       =						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 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Dict:
           lowercase__		       =						FocalNetBackbone(config=UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						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
           lowercase__		       =						None
           lowercase__		       =						FocalNetBackbone(config=UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						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 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Dict:
           lowercase__		       =						FocalNetForMaskedImageModeling(config=UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_      )
           self.parent.assertEqual(
               result.reconstruction.shape     ,(self.batch_size, self.num_channels, self.image_size, self.image_size)      )

           # test greyscale images
           lowercase__		       =						1
           lowercase__		       =						FocalNetForMaskedImageModeling(UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()

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



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Optional[Any]:
           lowercase__		       =						self.type_sequence_label_size
           lowercase__		       =						FocalNetForImageClassification(UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_     ,labels=UpperCAmelCase_      )
           self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.type_sequence_label_size)      )

           # test greyscale images
           lowercase__		       =						1
           lowercase__		       =						FocalNetForImageClassification(UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()

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







       def 							_a      (				self      )  ->							List[str]:
           lowercase__		       =						self.prepare_config_and_inputs()

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





@require_torch
class 				snake_case (UpperCamelCase		,      UpperCamelCase		,      unittest.TestCase   ):
       lowerCAmelCase__  :List[str]						   =					(
           (
               FocalNetModel,
               FocalNetForImageClassification,
               FocalNetForMaskedImageModeling,
               FocalNetBackbone,
           )
           if is_torch_available()
           else ()
       )
       lowerCAmelCase__  :str						   =					(
           {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification}
           if is_torch_available()
           else {}
       )
       lowerCAmelCase__  :str						   =					False

       lowerCAmelCase__  :List[Any]						   =					False
       lowerCAmelCase__  :Dict						   =					False
       lowerCAmelCase__  :List[Any]						   =					False
       lowerCAmelCase__  :Union[str, Any]						   =					False



       def 							_a      (				self      )  ->							Any:
           lowercase__		       =						FocalNetModelTester(self      )
           lowercase__		       =						ConfigTester(self     ,config_class=UpperCAmelCase_     ,embed_dim=37     ,has_text_modality=UpperCAmelCase_      )



       def 							_a      (				self      )  ->							Optional[int]:
           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 							_a      (				self      )  ->							List[Any]:
           return



       def 							_a      (				self      )  ->							Tuple:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCAmelCase_      )



       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*UpperCAmelCase_      )



       def 							_a      (				self      )  ->							str:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase_      )



       def 							_a      (				self      )  ->							Dict:
           lowercase__		       =						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 							_a      (				self      )  ->							str:
           pass



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



       def 							_a      (				self      )  ->							int:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()

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



       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()

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

               lowercase__		       =						["pixel_values"]
               self.assertListEqual(arg_names[:1]     ,UpperCAmelCase_      )



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							List[Any]:
           lowercase__		       =						model_class(UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()

           with torch.no_grad():
               lowercase__		       =						model(**self._prepare_for_class(UpperCAmelCase_     ,UpperCAmelCase_      )      )

           lowercase__		       =						outputs.hidden_states

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

           lowercase__		       =						(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]     ,)

           lowercase__		       =						outputs.reshaped_hidden_states
           self.assertEqual(len(UpperCAmelCase_      )     ,UpperCAmelCase_      )

           lowercase__       ,       lowercase__       ,       lowercase__       ,       lowercase__		       =						reshaped_hidden_states[0].shape
           lowercase__		       =						(
               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 							_a      (				self      )  ->							str:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()

           lowercase__		       =						(
               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]:
               lowercase__		       =						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"]
               lowercase__		       =						True

               self.check_hidden_states_output(UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )



       def 							_a      (				self      )  ->							int:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()
           lowercase__		       =						3

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

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

           for model_class in self.all_model_classes[:-1]:
               lowercase__		       =						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"]
               lowercase__		       =						True
               self.check_hidden_states_output(UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,(padded_height, padded_width)      )



       @slow
       def 							_a      (				self      )  ->							Dict:
           for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowercase__		       =						FocalNetModel.from_pretrained(UpperCAmelCase_      )
               self.assertIsNotNone(UpperCAmelCase_      )







       def 							_a      (				self      )  ->							List[Any]:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()

           lowercase__		       =						_config_zero_init(UpperCAmelCase_      )
           for model_class in self.all_model_classes:
               lowercase__		       =						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 				snake_case (unittest.TestCase   ):



       @cached_property
       def 							_a      (				self      )  ->							Optional[int]:
           # TODO update organization
           return AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny"      ) if is_vision_available() else None







       @slow
       def 							_a      (				self      )  ->							List[str]:
           lowercase__		       =						FocalNetForImageClassification.from_pretrained("microsoft/focalnet-tiny"      ).to(UpperCAmelCase_      )
           lowercase__		       =						self.default_image_processor

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

           # forward pass
           with torch.no_grad():
               lowercase__		       =						model(**UpperCAmelCase_      )

           # verify the logits
           lowercase__		       =						torch.Size((1, 1_000)      )
           self.assertEqual(outputs.logits.shape     ,UpperCAmelCase_      )
           lowercase__		       =						torch.tensor([0.21_66, -0.43_68, 0.21_91]      ).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 				snake_case (UpperCamelCase		,      unittest.TestCase   ):
       lowerCAmelCase__  :Tuple						   =					(FocalNetBackbone,) if is_torch_available() else ()
       lowerCAmelCase__  :int						   =					FocalNetConfig

       lowerCAmelCase__  :List[Any]						   =					False



       def 							_a      (				self      )  ->							Optional[int]:
           lowercase__		       =						FocalNetModelTester(self      )




