
import inspect
import os
from argparse import ArgumentParser, Namespace
from importlib import import_module

import huggingface_hub
import numpy as np
from packaging import version

from .. import (
    FEATURE_EXTRACTOR_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoImageProcessor,
    AutoProcessor,
    AutoTokenizer,
    is_datasets_available,
    is_tf_available,
    is_torch_available,
)
from ..utils import TF2_WEIGHTS_INDEX_NAME, TF2_WEIGHTS_NAME, logging
from . import BaseTransformersCLICommand


if is_tf_available():
					import tensorflow as tf

					tf.config.experimental.enable_tensor_float_aa_execution(False)

if is_torch_available():
					import torch

if is_datasets_available():
					from datasets import load_dataset


UpperCamelCase_  =	5E-5  # larger error tolerance than in our internal tests, to avoid flaky user-facing errors





def 							_lowerCamelCase			(					lowerCamelCase_:  Namespace		):



				'''simple docstring'''







				return PTtoTFCommand(
				    args.model_name				,	args.local_dir				,	args.max_error				,	args.new_weights				,	args.no_pr				,	args.push				,	args.extra_commit_description				,	args.override_model_class				,	)






class     _SCREAMING_SNAKE_CASE							(		snake_case							):





				@staticmethod
				def        _UpperCAmelCase						(		snake_case_ :		ArgumentParser							):


								"""simple docstring"""

								A     :  int   =				parser.add_parser(
								    '''pt-to-tf'''					,      help=(
								        '''CLI tool to run convert a transformers model from a PyTorch checkpoint to a TensorFlow checkpoint.'''
								        ''' Can also be used to validate existing weights without opening PRs, with --no-pr.'''
								    )					,      )
								train_parser.add_argument(
								    '''--model-name'''					,      type=snake_case_					,      required=snake_case_					,      help='''The model name, including owner/organization, as seen on the hub.'''					,      )
								train_parser.add_argument(
								    '''--local-dir'''					,      type=snake_case_					,      default=''''''					,      help='''Optional local directory of the model repository. Defaults to /tmp/{model_name}'''					,      )
								train_parser.add_argument(
								    '''--max-error'''					,      type=snake_case_					,      default=snake_case_					,      help=(
								        f"""Maximum error tolerance. Defaults to {MAX_ERROR}. This flag should be avoided, use at your own risk."""
								    )					,      )
								train_parser.add_argument(
								    '''--new-weights'''					,      action='''store_true'''					,      help='''Optional flag to create new TensorFlow weights, even if they already exist.'''					,      )
								train_parser.add_argument(
								    '''--no-pr'''					,      action='''store_true'''					,      help='''Optional flag to NOT open a PR with converted weights.'''							)
								train_parser.add_argument(
								    '''--push'''					,      action='''store_true'''					,      help='''Optional flag to push the weights directly to `main` (requires permissions)'''					,      )
								train_parser.add_argument(
								    '''--extra-commit-description'''					,      type=snake_case_					,      default=''''''					,      help='''Optional additional commit description to use when opening a PR (e.g. to tag the owner).'''					,      )
								train_parser.add_argument(
								    '''--override-model-class'''					,      type=snake_case_					,      default=snake_case_					,      help='''If you think you know better than the auto-detector, you can specify the model class here. '''
								    '''Can be either an AutoModel class or a specific model class like BertForSequenceClassification.'''					,      )
								train_parser.set_defaults(func=snake_case_							)





				@staticmethod
				def        _UpperCAmelCase						(		snake_case_ :		List[str]					,      snake_case_ :		List[Any]							):


								"""simple docstring"""

								A     :  Optional[Any]   =				set(pt_outputs.keys()							)
								A     :  Optional[Any]   =				set(tf_outputs.keys()							)
								if pt_out_attrs != tf_out_attrs:
												raise ValueError(
												    f"""The model outputs have different attributes, aborting. (Pytorch: {pt_out_attrs}, TensorFlow:"""
												    f""" {tf_out_attrs})"""							)

								# 2. For each output attribute, computes the difference
								def _find_pt_tf_differences(snake_case_ :		List[str]					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Optional[int]					,      snake_case_ :		Dict=""							):
												# If the current attribute is a tensor, it is a leaf and we make the comparison. Otherwise, we will dig in
												# recursivelly, keeping the name of the attribute.
												if isinstance(snake_case_					,      torch.Tensor							):
																A     :  Dict   =				np.max(np.abs(pt_out.numpy() - tf_out.numpy()							)							)
																A     :  Union[str, Any]   =				tensor_difference
												else:
																A     :  Tuple   =				attr_name
																for i, pt_item in enumerate(snake_case_							):
																				# If it is a named attribute, we keep the name. Otherwise, just its index.
																				if isinstance(snake_case_					,      snake_case_							):
																								A     :  Union[str, Any]   =				root_name + pt_item
																								A     :  Optional[int]   =				tf_out[pt_item]
																								A     :  int   =				pt_out[pt_item]
																				else:
																								A     :  Any   =				root_name + f"""[{i}]"""
																								A     :  int   =				tf_out[i]
																				A     :  Optional[Any]   =				_find_pt_tf_differences(snake_case_					,      snake_case_					,      snake_case_					,      snake_case_							)

												return differences

								return _find_pt_tf_differences(snake_case_					,      snake_case_					,      {}							)





				def __init__(		self :		List[Any]					,      snake_case_ :		str					,      snake_case_ :		str					,      snake_case_ :		float					,      snake_case_ :		bool					,      snake_case_ :		bool					,      snake_case_ :		bool					,      snake_case_ :		str					,      snake_case_ :		str					,      *snake_case_ :		List[str]					,      ):


								"""simple docstring"""

								A     :  Any   =				logging.get_logger('''transformers-cli/pt_to_tf'''							)
								A     :  Union[str, Any]   =				model_name
								A     :  Optional[Any]   =				local_dir if local_dir else os.path.join('''/tmp'''					,      snake_case_							)
								A     :  int   =				max_error
								A     :  Tuple   =				new_weights
								A     :  Optional[Any]   =				no_pr
								A     :  Tuple   =				push
								A     :  Any   =				extra_commit_description
								A     :  int   =				override_model_class





				def        _UpperCAmelCase						(		self :		Dict					,      snake_case_ :		Optional[Any]					,      snake_case_ :		Any					,      snake_case_ :		Any							):


								"""simple docstring"""

								def _get_audio_input():
												A     :  Any   =				load_dataset('''hf-internal-testing/librispeech_asr_dummy'''					,      '''clean'''					,      split='''validation'''							)
												A     :  Union[str, Any]   =				ds.sort('''id'''							).select(range(2							)							)[:2]['''audio''']
												A     :  List[Any]   =				[x['''array'''] for x in speech_samples]
												return raw_samples

								A     :  Optional[Any]   =				type(pt_model.config							)
								if model_config_class in PROCESSOR_MAPPING:
												A     :  List[str]   =				AutoProcessor.from_pretrained(self._local_dir							)
												if model_config_class in TOKENIZER_MAPPING and processor.tokenizer.pad_token is None:
																A     :  List[Any]   =				processor.tokenizer.eos_token
								elif model_config_class in IMAGE_PROCESSOR_MAPPING:
												A     :  List[str]   =				AutoImageProcessor.from_pretrained(self._local_dir							)
								elif model_config_class in FEATURE_EXTRACTOR_MAPPING:
												A     :  Dict   =				AutoFeatureExtractor.from_pretrained(self._local_dir							)
								elif model_config_class in TOKENIZER_MAPPING:
												A     :  Tuple   =				AutoTokenizer.from_pretrained(self._local_dir							)
												if processor.pad_token is None:
																A     :  str   =				processor.eos_token
								else:
												raise ValueError(f"""Unknown data processing type (model config type: {model_config_class})"""							)

								A     :  Union[str, Any]   =				set(inspect.signature(pt_model.forward							).parameters.keys()							)
								A     :  Dict   =				{}
								if "input_ids" in model_forward_signature:
												processor_inputs.update(
												    {
												        '''text''': ['''Hi there!''', '''I am a batch with more than one row and different input lengths.'''],
												        '''padding''': True,
												        '''truncation''': True,
												    }							)
								if "pixel_values" in model_forward_signature:
												A     :  List[str]   =				load_dataset('''cifar10'''					,      '''plain_text'''					,      split='''test'''							)[:2]['''img''']
												processor_inputs.update({'''images''': sample_images}							)
								if "input_features" in model_forward_signature:
												A     :  List[Any]   =				inspect.signature(processor.feature_extractor							).parameters
												# Pad to the largest input length by default but take feature extractor default
												# padding value if it exists e.g. "max_length" and is not False or None
												if "padding" in feature_extractor_signature:
																A     :  Any   =				feature_extractor_signature['''padding'''].default
																if default_strategy is not False and default_strategy is not None:
																				A     :  int   =				default_strategy
																else:
																				A     :  Any   =				True
												else:
																A     :  Any   =				True
												processor_inputs.update({'''audio''': _get_audio_input(), '''padding''': padding_strategy}							)
								if "input_values" in model_forward_signature:  # Wav2Vec2 audio input
												processor_inputs.update({'''audio''': _get_audio_input(), '''padding''': True}							)
								A     :  List[str]   =				processor(**snake_case_					,      return_tensors='''pt'''							)
								A     :  str   =				processor(**snake_case_					,      return_tensors='''tf'''							)

								# Extra input requirements, in addition to the input modality
								if (
								    config.is_encoder_decoder
								    or (hasattr(snake_case_					,      '''encoder'''							) and hasattr(snake_case_					,      '''decoder'''							))
								    or "decoder_input_ids" in tf_dummy_inputs
								):
												A     :  int   =				np.asarray([[1], [1]]					,      dtype=snake_case_							) * (pt_model.config.decoder_start_token_id or 0)
												pt_input.update({'''decoder_input_ids''': torch.tensor(snake_case_							)}							)
												tf_input.update({'''decoder_input_ids''': tf.convert_to_tensor(snake_case_							)}							)

								return pt_input, tf_input






				def        _UpperCAmelCase						(		self :		List[str]							):


								"""simple docstring"""

								if version.parse(huggingface_hub.__version__							) < version.parse('''0.9.0'''							):
												raise ImportError(
												    '''The huggingface_hub version must be >= 0.9.0 to use this command. Please update your huggingface_hub'''
												    ''' installation.'''							)
								else:
												from huggingface_hub import Repository, create_commit
												from huggingface_hub._commit_api import CommitOperationAdd

								# Fetch remote data
								A     :  List[str]   =				Repository(local_dir=self._local_dir					,      clone_from=self._model_name							)

								# Load config and get the appropriate architecture -- the latter is needed to convert the head's weights
								A     :  Union[str, Any]   =				AutoConfig.from_pretrained(self._local_dir							)
								A     :  Union[str, Any]   =				config.architectures
								if self._override_model_class is not None:
												if self._override_model_class.startswith('''TF'''							):
																A     :  Dict   =				[self._override_model_class[2:]]
												else:
																A     :  List[Any]   =				[self._override_model_class]
												try:
																A     :  Optional[int]   =				getattr(import_module('''transformers'''							)					,      architectures[0]							)
												except AttributeError:
																raise ValueError(f"""Model class {self._override_model_class} not found in transformers."""							)
												try:
																A     :  Optional[Any]   =				getattr(import_module('''transformers'''							)					,      '''TF''' + architectures[0]							)
												except AttributeError:
																raise ValueError(f"""TF model class TF{self._override_model_class} not found in transformers."""							)
								elif architectures is None:  # No architecture defined -- use auto classes
												A     :  List[str]   =				getattr(import_module('''transformers'''							)					,      '''AutoModel'''							)
												A     :  Tuple   =				getattr(import_module('''transformers'''							)					,      '''TFAutoModel'''							)
												self._logger.warning('''No detected architecture, using AutoModel/TFAutoModel'''							)
								else:  # Architecture defined -- use it
												if len(snake_case_							) > 1:
																raise ValueError(f"""More than one architecture was found, aborting. (architectures = {architectures})"""							)
												self._logger.warning(f"""Detected architecture: {architectures[0]}"""							)
												A     :  List[str]   =				getattr(import_module('''transformers'''							)					,      architectures[0]							)
												try:
																A     :  Dict   =				getattr(import_module('''transformers'''							)					,      '''TF''' + architectures[0]							)
												except AttributeError:
																raise AttributeError(f"""The TensorFlow equivalent of {architectures[0]} doesn't exist in transformers."""							)

        # Check the TF dummy inputs to see what keys we need in the forward pass
								A     :  Optional[int]   =				tf_class.from_config(snake_case_							)
								A     :  Dict   =				tf_from_pt_model.dummy_inputs

								del tf_from_pt_model  # Try to keep only one model in memory at a time

								# Load the model and get some basic inputs
								A     :  str   =				pt_class.from_pretrained(self._local_dir							)
								pt_model.eval()

								A ,       A     :  Tuple   =				self.get_inputs(snake_case_					,      snake_case_					,      snake_case_							)

								with torch.no_grad():
												A     :  Optional[Any]   =				pt_model(**snake_case_					,      output_hidden_states=snake_case_							)
								del pt_model  # will no longer be used, and may have a large memory footprint

								A     :  int   =				tf_class.from_pretrained(self._local_dir					,      from_pt=snake_case_							)
								A     :  int   =				tf_from_pt_model(**snake_case_					,      output_hidden_states=snake_case_					,      training=snake_case_							)

								# Confirms that cross loading PT weights into TF worked.
								A     :  Union[str, Any]   =				self.find_pt_tf_differences(snake_case_					,      snake_case_							)
								A     :  Dict   =				{k: v for k, v in crossload_differences.items() if '''hidden''' not in k}
								A     :  str   =				{k: v for k, v in crossload_differences.items() if '''hidden''' in k}
								if len(snake_case_							) == 0 and architectures is not None:
												raise ValueError(
												    f"""Something went wrong -- the config file has architectures ({architectures}), but no model head"""
												    ''' output was found. All outputs start with \'hidden\''''							)
								A     :  str   =				max(output_differences.values()							) if output_differences else 0.0
								A     :  str   =				max(hidden_differences.values()							)
								if max_crossload_output_diff > self._max_error or max_crossload_hidden_diff > self._max_error:
												raise ValueError(
												    '''The cross-loaded TensorFlow model has different outputs, something went wrong!\n'''
												    + f"""\nList of maximum output differences above the threshold ({self._max_error}):\n"""
												    + '''\n'''.join([f"""{k}: {v:.3e}""" for k, v in output_differences.items() if v > self._max_error]							)
												    + f"""\n\nList of maximum hidden layer differences above the threshold ({self._max_error}):\n"""
												    + '''\n'''.join([f"""{k}: {v:.3e}""" for k, v in hidden_differences.items() if v > self._max_error]							)							)

								# Save the weights in a TF format (if needed) and confirms that the results are still good
								A     :  int   =				os.path.join(self._local_dir					,      snake_case_							)
								A     :  Union[str, Any]   =				os.path.join(self._local_dir					,      snake_case_							)
								if (not os.path.exists(snake_case_							) and not os.path.exists(snake_case_							)) or self._new_weights:
												tf_from_pt_model.save_pretrained(self._local_dir							)
								del tf_from_pt_model  # will no longer be used, and may have a large memory footprint

								A     :  List[str]   =				tf_class.from_pretrained(self._local_dir							)
								A     :  Tuple   =				tf_model(**snake_case_					,      output_hidden_states=snake_case_							)

								A     :  Union[str, Any]   =				self.find_pt_tf_differences(snake_case_					,      snake_case_							)
								A     :  Optional[int]   =				{k: v for k, v in conversion_differences.items() if '''hidden''' not in k}
								A     :  List[str]   =				{k: v for k, v in conversion_differences.items() if '''hidden''' in k}
								if len(snake_case_							) == 0 and architectures is not None:
												raise ValueError(
												    f"""Something went wrong -- the config file has architectures ({architectures}), but no model head"""
												    ''' output was found. All outputs start with \'hidden\''''							)
								A     :  str   =				max(output_differences.values()							) if output_differences else 0.0
								A     :  Any   =				max(hidden_differences.values()							)
								if max_conversion_output_diff > self._max_error or max_conversion_hidden_diff > self._max_error:
												raise ValueError(
												    '''The converted TensorFlow model has different outputs, something went wrong!\n'''
												    + f"""\nList of maximum output differences above the threshold ({self._max_error}):\n"""
												    + '''\n'''.join([f"""{k}: {v:.3e}""" for k, v in output_differences.items() if v > self._max_error]							)
												    + f"""\n\nList of maximum hidden layer differences above the threshold ({self._max_error}):\n"""
												    + '''\n'''.join([f"""{k}: {v:.3e}""" for k, v in hidden_differences.items() if v > self._max_error]							)							)

								A     :  Union[str, Any]   =				'''Update TF weights''' if self._new_weights else '''Add TF weights'''
								if self._push:
												repo.git_add(auto_lfs_track=snake_case_							)
												repo.git_commit(snake_case_							)
												repo.git_push(blocking=snake_case_							)  # this prints a progress bar with the upload
												self._logger.warning(f"""TF weights pushed into {self._model_name}"""							)
								elif not self._no_pr:
												self._logger.warning('''Uploading the weights into a new PR...'''							)
												A     :  str   =				(
												    '''Model converted by the [`transformers`\' `pt_to_tf`'''
												    ''' CLI](https://github.com/huggingface/transformers/blob/main/src/transformers/commands/pt_to_tf.py). '''
												    '''All converted model outputs and hidden layers were validated against its PyTorch counterpart.\n\n'''
												    f"""Maximum crossload output difference={max_crossload_output_diff:.3e}; """
												    f"""Maximum crossload hidden layer difference={max_crossload_hidden_diff:.3e};\n"""
												    f"""Maximum conversion output difference={max_conversion_output_diff:.3e}; """
												    f"""Maximum conversion hidden layer difference={max_conversion_hidden_diff:.3e};\n"""
												)
												if self._max_error > MAX_ERROR:
																commit_descrition += (
																    f"""\n\nCAUTION: The maximum admissible error was manually increased to {self._max_error}!"""
																)
												if self._extra_commit_description:
																commit_descrition += "\n\n" + self._extra_commit_description

												# sharded model -> adds all related files (index and .h5 shards)
												if os.path.exists(snake_case_							):
																A     :  Any   =				[
																    CommitOperationAdd(path_in_repo=snake_case_					,      path_or_fileobj=snake_case_							)
																]
																for shard_path in tf.io.gfile.glob(self._local_dir + '''/tf_model-*.h5'''							):
																				operations += [
																				    CommitOperationAdd(path_in_repo=os.path.basename(snake_case_							)					,      path_or_fileobj=snake_case_							)
																				]
												else:
																A     :  Any   =				[CommitOperationAdd(path_in_repo=snake_case_					,      path_or_fileobj=snake_case_							)]

												A     :  Optional[Any]   =				create_commit(
												    repo_id=self._model_name					,      operations=snake_case_					,      commit_message=snake_case_					,      commit_description=snake_case_					,      repo_type='''model'''					,      create_pr=snake_case_					,      ).pr_url
												self._logger.warning(f"""PR open in {hub_pr_url}"""							)

import unittest

from transformers import LayoutLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    LayoutLMForMaskedLM,
					    LayoutLMForQuestionAnswering,
					    LayoutLMForSequenceClassification,
					    LayoutLMForTokenClassification,
					    LayoutLMModel,
					)

class     _SCREAMING_SNAKE_CASE							:





				def __init__(		self :		Optional[Any]					,      snake_case_ :		int					,      snake_case_ :		Union[str, Any]=13					,      snake_case_ :		int=7					,      snake_case_ :		List[str]=True					,      snake_case_ :		List[str]=True					,      snake_case_ :		Optional[Any]=True					,      snake_case_ :		int=True					,      snake_case_ :		Optional[Any]=99					,      snake_case_ :		List[Any]=32					,      snake_case_ :		Dict=5					,      snake_case_ :		Tuple=4					,      snake_case_ :		Optional[int]=37					,      snake_case_ :		List[Any]="gelu"					,      snake_case_ :		int=0.1					,      snake_case_ :		int=0.1					,      snake_case_ :		Optional[int]=512					,      snake_case_ :		Optional[int]=16					,      snake_case_ :		List[str]=2					,      snake_case_ :		List[str]=0.02					,      snake_case_ :		str=3					,      snake_case_ :		Tuple=4					,      snake_case_ :		Optional[int]=None					,      snake_case_ :		List[str]=1000					,      ):


								"""simple docstring"""

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





				def        _UpperCAmelCase						(		self :		Optional[int]							):


								"""simple docstring"""

								A     :  Any   =				ids_tensor([self.batch_size, self.seq_length]					,      self.vocab_size							)

								A     :  List[Any]   =				ids_tensor([self.batch_size, self.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]:
																				A     :  Dict   =				bbox[i, j, 3]
																				A     :  Optional[int]   =				bbox[i, j, 1]
																				A     :  Any   =				t
																if bbox[i, j, 2] < bbox[i, j, 0]:
																				A     :  Tuple   =				bbox[i, j, 2]
																				A     :  str   =				bbox[i, j, 0]
																				A     :  Any   =				t

								A     :  Any   =				None
								if self.use_input_mask:
												A     :  List[str]   =				ids_tensor([self.batch_size, self.seq_length]					,      vocab_size=2							)

								A     :  Dict   =				None
								if self.use_token_type_ids:
												A     :  Tuple   =				ids_tensor([self.batch_size, self.seq_length]					,      self.type_vocab_size							)

								A     :  Dict   =				None
								A     :  List[Any]   =				None
								A     :  Union[str, Any]   =				None
								if self.use_labels:
												A     :  Optional[int]   =				ids_tensor([self.batch_size]					,      self.type_sequence_label_size							)
												A     :  int   =				ids_tensor([self.batch_size, self.seq_length]					,      self.num_labels							)
												A     :  Dict   =				ids_tensor([self.batch_size]					,      self.num_choices							)

								A     :  List[Any]   =				self.get_config()

								return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels





				def        _UpperCAmelCase						(		self :		Optional[Any]							):


								"""simple docstring"""

								return LayoutLMConfig(
								    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					,      )





				def        _UpperCAmelCase						(		self :		Union[str, Any]					,      snake_case_ :		Any					,      snake_case_ :		List[Any]					,      snake_case_ :		List[str]					,      snake_case_ :		Any					,      snake_case_ :		Optional[Any]					,      snake_case_ :		str					,      snake_case_ :		Dict					,      snake_case_ :		int							):


								"""simple docstring"""

								A     :  int   =				LayoutLMModel(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  str   =				model(snake_case_					,      snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_							)
								A     :  Optional[Any]   =				model(snake_case_					,      snake_case_					,      token_type_ids=snake_case_							)
								A     :  int   =				model(snake_case_					,      snake_case_							)
								self.parent.assertEqual(result.last_hidden_state.shape					,      (self.batch_size, self.seq_length, self.hidden_size)							)
								self.parent.assertEqual(result.pooler_output.shape					,      (self.batch_size, self.hidden_size)							)





				def        _UpperCAmelCase						(		self :		List[Any]					,      snake_case_ :		Optional[Any]					,      snake_case_ :		Optional[int]					,      snake_case_ :		Tuple					,      snake_case_ :		Optional[int]					,      snake_case_ :		Dict					,      snake_case_ :		Any					,      snake_case_ :		str					,      snake_case_ :		int							):


								"""simple docstring"""

								A     :  Dict   =				LayoutLMForMaskedLM(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  List[str]   =				model(snake_case_					,      snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=snake_case_							)
								self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.seq_length, self.vocab_size)							)





				def        _UpperCAmelCase						(		self :		List[str]					,      snake_case_ :		List[str]					,      snake_case_ :		Optional[Any]					,      snake_case_ :		List[Any]					,      snake_case_ :		List[str]					,      snake_case_ :		List[Any]					,      snake_case_ :		List[str]					,      snake_case_ :		Any					,      snake_case_ :		List[str]							):


								"""simple docstring"""

								A     :  str   =				self.num_labels
								A     :  Any   =				LayoutLMForSequenceClassification(snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  Optional[Any]   =				model(
								    snake_case_					,      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        _UpperCAmelCase						(		self :		str					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Any					,      snake_case_ :		Tuple					,      snake_case_ :		int					,      snake_case_ :		List[Any]					,      snake_case_ :		Tuple					,      snake_case_ :		Optional[Any]					,      snake_case_ :		Optional[Any]							):


								"""simple docstring"""

								A     :  Any   =				self.num_labels
								A     :  List[str]   =				LayoutLMForTokenClassification(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  Tuple   =				model(snake_case_					,      snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=snake_case_							)
								self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.seq_length, self.num_labels)							)





				def        _UpperCAmelCase						(		self :		Optional[int]					,      snake_case_ :		Tuple					,      snake_case_ :		Optional[int]					,      snake_case_ :		List[Any]					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Dict							):


								"""simple docstring"""

								A     :  Any   =				LayoutLMForQuestionAnswering(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  List[str]   =				model(
								    snake_case_					,      bbox=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        _UpperCAmelCase						(		self :		Optional[Any]							):


								"""simple docstring"""

								A     :  Union[str, Any]   =				self.prepare_config_and_inputs()
								(
								    (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       
								)     :  Optional[int]   =				config_and_inputs
								A     :  Dict   =				{
								    '''input_ids''': input_ids,
								    '''bbox''': bbox,
								    '''token_type_ids''': token_type_ids,
								    '''attention_mask''': input_mask,
								}
								return config, inputs_dict



@require_torch
class     _SCREAMING_SNAKE_CASE							(		snake_case,    snake_case,    unittest.TestCase							):
				lowerCamelCase_       =     (
				    (
				        LayoutLMModel,
				        LayoutLMForMaskedLM,
				        LayoutLMForSequenceClassification,
				        LayoutLMForTokenClassification,
				        LayoutLMForQuestionAnswering,
				    )
				    if is_torch_available()
				    else None
				)
				lowerCamelCase_       =     (
				    {
				        'document-question-answering': LayoutLMForQuestionAnswering,
				        'feature-extraction': LayoutLMModel,
				        'fill-mask': LayoutLMForMaskedLM,
				        'text-classification': LayoutLMForSequenceClassification,
				        'token-classification': LayoutLMForTokenClassification,
				        'zero-shot': LayoutLMForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				lowerCamelCase_       =     True





				def        _UpperCAmelCase						(		self :		List[Any]							):


								"""simple docstring"""

								A     :  Union[str, Any]   =				LayoutLMModelTester(self							)
								A     :  Any   =				ConfigTester(self					,      config_class=snake_case_					,      hidden_size=37							)





				def        _UpperCAmelCase						(		self :		List[Any]							):


								"""simple docstring"""

								self.config_tester.run_common_tests()





				def        _UpperCAmelCase						(		self :		Union[str, Any]							):


								"""simple docstring"""

								A     :  Dict   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*snake_case_							)





				def        _UpperCAmelCase						(		self :		Dict							):


								"""simple docstring"""

								A     :  int   =				self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
												A     :  Optional[int]   =				type
												self.model_tester.create_and_check_model(*snake_case_							)





				def        _UpperCAmelCase						(		self :		List[str]							):


								"""simple docstring"""

								A     :  List[Any]   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_lm(*snake_case_							)





				def        _UpperCAmelCase						(		self :		Tuple							):


								"""simple docstring"""

								A     :  str   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(*snake_case_							)





				def        _UpperCAmelCase						(		self :		Optional[Any]							):


								"""simple docstring"""

								A     :  Dict   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_token_classification(*snake_case_							)





				def        _UpperCAmelCase						(		self :		Tuple							):


								"""simple docstring"""

								A     :  Any   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(*snake_case_							)






				@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''							)
				def        _UpperCAmelCase						(		self :		List[Any]							):


								"""simple docstring"""

								pass





def 							_lowerCamelCase			(					):



				'''simple docstring'''







				A     :  Optional[int]   =				torch.tensor([[101,1019,1014,1016,1037,1_2849,4747,1004,1_4246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,1_1300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,1_9274,2772,6205,2_7814,1_6147,1_6147,4343,2047,1_0283,1_0969,1_4389,1012,2338,102]]				,	device=lowerCamelCase_		)  # noqa: E231
				A     :  str   =				torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],]				,	device=lowerCamelCase_		)  # noqa: E231
				A     :  Dict   =				torch.tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1000,1000,1000,1000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1000,1000,1000,1000]]]				,	device=lowerCamelCase_		)  # noqa: E231
				A     :  Dict   =				torch.tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]				,	device=lowerCamelCase_		)  # noqa: E231
				# these are sequence labels (i.e. at the token level)
				A     :  List[Any]   =				torch.tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]]				,	device=lowerCamelCase_		)  # noqa: E231
				# fmt: on

				return input_ids, attention_mask, bbox, token_type_ids, labels






@require_torch
class     _SCREAMING_SNAKE_CASE							(		unittest.TestCase							):





				@slow
				def        _UpperCAmelCase						(		self :		List[Any]							):


								"""simple docstring"""

								A     :  Any   =				LayoutLMModel.from_pretrained('''microsoft/layoutlm-base-uncased'''							).to(snake_case_							)

								A ,       A ,       A ,       A ,       A     :  Optional[Any]   =				prepare_layoutlm_batch_inputs()

								# forward pass
								A     :  Dict   =				model(input_ids=snake_case_					,      bbox=snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_							)

								# test the sequence output on [0, :3, :3]
								A     :  Optional[int]   =				torch.tensor(
								    [[0.17_85, -0.19_47, -0.04_25], [-0.32_54, -0.28_07, 0.25_53], [-0.53_91, -0.33_22, 0.33_64]]					,      device=snake_case_					,      )

								self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]					,      snake_case_					,      atol=1E-3							)							)

								# test the pooled output on [1, :3]
								A     :  Any   =				torch.tensor([-0.65_80, -0.02_14, 0.85_52]					,      device=snake_case_							)

								self.assertTrue(torch.allclose(outputs.pooler_output[1, :3]					,      snake_case_					,      atol=1E-3							)							)





				@slow
				def        _UpperCAmelCase						(		self :		int							):


								"""simple docstring"""

								A     :  Any   =				LayoutLMForSequenceClassification.from_pretrained('''microsoft/layoutlm-base-uncased'''					,      num_labels=2							).to(
								    snake_case_							)

								A ,       A ,       A ,       A ,       A     :  Union[str, Any]   =				prepare_layoutlm_batch_inputs()

								# forward pass
								A     :  int   =				model(
								    input_ids=snake_case_					,      bbox=snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=torch.tensor([1, 1]					,      device=snake_case_							)					,      )

								# test whether we get a loss as a scalar
								A     :  int   =				outputs.loss
								A     :  Any   =				torch.Size([]							)
								self.assertEqual(loss.shape					,      snake_case_							)

								# test the shape of the logits
								A     :  List[Any]   =				outputs.logits
								A     :  Optional[Any]   =				torch.Size((2, 2)							)
								self.assertEqual(logits.shape					,      snake_case_							)





				@slow
				def        _UpperCAmelCase						(		self :		List[str]							):


								"""simple docstring"""

								A     :  Any   =				LayoutLMForTokenClassification.from_pretrained('''microsoft/layoutlm-base-uncased'''					,      num_labels=13							).to(
								    snake_case_							)

								A ,       A ,       A ,       A ,       A     :  Any   =				prepare_layoutlm_batch_inputs()

								# forward pass
								A     :  Union[str, Any]   =				model(
								    input_ids=snake_case_					,      bbox=snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=snake_case_							)

								# test the loss calculation to be around 2.65
								# expected_loss = torch.tensor(2.65, device=torch_device)

								# The loss is currently somewhat random and can vary between 0.1-0.3 atol.
								# self.assertTrue(torch.allclose(outputs.loss, expected_loss, atol=0.1))

								# test the shape of the logits
								A     :  List[Any]   =				outputs.logits
								A     :  str   =				torch.Size((2, 25, 13)							)
								self.assertEqual(logits.shape					,      snake_case_							)






				@slow
				def        _UpperCAmelCase						(		self :		Union[str, Any]							):


								"""simple docstring"""

								A     :  str   =				LayoutLMForQuestionAnswering.from_pretrained('''microsoft/layoutlm-base-uncased'''							).to(snake_case_							)

								A ,       A ,       A ,       A ,       A     :  str   =				prepare_layoutlm_batch_inputs()

								# forward pass
								A     :  str   =				model(input_ids=snake_case_					,      bbox=snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_							)

								# test the shape of the logits
								A     :  Optional[Any]   =				torch.Size((2, 25)							)
								self.assertEqual(outputs.start_logits.shape					,      snake_case_							)
								self.assertEqual(outputs.end_logits.shape					,      snake_case_							)