


'''simple docstring'''



import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor
from torchvision.transforms.functional import InterpolationMode

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    ViTImageProcessor,
    ViTMAEConfig,
    ViTMAEForPreTraining,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
__lowercase	:						Any       =	logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')

require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt')





@dataclass
class 							__UpperCamelCase				:
	A_				=    field(
	    default="cifar10"		,      metadata={"help": "Name of a dataset from the datasets package"}					)
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}					)
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={"help": "The column name of the images in the files."}					)
	A_				=    field(default=lowerCAmelCase_		,      metadata={"help": "A folder containing the training data."}					)
	A_				=    field(default=lowerCAmelCase_		,      metadata={"help": "A folder containing the validation data."}					)
	A_				=    field(
	    default=0.15		,      metadata={"help": "Percent to split off of train for validation."}					)
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of training examples to this "
	            "value if set."
	        )
	    }		,      )
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
	            "value if set."
	        )
	    }		,      )




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       List[Any]					    =  {}
						if self.train_dir is not None:
											__a			:       List[str]					    =  self.train_dir
						if self.validation_dir is not None:
											__a			:       Union[str, Any]					    =  self.validation_dir
						__a			:       Union[str, Any]					    =  data_files if data_files else None





@dataclass
class 							__UpperCamelCase				:
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={
	        "help": (
	            "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."
	        )
	    }		,      )
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={"help": "Pretrained config name or path if not the same as model_name_or_path"}					)
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={
	        "help": (
	            "Override some existing default config settings when a model is trained from scratch. Example: "
	            "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
	        )
	    }		,      )
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}					)
	A_				=    field(
	    default="main"		,      metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}		,      )
	A_				=    field(default=lowerCAmelCase_		,      metadata={"help": "Name or path of preprocessor config."}					)
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={
	        "help": (
	            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
	            "with private models)."
	        )
	    }		,      )
	A_				=    field(
	    default=0.75		,      metadata={"help": "The ratio of the number of masked tokens in the input sequence."}					)
	A_				=    field(
	    default=lowerCAmelCase_		,      metadata={"help": "Whether or not to train with normalized pixel values as target."}					)





@dataclass
class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    field(
	    default=1e-3		,      metadata={"help": "Base learning rate: absolute_lr = base_lr * total_batch_size / 256."}					)






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   int   ):
					__a			:       Union[str, Any]					    =  torch.stack([example['pixel_values'] for example in examples]   )
					return {"pixel_values": pixel_values}






def   lowerCamelCase							():
					# See all possible arguments in src/transformers/training_args.py
					# or by passing the --help flag to this script.
					# We now keep distinct sets of args, for a cleaner separation of concerns.

					__a			:       Optional[int]					    =  HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments)   )
					if len(sys.argv   ) == 2 and sys.argv[1].endswith('.json'   ):
										# If we pass only one argument to the script and it's the path to a json file,
										# let's parse it to get our arguments.
										__a    ,				__a    ,				__a			:       Optional[Any]					    =  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
					else:
										__a    ,				__a    ,				__a			:       Union[str, Any]					    =  parser.parse_args_into_dataclasses()

					# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
					# information sent is the one passed as arguments along with your Python/PyTorch versions.
					send_example_telemetry('run_mae'						,      _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )

					# Setup logging
					logging.basicConfig(
					    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'						,      datefmt='%m/%d/%Y %H:%M:%S'						,      handlers=[logging.StreamHandler(sys.stdout   )]						,      )

					if training_args.should_log:
										# The default of training_args.log_level is passive, so we set log level at info here to have that default.
										transformers.utils.logging.set_verbosity_info()

					__a			:       Optional[Any]					    =  training_args.get_process_log_level()
					logger.setLevel(_SCREAMING_SNAKE_CASE   )
					transformers.utils.logging.set_verbosity(_SCREAMING_SNAKE_CASE   )
					transformers.utils.logging.enable_default_handler()
					transformers.utils.logging.enable_explicit_format()

					# Log on each process the small summary:
					logger.warning(
					    F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
					    + F"""distributed training: {bool(training_args.local_rank != -1   )}, 16-bits training: {training_args.fpaa}"""   )
					logger.info(F"""Training/evaluation parameters {training_args}"""   )

					# Detecting last checkpoint.
					__a			:       Optional[Any]					    =  None
					if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
										__a			:       Optional[int]					    =  get_last_checkpoint(training_args.output_dir   )
										if last_checkpoint is None and len(os.listdir(training_args.output_dir   )   ) > 0:
															raise ValueError(
															    F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
															    'Use --overwrite_output_dir to overcome.'   )
										elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
															logger.info(
															    F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
															    'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'   )

    # Initialize our dataset.
					__a			:       Any					    =  load_dataset(
					    data_args.dataset_name						,      data_args.dataset_config_name						,      data_files=data_args.data_files						,      cache_dir=model_args.cache_dir						,      use_auth_token=True if model_args.use_auth_token else None						,      )

					# If we don't have a validation split, split off a percentage of train as validation.
					__a			:       str					    =  None if 'validation' in ds.keys() else data_args.train_val_split
					if isinstance(data_args.train_val_split						,      _SCREAMING_SNAKE_CASE   ) and data_args.train_val_split > 0.0:
										__a			:       List[str]					    =  ds['train'].train_test_split(data_args.train_val_split   )
										__a			:       str					    =  split['train']
										__a			:       List[Any]					    =  split['test']

					# Load pretrained model and image processor
					#
					# Distributed training:
					# The .from_pretrained methods guarantee that only one local process can concurrently
					# download model & vocab.
					__a			:       int					    =  {
					    'cache_dir': model_args.cache_dir,
					    'revision': model_args.model_revision,
					    'use_auth_token': True if model_args.use_auth_token else None,
					}
					if model_args.config_name:
										__a			:       Union[str, Any]					    =  ViTMAEConfig.from_pretrained(model_args.config_name						,      **_SCREAMING_SNAKE_CASE   )
					elif model_args.model_name_or_path:
										__a			:       Optional[int]					    =  ViTMAEConfig.from_pretrained(model_args.model_name_or_path						,      **_SCREAMING_SNAKE_CASE   )
					else:
										__a			:       str					    =  ViTMAEConfig()
										logger.warning('You are instantiating a new config instance from scratch.'   )
										if model_args.config_overrides is not None:
															logger.info(F"""Overriding config: {model_args.config_overrides}"""   )
															config.update_from_string(model_args.config_overrides   )
															logger.info(F"""New config: {config}"""   )

    # adapt config
					config.update(
					    {
					        'mask_ratio': model_args.mask_ratio,
					        'norm_pix_loss': model_args.norm_pix_loss,
					    }   )

					# create image processor
					if model_args.image_processor_name:
										__a			:       Dict					    =  ViTImageProcessor.from_pretrained(model_args.image_processor_name						,      **_SCREAMING_SNAKE_CASE   )
					elif model_args.model_name_or_path:
										__a			:       Optional[int]					    =  ViTImageProcessor.from_pretrained(model_args.model_name_or_path						,      **_SCREAMING_SNAKE_CASE   )
					else:
										__a			:       Tuple					    =  ViTImageProcessor()

					# create model
					if model_args.model_name_or_path:
										__a			:       Optional[int]					    =  ViTMAEForPreTraining.from_pretrained(
										    model_args.model_name_or_path						,      from_tf=bool('.ckpt' in model_args.model_name_or_path   )						,      config=_SCREAMING_SNAKE_CASE						,      cache_dir=model_args.cache_dir						,      revision=model_args.model_revision						,      use_auth_token=True if model_args.use_auth_token else None						,      )
					else:
										logger.info('Training new model from scratch'   )
										__a			:       Dict					    =  ViTMAEForPreTraining(_SCREAMING_SNAKE_CASE   )

					if training_args.do_train:
										__a			:       str					    =  ds['train'].column_names
					else:
										__a			:       str					    =  ds['validation'].column_names

					if data_args.image_column_name is not None:
										__a			:       List[str]					    =  data_args.image_column_name
					elif "image" in column_names:
										__a			:       Optional[Any]					    =  'image'
					elif "img" in column_names:
										__a			:       int					    =  'img'
					else:
										__a			:       List[Any]					    =  column_names[0]

					# transformations as done in original MAE paper
					# source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py
					if "shortest_edge" in image_processor.size:
										__a			:       Tuple					    =  image_processor.size['shortest_edge']
					else:
										__a			:       Union[str, Any]					    =  (image_processor.size['height'], image_processor.size['width'])
					__a			:       Dict					    =  Compose(
					    [
					        Lambda(lambda _SCREAMING_SNAKE_CASE   : img.convert('RGB'   ) if img.mode != "RGB" else img   ),
					        RandomResizedCrop(_SCREAMING_SNAKE_CASE						,      scale=(0.2, 1.0)						,      interpolation=InterpolationMode.BICUBIC   ),
					        RandomHorizontalFlip(),
					        ToTensor(),
					        Normalize(mean=image_processor.image_mean						,      std=image_processor.image_std   ),
					    ]   )

					def preprocess_images(_SCREAMING_SNAKE_CASE      :   List[Any]   ):
										__a			:       Optional[int]					    =  [transforms(_SCREAMING_SNAKE_CASE   ) for image in examples[image_column_name]]
										return examples

					if training_args.do_train:
										if "train" not in ds:
															raise ValueError('--do_train requires a train dataset'   )
										if data_args.max_train_samples is not None:
															__a			:       Any					    =  ds['train'].shuffle(seed=training_args.seed   ).select(range(data_args.max_train_samples   )   )
										# Set the training transforms
										ds["train"].set_transform(_SCREAMING_SNAKE_CASE   )

					if training_args.do_eval:
										if "validation" not in ds:
															raise ValueError('--do_eval requires a validation dataset'   )
										if data_args.max_eval_samples is not None:
															__a			:       Tuple					    =  (
															    ds['validation'].shuffle(seed=training_args.seed   ).select(range(data_args.max_eval_samples   )   )
															)
										# Set the validation transforms
										ds["validation"].set_transform(_SCREAMING_SNAKE_CASE   )

					# Compute absolute learning rate
					__a			:       int					    =  (
					    training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size
					)
					if training_args.base_learning_rate is not None:
										__a			:       Tuple					    =  training_args.base_learning_rate * total_train_batch_size / 256

					# Initialize our trainer
					__a			:       Dict					    =  Trainer(
					    model=_SCREAMING_SNAKE_CASE						,      args=_SCREAMING_SNAKE_CASE						,      train_dataset=ds['train'] if training_args.do_train else None						,      eval_dataset=ds['validation'] if training_args.do_eval else None						,      tokenizer=_SCREAMING_SNAKE_CASE						,      data_collator=_SCREAMING_SNAKE_CASE						,      )

					# Training
					if training_args.do_train:
										__a			:       Union[str, Any]					    =  None
										if training_args.resume_from_checkpoint is not None:
															__a			:       List[str]					    =  training_args.resume_from_checkpoint
										elif last_checkpoint is not None:
															__a			:       int					    =  last_checkpoint
										__a			:       Optional[int]					    =  trainer.train(resume_from_checkpoint=_SCREAMING_SNAKE_CASE   )
										trainer.save_model()
										trainer.log_metrics('train'						,      train_result.metrics   )
										trainer.save_metrics('train'						,      train_result.metrics   )
										trainer.save_state()

					# Evaluation
					if training_args.do_eval:
										__a			:       Dict					    =  trainer.evaluate()
										trainer.log_metrics('eval'						,      _SCREAMING_SNAKE_CASE   )
										trainer.save_metrics('eval'						,      _SCREAMING_SNAKE_CASE   )

					# Write model card and (optionally) push to hub
					__a			:       List[str]					    =  {
					    'tasks': 'masked-auto-encoding',
					    'dataset': data_args.dataset_name,
					    'tags': ['masked-auto-encoding'],
					}
					if training_args.push_to_hub:
										trainer.push_to_hub(**_SCREAMING_SNAKE_CASE   )
					else:
										trainer.create_model_card(**_SCREAMING_SNAKE_CASE   )






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   List[str]   ):
					# For xla_spawn (TPUs)
					main()


if __name__ == "__main__":
	main()







'''simple docstring'''



from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
	import tensorflow as tf

	from transformers import (
	    TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
	    TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
	    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
	    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
	    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
	    LayoutLMvaConfig,
	    TFLayoutLMvaForQuestionAnswering,
	    TFLayoutLMvaForSequenceClassification,
	    TFLayoutLMvaForTokenClassification,
	    TFLayoutLMvaModel,
	)

if is_vision_available():
	from PIL import Image

	from transformers import LayoutLMvaImageProcessor





class 							__UpperCamelCase				:




	def __init__(   self						,				__a						,				__a=2						,				__a=3						,				__a=4						,				__a=2						,				__a=7						,				__a=True						,				__a=True						,				__a=True						,				__a=True						,				__a=99						,				__a=36						,				__a=2						,				__a=4						,				__a=37						,				__a="gelu"						,				__a=0.1						,				__a=0.1						,				__a=512						,				__a=16						,				__a=2						,				__a=0.02						,				__a=6						,				__a=6						,				__a=3						,				__a=4						,				__a=None						,				__a=1000						,				):

						'''simple docstring'''





						__a			:       Optional[Any]					    =  parent
						__a			:       int					    =  batch_size
						__a			:       Any					    =  num_channels
						__a			:       Optional[int]					    =  image_size
						__a			:       Dict					    =  patch_size
						__a			:       int					    =  is_training
						__a			:       Union[str, Any]					    =  use_input_mask
						__a			:       Optional[int]					    =  use_token_type_ids
						__a			:       Dict					    =  use_labels
						__a			:       str					    =  vocab_size
						__a			:       List[Any]					    =  hidden_size
						__a			:       Union[str, Any]					    =  num_hidden_layers
						__a			:       str					    =  num_attention_heads
						__a			:       Union[str, Any]					    =  intermediate_size
						__a			:       Any					    =  hidden_act
						__a			:       List[str]					    =  hidden_dropout_prob
						__a			:       List[str]					    =  attention_probs_dropout_prob
						__a			:       List[Any]					    =  max_position_embeddings
						__a			:       Tuple					    =  type_vocab_size
						__a			:       Any					    =  type_sequence_label_size
						__a			:       Optional[int]					    =  initializer_range
						__a			:       Any					    =  coordinate_size
						__a			:       List[Any]					    =  shape_size
						__a			:       Optional[int]					    =  num_labels
						__a			:       Dict					    =  num_choices
						__a			:       Union[str, Any]					    =  scope
						__a			:       Union[str, Any]					    =  range_bbox

						# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
						__a			:       Optional[int]					    =  text_seq_length
						__a			:       Any					    =  (image_size // patch_size) ** 2 + 1
						__a			:       Dict					    =  self.text_seq_length + self.image_seq_length




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       str					    =  ids_tensor([self.batch_size, self.text_seq_length]						,				self.vocab_size							)

						__a			:       Tuple					    =  ids_tensor([self.batch_size, self.text_seq_length, 4]						,				self.range_bbox							)
						__a			:       Any					    =  bbox.numpy()
						# 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]:
																					__a			:       List[Any]					    =  bbox[i, j, 3]
																					__a			:       Tuple					    =  bbox[i, j, 1]
																					__a			:       str					    =  tmp_coordinate
																if bbox[i, j, 2] < bbox[i, j, 0]:
																					__a			:       int					    =  bbox[i, j, 2]
																					__a			:       Dict					    =  bbox[i, j, 0]
																					__a			:       int					    =  tmp_coordinate
						__a			:       Optional[int]					    =  tf.constant(__a							)

						__a			:       Dict					    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

						__a			:       str					    =  None
						if self.use_input_mask:
											__a			:       Optional[Any]					    =  random_attention_mask([self.batch_size, self.text_seq_length]							)

						__a			:       str					    =  None
						if self.use_token_type_ids:
											__a			:       List[Any]					    =  ids_tensor([self.batch_size, self.text_seq_length]						,				self.type_vocab_size							)

						__a			:       Optional[Any]					    =  None
						__a			:       Optional[int]					    =  None
						if self.use_labels:
											__a			:       List[Any]					    =  ids_tensor([self.batch_size]						,				self.type_sequence_label_size							)
											__a			:       Optional[int]					    =  ids_tensor([self.batch_size, self.text_seq_length]						,				self.num_labels							)

						__a			:       int					    =  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       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       Dict					    =  TFLayoutLMvaModel(config=__a							)

						# text + image
						__a			:       List[Any]					    =  model(__a						,				pixel_values=__a						,				training=__a							)
						__a			:       Any					    =  model(
						    __a						,				bbox=__a						,				pixel_values=__a						,				attention_mask=__a						,				token_type_ids=__a						,				training=__a						,				)
						__a			:       Optional[int]					    =  model(__a						,				bbox=__a						,				pixel_values=__a						,				training=__a							)

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

						# text only
						__a			:       Any					    =  model(__a						,				training=__a							)
						self.parent.assertEqual(
						    result.last_hidden_state.shape						,				(self.batch_size, self.text_seq_length, self.hidden_size)							)

						# image only
						__a			:       str					    =  model({'pixel_values': pixel_values}						,				training=__a							)
						self.parent.assertEqual(
						    result.last_hidden_state.shape						,				(self.batch_size, self.image_seq_length, self.hidden_size)							)




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       Any					    =  self.num_labels
						__a			:       Dict					    =  TFLayoutLMvaForSequenceClassification(config=__a							)
						__a			:       List[str]					    =  model(
						    __a						,				bbox=__a						,				pixel_values=__a						,				attention_mask=__a						,				token_type_ids=__a						,				labels=__a						,				training=__a						,				)
						self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.num_labels)							)




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       str					    =  self.num_labels
						__a			:       Optional[Any]					    =  TFLayoutLMvaForTokenClassification(config=__a							)
						__a			:       List[str]					    =  model(
						    __a						,				bbox=__a						,				pixel_values=__a						,				attention_mask=__a						,				token_type_ids=__a						,				labels=__a						,				training=__a						,				)
						self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.text_seq_length, self.num_labels)							)




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       List[Any]					    =  2
						__a			:       Any					    =  TFLayoutLMvaForQuestionAnswering(config=__a							)
						__a			:       Any					    =  model(
						    __a						,				bbox=__a						,				pixel_values=__a						,				attention_mask=__a						,				token_type_ids=__a						,				start_positions=__a						,				end_positions=__a						,				training=__a						,				)
						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       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Dict					    =  self.prepare_config_and_inputs()
						((__a)    ,				(__a)    ,				(__a)    ,				(__a)    ,				(__a)    ,				(__a)    ,				(__a)    ,				(__a))			:       Dict					    =  config_and_inputs
						__a			:       Any					    =  {
						    '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_tf
class 							__UpperCamelCase				(		lowerCAmelCase_		,      lowerCAmelCase_		,      unittest.TestCase					):
	A_				=    (
	    (
	        TFLayoutLMvaModel,
	        TFLayoutLMvaForQuestionAnswering,
	        TFLayoutLMvaForSequenceClassification,
	        TFLayoutLMvaForTokenClassification,
	    )
	    if is_tf_available()
	    else ()
	)
	A_				=    (
	    {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel}
	    if is_tf_available()
	    else {}
	)

	A_				=    False
	A_				=    False
	A_				=    False




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						return True




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a=False							):

						'''simple docstring'''





						__a			:       str					    =  copy.deepcopy(__a							)

						if model_class in get_values(__a							):
											__a			:       str					    =  {
											    k: tf.tile(tf.expand_dims(__a						,				1							)						,				(1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)							)
											    if isinstance(__a						,				tf.Tensor							) and v.ndim > 0
											    else v
											    for k, v in inputs_dict.items()
											}

						if return_labels:
											if model_class in get_values(__a							):
																__a			:       Optional[int]					    =  tf.ones(self.model_tester.batch_size						,				dtype=tf.intaa							)
											elif model_class in get_values(__a							):
																__a			:       int					    =  tf.zeros(self.model_tester.batch_size						,				dtype=tf.intaa							)
																__a			:       Optional[Any]					    =  tf.zeros(self.model_tester.batch_size						,				dtype=tf.intaa							)
											elif model_class in get_values(__a							):
																__a			:       Any					    =  tf.zeros(self.model_tester.batch_size						,				dtype=tf.intaa							)
											elif model_class in get_values(__a							):
																__a			:       Union[str, Any]					    =  tf.zeros(
																    (self.model_tester.batch_size, self.model_tester.text_seq_length)						,				dtype=tf.intaa							)

						return inputs_dict




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Optional[Any]					    =  TFLayoutLMvaModelTester(self							)
						__a			:       Optional[int]					    =  ConfigTester(self						,				config_class=__a						,				hidden_size=37							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						self.config_tester.run_common_tests()




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a    ,				__a			:       Dict					    =  self.model_tester.prepare_config_and_inputs_for_common()
						for model_class in self.all_model_classes:
											__a			:       Dict					    =  model_class(__a							)
											if getattr(__a						,				'hf_compute_loss'						,				__a							):
																# The number of elements in the loss should be the same as the number of elements in the label
																__a			:       Union[str, Any]					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)
																__a			:       str					    =  prepared_for_class[
																    sorted(prepared_for_class.keys() - inputs_dict.keys()						,				reverse=__a							)[0]
																]
																__a			:       Dict					    =  added_label.shape.as_list()[:1]

																# Test that model correctly compute the loss with kwargs
																__a			:       int					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)
																__a			:       Dict					    =  prepared_for_class.pop('input_ids'							)

																__a			:       Tuple					    =  model(__a						,				**__a							)[0]
																self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]							)

																# Test that model correctly compute the loss when we mask some positions
																__a			:       int					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)
																__a			:       str					    =  prepared_for_class.pop('input_ids'							)
																if "labels" in prepared_for_class:
																					__a			:       Union[str, Any]					    =  prepared_for_class['labels'].numpy()
																					if len(labels.shape							) > 1 and labels.shape[1] != 1:
																										__a			:       List[Any]					    =  -100
																										__a			:       List[str]					    =  tf.convert_to_tensor(__a							)
																										__a			:       Any					    =  model(__a						,				**__a							)[0]
																										self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]							)
																										self.assertTrue(not np.any(np.isnan(loss.numpy()							)							)							)

                # Test that model correctly compute the loss with a dict
																__a			:       Union[str, Any]					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)
																__a			:       str					    =  model(__a							)[0]
																self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]							)

																# Test that model correctly compute the loss with a tuple
																__a			:       Tuple					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)

																# Get keys that were added with the _prepare_for_class function
																__a			:       Dict					    =  prepared_for_class.keys() - inputs_dict.keys()
																__a			:       Any					    =  inspect.signature(model.call							).parameters
																__a			:       str					    =  list(signature.keys()							)

																# Create a dictionary holding the location of the tensors in the tuple
																__a			:       List[Any]					    =  {0: 'input_ids'}
																for label_key in label_keys:
																					__a			:       List[Any]					    =  signature_names.index(__a							)
																					__a			:       Union[str, Any]					    =  label_key
																__a			:       List[str]					    =  sorted(tuple_index_mapping.items()							)
																# Initialize a list with their default values, update the values and convert to a tuple
																__a			:       Union[str, Any]					    =  []

																for name in signature_names:
																					if name != "kwargs":
																										list_input.append(signature[name].default							)

																for index, value in sorted_tuple_index_mapping:
																					__a			:       Optional[Any]					    =  prepared_for_class[value]

																__a			:       str					    =  tuple(__a							)

																# Send to model
																__a			:       Tuple					    =  model(tuple_input[:-1]							)[0]

																self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       Optional[int]					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(__a						,				__a						,				__a						,				__a						,				__a						,				__a							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       Dict					    =  self.model_tester.prepare_config_and_inputs()
						for type in ["absolute", "relative_key", "relative_key_query"]:
											__a			:       Any					    =  type
											self.model_tester.create_and_check_model(__a						,				__a						,				__a						,				__a						,				__a						,				__a							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       List[str]					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_sequence_classification(
						    __a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       Optional[Any]					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_token_classification(
						    __a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       int					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_question_answering(
						    __a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							)





	@slow
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__a			:       List[Any]					    =  TFLayoutLMvaModel.from_pretrained(__a							)
											self.assertIsNotNone(__a							)






def   lowerCamelCase							():
					__a			:       Optional[Any]					    =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
					return image





@require_tf
class 							__UpperCamelCase				(		unittest.TestCase					):




	@cached_property
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						return LayoutLMvaImageProcessor(apply_ocr=__a							) if is_vision_available() else None





	@slow
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       str					    =  TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'							)

						__a			:       Tuple					    =  self.default_image_processor
						__a			:       List[Any]					    =  prepare_img()
						__a			:       int					    =  image_processor(images=__a						,				return_tensors='tf'							).pixel_values

						__a			:       Union[str, Any]					    =  tf.constant([[1, 2]]							)
						__a			:       Optional[Any]					    =  tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]							)						,				axis=0							)

						# forward pass
						__a			:       Tuple					    =  model(input_ids=__a						,				bbox=__a						,				pixel_values=__a						,				training=__a							)

						# verify the logits
						__a			:       List[Any]					    =  (1, 199, 768)
						self.assertEqual(outputs.last_hidden_state.shape						,				__a							)

						__a			:       Optional[Any]					    =  tf.constant(
						    [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]							)

						self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3]						,				__a						,				atol=1E-4							)							)



