from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


A						=			logging.get_logger(__name__)

# General docstring
A						=			'RegNetConfig'

# Base docstring
A						=			'facebook/regnet-y-040'
A						=			[1, 1_0_8_8, 7, 7]

# Image classification docstring
A						=			'facebook/regnet-y-040'
A						=			'tabby, tabby cat'

A						=			[
    'facebook/regnet-y-040',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Optional[Any]     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int = 3     ,  snake_case__     :     int = 1     ,  snake_case__     :     int = 1     ,  snake_case__     :     Optional[str] = "relu"     ,  )      ->	int:
				super().__init__()
				_lowerCamelCase				   =  nn.Convad(
				    snake_case__     ,  snake_case__     ,  kernel_size=snake_case__     ,  stride=snake_case__     ,  padding=kernel_size // 2     ,  groups=snake_case__     ,  bias=snake_case__     ,  )
				_lowerCamelCase				   =  nn.BatchNormad(snake_case__		)
				_lowerCamelCase				   =  ACTaFN[activation] if activation is not None else nn.Identity()



		def   _snake_case       (       self     :     Dict     ,  snake_case__     :     List[Any]		)      ->	List[str]:
				_lowerCamelCase				   =  self.convolution(snake_case__		)
				_lowerCamelCase				   =  self.normalization(snake_case__		)
				_lowerCamelCase				   =  self.activation(snake_case__		)
				return hidden_state





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     RegNetConfig		)      ->	Optional[int]:
				super().__init__()
				_lowerCamelCase				   =  RegNetConvLayer(
				    config.num_channels     ,  config.embedding_size     ,  kernel_size=3     ,  stride=2     ,  activation=config.hidden_act		)
				_lowerCamelCase				   =  config.num_channels



		def   _snake_case       (       self     :     Any     ,  snake_case__     :     Optional[Any]		)      ->	Union[str, Any]:
				_lowerCamelCase				   =  pixel_values.shape[1]
				if num_channels != self.num_channels:
						raise ValueError(
						    'Make sure that the channel dimension of the pixel values match with the one set in the configuration.'		)
				_lowerCamelCase				   =  self.embedder(snake_case__		)
				return hidden_state





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Tuple     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int = 2		)      ->	List[Any]:
				super().__init__()
				_lowerCamelCase				   =  nn.Convad(snake_case__     ,  snake_case__     ,  kernel_size=1     ,  stride=snake_case__     ,  bias=snake_case__		)
				_lowerCamelCase				   =  nn.BatchNormad(snake_case__		)



		def   _snake_case       (       self     :     Any     ,  snake_case__     :     Tensor		)      ->	Tensor:
				_lowerCamelCase				   =  self.convolution(snake_case__		)
				_lowerCamelCase				   =  self.normalization(snake_case__		)
				return hidden_state





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Tuple     ,  snake_case__     :     int     ,  snake_case__     :     int		)      ->	int:
				super().__init__()

				_lowerCamelCase				   =  nn.AdaptiveAvgPoolad((1, 1)		)
				_lowerCamelCase				   =  nn.Sequential(
				    nn.Convad(snake_case__     ,  snake_case__     ,  kernel_size=1		)     ,  nn.ReLU()     ,  nn.Convad(snake_case__     ,  snake_case__     ,  kernel_size=1		)     ,  nn.Sigmoid()     ,  )



		def   _snake_case       (       self     :     Optional[int]     ,  snake_case__     :     Union[str, Any]		)      ->	Tuple:
				# b c h w -> b c 1 1
				_lowerCamelCase				   =  self.pooler(snake_case__		)
				_lowerCamelCase				   =  self.attention(snake_case__		)
				_lowerCamelCase				   =  hidden_state * attention
				return hidden_state





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Any     ,  snake_case__     :     RegNetConfig     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int = 1		)      ->	Optional[int]:
				super().__init__()
				_lowerCamelCase				   =  in_channels != out_channels or stride != 1
				_lowerCamelCase				   =  max(1     ,  out_channels // config.groups_width		)
				_lowerCamelCase				   =  (
				    RegNetShortCut(snake_case__     ,  snake_case__     ,  stride=snake_case__		) if should_apply_shortcut else nn.Identity()
				)
				_lowerCamelCase				   =  nn.Sequential(
				    RegNetConvLayer(snake_case__     ,  snake_case__     ,  kernel_size=1     ,  activation=config.hidden_act		)     ,  RegNetConvLayer(snake_case__     ,  snake_case__     ,  stride=snake_case__     ,  groups=snake_case__     ,  activation=config.hidden_act		)     ,  RegNetConvLayer(snake_case__     ,  snake_case__     ,  kernel_size=1     ,  activation=snake_case__		)     ,  )
				_lowerCamelCase				   =  ACTaFN[config.hidden_act]



		def   _snake_case       (       self     :     List[Any]     ,  snake_case__     :     List[str]		)      ->	Any:
				_lowerCamelCase				   =  hidden_state
				_lowerCamelCase				   =  self.layer(snake_case__		)
				_lowerCamelCase				   =  self.shortcut(snake_case__		)
				hidden_state += residual
				_lowerCamelCase				   =  self.activation(snake_case__		)
				return hidden_state





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Optional[int]     ,  snake_case__     :     RegNetConfig     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int = 1		)      ->	Tuple:
				super().__init__()
				_lowerCamelCase				   =  in_channels != out_channels or stride != 1
				_lowerCamelCase				   =  max(1     ,  out_channels // config.groups_width		)
				_lowerCamelCase				   =  (
				    RegNetShortCut(snake_case__     ,  snake_case__     ,  stride=snake_case__		) if should_apply_shortcut else nn.Identity()
				)
				_lowerCamelCase				   =  nn.Sequential(
				    RegNetConvLayer(snake_case__     ,  snake_case__     ,  kernel_size=1     ,  activation=config.hidden_act		)     ,  RegNetConvLayer(snake_case__     ,  snake_case__     ,  stride=snake_case__     ,  groups=snake_case__     ,  activation=config.hidden_act		)     ,  RegNetSELayer(snake_case__     ,  reduced_channels=int(round(in_channels / 4		)		)		)     ,  RegNetConvLayer(snake_case__     ,  snake_case__     ,  kernel_size=1     ,  activation=snake_case__		)     ,  )
				_lowerCamelCase				   =  ACTaFN[config.hidden_act]



		def   _snake_case       (       self     :     Tuple     ,  snake_case__     :     List[str]		)      ->	Optional[Any]:
				_lowerCamelCase				   =  hidden_state
				_lowerCamelCase				   =  self.layer(snake_case__		)
				_lowerCamelCase				   =  self.shortcut(snake_case__		)
				hidden_state += residual
				_lowerCamelCase				   =  self.activation(snake_case__		)
				return hidden_state





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Optional[int]     ,  snake_case__     :     RegNetConfig     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int = 2     ,  snake_case__     :     int = 2     ,  )      ->	List[Any]:
				super().__init__()

				_lowerCamelCase				   =  RegNetXLayer if config.layer_type == 'x' else RegNetYLayer

				_lowerCamelCase				   =  nn.Sequential(
				    # downsampling is done in the first layer with stride of 2
				    layer(
				        snake_case__     ,  snake_case__     ,  snake_case__     ,  stride=snake_case__     ,  )     ,  *[layer(snake_case__     ,  snake_case__     ,  snake_case__		) for _ in range(depth - 1		)]     ,  )



		def   _snake_case       (       self     :     Union[str, Any]     ,  snake_case__     :     Tuple		)      ->	str:
				_lowerCamelCase				   =  self.layers(snake_case__		)
				return hidden_state





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Union[str, Any]     ,  snake_case__     :     RegNetConfig		)      ->	Any:
				super().__init__()
				_lowerCamelCase				   =  nn.ModuleList([]		)
				# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
				self.stages.append(
				    RegNetStage(
				        snake_case__     ,  config.embedding_size     ,  config.hidden_sizes[0]     ,  stride=2 if config.downsample_in_first_stage else 1     ,  depth=config.depths[0]     ,  )		)
				_lowerCamelCase				   =  zip(config.hidden_sizes     ,  config.hidden_sizes[1:]		)
				for (in_channels, out_channels), depth in zip(snake_case__     ,  config.depths[1:]		):
						self.stages.append(RegNetStage(snake_case__     ,  snake_case__     ,  snake_case__     ,  depth=snake_case__		)		)



		def   _snake_case       (       self     :     Optional[Any]     ,  snake_case__     :     Tensor     ,  snake_case__     :     bool = False     ,  snake_case__     :     bool = True		)      ->	BaseModelOutputWithNoAttention:
				_lowerCamelCase				   =  () if output_hidden_states else None

				for stage_module in self.stages:
						if output_hidden_states:
								_lowerCamelCase				   =  hidden_states + (hidden_state,)

						_lowerCamelCase				   =  stage_module(snake_case__		)

				if output_hidden_states:
						_lowerCamelCase				   =  hidden_states + (hidden_state,)

				if not return_dict:
						return tuple(v for v in [hidden_state, hidden_states] if v is not None		)

				return BaseModelOutputWithNoAttention(last_hidden_state=snake_case__     ,  hidden_states=snake_case__		)





class     lowerCAmelCase__     (				SCREAMING_SNAKE_CASE_			):


		'''simple docstring'''






		lowerCAmelCase_     =   RegNetConfig
		lowerCAmelCase_     =   'regnet'
		lowerCAmelCase_     =   'pixel_values'
		lowerCAmelCase_     =   True
		def   _snake_case       (       self     :     int     ,  snake_case__     :     Union[str, Any]		)      ->	Any:
				if isinstance(snake_case__     ,  nn.Convad		):
						nn.init.kaiming_normal_(module.weight     ,  mode='fan_out'     ,  nonlinearity='relu'		)
				elif isinstance(snake_case__     ,  (nn.BatchNormad, nn.GroupNorm)		):
						nn.init.constant_(module.weight     ,  1		)
						nn.init.constant_(module.bias     ,  0		)



		def   _snake_case       (       self     :     Optional[Any]     ,  snake_case__     :     Tuple     ,  snake_case__     :     List[Any]=False		)      ->	Any:
				if isinstance(snake_case__     ,  snake_case__		):
						_lowerCamelCase				   =  value



A						=			r'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

A						=			r'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n'





@add_start_docstrings(
    'The bare RegNet model outputting raw features without any specific head on top.'     ,SCREAMING_SNAKE_CASE_     ,)
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class     lowerCAmelCase__     (				SCREAMING_SNAKE_CASE_			):


		'''simple docstring'''






		def __init__(       self     :     str     ,  snake_case__     :     str		)      ->	Union[str, Any]:
				super().__init__(snake_case__		)
				_lowerCamelCase				   =  config
				_lowerCamelCase				   =  RegNetEmbeddings(snake_case__		)
				_lowerCamelCase				   =  RegNetEncoder(snake_case__		)
				_lowerCamelCase				   =  nn.AdaptiveAvgPoolad((1, 1)		)
				# Initialize weights and apply final processing
				self.post_init()



		@add_start_docstrings_to_model_forward(snake_case__		)
		@add_code_sample_docstrings(
		    checkpoint=_CHECKPOINT_FOR_DOC     ,  output_type=snake_case__     ,  config_class=_CONFIG_FOR_DOC     ,  modality='vision'     ,  expected_output=_EXPECTED_OUTPUT_SHAPE     ,  )
		def   _snake_case       (       self     :     int     ,  snake_case__     :     Tensor     ,  snake_case__     :     Optional[bool] = None     ,  snake_case__     :     Optional[bool] = None		)      ->	BaseModelOutputWithPoolingAndNoAttention:
				_lowerCamelCase				   =  (
				    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
				)
				_lowerCamelCase				   =  return_dict if return_dict is not None else self.config.use_return_dict

				_lowerCamelCase				   =  self.embedder(snake_case__		)

				_lowerCamelCase				   =  self.encoder(
				    snake_case__     ,  output_hidden_states=snake_case__     ,  return_dict=snake_case__		)

				_lowerCamelCase				   =  encoder_outputs[0]

				_lowerCamelCase				   =  self.pooler(snake_case__		)

				if not return_dict:
						return (last_hidden_state, pooled_output) + encoder_outputs[1:]

				return BaseModelOutputWithPoolingAndNoAttention(
				    last_hidden_state=snake_case__     ,  pooler_output=snake_case__     ,  hidden_states=encoder_outputs.hidden_states     ,  )





@add_start_docstrings(
    '\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '     ,SCREAMING_SNAKE_CASE_     ,)
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class     lowerCAmelCase__     (				SCREAMING_SNAKE_CASE_			):


		'''simple docstring'''






		def __init__(       self     :     Optional[Any]     ,  snake_case__     :     int		)      ->	Any:
				super().__init__(snake_case__		)
				_lowerCamelCase				   =  config.num_labels
				_lowerCamelCase				   =  RegNetModel(snake_case__		)
				# classification head
				_lowerCamelCase				   =  nn.Sequential(
				    nn.Flatten()     ,  nn.Linear(config.hidden_sizes[-1]     ,  config.num_labels		) if config.num_labels > 0 else nn.Identity()     ,  )
				# initialize weights and apply final processing
				self.post_init()



		@add_start_docstrings_to_model_forward(snake_case__		)
		@add_code_sample_docstrings(
		    checkpoint=_IMAGE_CLASS_CHECKPOINT     ,  output_type=snake_case__     ,  config_class=_CONFIG_FOR_DOC     ,  expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT     ,  )
		def   _snake_case       (       self     :     List[str]     ,  snake_case__     :     Optional[torch.FloatTensor] = None     ,  snake_case__     :     Optional[torch.LongTensor] = None     ,  snake_case__     :     Optional[bool] = None     ,  snake_case__     :     Optional[bool] = None     ,  )      ->	ImageClassifierOutputWithNoAttention:
				_lowerCamelCase				   =  return_dict if return_dict is not None else self.config.use_return_dict

				_lowerCamelCase				   =  self.regnet(snake_case__     ,  output_hidden_states=snake_case__     ,  return_dict=snake_case__		)

				_lowerCamelCase				   =  outputs.pooler_output if return_dict else outputs[1]

				_lowerCamelCase				   =  self.classifier(snake_case__		)

				_lowerCamelCase				   =  None

				if labels is not None:
						if self.config.problem_type is None:
								if self.num_labels == 1:
										_lowerCamelCase				   =  'regression'
								elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
										_lowerCamelCase				   =  'single_label_classification'
								else:
										_lowerCamelCase				   =  'multi_label_classification'
						if self.config.problem_type == "regression":
								_lowerCamelCase				   =  MSELoss()
								if self.num_labels == 1:
										_lowerCamelCase				   =  loss_fct(logits.squeeze()     ,  labels.squeeze()		)
								else:
										_lowerCamelCase				   =  loss_fct(snake_case__     ,  snake_case__		)
						elif self.config.problem_type == "single_label_classification":
								_lowerCamelCase				   =  CrossEntropyLoss()
								_lowerCamelCase				   =  loss_fct(logits.view(-1     ,  self.num_labels		)     ,  labels.view(-1		)		)
						elif self.config.problem_type == "multi_label_classification":
								_lowerCamelCase				   =  BCEWithLogitsLoss()
								_lowerCamelCase				   =  loss_fct(snake_case__     ,  snake_case__		)

				if not return_dict:
						_lowerCamelCase				   =  (logits,) + outputs[2:]
						return (loss,) + output if loss is not None else output

				return ImageClassifierOutputWithNoAttention(loss=snake_case__     ,  logits=snake_case__     ,  hidden_states=outputs.hidden_states		)
import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
				    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
				    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
				    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
				    LayoutLMvaConfig,
				    LayoutLMvaForQuestionAnswering,
				    LayoutLMvaForSequenceClassification,
				    LayoutLMvaForTokenClassification,
				    LayoutLMvaModel,
				)
				from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
				from PIL import Image

				from transformers import LayoutLMvaImageProcessor





class     lowerCAmelCase__     :


		'''simple docstring'''






		def __init__(       self     :     Union[str, Any]     ,  snake_case__     :     int     ,  snake_case__     :     List[str]=2     ,  snake_case__     :     List[str]=3     ,  snake_case__     :     Tuple=4     ,  snake_case__     :     Optional[Any]=2     ,  snake_case__     :     int=7     ,  snake_case__     :     Optional[Any]=True     ,  snake_case__     :     Union[str, Any]=True     ,  snake_case__     :     Tuple=True     ,  snake_case__     :     int=True     ,  snake_case__     :     Optional[Any]=9_9     ,  snake_case__     :     Optional[Any]=3_6     ,  snake_case__     :     Tuple=3     ,  snake_case__     :     int=4     ,  snake_case__     :     Tuple=3_7     ,  snake_case__     :     Union[str, Any]="gelu"     ,  snake_case__     :     Any=0.1     ,  snake_case__     :     Optional[int]=0.1     ,  snake_case__     :     Dict=5_1_2     ,  snake_case__     :     Optional[int]=1_6     ,  snake_case__     :     Dict=2     ,  snake_case__     :     Dict=0.02     ,  snake_case__     :     List[Any]=6     ,  snake_case__     :     int=6     ,  snake_case__     :     Tuple=3     ,  snake_case__     :     List[Any]=4     ,  snake_case__     :     List[str]=None     ,  snake_case__     :     Optional[Any]=1_0_0_0     ,  )      ->	Optional[int]:
				_lowerCamelCase				   =  parent
				_lowerCamelCase				   =  batch_size
				_lowerCamelCase				   =  num_channels
				_lowerCamelCase				   =  image_size
				_lowerCamelCase				   =  patch_size
				_lowerCamelCase				   =  text_seq_length
				_lowerCamelCase				   =  is_training
				_lowerCamelCase				   =  use_input_mask
				_lowerCamelCase				   =  use_token_type_ids
				_lowerCamelCase				   =  use_labels
				_lowerCamelCase				   =  vocab_size
				_lowerCamelCase				   =  hidden_size
				_lowerCamelCase				   =  num_hidden_layers
				_lowerCamelCase				   =  num_attention_heads
				_lowerCamelCase				   =  intermediate_size
				_lowerCamelCase				   =  hidden_act
				_lowerCamelCase				   =  hidden_dropout_prob
				_lowerCamelCase				   =  attention_probs_dropout_prob
				_lowerCamelCase				   =  max_position_embeddings
				_lowerCamelCase				   =  type_vocab_size
				_lowerCamelCase				   =  type_sequence_label_size
				_lowerCamelCase				   =  initializer_range
				_lowerCamelCase				   =  coordinate_size
				_lowerCamelCase				   =  shape_size
				_lowerCamelCase				   =  num_labels
				_lowerCamelCase				   =  num_choices
				_lowerCamelCase				   =  scope
				_lowerCamelCase				   =  range_bbox

				# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
				_lowerCamelCase				   =  text_seq_length
				_lowerCamelCase				   =  (image_size // patch_size) ** 2 + 1
				_lowerCamelCase				   =  self.text_seq_length + self.image_seq_length
		def   _snake_case       (       self     :     int		)      ->	Any:
				_lowerCamelCase				   =  ids_tensor([self.batch_size, self.text_seq_length]     ,  self.vocab_size		)

				_lowerCamelCase				   =  ids_tensor([self.batch_size, self.text_seq_length, 4]     ,  self.range_bbox		)
				# Ensure that bbox is legal
				for i in range(bbox.shape[0]		):
						for j in range(bbox.shape[1]		):
								if bbox[i, j, 3] < bbox[i, j, 1]:
										_lowerCamelCase				   =  bbox[i, j, 3]
										_lowerCamelCase				   =  bbox[i, j, 1]
										_lowerCamelCase				   =  t
								if bbox[i, j, 2] < bbox[i, j, 0]:
										_lowerCamelCase				   =  bbox[i, j, 2]
										_lowerCamelCase				   =  bbox[i, j, 0]
										_lowerCamelCase				   =  t

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

				_lowerCamelCase				   =  None
				if self.use_input_mask:
						_lowerCamelCase				   =  random_attention_mask([self.batch_size, self.text_seq_length]		)

				_lowerCamelCase				   =  None
				if self.use_token_type_ids:
						_lowerCamelCase				   =  ids_tensor([self.batch_size, self.text_seq_length]     ,  self.type_vocab_size		)

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

				_lowerCamelCase				   =  LayoutLMvaConfig(
				    vocab_size=self.vocab_size     ,  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     ,  max_position_embeddings=self.max_position_embeddings     ,  type_vocab_size=self.type_vocab_size     ,  initializer_range=self.initializer_range     ,  coordinate_size=self.coordinate_size     ,  shape_size=self.shape_size     ,  input_size=self.image_size     ,  patch_size=self.patch_size     ,  )

				return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
		def   _snake_case       (       self     :     Optional[int]     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     Any     ,  snake_case__     :     str     ,  snake_case__     :     Tuple     ,  snake_case__     :     Dict     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     int     ,  snake_case__     :     Optional[Any]		)      ->	Any:
				_lowerCamelCase				   =  LayoutLMvaModel(config=snake_case__		)
				model.to(snake_case__		)
				model.eval()

				# text + image
				_lowerCamelCase				   =  model(snake_case__     ,  pixel_values=snake_case__		)
				_lowerCamelCase				   =  model(
				    snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  attention_mask=snake_case__     ,  token_type_ids=snake_case__		)
				_lowerCamelCase				   =  model(snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  token_type_ids=snake_case__		)
				_lowerCamelCase				   =  model(snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__		)

				self.parent.assertEqual(result.last_hidden_state.shape     ,  (self.batch_size, self.seq_length, self.hidden_size)		)

				# text only
				_lowerCamelCase				   =  model(snake_case__		)
				self.parent.assertEqual(
				    result.last_hidden_state.shape     ,  (self.batch_size, self.text_seq_length, self.hidden_size)		)

				# image only
				_lowerCamelCase				   =  model(pixel_values=snake_case__		)
				self.parent.assertEqual(
				    result.last_hidden_state.shape     ,  (self.batch_size, self.image_seq_length, self.hidden_size)		)
		def   _snake_case       (       self     :     Any     ,  snake_case__     :     Tuple     ,  snake_case__     :     Union[str, Any]     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     List[Any]     ,  snake_case__     :     Any     ,  snake_case__     :     str     ,  snake_case__     :     str     ,  snake_case__     :     int		)      ->	List[Any]:
				_lowerCamelCase				   =  self.num_labels
				_lowerCamelCase				   =  LayoutLMvaForSequenceClassification(snake_case__		)
				model.to(snake_case__		)
				model.eval()
				_lowerCamelCase				   =  model(
				    snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  attention_mask=snake_case__     ,  token_type_ids=snake_case__     ,  labels=snake_case__     ,  )
				self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.num_labels)		)
		def   _snake_case       (       self     :     Dict     ,  snake_case__     :     Tuple     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     str     ,  snake_case__     :     str     ,  snake_case__     :     Any     ,  snake_case__     :     List[str]     ,  snake_case__     :     Tuple     ,  snake_case__     :     Dict		)      ->	Optional[Any]:
				_lowerCamelCase				   =  self.num_labels
				_lowerCamelCase				   =  LayoutLMvaForTokenClassification(config=snake_case__		)
				model.to(snake_case__		)
				model.eval()
				_lowerCamelCase				   =  model(
				    snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  attention_mask=snake_case__     ,  token_type_ids=snake_case__     ,  labels=snake_case__     ,  )
				self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.text_seq_length, self.num_labels)		)
		def   _snake_case       (       self     :     str     ,  snake_case__     :     int     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     str     ,  snake_case__     :     List[str]     ,  snake_case__     :     List[Any]     ,  snake_case__     :     List[Any]     ,  snake_case__     :     int     ,  snake_case__     :     Any		)      ->	Dict:
				_lowerCamelCase				   =  LayoutLMvaForQuestionAnswering(config=snake_case__		)
				model.to(snake_case__		)
				model.eval()
				_lowerCamelCase				   =  model(
				    snake_case__     ,  bbox=snake_case__     ,  pixel_values=snake_case__     ,  attention_mask=snake_case__     ,  token_type_ids=snake_case__     ,  start_positions=snake_case__     ,  end_positions=snake_case__     ,  )
				self.parent.assertEqual(result.start_logits.shape     ,  (self.batch_size, self.seq_length)		)
				self.parent.assertEqual(result.end_logits.shape     ,  (self.batch_size, self.seq_length)		)



		def   _snake_case       (       self     :     str		)      ->	List[str]:
				_lowerCamelCase				   =  self.prepare_config_and_inputs()
				(
				    (
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							(
				    _lowerCamelCase
				)   ,							
				)				   =  config_and_inputs
				_lowerCamelCase				   =  {
				    'input_ids': input_ids,
				    'bbox': bbox,
				    'pixel_values': pixel_values,
				    'token_type_ids': token_type_ids,
				    'attention_mask': input_mask,
				}
				return config, inputs_dict





@require_torch
class     lowerCAmelCase__     (				SCREAMING_SNAKE_CASE_     ,SCREAMING_SNAKE_CASE_     ,unittest.TestCase			):


		'''simple docstring'''






		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False

		lowerCAmelCase_     =   (
		    (
		        LayoutLMvaModel,
		        LayoutLMvaForSequenceClassification,
		        LayoutLMvaForTokenClassification,
		        LayoutLMvaForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		lowerCAmelCase_     =   (
		    {'document-question-answering': LayoutLMvaForQuestionAnswering, 'feature-extraction': LayoutLMvaModel}
		    if is_torch_available()
		    else {}
		)
		def   _snake_case       (       self     :     Union[str, Any]     ,  snake_case__     :     Tuple     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     int     ,  snake_case__     :     Tuple     ,  snake_case__     :     Union[str, Any]		)      ->	str:
				# `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual
				# embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has
				# the sequence dimension of the text embedding only.
				# (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`)
				return True
		def   _snake_case       (       self     :     str		)      ->	Any:
				_lowerCamelCase				   =  LayoutLMvaModelTester(self		)
				_lowerCamelCase				   =  ConfigTester(self     ,  config_class=snake_case__     ,  hidden_size=3_7		)
		def   _snake_case       (       self     :     List[str]     ,  snake_case__     :     str     ,  snake_case__     :     List[Any]     ,  snake_case__     :     Dict=False		)      ->	str:
				_lowerCamelCase				   =  copy.deepcopy(snake_case__		)
				if model_class in get_values(snake_case__		):
						_lowerCamelCase				   =  {
						    k: v.unsqueeze(1		).expand(-1     ,  self.model_tester.num_choices     ,  -1		).contiguous()
						    if isinstance(snake_case__     ,  torch.Tensor		) and v.ndim > 1
						    else v
						    for k, v in inputs_dict.items()
						}
				if return_labels:
						if model_class in get_values(snake_case__		):
								_lowerCamelCase				   =  torch.ones(self.model_tester.batch_size     ,  dtype=torch.long     ,  device=snake_case__		)
						elif model_class in get_values(snake_case__		):
								_lowerCamelCase				   =  torch.zeros(
								    self.model_tester.batch_size     ,  dtype=torch.long     ,  device=snake_case__		)
								_lowerCamelCase				   =  torch.zeros(
								    self.model_tester.batch_size     ,  dtype=torch.long     ,  device=snake_case__		)
						elif model_class in [
						    *get_values(snake_case__		),
						]:
								_lowerCamelCase				   =  torch.zeros(
								    self.model_tester.batch_size     ,  dtype=torch.long     ,  device=snake_case__		)
						elif model_class in [
						    *get_values(snake_case__		),
						]:
								_lowerCamelCase				   =  torch.zeros(
								    (self.model_tester.batch_size, self.model_tester.text_seq_length)     ,  dtype=torch.long     ,  device=snake_case__     ,  )

				return inputs_dict
		def   _snake_case       (       self     :     Any		)      ->	List[str]:
				self.config_tester.run_common_tests()
		def   _snake_case       (       self     :     int		)      ->	Optional[int]:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*snake_case__		)
		def   _snake_case       (       self     :     int		)      ->	Any:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				for type in ["absolute", "relative_key", "relative_key_query"]:
						_lowerCamelCase				   =  type
						self.model_tester.create_and_check_model(*snake_case__		)
		def   _snake_case       (       self     :     int		)      ->	Any:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_sequence_classification(*snake_case__		)
		def   _snake_case       (       self     :     Any		)      ->	Any:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_token_classification(*snake_case__		)
		def   _snake_case       (       self     :     int		)      ->	List[Any]:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_question_answering(*snake_case__		)



		@slow
		def   _snake_case       (       self     :     Optional[int]		)      ->	List[Any]:
				for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						_lowerCamelCase				   =  LayoutLMvaModel.from_pretrained(snake_case__		)
						self.assertIsNotNone(snake_case__		)



def 	lowerCamelCase					(	)   ->    List[Any]:
		_lowerCamelCase				   =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
		return image





@require_torch
class     lowerCAmelCase__     (				unittest.TestCase			):


		'''simple docstring'''






		@cached_property
		def   _snake_case       (       self     :     int		)      ->	Any:
				return LayoutLMvaImageProcessor(apply_ocr=snake_case__		) if is_vision_available() else None



		@slow
		def   _snake_case       (       self     :     List[str]		)      ->	Tuple:
				_lowerCamelCase				   =  LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'		).to(snake_case__		)

				_lowerCamelCase				   =  self.default_image_processor
				_lowerCamelCase				   =  prepare_img()
				_lowerCamelCase				   =  image_processor(images=snake_case__     ,  return_tensors='pt'		).pixel_values.to(snake_case__		)

				_lowerCamelCase				   =  torch.tensor([[1, 2]]		)
				_lowerCamelCase				   =  torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]		).unsqueeze(0		)

				# forward pass
				_lowerCamelCase				   =  model(
				    input_ids=input_ids.to(snake_case__		)     ,  bbox=bbox.to(snake_case__		)     ,  pixel_values=pixel_values.to(snake_case__		)     ,  )

				# verify the logits
				_lowerCamelCase				   =  torch.Size((1, 1_9_9, 7_6_8)		)
				self.assertEqual(outputs.last_hidden_state.shape     ,  snake_case__		)

				_lowerCamelCase				   =  torch.tensor(
				    [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]		).to(snake_case__		)

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