




import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
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 torch import nn

     from transformers import RegNetForImageClassification, RegNetModel
     from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor




class    a__       :






       def __init__(   self:					Optional[int]       ,					_lowerCAmelCase:					int       ,					_lowerCAmelCase:					str=3       ,					_lowerCAmelCase:					Optional[int]=32       ,					_lowerCAmelCase:					int=3       ,					_lowerCAmelCase:					Dict=10       ,					_lowerCAmelCase:					Optional[int]=[10, 20, 30, 40]       ,					_lowerCAmelCase:					Tuple=[1, 1, 2, 1]       ,					_lowerCAmelCase:					List[Any]=True       ,					_lowerCAmelCase:					str=True       ,					_lowerCAmelCase:					Union[str, Any]="relu"       ,					_lowerCAmelCase:					Tuple=3       ,					_lowerCAmelCase:					Union[str, Any]=None       ,					):
         lowercase    :List[Any]      	=						parent
         lowercase    :List[str]      	=						batch_size
         lowercase    :Any      	=						image_size
         lowercase    :Optional[int]      	=						num_channels
         lowercase    :Optional[Any]      	=						embeddings_size
         lowercase    :Any      	=						hidden_sizes
         lowercase    :Dict      	=						depths
         lowercase    :Union[str, Any]      	=						is_training
         lowercase    :Dict      	=						use_labels
         lowercase    :List[Any]      	=						hidden_act
         lowercase    :str      	=						num_labels
         lowercase    :Tuple      	=						scope
         lowercase    :Union[str, Any]      	=						len(_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]				):
         lowercase    :str      	=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

         lowercase    :str      	=						self.get_config()

         return config, pixel_values, labels






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]				):
         return RegNetConfig(
             num_channels=self.num_channels       ,					embeddings_size=self.embeddings_size       ,					hidden_sizes=self.hidden_sizes       ,					depths=self.depths       ,					hidden_act=self.hidden_act       ,					num_labels=self.num_labels       ,					)






       def 					SCREAMING_SNAKE_CASE    (   self:					int       ,					_lowerCAmelCase:					Optional[int]       ,					_lowerCAmelCase:					int       ,					_lowerCAmelCase:					Any				):
         lowercase    :Optional[Any]      	=						RegNetModel(config=_lowerCAmelCase				)
         model.to(_lowerCAmelCase				)
         model.eval()
         lowercase    :Tuple      	=						model(_lowerCAmelCase				)
         # expected last hidden states: B, C, H // 32, W // 32
         self.parent.assertEqual(
             result.last_hidden_state.shape       ,					(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)       ,					)






       def 					SCREAMING_SNAKE_CASE    (   self:					Union[str, Any]       ,					_lowerCAmelCase:					Dict       ,					_lowerCAmelCase:					List[str]       ,					_lowerCAmelCase:					str				):
         lowercase    :Tuple      	=						self.num_labels
         lowercase    :Tuple      	=						RegNetForImageClassification(_lowerCAmelCase				)
         model.to(_lowerCAmelCase				)
         model.eval()
         lowercase    :List[Any]      	=						model(_lowerCAmelCase       ,					labels=_lowerCAmelCase				)
         self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_labels)				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple				):
         lowercase    :Optional[int]      	=						self.prepare_config_and_inputs()
         lowercase    :Optional[int]      	=						config_and_inputs
         lowercase    :Tuple      	=						{"pixel_values": pixel_values}
         return config, inputs_dict







@require_torch
class    a__       (							lowerCAmelCase      , lowerCAmelCase      , unittest.TestCase):
       _a 					=						(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
       _a 					=						(
           {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification}
           if is_torch_available()
           else {}
       )

       _a 					=						False
       _a 					=						False
       _a 					=						False
       _a 					=						False






       def 					SCREAMING_SNAKE_CASE    (   self:					int				):
         lowercase    :Union[str, Any]      	=						RegNetModelTester(self				)
         lowercase    :Union[str, Any]      	=						ConfigTester(self       ,					config_class=_lowerCAmelCase       ,					has_text_modality=_lowerCAmelCase				)






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






       @unittest.skip(reason="RegNet does not use inputs_embeds"				)
       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]				):
         pass






       @unittest.skip(reason="RegNet does not support input and output embeddings"				)
       def 					SCREAMING_SNAKE_CASE    (   self:					List[Any]				):
         pass






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :Dict      	=						self.model_tester.prepare_config_and_inputs_for_common()

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

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






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :List[str]      	=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :List[Any]      	=						self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           lowercase    :int      	=						model_class(config=_lowerCAmelCase				)
           for name, module in model.named_modules():
             if isinstance(_lowerCAmelCase       ,					(nn.BatchNormad, nn.GroupNorm)				):
               self.assertTrue(
                   torch.all(module.weight == 1				)       ,					msg=F"Parameter {name} of model {model_class} seems not properly initialized"       ,					)
               self.assertTrue(
                   torch.all(module.bias == 0				)       ,					msg=F"Parameter {name} of model {model_class} seems not properly initialized"       ,					)






       def 					SCREAMING_SNAKE_CASE    (   self:					int				):
         def check_hidden_states_output(_lowerCAmelCase:					Optional[Any]       ,					_lowerCAmelCase:					Optional[int]       ,					_lowerCAmelCase:					Optional[Any]				):
           lowercase    :str      	=						model_class(_lowerCAmelCase				)
           model.to(_lowerCAmelCase				)
           model.eval()

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

           lowercase    :Optional[int]      	=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           lowercase    :Dict      	=						self.model_tester.num_stages
           self.assertEqual(len(_lowerCAmelCase				)       ,					expected_num_stages + 1				)

           # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
           self.assertListEqual(
               list(hidden_states[0].shape[-2:]				)       ,					[self.model_tester.image_size // 2, self.model_tester.image_size // 2]       ,					)

         lowercase    :Tuple      	=						self.model_tester.prepare_config_and_inputs_for_common()
         lowercase    :str      	=						["basic", "bottleneck"]
         for model_class in self.all_model_classes:
           for layer_type in layers_type:
             lowercase    :Optional[Any]      	=						layer_type
             lowercase    :Union[str, Any]      	=						True
             check_hidden_states_output(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             lowercase    :List[Any]      	=						True

             check_hidden_states_output(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :List[str]      	=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase				)






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase    :Any      	=						RegNetModel.from_pretrained(_lowerCAmelCase				)
           self.assertIsNotNone(_lowerCAmelCase				)







def       UpperCAmelCase__  (     ):
  lowercase    :Optional[Any]      	=						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
  return image







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






       @cached_property
       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple				):
         return (
             AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
             if is_vision_available()
             else None
         )






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :List[str]      	=						RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(_lowerCAmelCase				)

         lowercase    :str      	=						self.default_image_processor
         lowercase    :List[str]      	=						prepare_img()
         lowercase    :Optional[int]      	=						image_processor(images=_lowerCAmelCase       ,					return_tensors="pt"				).to(_lowerCAmelCase				)

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

         # verify the logits
         lowercase    :Any      	=						torch.Size((1, 10_00)				)
         self.assertEqual(outputs.logits.shape       ,					_lowerCAmelCase				)

         lowercase    :int      	=						torch.tensor([-0.41_80, -1.50_51, -3.48_36]				).to(_lowerCAmelCase				)

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









import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType




class    __lowerCAmelCase       (							lowerCAmelCase):
       _a 					=						['''image_processor''', '''tokenizer''']
       _a 					=						'''LayoutLMv2ImageProcessor'''
       _a 					=						('''LayoutXLMTokenizer''', '''LayoutXLMTokenizerFast''')






       def __init__(   self:					int       ,					_lowerCAmelCase:					Any=None       ,					_lowerCAmelCase:					List[Any]=None       ,					**_lowerCAmelCase:					Optional[Any]				):
         if "feature_extractor" in kwargs:
           warnings.warn(
               "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
               " instead."       ,					_lowerCAmelCase       ,					)
           lowercase    :Optional[Any]      	=						kwargs.pop("feature_extractor"				)

         lowercase    :Union[str, Any]      	=						image_processor if image_processor is not None else feature_extractor
         if image_processor is None:
           raise ValueError("You need to specify an `image_processor`."				)
         if tokenizer is None:
           raise ValueError("You need to specify a `tokenizer`."				)

         super().__init__(_lowerCAmelCase       ,					_lowerCAmelCase				)






       def __call__(   self:					List[str]       ,					_lowerCAmelCase:					Optional[Any]       ,					_lowerCAmelCase:					Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None       ,					_lowerCAmelCase:					Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None       ,					_lowerCAmelCase:					Union[List[List[int]], List[List[List[int]]]] = None       ,					_lowerCAmelCase:					Optional[Union[List[int], List[List[int]]]] = None       ,					_lowerCAmelCase:					bool = True       ,					_lowerCAmelCase:					Union[bool, str, PaddingStrategy] = False       ,					_lowerCAmelCase:					Union[bool, str, TruncationStrategy] = None       ,					_lowerCAmelCase:					Optional[int] = None       ,					_lowerCAmelCase:					int = 0       ,					_lowerCAmelCase:					Optional[int] = None       ,					_lowerCAmelCase:					Optional[bool] = None       ,					_lowerCAmelCase:					Optional[bool] = None       ,					_lowerCAmelCase:					bool = False       ,					_lowerCAmelCase:					bool = False       ,					_lowerCAmelCase:					bool = False       ,					_lowerCAmelCase:					bool = False       ,					_lowerCAmelCase:					bool = True       ,					_lowerCAmelCase:					Optional[Union[str, TensorType]] = None       ,					**_lowerCAmelCase:					Tuple       ,					):
         # verify input
         if self.image_processor.apply_ocr and (boxes is not None):
           raise ValueError(
               "You cannot provide bounding boxes "
               "if you initialized the image processor with apply_ocr set to True."				)

         if self.image_processor.apply_ocr and (word_labels is not None):
           raise ValueError(
               "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."				)

         if return_overflowing_tokens is True and return_offsets_mapping is False:
           raise ValueError("You cannot return overflowing tokens without returning the offsets mapping."				)

         # first, apply the image processor
         lowercase    :int      	=						self.image_processor(images=_lowerCAmelCase       ,					return_tensors=_lowerCAmelCase				)

         # second, apply the tokenizer
         if text is not None and self.image_processor.apply_ocr and text_pair is None:
           if isinstance(_lowerCAmelCase       ,					_lowerCAmelCase				):
             lowercase    :int      	=						[text]  # add batch dimension (as the image processor always adds a batch dimension)
           lowercase    :int      	=						features["words"]

         lowercase    :Optional[Any]      	=						self.tokenizer(
             text=text if text is not None else features["words"]       ,					text_pair=text_pair if text_pair is not None else None       ,					boxes=boxes if boxes is not None else features["boxes"]       ,					word_labels=_lowerCAmelCase       ,					add_special_tokens=_lowerCAmelCase       ,					padding=_lowerCAmelCase       ,					truncation=_lowerCAmelCase       ,					max_length=_lowerCAmelCase       ,					stride=_lowerCAmelCase       ,					pad_to_multiple_of=_lowerCAmelCase       ,					return_token_type_ids=_lowerCAmelCase       ,					return_attention_mask=_lowerCAmelCase       ,					return_overflowing_tokens=_lowerCAmelCase       ,					return_special_tokens_mask=_lowerCAmelCase       ,					return_offsets_mapping=_lowerCAmelCase       ,					return_length=_lowerCAmelCase       ,					verbose=_lowerCAmelCase       ,					return_tensors=_lowerCAmelCase       ,					**_lowerCAmelCase       ,					)

         # add pixel values
         lowercase    :Any      	=						features.pop("pixel_values"				)
         if return_overflowing_tokens is True:
           lowercase    :Any      	=						self.get_overflowing_images(_lowerCAmelCase       ,					encoded_inputs["overflow_to_sample_mapping"]				)
         lowercase    :Optional[int]      	=						images

         return encoded_inputs






       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple       ,					_lowerCAmelCase:					Tuple       ,					_lowerCAmelCase:					List[Any]				):
         # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
         lowercase    :Dict      	=						[]
         for sample_idx in overflow_to_sample_mapping:
           images_with_overflow.append(images[sample_idx]				)

         if len(_lowerCAmelCase				) != len(_lowerCAmelCase				):
           raise ValueError(
               "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
               F" {len(_lowerCAmelCase				)} and {len(_lowerCAmelCase				)}"				)

         return images_with_overflow






       def 					SCREAMING_SNAKE_CASE    (   self:					Dict       ,					*_lowerCAmelCase:					str       ,					**_lowerCAmelCase:					List[Any]				):
         return self.tokenizer.batch_decode(*_lowerCAmelCase       ,					**_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					str       ,					*_lowerCAmelCase:					Tuple       ,					**_lowerCAmelCase:					Union[str, Any]				):
         return self.tokenizer.decode(*_lowerCAmelCase       ,					**_lowerCAmelCase				)






       @property
       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         return ["input_ids", "bbox", "attention_mask", "image"]






       @property
       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]				):
         warnings.warn(
             "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."       ,					_lowerCAmelCase       ,					)
         return self.image_processor_class






       @property
       def 					SCREAMING_SNAKE_CASE    (   self:					List[Any]				):
         warnings.warn(
             "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."       ,					_lowerCAmelCase       ,					)
         return self.image_processor



