




'''simple docstring'''







import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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


if is_torch_available():
   import torch

   from transformers import (
       MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
       MODEL_MAPPING,
       LevitForImageClassification,
       LevitForImageClassificationWithTeacher,
       LevitModel,
   )
   from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import LevitImageProcessor


class     _a						(			__a				):
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.config_class(**self.inputs_dict       )
           self.parent.assertTrue(hasattr(lowercase     ,       '''hidden_sizes'''       )       )
           self.parent.assertTrue(hasattr(lowercase     ,       '''num_attention_heads'''       )       )






class     _a						:
       def __init__(			self		:			Any     ,       lowercase		:			Optional[Any]     ,       lowercase		:			Dict=13     ,       lowercase		:			List[Any]=64     ,       lowercase		:			int=3     ,       lowercase		:			Dict=3     ,       lowercase		:			Dict=2     ,       lowercase		:			Any=1     ,       lowercase		:			Optional[int]=16     ,       lowercase		:			List[str]=[128, 256, 384]     ,       lowercase		:			List[str]=[4, 6, 8]     ,       lowercase		:			List[str]=[2, 3, 4]     ,       lowercase		:			List[Any]=[16, 16, 16]     ,       lowercase		:			Union[str, Any]=0     ,       lowercase		:			str=[2, 2, 2]     ,       lowercase		:			str=[2, 2, 2]     ,       lowercase		:			Union[str, Any]=0.02     ,       lowercase		:			Optional[Any]=True     ,       lowercase		:			Union[str, Any]=True     ,       lowercase		:			str=2     ,       ):



           '''simple docstring'''

           UpperCAmelCase     =	parent
           UpperCAmelCase     =	batch_size
           UpperCAmelCase     =	image_size
           UpperCAmelCase     =	num_channels
           UpperCAmelCase     =	kernel_size
           UpperCAmelCase     =	stride
           UpperCAmelCase     =	padding
           UpperCAmelCase     =	hidden_sizes
           UpperCAmelCase     =	num_attention_heads
           UpperCAmelCase     =	depths
           UpperCAmelCase     =	key_dim
           UpperCAmelCase     =	drop_path_rate
           UpperCAmelCase     =	patch_size
           UpperCAmelCase     =	attention_ratio
           UpperCAmelCase     =	mlp_ratio
           UpperCAmelCase     =	initializer_range
           UpperCAmelCase     =	[
               ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
               ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
           ]
           UpperCAmelCase     =	is_training
           UpperCAmelCase     =	use_labels
           UpperCAmelCase     =	num_labels
           UpperCAmelCase     =	initializer_range
       def 					A   (			self		:			str       ):



           '''simple docstring'''

           UpperCAmelCase     =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

           UpperCAmelCase     =	None
           if self.use_labels:
               UpperCAmelCase     =	ids_tensor([self.batch_size]     ,       self.num_labels       )

           UpperCAmelCase     =	self.get_config()
           return config, pixel_values, labels
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           return LevitConfig(
               image_size=self.image_size     ,       num_channels=self.num_channels     ,       kernel_size=self.kernel_size     ,       stride=self.stride     ,       padding=self.padding     ,       patch_size=self.patch_size     ,       hidden_sizes=self.hidden_sizes     ,       num_attention_heads=self.num_attention_heads     ,       depths=self.depths     ,       key_dim=self.key_dim     ,       drop_path_rate=self.drop_path_rate     ,       mlp_ratio=self.mlp_ratio     ,       attention_ratio=self.attention_ratio     ,       initializer_range=self.initializer_range     ,       down_ops=self.down_ops     ,       )
       def 					A   (			self		:			Dict     ,       lowercase		:			Any     ,       lowercase		:			Dict     ,       lowercase		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	LevitModel(config=lowercase       )
           model.to(lowercase       )
           model.eval()
           UpperCAmelCase     =	model(lowercase       )
           UpperCAmelCase     =	(self.image_size, self.image_size)
           UpperCAmelCase ,  UpperCAmelCase     =	image_size[0], image_size[1]
           for _ in range(4       ):
               UpperCAmelCase     =	floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1       )
               UpperCAmelCase     =	floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1       )
           self.parent.assertEqual(
               result.last_hidden_state.shape     ,       (self.batch_size, ceil(height / 4       ) * ceil(width / 4       ), self.hidden_sizes[-1])     ,       )
       def 					A   (			self		:			Any     ,       lowercase		:			Dict     ,       lowercase		:			List[Any]     ,       lowercase		:			Tuple       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.num_labels
           UpperCAmelCase     =	LevitForImageClassification(lowercase       )
           model.to(lowercase       )
           model.eval()
           UpperCAmelCase     =	model(lowercase     ,       labels=lowercase       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.num_labels)       )







       def 					A   (			self		:			Tuple       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.prepare_config_and_inputs()
           UpperCAmelCase ,  UpperCAmelCase ,  UpperCAmelCase     =	config_and_inputs
           UpperCAmelCase     =	{'''pixel_values''': pixel_values}
           return config, inputs_dict






@require_torch
class     _a						(			__a							,							__a							,							unittest.TestCase				):
       __a       :  str            =      (
           (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
           if is_torch_available()
           else ()
       )
       __a       :  Union[str, Any]            =      (
           {
               """feature-extraction""": LevitModel,
               """image-classification""": (LevitForImageClassification, LevitForImageClassificationWithTeacher),
           }
           if is_torch_available()
           else {}
       )

       __a       :  Any            =      False
       __a       :  Optional[Any]            =      False
       __a       :  Union[str, Any]            =      False
       __a       :  Optional[Any]            =      False
       __a       :  List[Any]            =      False
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	LevitModelTester(self       )
           UpperCAmelCase     =	ConfigTester(self     ,       config_class=lowercase     ,       has_text_modality=lowercase     ,       hidden_size=37       )
       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           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		:			Optional[Any]       ):



           '''simple docstring'''

           return
       @unittest.skip(reason='''Levit does not use inputs_embeds'''       )
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           pass
       @unittest.skip(reason='''Levit does not support input and output embeddings'''       )
       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           pass
       @unittest.skip(reason='''Levit does not output attentions'''       )
       def 					A   (			self		:			int       ):



           '''simple docstring'''

           pass
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase ,  UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs_for_common()

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

               UpperCAmelCase     =	['''pixel_values''']
               self.assertListEqual(arg_names[:1]     ,       lowercase       )
       def 					A   (			self		:			Dict       ):



           '''simple docstring'''

           def check_hidden_states_output(lowercase		:			Optional[int]     ,       lowercase		:			Any     ,       lowercase		:			Tuple       ):
               UpperCAmelCase     =	model_class(lowercase       )
               model.to(lowercase       )
               model.eval()

               with torch.no_grad():
                   UpperCAmelCase     =	model(**self._prepare_for_class(lowercase     ,       lowercase       )       )

               UpperCAmelCase     =	outputs.hidden_states

               UpperCAmelCase     =	len(self.model_tester.depths       ) + 1
               self.assertEqual(len(lowercase       )     ,       lowercase       )

               UpperCAmelCase     =	(self.model_tester.image_size, self.model_tester.image_size)
               UpperCAmelCase ,  UpperCAmelCase     =	image_size[0], image_size[1]
               for _ in range(4       ):
                   UpperCAmelCase     =	floor(
                       (
                           (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
                           / self.model_tester.stride
                       )
                       + 1       )
                   UpperCAmelCase     =	floor(
                       (
                           (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
                           / self.model_tester.stride
                       )
                       + 1       )
               # verify the first hidden states (first block)
               self.assertListEqual(
                   list(hidden_states[0].shape[-2:]       )     ,       [
                       height * width,
                       self.model_tester.hidden_sizes[0],
                   ]     ,       )

           UpperCAmelCase ,  UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               UpperCAmelCase     =	True
               check_hidden_states_output(lowercase     ,       lowercase     ,       lowercase       )

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

               check_hidden_states_output(lowercase     ,       lowercase     ,       lowercase       )
       @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''       )
       def 					A   (			self		:			int       ):



           '''simple docstring'''

           pass
       def 					A   (			self		:			Tuple     ,       lowercase		:			str     ,       lowercase		:			Optional[Any]     ,       lowercase		:			Union[str, Any]=False       ):



           '''simple docstring'''

           UpperCAmelCase     =	super()._prepare_for_class(lowercase     ,       lowercase     ,       return_labels=lowercase       )

           if return_labels:
               if model_class.__name__ == "LevitForImageClassificationWithTeacher":
                   del inputs_dict["labels"]

           return inputs_dict
       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase       )
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowercase       )
       def 					A   (			self		:			Dict       ):



           '''simple docstring'''

           if not self.model_tester.is_training:
               return

           UpperCAmelCase ,  UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs_for_common()
           UpperCAmelCase     =	True

           for model_class in self.all_model_classes:
               # LevitForImageClassificationWithTeacher supports inference-only
               if (
                   model_class in get_values(lowercase       )
                   or model_class.__name__ == "LevitForImageClassificationWithTeacher"
               ):
                   continue
               UpperCAmelCase     =	model_class(lowercase       )
               model.to(lowercase       )
               model.train()
               UpperCAmelCase     =	self._prepare_for_class(lowercase     ,       lowercase     ,       return_labels=lowercase       )
               UpperCAmelCase     =	model(**lowercase       ).loss
               loss.backward()
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase ,  UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs_for_common()
           if not self.model_tester.is_training:
               return

           UpperCAmelCase     =	False
           UpperCAmelCase     =	True

           for model_class in self.all_model_classes:
               if model_class in get_values(lowercase       ) or not model_class.supports_gradient_checkpointing:
                   continue
               # LevitForImageClassificationWithTeacher supports inference-only
               if model_class.__name__ == "LevitForImageClassificationWithTeacher":
                   continue
               UpperCAmelCase     =	model_class(lowercase       )
               model.gradient_checkpointing_enable()
               model.to(lowercase       )
               model.train()
               UpperCAmelCase     =	self._prepare_for_class(lowercase     ,       lowercase     ,       return_labels=lowercase       )
               UpperCAmelCase     =	model(**lowercase       ).loss
               loss.backward()
       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase ,  UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs_for_common()

           UpperCAmelCase     =	[
               {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float},
               {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long},
               {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float},
           ]

           for model_class in self.all_model_classes:
               if (
                   model_class
                   not in [
                       *get_values(lowercase       ),
                   ]
                   or model_class.__name__ == "LevitForImageClassificationWithTeacher"
               ):
                   continue

               for problem_type in problem_types:
                   with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}"       ):
                       UpperCAmelCase     =	problem_type['''title''']
                       UpperCAmelCase     =	problem_type['''num_labels''']

                       UpperCAmelCase     =	model_class(lowercase       )
                       model.to(lowercase       )
                       model.train()

                       UpperCAmelCase     =	self._prepare_for_class(lowercase     ,       lowercase     ,       return_labels=lowercase       )

                       if problem_type["num_labels"] > 1:
                           UpperCAmelCase     =	inputs['''labels'''].unsqueeze(1       ).repeat(1     ,       problem_type['''num_labels''']       )

                       UpperCAmelCase     =	inputs['''labels'''].to(problem_type['''dtype''']       )

                       # This tests that we do not trigger the warning form PyTorch "Using a target size that is different
                       # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
                       # they have the same size." which is a symptom something in wrong for the regression problem.
                       # See https://github.com/huggingface/transformers/issues/11780
                       with warnings.catch_warnings(record=lowercase       ) as warning_list:
                           UpperCAmelCase     =	model(**lowercase       ).loss
                       for w in warning_list:
                           if "Using a target size that is different to the input size" in str(w.message       ):
                               raise ValueError(
                                   f"Something is going wrong in the regression problem: intercepted {w.message}"       )

                       loss.backward()







       @slow
       def 					A   (			self		:			Dict       ):



           '''simple docstring'''

           for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase     =	LevitModel.from_pretrained(lowercase       )
               self.assertIsNotNone(lowercase       )






def 		snake_case_							():
    UpperCAmelCase     =	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
    return image







@require_torch
@require_vision
class     _a						(			unittest.TestCase				):
       @cached_property
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )







       @slow
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(
               lowercase       )

           UpperCAmelCase     =	self.default_image_processor
           UpperCAmelCase     =	prepare_img()
           UpperCAmelCase     =	image_processor(images=lowercase     ,       return_tensors='''pt'''       ).to(lowercase       )

           # forward pass
           with torch.no_grad():
               UpperCAmelCase     =	model(**lowercase       )

           # verify the logits
           UpperCAmelCase     =	torch.Size((1, 1_000)       )
           self.assertEqual(outputs.logits.shape     ,       lowercase       )

           UpperCAmelCase     =	torch.tensor([1.0448, -0.3745, -1.8317]       ).to(lowercase       )

           self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,       lowercase     ,       atol=1E-4       )       )










'''simple docstring'''







import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging


logging.set_verbosity_info()
A									=logging.get_logger(__name__)





def 		snake_case_							(_a			:							Tuple					,     _a			:							Any=False					,     _a			:							str=False  ):
    UpperCAmelCase     =	'''backbone.''' if is_semantic else ''''''

    UpperCAmelCase     =	[]
    for i in range(config.num_hidden_layers  ):
        # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
        rename_keys.append((F"{prefix}blocks.{i}.norm1.weight", F"beit.encoder.layer.{i}.layernorm_before.weight")  )
        rename_keys.append((F"{prefix}blocks.{i}.norm1.bias", F"beit.encoder.layer.{i}.layernorm_before.bias")  )
        rename_keys.append(
            (F"{prefix}blocks.{i}.attn.proj.weight", F"beit.encoder.layer.{i}.attention.output.dense.weight")  )
        rename_keys.append(
            (F"{prefix}blocks.{i}.attn.proj.bias", F"beit.encoder.layer.{i}.attention.output.dense.bias")  )
        rename_keys.append((F"{prefix}blocks.{i}.norm2.weight", F"beit.encoder.layer.{i}.layernorm_after.weight")  )
        rename_keys.append((F"{prefix}blocks.{i}.norm2.bias", F"beit.encoder.layer.{i}.layernorm_after.bias")  )
        rename_keys.append((F"{prefix}blocks.{i}.mlp.fc1.weight", F"beit.encoder.layer.{i}.intermediate.dense.weight")  )
        rename_keys.append((F"{prefix}blocks.{i}.mlp.fc1.bias", F"beit.encoder.layer.{i}.intermediate.dense.bias")  )
        rename_keys.append((F"{prefix}blocks.{i}.mlp.fc2.weight", F"beit.encoder.layer.{i}.output.dense.weight")  )
        rename_keys.append((F"{prefix}blocks.{i}.mlp.fc2.bias", F"beit.encoder.layer.{i}.output.dense.bias")  )

    # projection layer + position embeddings
    rename_keys.extend(
        [
            (F"{prefix}cls_token", '''beit.embeddings.cls_token'''),
            (F"{prefix}patch_embed.proj.weight", '''beit.embeddings.patch_embeddings.projection.weight'''),
            (F"{prefix}patch_embed.proj.bias", '''beit.embeddings.patch_embeddings.projection.bias'''),
            (F"{prefix}pos_embed", '''beit.embeddings.position_embeddings'''),
        ]  )

    if has_lm_head:
        # mask token + layernorm
        rename_keys.extend(
            [
                ('''mask_token''', '''beit.embeddings.mask_token'''),
                ('''norm.weight''', '''layernorm.weight'''),
                ('''norm.bias''', '''layernorm.bias'''),
            ]  )
    else:
        # layernorm + classification head
        rename_keys.extend(
            [
                ('''fc_norm.weight''', '''beit.pooler.layernorm.weight'''),
                ('''fc_norm.bias''', '''beit.pooler.layernorm.bias'''),
                ('''head.weight''', '''classifier.weight'''),
                ('''head.bias''', '''classifier.bias'''),
            ]  )

    return rename_keys





def 		snake_case_							(_a			:							str					,     _a			:							List[Any]					,     _a			:							List[Any]=False					,     _a			:							Union[str, Any]=False  ):
    for i in range(config.num_hidden_layers  ):
        UpperCAmelCase     =	'''backbone.''' if is_semantic else ''''''
        # queries, keys and values
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.attn.qkv.weight"  )
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.attn.q_bias"  )
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.attn.v_bias"  )

        UpperCAmelCase     =	in_proj_weight[
            : config.hidden_size, :
        ]
        UpperCAmelCase     =	q_bias
        UpperCAmelCase     =	in_proj_weight[
            config.hidden_size : config.hidden_size * 2, :
        ]
        UpperCAmelCase     =	in_proj_weight[
            -config.hidden_size :, :
        ]
        UpperCAmelCase     =	v_bias

        # gamma_1 and gamma_2
        # we call them lambda because otherwise they are renamed when using .from_pretrained
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.gamma_1"  )
        UpperCAmelCase     =	state_dict.pop(F"{prefix}blocks.{i}.gamma_2"  )

        UpperCAmelCase     =	gamma_a
        UpperCAmelCase     =	gamma_a





def 		snake_case_							(_a			:							Union[str, Any]					,     _a			:							str					,     _a			:							Optional[int]  ):
    UpperCAmelCase     =	dct.pop(_a  )
    UpperCAmelCase     =	val





def 		snake_case_							():
    UpperCAmelCase     =	'''http://images.cocodataset.org/val2017/000000039769.jpg'''
    UpperCAmelCase     =	Image.open(requests.get(_a					,     stream=_a  ).raw  )
    return im





@torch.no_grad()
def 		snake_case_							(_a			:							Optional[Any]					,     _a			:							Optional[Any]					,     _a			:							Optional[Any]=False  ):
    UpperCAmelCase     =	False if '''rvlcdip''' in checkpoint_url else True
    UpperCAmelCase     =	BeitConfig(use_absolute_position_embeddings=_a					,     use_mask_token=_a  )

    # size of the architecture
    if "large" in checkpoint_url or "dit-l" in checkpoint_url:
        UpperCAmelCase     =	1_0_2_4
        UpperCAmelCase     =	4_0_9_6
        UpperCAmelCase     =	2_4
        UpperCAmelCase     =	1_6

    # labels
    if "rvlcdip" in checkpoint_url:
        UpperCAmelCase     =	1_6
        UpperCAmelCase     =	'''huggingface/label-files'''
        UpperCAmelCase     =	'''rvlcdip-id2label.json'''
        UpperCAmelCase     =	json.load(open(hf_hub_download(_a					,     _a					,     repo_type='''dataset'''  )					,     '''r'''  )  )
        UpperCAmelCase     =	{int(_a  ): v for k, v in idalabel.items()}
        UpperCAmelCase     =	idalabel
        UpperCAmelCase     =	{v: k for k, v in idalabel.items()}

    # load state_dict of original model, remove and rename some keys
    UpperCAmelCase     =	torch.hub.load_state_dict_from_url(_a					,     map_location='''cpu'''  )['''model''']

    UpperCAmelCase     =	create_rename_keys(_a					,     has_lm_head=_a  )
    for src, dest in rename_keys:
        rename_key(_a					,     _a					,     _a  )
    read_in_q_k_v(_a					,     _a					,     has_lm_head=_a  )

    # load HuggingFace model
    UpperCAmelCase     =	BeitForMaskedImageModeling(_a  ) if has_lm_head else BeitForImageClassification(_a  )
    model.eval()
    model.load_state_dict(_a  )

    # Check outputs on an image
    UpperCAmelCase     =	BeitImageProcessor(
        size=config.image_size					,     resample=PILImageResampling.BILINEAR					,     do_center_crop=_a  )
    UpperCAmelCase     =	prepare_img()

    UpperCAmelCase     =	image_processor(images=_a					,     return_tensors='''pt'''  )
    UpperCAmelCase     =	encoding['''pixel_values''']

    UpperCAmelCase     =	model(_a  )
    UpperCAmelCase     =	outputs.logits

    # verify logits
    UpperCAmelCase     =	[1, 1_6] if '''rvlcdip''' in checkpoint_url else [1, 1_9_6, 8_1_9_2]
    assert logits.shape == torch.Size(_a  ), "Shape of logits not as expected"

    Path(_a  ).mkdir(exist_ok=_a  )
    print(F"Saving model to {pytorch_dump_folder_path}"  )
    model.save_pretrained(_a  )
    print(F"Saving image processor to {pytorch_dump_folder_path}"  )
    image_processor.save_pretrained(_a  )

    if push_to_hub:
        if has_lm_head:
            UpperCAmelCase     =	'''dit-base''' if '''base''' in checkpoint_url else '''dit-large'''
        else:
            UpperCAmelCase     =	'''dit-base-finetuned-rvlcdip''' if '''dit-b''' in checkpoint_url else '''dit-large-finetuned-rvlcdip'''
        image_processor.push_to_hub(
            repo_path_or_name=Path(_a					,     _a  )					,     organization='''nielsr'''					,     commit_message='''Add image processor'''					,     use_temp_dir=_a					,     )
        model.push_to_hub(
            repo_path_or_name=Path(_a					,     _a  )					,     organization='''nielsr'''					,     commit_message='''Add model'''					,     use_temp_dir=_a					,     )


if __name__ == "__main__":
   A									=argparse.ArgumentParser()

   parser.add_argument(
       '--checkpoint_url',
       default='https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth',
       type=str,
       help='URL to the original PyTorch checkpoint (.pth file).',
   )
   parser.add_argument(
       '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.'
   )
   parser.add_argument(
       '--push_to_hub',
       action='store_true',
   )
   A									=parser.parse_args()
   convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)




