



'''simple docstring'''





import argparse
import json
import os
from collections import OrderedDict

import numpy as np
import tensorflow as tf
import torch




def        lowerCamelCase  (				_snake_case  :						Tuple       ):





    '''simple docstring'''


    lowercase__		       =						os.path.join(args.tf_model_dir     ,"parameters.json"       )
    lowercase__		       =						json.loads(open(_snake_case       ).read()       )
    if not params:
        raise ValueError(
            f'''It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.'''       )
    if not args.output.endswith(".pt"       ):
        lowercase__		       =						args.output + ".pt"
    lowercase__		       =						OrderedDict()
    with tf.device("/CPU:0"       ):
        lowercase__		       =						tf.train.load_checkpoint(args.tf_model_dir       )
        lowercase__		       =						reader.get_variable_to_shape_map()
        for key_name in shapes.keys():
            lowercase__		       =						reader.get_tensor(_snake_case       ).astype(np.floataa       )
            if key_name.endswith("/adam_m"       ) or key_name.endswith("/adam_v"       ):
                continue
            if key_name.startswith("pasts/"       ):
                if key_name.startswith("pasts/mlp"       ):
                    lowercase__		       =						int(key_name[9]       )
                elif key_name.startswith("pasts/out"       ):
                    lowercase__		       =						8
                lowercase__		       =						"model.sqout.%d.weight" % (player * 2)  # enter to nn.Sequencial with Tanh, so 2 at a time
                lowercase__		       =						vnp.transpose([1, 0]       ).copy()  # Mesh-Tensorflow is a diagonal matrix
                lowercase__		       =						torch.tensor(_snake_case       )
            elif key_name.startswith("model/moe"       ):
                lowercase__		       =						int(key_name[9:].split("/"       )[0]       )
                if key_name.endswith("/switch_gating/kernel"       ):
                    lowercase__		       =						"model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player
                    lowercase__		       =						vnp.transpose([1, 0]       ).copy()  # Mesh-Tensorflow is a diagonal matrix
                    lowercase__		       =						torch.tensor(_snake_case       )
                elif key_name.endswith("/softmlp/kernel"       ):
                    lowercase__		       =						"model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player
                    lowercase__		       =						vnp.transpose([1, 0]       ).copy()  # Mesh-Tensorflow is a diagonal matrix
                    lowercase__		       =						torch.tensor(_snake_case       )
                elif key_name.endswith("/wo/kernel"       ) or key_name.endswith("/wi/kernel"       ):
                    lowercase__		       =						key_name[-9:-7]
                    for i in range(16       ):
                        lowercase__		       =						"model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer)
                        lowercase__		       =						(
                            vnp[i].transpose([1, 0]       ).copy()
                        )  # In Mesh-Tensorflow, it is one array, so it is divided
                        lowercase__		       =						torch.tensor(_snake_case       )
            elif key_name.startswith("model/mlp"       ):
                lowercase__		       =						int(key_name[9:].split("/"       )[0]       )
                if key_name.endswith("/p1/kernel"       ):
                    lowercase__		       =						"model.blocks.%d.feed_forward.mlp.wi.weight" % player
                    lowercase__		       =						vnp.transpose([1, 0]       ).copy()  # Mesh-Tensorflow is a diagonal matrix
                    lowercase__		       =						torch.tensor(_snake_case       )
                elif key_name.endswith("/p1/bias"       ):
                    lowercase__		       =						"model.blocks.%d.feed_forward.mlp.wi.bias" % player
                    lowercase__		       =						vnp.copy()  # same because it is one dimensional
                    lowercase__		       =						torch.tensor(_snake_case       )
                elif key_name.endswith("/p2/kernel"       ):
                    lowercase__		       =						"model.blocks.%d.feed_forward.mlp.wo.weight" % player
                    lowercase__		       =						vnp.transpose([1, 0]       ).copy()  # Mesh-Tensorflow is a diagonal matrix
                    lowercase__		       =						torch.tensor(_snake_case       )
                elif key_name.endswith("/p2/bias"       ):
                    lowercase__		       =						"model.blocks.%d.feed_forward.mlp.wo.bias" % player
                    lowercase__		       =						vnp.copy()  # same because it is one dimensional
                    lowercase__		       =						torch.tensor(_snake_case       )
            elif key_name.startswith("model/ln"       ):
                lowercase__		       =						int(key_name[8:].split("/"       )[0]       )
                if key_name.endswith("/b"       ):
                    lowercase__		       =						"model.blocks.%d.feed_forward.norm.bias" % player
                    lowercase__		       =						vnp.copy()  # same because it is one dimensional
                    lowercase__		       =						torch.tensor(_snake_case       )
                elif key_name.endswith("/g"       ):
                    lowercase__		       =						"model.blocks.%d.feed_forward.norm.weight" % player
                    lowercase__		       =						vnp.copy()  # same because it is one dimensional
                    lowercase__		       =						torch.tensor(_snake_case       )
            elif key_name.startswith("model/att"       ):
                lowercase__		       =						int(key_name[9:].split("/"       )[0]       )
                if key_name.endswith("/qkv/kernel"       ):
                    lowercase__		       =						vnp.copy()  # Compute same dimension as Mesh-tensorflow using einsum
                    lowercase__		       =						state[:, 0, :, :]
                    lowercase__		       =						state[:, 1, :, :]
                    lowercase__		       =						state[:, 2, :, :]
                    lowercase__		       =						(
                        state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]]       )
                        .transpose([1, 0]       )
                        .copy()
                    )  # Mesh-Tensorflow is a diagonal matrix
                    lowercase__		       =						(
                        state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]]       )
                        .transpose([1, 0]       )
                        .copy()
                    )  # Mesh-Tensorflow is a diagonal matrix
                    lowercase__		       =						(
                        state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]]       )
                        .transpose([1, 0]       )
                        .copy()
                    )  # Mesh-Tensorflow is a diagonal matrix
                    lowercase__		       =						"model.blocks.%d.self_attn.self_attn.q_proj.weight" % player
                    lowercase__		       =						torch.tensor(_snake_case       )
                    lowercase__		       =						"model.blocks.%d.self_attn.self_attn.k_proj.weight" % player
                    lowercase__		       =						torch.tensor(_snake_case       )
                    lowercase__		       =						"model.blocks.%d.self_attn.self_attn.v_proj.weight" % player
                    lowercase__		       =						torch.tensor(_snake_case       )
                elif key_name.endswith("/o/kernel"       ):
                    lowercase__		       =						"model.blocks.%d.self_attn.self_attn.out_proj.weight" % player
                    lowercase__		       =						(
                        vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]]       ).transpose([1, 0]       ).copy()
                    )  # Mesh-Tensorflow is a diagonal matrix
                    lowercase__		       =						torch.tensor(_snake_case       )
            elif key_name.startswith("model/an"       ):
                lowercase__		       =						int(key_name[8:].split("/"       )[0]       )
                if key_name.endswith("/b"       ):
                    lowercase__		       =						"model.blocks.%d.self_attn.norm.bias" % player
                    lowercase__		       =						vnp.copy()  # same because it is one dimensional
                    lowercase__		       =						torch.tensor(_snake_case       )
                elif key_name.endswith("/g"       ):
                    lowercase__		       =						"model.blocks.%d.self_attn.norm.weight" % player
                    lowercase__		       =						vnp.copy()  # same because it is one dimensional
                    lowercase__		       =						torch.tensor(_snake_case       )
            elif (
                key_name.startswith("model/wte"       )
                or key_name.startswith("model/wpe"       )
                or key_name.startswith("model/ete"       )
            ):
                lowercase__		       =						{"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[
                    key_name[-3:]
                ]
                lowercase__		       =						"model.%s.weight" % nlayer
                lowercase__		       =						vnp.copy()  # same in embedded
                lowercase__		       =						torch.tensor(_snake_case       )
                if key_name.startswith("model/wte"       ):
                    lowercase__		       =						"lm_head.weight"
                    lowercase__		       =						vnp.copy()  # same in embedded
                    lowercase__		       =						torch.tensor(_snake_case       )
            elif key_name.startswith("model/wob"       ):
                lowercase__		       =						"final_logits_bias"
                lowercase__		       =						vnp.copy()  # same in embedded
                lowercase__		       =						state.reshape((1, -1)       )
                lowercase__		       =						torch.tensor(_snake_case       )
            elif key_name == "model/dense/kernel":
                lowercase__		       =						"model.last_project.weight"
                lowercase__		       =						vnp.transpose([1, 0]       ).copy()  # Mesh-Tensorflow is a diagonal matrix
                lowercase__		       =						torch.tensor(_snake_case       )
            elif key_name == "model/dense_1/bias":
                lowercase__		       =						"model.last_project.bias"
                lowercase__		       =						vnp.copy()  # same because it is one dimensional
                lowercase__		       =						torch.tensor(_snake_case       )
    torch.save(_snake_case     ,args.output       )


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE__      					=     argparse.ArgumentParser(
     description="model converter.", formatter_class=argparse.ArgumentDefaultsHelpFormatter
 )
 parser.add_argument("--tf_model_dir", metavar="PATH", type=str, required=True, help="import model")
 parser.add_argument("--output", metavar="PATH", type=str, required=True, help="output model")
 SCREAMING_SNAKE_CASE__      					=     parser.parse_args()
 convert_tf_gptsan_to_pt(args)









'''simple docstring'''





import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 (
     MODEL_MAPPING,
     BeitForImageClassification,
     BeitForMaskedImageModeling,
     BeitForSemanticSegmentation,
     BeitModel,
 )
 from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 import PIL
 from PIL import Image

 from transformers import BeitImageProcessor


class 				snake_case :



       def __init__(				self     ,UpperCAmelCase_     ,UpperCAmelCase_=100     ,UpperCAmelCase_=13     ,UpperCAmelCase_=30     ,UpperCAmelCase_=2     ,UpperCAmelCase_=3     ,UpperCAmelCase_=True     ,UpperCAmelCase_=True     ,UpperCAmelCase_=32     ,UpperCAmelCase_=4     ,UpperCAmelCase_=4     ,UpperCAmelCase_=37     ,UpperCAmelCase_="gelu"     ,UpperCAmelCase_=0.1     ,UpperCAmelCase_=0.1     ,UpperCAmelCase_=10     ,UpperCAmelCase_=0.02     ,UpperCAmelCase_=3     ,UpperCAmelCase_=None     ,UpperCAmelCase_=[0, 1, 2, 3]     ,)  ->							Any:
           lowercase__		       =						parent
           lowercase__		       =						100
           lowercase__		       =						batch_size
           lowercase__		       =						image_size
           lowercase__		       =						patch_size
           lowercase__		       =						num_channels
           lowercase__		       =						is_training
           lowercase__		       =						use_labels
           lowercase__		       =						hidden_size
           lowercase__		       =						num_hidden_layers
           lowercase__		       =						num_attention_heads
           lowercase__		       =						intermediate_size
           lowercase__		       =						hidden_act
           lowercase__		       =						hidden_dropout_prob
           lowercase__		       =						attention_probs_dropout_prob
           lowercase__		       =						type_sequence_label_size
           lowercase__		       =						initializer_range
           lowercase__		       =						scope
           lowercase__		       =						out_indices
           lowercase__		       =						num_labels

           # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
           lowercase__		       =						(image_size // patch_size) ** 2
           lowercase__		       =						num_patches + 1



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

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

           lowercase__		       =						self.get_config()

           return config, pixel_values, labels, pixel_labels



       def 							_a      (				self      )  ->							List[str]:
           return BeitConfig(
               vocab_size=self.vocab_size     ,image_size=self.image_size     ,patch_size=self.patch_size     ,num_channels=self.num_channels     ,hidden_size=self.hidden_size     ,num_hidden_layers=self.num_hidden_layers     ,num_attention_heads=self.num_attention_heads     ,intermediate_size=self.intermediate_size     ,hidden_act=self.hidden_act     ,hidden_dropout_prob=self.hidden_dropout_prob     ,attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,is_decoder=UpperCAmelCase_     ,initializer_range=self.initializer_range     ,out_indices=self.out_indices     ,)



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Optional[int]:
           lowercase__		       =						BeitModel(config=UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_      )
           self.parent.assertEqual(result.last_hidden_state.shape     ,(self.batch_size, self.seq_length, self.hidden_size)      )



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Tuple:
           lowercase__		       =						BeitForMaskedImageModeling(config=UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_      )
           self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.seq_length - 1, self.vocab_size)      )



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Dict:
           lowercase__		       =						self.type_sequence_label_size
           lowercase__		       =						BeitForImageClassification(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__		       =						BeitForImageClassification(UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()

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



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Dict:
           lowercase__		       =						self.num_labels
           lowercase__		       =						BeitForSemanticSegmentation(UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_      )
           self.parent.assertEqual(
               result.logits.shape     ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )
           lowercase__		       =						model(UpperCAmelCase_     ,labels=UpperCAmelCase_      )
           self.parent.assertEqual(
               result.logits.shape     ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )







       def 							_a      (				self      )  ->							str:
           lowercase__		       =						self.prepare_config_and_inputs()
           lowercase__       ,       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__  :Optional[Any]						   =					(
           (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       lowerCAmelCase__  :Optional[int]						   =					(
           {
               "feature-extraction": BeitModel,
               "image-classification": BeitForImageClassification,
               "image-segmentation": BeitForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       lowerCAmelCase__  :Any						   =					False
       lowerCAmelCase__  :Optional[Any]						   =					False
       lowerCAmelCase__  :Optional[Any]						   =					False



       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__		       =						BeitModelTester(self      )
           lowercase__		       =						ConfigTester(self     ,config_class=UpperCAmelCase_     ,has_text_modality=UpperCAmelCase_     ,hidden_size=37      )



       def 							_a      (				self      )  ->							Tuple:
           self.config_tester.run_common_tests()



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



       @require_torch_multi_gpu
       @unittest.skip(reason="BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`"      )
       def 							_a      (				self      )  ->							int:
           pass



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

           for model_class in self.all_model_classes:
               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      )  ->							Tuple:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               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      )  ->							Tuple:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCAmelCase_      )



       def 							_a      (				self      )  ->							List[Any]:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase_      )



       def 							_a      (				self      )  ->							Any:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_      )



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



       def 							_a      (				self      )  ->							int:
           if not self.model_tester.is_training:
               return

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

           for model_class in self.all_model_classes:
               # we don't test BeitForMaskedImageModeling
               if model_class in [*get_values(UpperCAmelCase_      ), BeitForMaskedImageModeling]:
                   continue

               lowercase__		       =						model_class(UpperCAmelCase_      )
               model.to(UpperCAmelCase_      )
               model.train()
               lowercase__		       =						self._prepare_for_class(UpperCAmelCase_     ,UpperCAmelCase_     ,return_labels=UpperCAmelCase_      )
               lowercase__		       =						model(**UpperCAmelCase_      ).loss
               loss.backward()



       def 							_a      (				self      )  ->							str:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()
           if not self.model_tester.is_training:
               return

           lowercase__		       =						False
           lowercase__		       =						True

           for model_class in self.all_model_classes:
               # we don't test BeitForMaskedImageModeling
               if (
                   model_class in [*get_values(UpperCAmelCase_      ), BeitForMaskedImageModeling]
                   or not model_class.supports_gradient_checkpointing
               ):
                   continue

               lowercase__		       =						model_class(UpperCAmelCase_      )
               model.gradient_checkpointing_enable()
               model.to(UpperCAmelCase_      )
               model.train()
               lowercase__		       =						self._prepare_for_class(UpperCAmelCase_     ,UpperCAmelCase_     ,return_labels=UpperCAmelCase_      )
               lowercase__		       =						model(**UpperCAmelCase_      ).loss
               loss.backward()



       def 							_a      (				self      )  ->							int:
           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():
                   # we skip lambda parameters as these require special initial values
                   # determined by config.layer_scale_init_value
                   if "lambda" in name:
                       continue
                   if 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'''     ,)







       @slow
       def 							_a      (				self      )  ->							Optional[Any]:
           for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowercase__		       =						BeitModel.from_pretrained(UpperCAmelCase_      )
               self.assertIsNotNone(UpperCAmelCase_      )





def        lowerCamelCase  (				):





    '''simple docstring'''


    lowercase__		       =						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
    return image



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



       @cached_property
       def 							_a      (				self      )  ->							Any:
           return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224"      ) if is_vision_available() else None



       @slow
       def 							_a      (				self      )  ->							int:
           lowercase__		       =						BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k"      ).to(UpperCAmelCase_      )

           lowercase__		       =						self.default_image_processor
           lowercase__		       =						prepare_img()
           lowercase__		       =						image_processor(images=UpperCAmelCase_     ,return_tensors="pt"      ).pixel_values.to(UpperCAmelCase_      )

           # prepare bool_masked_pos
           lowercase__		       =						torch.ones((1, 196)     ,dtype=torch.bool      ).to(UpperCAmelCase_      )

           # forward pass
           with torch.no_grad():
               lowercase__		       =						model(pixel_values=UpperCAmelCase_     ,bool_masked_pos=UpperCAmelCase_      )
           lowercase__		       =						outputs.logits

           # verify the logits
           lowercase__		       =						torch.Size((1, 196, 8_192)      )
           self.assertEqual(logits.shape     ,UpperCAmelCase_      )

           lowercase__		       =						torch.tensor(
               [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]]      ).to(UpperCAmelCase_      )

           self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]     ,UpperCAmelCase_     ,atol=1E-2      )      )



       @slow
       def 							_a      (				self      )  ->							Optional[Any]:
           lowercase__		       =						BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224"      ).to(UpperCAmelCase_      )

           lowercase__		       =						self.default_image_processor
           lowercase__		       =						prepare_img()
           lowercase__		       =						image_processor(images=UpperCAmelCase_     ,return_tensors="pt"      ).to(UpperCAmelCase_      )

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

           # verify the logits
           lowercase__		       =						torch.Size((1, 1_000)      )
           self.assertEqual(logits.shape     ,UpperCAmelCase_      )

           lowercase__		       =						torch.tensor([-1.23_85, -1.09_87, -1.01_08]      ).to(UpperCAmelCase_      )

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

           lowercase__		       =						281
           self.assertEqual(logits.argmax(-1      ).item()     ,UpperCAmelCase_      )



       @slow
       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__		       =						BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k"      ).to(
               UpperCAmelCase_      )

           lowercase__		       =						self.default_image_processor
           lowercase__		       =						prepare_img()
           lowercase__		       =						image_processor(images=UpperCAmelCase_     ,return_tensors="pt"      ).to(UpperCAmelCase_      )

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

           # verify the logits
           lowercase__		       =						torch.Size((1, 21_841)      )
           self.assertEqual(logits.shape     ,UpperCAmelCase_      )

           lowercase__		       =						torch.tensor([1.68_81, -0.27_87, 0.59_01]      ).to(UpperCAmelCase_      )

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

           lowercase__		       =						2_396
           self.assertEqual(logits.argmax(-1      ).item()     ,UpperCAmelCase_      )



       @slow
       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__		       =						BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"      )
           lowercase__		       =						model.to(UpperCAmelCase_      )

           lowercase__		       =						BeitImageProcessor(do_resize=UpperCAmelCase_     ,size=640     ,do_center_crop=UpperCAmelCase_      )

           lowercase__		       =						load_dataset("hf-internal-testing/fixtures_ade20k"     ,split="test"      )
           lowercase__		       =						Image.open(ds[0]["file"]      )
           lowercase__		       =						image_processor(images=UpperCAmelCase_     ,return_tensors="pt"      ).to(UpperCAmelCase_      )

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

           # verify the logits
           lowercase__		       =						torch.Size((1, 150, 160, 160)      )
           self.assertEqual(logits.shape     ,UpperCAmelCase_      )

           lowercase__		       =						version.parse(PIL.__version__      ) < version.parse("9.0.0"      )

           if is_pillow_less_than_a:
               lowercase__		       =						torch.tensor(
                   [
                       [[-4.92_25, -2.39_54, -3.05_22], [-2.88_22, -1.00_46, -1.75_61], [-2.95_49, -1.32_28, -2.13_47]],
                       [[-5.81_68, -3.41_29, -4.07_78], [-3.86_51, -2.22_14, -3.02_77], [-3.83_56, -2.46_43, -3.35_35]],
                       [[-0.00_78, 3.99_52, 4.07_54], [2.98_56, 4.69_44, 5.00_35], [3.24_13, 4.78_13, 4.99_69]],
                   ]     ,device=UpperCAmelCase_     ,)
           else:
               lowercase__		       =						torch.tensor(
                   [
                       [[-4.89_60, -2.36_88, -3.03_55], [-2.84_78, -0.98_36, -1.74_18], [-2.94_49, -1.33_32, -2.14_56]],
                       [[-5.80_81, -3.41_24, -4.10_06], [-3.85_61, -2.20_81, -3.03_23], [-3.83_65, -2.46_01, -3.36_69]],
                       [[-0.03_09, 3.98_68, 4.05_40], [2.96_40, 4.68_77, 4.99_76], [3.20_81, 4.76_90, 4.99_42]],
                   ]     ,device=UpperCAmelCase_     ,)

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







       @slow
       def 							_a      (				self      )  ->							str:
           lowercase__		       =						BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"      )
           lowercase__		       =						model.to(UpperCAmelCase_      )

           lowercase__		       =						BeitImageProcessor(do_resize=UpperCAmelCase_     ,size=640     ,do_center_crop=UpperCAmelCase_      )

           lowercase__		       =						load_dataset("hf-internal-testing/fixtures_ade20k"     ,split="test"      )
           lowercase__		       =						Image.open(ds[0]["file"]      )
           lowercase__		       =						image_processor(images=UpperCAmelCase_     ,return_tensors="pt"      ).to(UpperCAmelCase_      )

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

           lowercase__		       =						outputs.logits.detach().cpu()

           lowercase__		       =						image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_     ,target_sizes=[(500, 300)]      )
           lowercase__		       =						torch.Size((500, 300)      )
           self.assertEqual(segmentation[0].shape     ,UpperCAmelCase_      )

           lowercase__		       =						image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_      )
           lowercase__		       =						torch.Size((160, 160)      )
           self.assertEqual(segmentation[0].shape     ,UpperCAmelCase_      )




