
import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


lowerCamelCase_  :	Union[str, Any] 				=					logging.getLogger(__name__)

@dataclass
class     _UpperCamelCase			:






			'''simple docstring'''

			__UpperCamelCase :  str
			__UpperCamelCase :  List[str]
			__UpperCamelCase :  Optional[List[str]]




@dataclass
class     _UpperCamelCase			:






			'''simple docstring'''

			__UpperCamelCase :  List[int]
			__UpperCamelCase :  List[int]
			__UpperCamelCase :  Optional[List[int]]    =	None
			__UpperCamelCase :  Optional[List[int]]    =	None




class     _UpperCamelCase			(   _UpperCAmelCase					):






			'''simple docstring'''

			__UpperCamelCase :  Tuple    =	"train"
			__UpperCamelCase :  Optional[int]    =	"dev"
			__UpperCamelCase :  List[str]    =	"test"




class     _UpperCamelCase			:






			'''simple docstring'''

			@staticmethod
			def  lowerCAmelCase__		(    snake_case_	:    Union[str, Any]  ,		snake_case_	:    List[str] ):
							raise NotImplementedError

			@staticmethod
			def  lowerCAmelCase__		(    snake_case_	:    Optional[Any] ):
							raise NotImplementedError




			@staticmethod
			def  lowerCAmelCase__		(    snake_case_	:    str  ,		snake_case_	:    str  ,		snake_case_	:    int  ,		snake_case_	:    Optional[int]  ,		snake_case_	:    Tuple=False  ,		snake_case_	:    List[str]="[CLS]"  ,		snake_case_	:    Any=1  ,		snake_case_	:    Union[str, Any]="[SEP]"  ,		snake_case_	:    Optional[Any]=False  ,		snake_case_	:    Dict=False  ,		snake_case_	:    Dict=0  ,		snake_case_	:    List[Any]=0  ,		snake_case_	:    Union[str, Any]=-100  ,		snake_case_	:    Any=0  ,		snake_case_	:    Any=True  ,		):
							UpperCamelCase_:							int		=  {label: i for i, label in enumerate(_UpperCAmelCase )}

							UpperCamelCase_:							int		=  []
							for ex_index, example in enumerate(_UpperCAmelCase ):
											if ex_index % 1_0000 == 0:
															logger.info("""Writing example %d of %d"""  ,		_UpperCAmelCase  ,		len(_UpperCAmelCase ) )

											UpperCamelCase_:							Optional[int]		=  []
											UpperCamelCase_:							Optional[Any]		=  []
											for word, label in zip(example.words  ,		example.labels ):
															UpperCamelCase_:							Tuple		=  tokenizer.tokenize(_UpperCAmelCase )

															# bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
															if len(_UpperCAmelCase ) > 0:
																			tokens.extend(_UpperCAmelCase )
																			# Use the real label id for the first token of the word, and padding ids for the remaining tokens
																			label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_UpperCAmelCase ) - 1) )

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
											UpperCamelCase_:							List[Any]		=  tokenizer.num_special_tokens_to_add()
											if len(_UpperCAmelCase ) > max_seq_length - special_tokens_count:
															UpperCamelCase_:							Optional[int]		=  tokens[: (max_seq_length - special_tokens_count)]
															UpperCamelCase_:							Tuple		=  label_ids[: (max_seq_length - special_tokens_count)]

											# The convention in BERT is:
											# (a) For sequence pairs:
											#  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
											#  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
											# (b) For single sequences:
											#  tokens:   [CLS] the dog is hairy . [SEP]
											#  type_ids:   0   0   0   0  0     0   0
											#
											# Where "type_ids" are used to indicate whether this is the first
											# sequence or the second sequence. The embedding vectors for `type=0` and
											# `type=1` were learned during pre-training and are added to the wordpiece
											# embedding vector (and position vector). This is not *strictly* necessary
											# since the [SEP] token unambiguously separates the sequences, but it makes
											# it easier for the model to learn the concept of sequences.
											#
											# For classification tasks, the first vector (corresponding to [CLS]) is
											# used as the "sentence vector". Note that this only makes sense because
											# the entire model is fine-tuned.
											tokens += [sep_token]
											label_ids += [pad_token_label_id]
											if sep_token_extra:
															# roberta uses an extra separator b/w pairs of sentences
															tokens += [sep_token]
															label_ids += [pad_token_label_id]
											UpperCamelCase_:							int		=  [sequence_a_segment_id] * len(_UpperCAmelCase )

											if cls_token_at_end:
															tokens += [cls_token]
															label_ids += [pad_token_label_id]
															segment_ids += [cls_token_segment_id]
											else:
															UpperCamelCase_:							Any		=  [cls_token] + tokens
															UpperCamelCase_:							Dict		=  [pad_token_label_id] + label_ids
															UpperCamelCase_:							List[Any]		=  [cls_token_segment_id] + segment_ids

											UpperCamelCase_:							Dict		=  tokenizer.convert_tokens_to_ids(_UpperCAmelCase )

											# The mask has 1 for real tokens and 0 for padding tokens. Only real
											# tokens are attended to.
											UpperCamelCase_:							Dict		=  [1 if mask_padding_with_zero else 0] * len(_UpperCAmelCase )

											# Zero-pad up to the sequence length.
											UpperCamelCase_:							Any		=  max_seq_length - len(_UpperCAmelCase )
											if pad_on_left:
															UpperCamelCase_:							Union[str, Any]		=  ([pad_token] * padding_length) + input_ids
															UpperCamelCase_:							int		=  ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
															UpperCamelCase_:							Dict		=  ([pad_token_segment_id] * padding_length) + segment_ids
															UpperCamelCase_:							Optional[Any]		=  ([pad_token_label_id] * padding_length) + label_ids
											else:
															input_ids += [pad_token] * padding_length
															input_mask += [0 if mask_padding_with_zero else 1] * padding_length
															segment_ids += [pad_token_segment_id] * padding_length
															label_ids += [pad_token_label_id] * padding_length

											assert len(_UpperCAmelCase ) == max_seq_length
											assert len(_UpperCAmelCase ) == max_seq_length
											assert len(_UpperCAmelCase ) == max_seq_length
											assert len(_UpperCAmelCase ) == max_seq_length

											if ex_index < 5:
															logger.info("""*** Example ***""" )
															logger.info("""guid: %s"""  ,		example.guid )
															logger.info("""tokens: %s"""  ,		""" """.join([str(_UpperCAmelCase ) for x in tokens] ) )
															logger.info("""input_ids: %s"""  ,		""" """.join([str(_UpperCAmelCase ) for x in input_ids] ) )
															logger.info("""input_mask: %s"""  ,		""" """.join([str(_UpperCAmelCase ) for x in input_mask] ) )
															logger.info("""segment_ids: %s"""  ,		""" """.join([str(_UpperCAmelCase ) for x in segment_ids] ) )
															logger.info("""label_ids: %s"""  ,		""" """.join([str(_UpperCAmelCase ) for x in label_ids] ) )

											if "token_type_ids" not in tokenizer.model_input_names:
															UpperCamelCase_:							str		=  None

											features.append(
											    InputFeatures(
											        input_ids=_UpperCAmelCase  ,		attention_mask=_UpperCAmelCase  ,		token_type_ids=_UpperCAmelCase  ,		label_ids=_UpperCAmelCase ) )
							return features


if is_torch_available():
				import torch
				from torch import nn
				from torch.utils.data import Dataset

				class     _UpperCamelCase			(   _UpperCAmelCase					):






							'''simple docstring'''

							__UpperCamelCase :  List[InputFeatures]
							__UpperCamelCase :  int    =	nn.CrossEntropyLoss().ignore_index

							def __init__(    self	:    int  ,		snake_case_	:    List[Any]  ,		snake_case_	:    Tuple  ,		snake_case_	:    List[Any]  ,		snake_case_	:    Optional[Any]  ,		snake_case_	:    Optional[int]  ,		snake_case_	:    List[str] = None  ,		snake_case_	:    List[str]=False  ,		snake_case_	:    List[str] = Split.train  ,		):
											# Load data features from cache or dataset file
											UpperCamelCase_:							List[Any]		=  os.path.join(
											    _UpperCAmelCase  ,		"""cached_{}_{}_{}""".format(mode.value  ,		tokenizer.__class__.__name__  ,		str(_UpperCAmelCase ) )  ,		)

											# Make sure only the first process in distributed training processes the dataset,
											# and the others will use the cache.
											UpperCamelCase_:							str		=  cached_features_file + '''.lock'''
											with FileLock(_UpperCAmelCase ):
															if os.path.exists(_UpperCAmelCase ) and not overwrite_cache:
																			logger.info(f'''Loading features from cached file {cached_features_file}''' )
																			UpperCamelCase_:							Optional[Any]		=  torch.load(_UpperCAmelCase )
															else:
																			logger.info(f'''Creating features from dataset file at {data_dir}''' )
																			UpperCamelCase_:							int		=  token_classification_task.read_examples_from_file(_UpperCAmelCase  ,		_UpperCAmelCase )
																			# TODO clean up all this to leverage built-in features of tokenizers
																			UpperCamelCase_:							Dict		=  token_classification_task.convert_examples_to_features(
																			    _UpperCAmelCase  ,		_UpperCAmelCase  ,		_UpperCAmelCase  ,		_UpperCAmelCase  ,		cls_token_at_end=bool(model_type in ["""xlnet"""] )  ,		cls_token=tokenizer.cls_token  ,		cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0  ,		sep_token=tokenizer.sep_token  ,		sep_token_extra=_UpperCAmelCase  ,		pad_on_left=bool(tokenizer.padding_side == """left""" )  ,		pad_token=tokenizer.pad_token_id  ,		pad_token_segment_id=tokenizer.pad_token_type_id  ,		pad_token_label_id=self.pad_token_label_id  ,		)
																			logger.info(f'''Saving features into cached file {cached_features_file}''' )
																			torch.save(self.features  ,		_UpperCAmelCase )

							def __len__(    self	:    Union[str, Any] ):
											return len(self.features )




							def __getitem__(    self	:    Dict  ,		snake_case_	:    List[Any] ):
											return self.features[i]


if is_tf_available():
				import tensorflow as tf

				class     _UpperCamelCase			:






							'''simple docstring'''

							__UpperCamelCase :  List[InputFeatures]
							__UpperCamelCase :  int    =	-100

							def __init__(    self	:    int  ,		snake_case_	:    List[Any]  ,		snake_case_	:    Optional[int]  ,		snake_case_	:    Union[str, Any]  ,		snake_case_	:    str  ,		snake_case_	:    Optional[Any]  ,		snake_case_	:    Optional[Any] = None  ,		snake_case_	:    Any=False  ,		snake_case_	:    Optional[int] = Split.train  ,		):
											UpperCamelCase_:							List[str]		=  token_classification_task.read_examples_from_file(_UpperCAmelCase  ,		_UpperCAmelCase )
											# TODO clean up all this to leverage built-in features of tokenizers
											UpperCamelCase_:							Optional[Any]		=  token_classification_task.convert_examples_to_features(
											    _UpperCAmelCase  ,		_UpperCAmelCase  ,		_UpperCAmelCase  ,		_UpperCAmelCase  ,		cls_token_at_end=bool(model_type in ["""xlnet"""] )  ,		cls_token=tokenizer.cls_token  ,		cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0  ,		sep_token=tokenizer.sep_token  ,		sep_token_extra=_UpperCAmelCase  ,		pad_on_left=bool(tokenizer.padding_side == """left""" )  ,		pad_token=tokenizer.pad_token_id  ,		pad_token_segment_id=tokenizer.pad_token_type_id  ,		pad_token_label_id=self.pad_token_label_id  ,		)

											def gen():
															for ex in self.features:
																			if ex.token_type_ids is None:
																							yield (
																							    {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
																							    ex.label_ids,
																							)
																			else:
																							yield (
																							    {
																							        "input_ids": ex.input_ids,
																							        "attention_mask": ex.attention_mask,
																							        "token_type_ids": ex.token_type_ids,
																							    },
																							    ex.label_ids,
																							)

											if "token_type_ids" not in tokenizer.model_input_names:
															UpperCamelCase_:							Optional[int]		=  tf.data.Dataset.from_generator(
															    _UpperCAmelCase  ,		({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa)  ,		(
															        {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )},
															        tf.TensorShape([None] ),
															    )  ,		)
											else:
															UpperCamelCase_:							Union[str, Any]		=  tf.data.Dataset.from_generator(
															    _UpperCAmelCase  ,		({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa)  ,		(
															        {
															            """input_ids""": tf.TensorShape([None] ),
															            """attention_mask""": tf.TensorShape([None] ),
															            """token_type_ids""": tf.TensorShape([None] ),
															        },
															        tf.TensorShape([None] ),
															    )  ,		)

							def  lowerCAmelCase__		(    self	:    List[str] ):
											UpperCamelCase_:							List[str]		=  self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) )

											return self.dataset

							def __len__(    self	:    Any ):
											return len(self.features )




							def __getitem__(    self	:    Union[str, Any]  ,		snake_case_	:    Optional[int] ):
											return self.features[i]








from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase_  :	Tuple 				=					logging.get_logger(__name__)

lowerCamelCase_  :	str 				=					{
    """unc-nlp/lxmert-base-uncased""": """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json""",
}

class     _UpperCamelCase			(   _A					):






			'''simple docstring'''

			__UpperCamelCase :  Any    =	"""lxmert"""
			__UpperCamelCase :  Optional[Any]    =	{}

			def __init__(    self	:    Dict  ,		snake_case_	:    List[str]=3_0522  ,		snake_case_	:    int=768  ,		snake_case_	:    str=12  ,		snake_case_	:    Tuple=9500  ,		snake_case_	:    Optional[Any]=1600  ,		snake_case_	:    str=400  ,		snake_case_	:    List[str]=3072  ,		snake_case_	:    Dict="gelu"  ,		snake_case_	:    Optional[Any]=0.1  ,		snake_case_	:    int=0.1  ,		snake_case_	:    Optional[int]=512  ,		snake_case_	:    Tuple=2  ,		snake_case_	:    Optional[int]=0.02  ,		snake_case_	:    Union[str, Any]=1e-12  ,		snake_case_	:    Tuple=9  ,		snake_case_	:    Tuple=5  ,		snake_case_	:    Union[str, Any]=5  ,		snake_case_	:    List[str]=2048  ,		snake_case_	:    Any=4  ,		snake_case_	:    int=6.67  ,		snake_case_	:    Dict=True  ,		snake_case_	:    Tuple=True  ,		snake_case_	:    int=True  ,		snake_case_	:    str=True  ,		snake_case_	:    List[Any]=True  ,		snake_case_	:    List[Any]=True  ,		snake_case_	:    List[str]=True  ,		**snake_case_	:    Optional[int]  ,		):
							UpperCamelCase_:							int		=  vocab_size
							UpperCamelCase_:							Tuple		=  hidden_size
							UpperCamelCase_:							Optional[Any]		=  num_attention_heads
							UpperCamelCase_:							List[str]		=  hidden_act
							UpperCamelCase_:							int		=  intermediate_size
							UpperCamelCase_:							Any		=  hidden_dropout_prob
							UpperCamelCase_:							List[Any]		=  attention_probs_dropout_prob
							UpperCamelCase_:							List[str]		=  max_position_embeddings
							UpperCamelCase_:							Optional[Any]		=  type_vocab_size
							UpperCamelCase_:							Optional[Any]		=  initializer_range
							UpperCamelCase_:							str		=  layer_norm_eps
							UpperCamelCase_:							List[str]		=  num_qa_labels
							UpperCamelCase_:							List[str]		=  num_object_labels
							UpperCamelCase_:							Tuple		=  num_attr_labels
							UpperCamelCase_:							List[Any]		=  l_layers
							UpperCamelCase_:							List[Any]		=  x_layers
							UpperCamelCase_:							Any		=  r_layers
							UpperCamelCase_:							str		=  visual_feat_dim
							UpperCamelCase_:							Union[str, Any]		=  visual_pos_dim
							UpperCamelCase_:							str		=  visual_loss_normalizer
							UpperCamelCase_:							Dict		=  task_matched
							UpperCamelCase_:							Tuple		=  task_mask_lm
							UpperCamelCase_:							List[str]		=  task_obj_predict
							UpperCamelCase_:							Any		=  task_qa
							UpperCamelCase_:							Dict		=  visual_obj_loss
							UpperCamelCase_:							Optional[Any]		=  visual_attr_loss
							UpperCamelCase_:							List[Any]		=  visual_feat_loss
							UpperCamelCase_:							Tuple		=  {"""vision""": r_layers, """cross_encoder""": x_layers, """language""": l_layers}
							super().__init__(**snake_case_ )






