






'''simple docstring'''







import gc
import importlib.metadata
import tempfile
import unittest

from packaging import version

from transformers import (
    AutoModel,
    AutoModelForCausalLM,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    BitsAndBytesConfig,
    pipeline,
)
from transformers.testing_utils import (
    is_torch_available,
    require_accelerate,
    require_bitsandbytes,
    require_torch,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> int:
							if model.config.model_type == "gpt2":
														return model.transformer.h[0].mlp.c_fc
							return model.transformer.h[0].mlp.dense_ah_to_h


if is_torch_available():
			import torch
			import torch.nn as nn

			class _lowercase			(       nn.Module	):




										def __init__(							self:       Any    ,							UpperCamelCase__:       nn.Module    ,							UpperCamelCase__:       int  ):
																	super().__init__()
																	lowerCamelCase__      :			List[Any] 						= module
																	lowerCamelCase__      :			Any 						= nn.Sequential(
																	    nn.Linear(module.in_features    ,							UpperCamelCase__    ,							bias=UpperCamelCase__  )    ,							nn.Linear(UpperCamelCase__    ,							module.out_features    ,							bias=UpperCamelCase__  )    ,							)
																	lowerCamelCase__      :			Tuple 						= (2.0 / (5 * min(module.in_features    ,							module.out_features  ))) ** 0.5
																	nn.init.normal_(self.adapter[0].weight    ,							std=UpperCamelCase__  )
																	nn.init.zeros_(self.adapter[1].weight  )
																	self.adapter.to(module.weight.device  )




										def 	lowerCamelCase_       (							self:       Optional[Any]    ,							UpperCamelCase__:       Any    ,							*UpperCamelCase__:       Any    ,							**UpperCamelCase__:       Tuple  ):
																	return self.module(UpperCamelCase__    ,							*UpperCamelCase__    ,							**UpperCamelCase__  ) + self.adapter(UpperCamelCase__  )

@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class _lowercase			(       unittest.TestCase	):
							# We keep the constants inside the init function and model loading inside setUp function

							# We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
							# Therefore here we use only bloom-1b3 to test our module
							a          = """bigscience/bloom-1b7"""

							# Constant values
							a          = 2.1_09_65_95_52_69_25_74

							a          = """Hello my name is"""
							a          = set()
							EXPECTED_OUTPUTS.add("""Hello my name is John and I am a professional photographer. I"""	)
							EXPECTED_OUTPUTS.add("""Hello my name is John.\nI am a friend of your father.\n"""	)
							EXPECTED_OUTPUTS.add("""Hello my name is John Doe, I am a student at the University"""	)
							a          = 10




							def 	lowerCamelCase_       (							self:       Any  ):
														# Models and tokenizer
														lowerCamelCase__      :			int 						= AutoTokenizer.from_pretrained(self.model_name  )



class _lowercase			(       _lowercase	):




							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														super().setUp()

														# Models and tokenizer
														lowerCamelCase__      :			Optional[Any] 						= AutoModelForCausalLM.from_pretrained(
														    self.model_name    ,							torch_dtype=torch.floataa    ,							device_map="""auto"""  )
														lowerCamelCase__      :			List[Any] 						= AutoModelForCausalLM.from_pretrained(self.model_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )




							def 	lowerCamelCase_       (							self:       Tuple  ):
														del self.model_fpaa
														del self.model_abit

														gc.collect()
														torch.cuda.empty_cache()




							def 	lowerCamelCase_       (							self:       List[str]  ):
														lowerCamelCase__      :			Any 						= self.model_abit.config

														self.assertTrue(hasattr(UpperCamelCase__    ,							"""quantization_config"""  )  )

														lowerCamelCase__      :			List[str] 						= config.to_dict()
														lowerCamelCase__      :			Optional[int] 						= config.to_diff_dict()

														lowerCamelCase__      :			List[str] 						= config.to_json_string()




							def 	lowerCamelCase_       (							self:       Dict  ):
														from bitsandbytes.nn import Paramsabit

														lowerCamelCase__      :			Optional[int] 						= self.model_fpaa.get_memory_footprint()
														lowerCamelCase__      :			Dict 						= self.model_abit.get_memory_footprint()

														self.assertAlmostEqual(mem_fpaa / mem_abit    ,							self.EXPECTED_RELATIVE_DIFFERENCE  )
														lowerCamelCase__      :			Optional[int] 						= get_some_linear_layer(self.model_abit  )
														self.assertTrue(linear.weight.__class__ == Paramsabit  )




							def 	lowerCamelCase_       (							self:       Tuple  ):
														from transformers import TaPreTrainedModel

														self.model_fpaa.get_memory_footprint()
														self.model_abit.get_memory_footprint()

														for name, module in self.model_abit.named_modules():
																					if isinstance(UpperCamelCase__    ,							torch.nn.Linear  ):
																												if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules:
																																			# 4-bit parameters are packed in uint8 variables
																																			self.assertTrue(module.weight.dtype == torch.uinta  )




							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														lowerCamelCase__      :			List[str] 						= self.tokenizer(self.input_text    ,							return_tensors="""pt"""  )
														lowerCamelCase__      :			Optional[int] 						= self.model_abit.generate(input_ids=encoded_input["""input_ids"""].to(0  )    ,							max_new_tokens=10  )

														self.assertIn(self.tokenizer.decode(output_sequences[0]    ,							skip_special_tokens=UpperCamelCase__  )    ,							self.EXPECTED_OUTPUTS  )




							def 	lowerCamelCase_       (							self:       List[Any]  ):
														lowerCamelCase__      :			Dict 						= BitsAndBytesConfig()
														lowerCamelCase__      :			str 						= True

														lowerCamelCase__      :			int 						= AutoModelForCausalLM.from_pretrained(
														    self.model_name    ,							quantization_config=UpperCamelCase__    ,							device_map="""auto"""  )

														lowerCamelCase__      :			Optional[Any] 						= self.tokenizer(self.input_text    ,							return_tensors="""pt"""  )
														lowerCamelCase__      :			Optional[int] 						= model_abit_from_config.generate(
														    input_ids=encoded_input["""input_ids"""].to(0  )    ,							max_new_tokens=10  )

														self.assertIn(self.tokenizer.decode(output_sequences[0]    ,							skip_special_tokens=UpperCamelCase__  )    ,							self.EXPECTED_OUTPUTS  )




							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														with self.assertRaises(UpperCamelCase__  ), tempfile.TemporaryDirectory() as tmpdirname:
																					self.model_abit.save_pretrained(UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														lowerCamelCase__      :			Dict 						= BitsAndBytesConfig()

														with self.assertRaises(UpperCamelCase__  ):
																					lowerCamelCase__      :			str 						= AutoModelForCausalLM.from_pretrained(
																					    self.model_name    ,							quantization_config=UpperCamelCase__    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""    ,							bnb_abit_quant_type="""nf4"""    ,							)




							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														with self.assertRaises(UpperCamelCase__  ):
																					# Tries with `str`
																					self.model_abit.to("""cpu"""  )

														with self.assertRaises(UpperCamelCase__  ):
																					# Tries with a `dtype``
																					self.model_abit.to(torch.floataa  )

														with self.assertRaises(UpperCamelCase__  ):
																					# Tries with a `device`
																					self.model_abit.to(torch.device("""cuda:0"""  )  )

														with self.assertRaises(UpperCamelCase__  ):
																					# Tries with a `device`
																					self.model_abit.float()

														with self.assertRaises(UpperCamelCase__  ):
																					# Tries with a `device`
																					self.model_abit.half()

														# Test if we did not break anything
														lowerCamelCase__      :			Any 						= self.tokenizer(self.input_text    ,							return_tensors="""pt"""  )

														lowerCamelCase__      :			str 						= self.model_fpaa.to(torch.floataa  )
														lowerCamelCase__      :			Union[str, Any] 						= self.model_fpaa.generate(input_ids=encoded_input["""input_ids"""].to(0  )    ,							max_new_tokens=10  )

														# Check this does not throw an error
														lowerCamelCase__      :			str 						= self.model_fpaa.to("""cpu"""  )

														# Check this does not throw an error
														lowerCamelCase__      :			Any 						= self.model_fpaa.half()

														# Check this does not throw an error
														lowerCamelCase__      :			Optional[Any] 						= self.model_fpaa.float()




							def 	lowerCamelCase_       (							self:       List[str]  ):
														lowerCamelCase__      :			str 						= AutoModelForSeqaSeqLM.from_pretrained("""t5-small"""    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )
														self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa  )



@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class _lowercase			(       unittest.TestCase	):




							@classmethod
							def 	lowerCamelCase_       (							cls:       List[str]  ):
														lowerCamelCase__      :			List[Any] 						= """t5-small"""
														lowerCamelCase__      :			int 						= """google/flan-t5-small"""  # flan-t5 uses dense-act instead of dense-relu-dense
														lowerCamelCase__      :			List[str] 						= AutoTokenizer.from_pretrained(cls.model_name  )
														lowerCamelCase__      :			Optional[Any] 						= """Translate in German: Hello, my dog is cute"""




							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														gc.collect()
														torch.cuda.empty_cache()




							def 	lowerCamelCase_       (							self:       str  ):
														from transformers import TaForConditionalGeneration

														lowerCamelCase__      :			Union[str, Any] 						= TaForConditionalGeneration._keep_in_fpaa_modules
														lowerCamelCase__      :			Dict 						= None

														# test with `t5-small`
														lowerCamelCase__      :			Union[str, Any] 						= TaForConditionalGeneration.from_pretrained(self.model_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )
														lowerCamelCase__      :			Tuple 						= self.tokenizer(self.input_text    ,							return_tensors="""pt"""  ).to(0  )
														lowerCamelCase__      :			List[Any] 						= model.generate(**UpperCamelCase__  )

														# test with `flan-t5-small`
														lowerCamelCase__      :			List[str] 						= TaForConditionalGeneration.from_pretrained(
														    self.dense_act_model_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )
														lowerCamelCase__      :			Optional[Any] 						= self.tokenizer(self.input_text    ,							return_tensors="""pt"""  ).to(0  )
														lowerCamelCase__      :			Dict 						= model.generate(**UpperCamelCase__  )
														lowerCamelCase__      :			Tuple 						= modules




							def 	lowerCamelCase_       (							self:       int  ):
														import bitsandbytes as bnb

														from transformers import TaForConditionalGeneration

														# test with `t5-small`
														lowerCamelCase__      :			Any 						= TaForConditionalGeneration.from_pretrained(self.model_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )

														# there was a bug with decoders - this test checks that it is fixed
														self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q    ,							bnb.nn.Linearabit  )  )

														lowerCamelCase__      :			Any 						= self.tokenizer(self.input_text    ,							return_tensors="""pt"""  ).to(0  )
														lowerCamelCase__      :			int 						= model.generate(**UpperCamelCase__  )

														# test with `flan-t5-small`
														lowerCamelCase__      :			Optional[Any] 						= TaForConditionalGeneration.from_pretrained(
														    self.dense_act_model_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )
														lowerCamelCase__      :			Tuple 						= self.tokenizer(self.input_text    ,							return_tensors="""pt"""  ).to(0  )
														lowerCamelCase__      :			List[str] 						= model.generate(**UpperCamelCase__  )



class _lowercase			(       _lowercase	):




							def 	lowerCamelCase_       (							self:       str  ):
														super().setUp()
														# model_name
														lowerCamelCase__      :			List[str] 						= """bigscience/bloom-560m"""
														lowerCamelCase__      :			List[Any] 						= """t5-small"""

														# Different types of model

														lowerCamelCase__      :			str 						= AutoModel.from_pretrained(self.model_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )
														# Sequence classification model
														lowerCamelCase__      :			int 						= AutoModelForSequenceClassification.from_pretrained(
														    self.model_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )
														# CausalLM model
														lowerCamelCase__      :			Union[str, Any] 						= AutoModelForCausalLM.from_pretrained(self.model_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )
														# Seq2seq model
														lowerCamelCase__      :			Union[str, Any] 						= AutoModelForSeqaSeqLM.from_pretrained(
														    self.seq_to_seq_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""auto"""  )




							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														del self.base_model
														del self.sequence_model
														del self.model_abit
														del self.seq_to_seq_model

														gc.collect()
														torch.cuda.empty_cache()




							def 	lowerCamelCase_       (							self:       str  ):
														from bitsandbytes.nn import Paramsabit

														self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit  )

														# Other heads should be nn.Parameter
														self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter  )
														self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter  )
														self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter  )



class _lowercase			(       _lowercase	):




							def 	lowerCamelCase_       (							self:       List[str]  ):
														super().setUp()




							def 	lowerCamelCase_       (							self:       str  ):
														del self.pipe

														gc.collect()
														torch.cuda.empty_cache()




							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														lowerCamelCase__      :			Union[str, Any] 						= pipeline(
														    """text-generation"""    ,							model=self.model_name    ,							model_kwargs={"""device_map""": """auto""", """load_in_4bit""": True, """torch_dtype""": torch.floataa}    ,							max_new_tokens=self.MAX_NEW_TOKENS    ,							)

														# Real second forward pass
														lowerCamelCase__      :			List[str] 						= self.pipe(self.input_text  )
														self.assertIn(pipeline_output[0]["""generated_text"""]    ,							self.EXPECTED_OUTPUTS  )



@require_torch_multi_gpu
class _lowercase			(       _lowercase	):




							def 	lowerCamelCase_       (							self:       Dict  ):
														super().setUp()




							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														lowerCamelCase__      :			int 						= AutoModelForCausalLM.from_pretrained(
														    self.model_name    ,							load_in_abit=UpperCamelCase__    ,							device_map="""balanced"""  )

														# Check correct device map
														self.assertEqual(set(model_parallel.hf_device_map.values()  )    ,							{0, 1}  )

														# Check that inference pass works on the model
														lowerCamelCase__      :			Dict 						= self.tokenizer(self.input_text    ,							return_tensors="""pt"""  )

														# Second real batch
														lowerCamelCase__      :			str 						= model_parallel.generate(input_ids=encoded_input["""input_ids"""].to(0  )    ,							max_new_tokens=10  )
														self.assertIn(self.tokenizer.decode(output_parallel[0]    ,							skip_special_tokens=UpperCamelCase__  )    ,							self.EXPECTED_OUTPUTS  )



class _lowercase			(       _lowercase	):




							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														lowerCamelCase__      :			Any 						= """facebook/opt-350m"""
														super().setUp()




							def 	lowerCamelCase_       (							self:       Any  ):
														if version.parse(importlib.metadata.version("""bitsandbytes"""  )  ) < version.parse("""0.37.0"""  ):
																					return

														# Step 1: freeze all parameters
														lowerCamelCase__      :			Dict 						= AutoModelForCausalLM.from_pretrained(self.model_name    ,							load_in_abit=UpperCamelCase__  )

														self.assertEqual(set(model.hf_device_map.values()  )    ,							{torch.cuda.current_device()}  )

														for param in model.parameters():
																					lowerCamelCase__      :			List[Any] 						= False  # freeze the model - train adapters later
																					if param.ndim == 1:
																												# cast the small parameters (e.g. layernorm) to fp32 for stability
																												lowerCamelCase__      :			Optional[int] 						= param.data.to(torch.floataa  )

        # Step 2: add adapters
														for _, module in model.named_modules():
																					if "OPTAttention" in repr(type(UpperCamelCase__  )  ):
																												lowerCamelCase__      :			List[str] 						= LoRALayer(module.q_proj    ,							rank=16  )
																												lowerCamelCase__      :			List[str] 						= LoRALayer(module.k_proj    ,							rank=16  )
																												lowerCamelCase__      :			Tuple 						= LoRALayer(module.v_proj    ,							rank=16  )

        # Step 3: dummy batch
														lowerCamelCase__      :			Any 						= self.tokenizer("""Test batch """    ,							return_tensors="""pt"""  ).to(0  )

														# Step 4: Check if the gradient is not None
														with torch.cuda.amp.autocast():
																					lowerCamelCase__      :			str 						= model.forward(**UpperCamelCase__  )
																					out.logits.norm().backward()

														for module in model.modules():
																					if isinstance(UpperCamelCase__    ,							UpperCamelCase__  ):
																												self.assertTrue(module.adapter[1].weight.grad is not None  )
																												self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0  )
																					elif isinstance(UpperCamelCase__    ,							nn.Embedding  ):
																												self.assertTrue(module.weight.grad is None  )



class _lowercase			(       _lowercase	):
							a          = """gpt2-xl"""
							a          = 3.31_91_85_48_54_15_21_87









'''simple docstring'''







import inspect
import math
import tempfile
import unittest

import numpy as np

from transformers import ViTMAEConfig
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_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 torch import nn

			from transformers import ViTMAEForPreTraining, ViTMAEModel
			from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import ViTImageProcessor

class _lowercase			:




							def __init__(							self:       List[str]    ,							UpperCamelCase__:       Union[str, Any]    ,							UpperCamelCase__:       List[str]=13    ,							UpperCamelCase__:       Optional[int]=30    ,							UpperCamelCase__:       Optional[int]=2    ,							UpperCamelCase__:       List[str]=3    ,							UpperCamelCase__:       List[str]=True    ,							UpperCamelCase__:       Any=True    ,							UpperCamelCase__:       List[Any]=32    ,							UpperCamelCase__:       Any=5    ,							UpperCamelCase__:       Optional[Any]=4    ,							UpperCamelCase__:       Dict=37    ,							UpperCamelCase__:       List[Any]="gelu"    ,							UpperCamelCase__:       Union[str, Any]=0.1    ,							UpperCamelCase__:       Union[str, Any]=0.1    ,							UpperCamelCase__:       List[Any]=10    ,							UpperCamelCase__:       Tuple=0.02    ,							UpperCamelCase__:       Optional[int]=3    ,							UpperCamelCase__:       Dict=0.6    ,							UpperCamelCase__:       int=None    ,							):
														lowerCamelCase__      :			Dict 						= parent
														lowerCamelCase__      :			Optional[Any] 						= batch_size
														lowerCamelCase__      :			Optional[int] 						= image_size
														lowerCamelCase__      :			Optional[Any] 						= patch_size
														lowerCamelCase__      :			Any 						= num_channels
														lowerCamelCase__      :			Any 						= is_training
														lowerCamelCase__      :			Union[str, Any] 						= use_labels
														lowerCamelCase__      :			List[str] 						= hidden_size
														lowerCamelCase__      :			List[str] 						= num_hidden_layers
														lowerCamelCase__      :			List[Any] 						= num_attention_heads
														lowerCamelCase__      :			str 						= intermediate_size
														lowerCamelCase__      :			str 						= hidden_act
														lowerCamelCase__      :			Any 						= hidden_dropout_prob
														lowerCamelCase__      :			Optional[int] 						= attention_probs_dropout_prob
														lowerCamelCase__      :			List[Any] 						= type_sequence_label_size
														lowerCamelCase__      :			int 						= initializer_range
														lowerCamelCase__      :			List[str] 						= mask_ratio
														lowerCamelCase__      :			List[Any] 						= scope

														# in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
														# (we add 1 for the [CLS] token)
														lowerCamelCase__      :			str 						= (image_size // patch_size) ** 2
														lowerCamelCase__      :			Optional[int] 						= int(math.ceil((1 - mask_ratio) * (num_patches + 1)  )  )




							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														lowerCamelCase__      :			Tuple 						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

														lowerCamelCase__      :			Optional[int] 						= None
														if self.use_labels:
																					lowerCamelCase__      :			List[str] 						= ids_tensor([self.batch_size]    ,							self.type_sequence_label_size  )

														lowerCamelCase__      :			Any 						= self.get_config()

														return config, pixel_values, labels




							def 	lowerCamelCase_       (							self:       str  ):
														return ViTMAEConfig(
														    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    ,							mask_ratio=self.mask_ratio    ,							)




							def 	lowerCamelCase_       (							self:       List[Any]    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       int  ):
														lowerCamelCase__      :			Tuple 						= ViTMAEModel(config=UpperCamelCase__  )
														model.to(UpperCamelCase__  )
														model.eval()
														lowerCamelCase__      :			List[Any] 						= model(UpperCamelCase__  )
														self.parent.assertEqual(result.last_hidden_state.shape    ,							(self.batch_size, self.seq_length, self.hidden_size)  )




							def 	lowerCamelCase_       (							self:       str    ,							UpperCamelCase__:       Union[str, Any]    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       Dict  ):
														lowerCamelCase__      :			int 						= ViTMAEForPreTraining(UpperCamelCase__  )
														model.to(UpperCamelCase__  )
														model.eval()
														lowerCamelCase__      :			Optional[int] 						= model(UpperCamelCase__  )
														lowerCamelCase__      :			Any 						= (self.image_size // self.patch_size) ** 2
														lowerCamelCase__      :			str 						= self.patch_size**2 * self.num_channels
														self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, num_patches, expected_num_channels)  )

														# test greyscale images
														lowerCamelCase__      :			Dict 						= 1
														lowerCamelCase__      :			Optional[int] 						= ViTMAEForPreTraining(UpperCamelCase__  )
														model.to(UpperCamelCase__  )
														model.eval()
														lowerCamelCase__      :			Dict 						= floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
														lowerCamelCase__      :			Optional[Any] 						= model(UpperCamelCase__  )
														lowerCamelCase__      :			Tuple 						= self.patch_size**2
														self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, num_patches, expected_num_channels)  )




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			Optional[int] 						= self.prepare_config_and_inputs()
														lowerCamelCase__						,	lowerCamelCase__						,	lowerCamelCase__      :			Any 						= config_and_inputs
														lowerCamelCase__      :			Optional[int] 						= {"""pixel_values""": pixel_values}
														return config, inputs_dict



@require_torch
class _lowercase			(       _lowercase       ,   _lowercase       ,   unittest.TestCase	):
							a          = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else ()
							a          = {"""feature-extraction""": ViTMAEModel} if is_torch_available() else {}

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




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			Tuple 						= ViTMAEModelTester(self  )
														lowerCamelCase__      :			Union[str, Any] 						= ConfigTester(self    ,							config_class=UpperCamelCase__    ,							has_text_modality=UpperCamelCase__    ,							hidden_size=37  )




							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														self.config_tester.run_common_tests()




							@unittest.skip(reason="""ViTMAE does not use inputs_embeds"""  )
							def 	lowerCamelCase_       (							self:       Dict  ):
														pass




							def 	lowerCamelCase_       (							self:       List[str]  ):
														lowerCamelCase__						,	lowerCamelCase__      :			str 						= self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			str 						= model_class(UpperCamelCase__  )
																					self.assertIsInstance(model.get_input_embeddings()    ,							(nn.Module)  )
																					lowerCamelCase__      :			Optional[Any] 						= model.get_output_embeddings()
																					self.assertTrue(x is None or isinstance(UpperCamelCase__    ,							nn.Linear  )  )




							def 	lowerCamelCase_       (							self:       List[Any]  ):
														lowerCamelCase__						,	lowerCamelCase__      :			Union[str, Any] 						= self.model_tester.prepare_config_and_inputs_for_common()

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

																					lowerCamelCase__      :			List[str] 						= ["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]    ,							UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														lowerCamelCase__      :			Union[str, Any] 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			int 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Optional[int]    ,							UpperCamelCase__:       Union[str, Any]    ,							UpperCamelCase__:       Dict    ,							UpperCamelCase__:       Optional[int]  ):
														# make masks reproducible
														np.random.seed(2  )

														lowerCamelCase__      :			Tuple 						= int((pt_model.config.image_size // pt_model.config.patch_size) ** 2  )
														lowerCamelCase__      :			List[str] 						= np.random.uniform(size=(self.model_tester.batch_size, num_patches)  )
														lowerCamelCase__      :			Tuple 						= torch.from_numpy(UpperCamelCase__  )

														# Add `noise` argument.
														# PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
														lowerCamelCase__      :			Tuple 						= pt_noise

														super().check_pt_tf_models(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       str  ):
														lowerCamelCase__						,	lowerCamelCase__      :			Optional[Any] 						= self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__      :			Union[str, Any] 						= model_class(UpperCamelCase__  )
																					model.to(UpperCamelCase__  )
																					model.eval()
																					# make random mask reproducible
																					torch.manual_seed(2  )
																					with torch.no_grad():
																												lowerCamelCase__      :			Optional[int] 						= model(**self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )  )

																					lowerCamelCase__      :			Optional[int] 						= outputs[0].cpu().numpy()
																					lowerCamelCase__      :			List[str] 						= 0

																					with tempfile.TemporaryDirectory() as tmpdirname:
																												model.save_pretrained(UpperCamelCase__  )
																												lowerCamelCase__      :			List[str] 						= model_class.from_pretrained(UpperCamelCase__  )
																												model.to(UpperCamelCase__  )
																												# make random mask reproducible
																												torch.manual_seed(2  )
																												with torch.no_grad():
																																			lowerCamelCase__      :			Tuple 						= model(**self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )  )

																												# Make sure we don't have nans
																												lowerCamelCase__      :			Dict 						= after_outputs[0].cpu().numpy()
																												lowerCamelCase__      :			Tuple 						= 0
																												lowerCamelCase__      :			Union[str, Any] 						= np.amax(np.abs(out_a - out_a  )  )
																												self.assertLessEqual(UpperCamelCase__    ,							1e-5  )




							@unittest.skip(
							    reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results."""  )
							def 	lowerCamelCase_       (							self:       int  ):
														pass




							@unittest.skip(
							    reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results."""  )
							def 	lowerCamelCase_       (							self:       Any  ):
														pass




							@unittest.skip(
							    reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results."""  )
							def 	lowerCamelCase_       (							self:       List[str]  ):
														pass




							@unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load"""  )
							def 	lowerCamelCase_       (							self:       Tuple  ):
														pass




							@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""  )
							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														pass




							@slow
							def 	lowerCamelCase_       (							self:       List[str]  ):
														for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__      :			Tuple 						= ViTMAEModel.from_pretrained(UpperCamelCase__  )
																					self.assertIsNotNone(UpperCamelCase__  )





def 				SCREAMING_SNAKE_CASE_ ()   -> List[Any]:
							lowerCamelCase__      :			Union[str, Any] 						= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
							return image



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




							@cached_property
							def 	lowerCamelCase_       (							self:       List[str]  ):
														return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base"""  ) if is_vision_available() else None




							@slow
							def 	lowerCamelCase_       (							self:       Tuple  ):
														# make random mask reproducible across the PT and TF model
														np.random.seed(2  )

														lowerCamelCase__      :			str 						= ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base"""  ).to(UpperCamelCase__  )

														lowerCamelCase__      :			Tuple 						= self.default_image_processor
														lowerCamelCase__      :			List[str] 						= prepare_img()
														lowerCamelCase__      :			int 						= image_processor(images=UpperCamelCase__    ,							return_tensors="""pt"""  ).to(UpperCamelCase__  )

														# prepare a noise vector that will be also used for testing the TF model
														# (this way we can ensure that the PT and TF models operate on the same inputs)
														lowerCamelCase__      :			List[str] 						= ViTMAEConfig()
														lowerCamelCase__      :			int 						= int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2  )
														lowerCamelCase__      :			Any 						= np.random.uniform(size=(1, num_patches)  )

														# forward pass
														with torch.no_grad():
																					lowerCamelCase__      :			List[Any] 						= model(**UpperCamelCase__    ,							noise=torch.from_numpy(UpperCamelCase__  ).to(device=UpperCamelCase__  )  )

														# verify the logits
														lowerCamelCase__      :			List[str] 						= torch.Size((1, 196, 768)  )
														self.assertEqual(outputs.logits.shape    ,							UpperCamelCase__  )

														lowerCamelCase__      :			str 						= torch.tensor(
														    [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]]  )

														self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]    ,							expected_slice.to(UpperCamelCase__  )    ,							atol=1e-4  )  )

