




import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VideoMAEConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
					import torch
					from torch import nn

					from transformers import (
					    MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
					    VideoMAEForPreTraining,
					    VideoMAEForVideoClassification,
					    VideoMAEModel,
					)
					from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from transformers import VideoMAEImageProcessor
class       a__   :






						def __init__(       self		,      _A		,      _A=1_3		,      _A=1_0		,      _A=3		,      _A=2		,      _A=2		,      _A=2		,      _A=True		,      _A=True		,      _A=3_2		,      _A=5		,      _A=4		,      _A=3_7		,      _A="gelu"		,      _A=0.1		,      _A=0.1		,      _A=1_0		,      _A=0.02		,      _A=0.9		,      _A=None		,      ):




											"""simple docstring"""



											__lowerCAmelCase           =	parent
											__lowerCAmelCase           =	batch_size
											__lowerCAmelCase           =	image_size
											__lowerCAmelCase           =	num_channels
											__lowerCAmelCase           =	patch_size
											__lowerCAmelCase           =	tubelet_size
											__lowerCAmelCase           =	num_frames
											__lowerCAmelCase           =	is_training
											__lowerCAmelCase           =	use_labels
											__lowerCAmelCase           =	hidden_size
											__lowerCAmelCase           =	num_hidden_layers
											__lowerCAmelCase           =	num_attention_heads
											__lowerCAmelCase           =	intermediate_size
											__lowerCAmelCase           =	hidden_act
											__lowerCAmelCase           =	hidden_dropout_prob
											__lowerCAmelCase           =	attention_probs_dropout_prob
											__lowerCAmelCase           =	type_sequence_label_size
											__lowerCAmelCase           =	initializer_range
											__lowerCAmelCase           =	mask_ratio
											__lowerCAmelCase           =	scope

											# in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
											__lowerCAmelCase           =	(image_size // patch_size) ** 2
											__lowerCAmelCase           =	(num_frames // tubelet_size) * self.num_patches_per_frame

											# use this variable to define bool_masked_pos
											__lowerCAmelCase           =	int(mask_ratio * self.seq_length      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



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

											__lowerCAmelCase           =	None
											if self.use_labels:
																__lowerCAmelCase           =	ids_tensor([self.batch_size]		,      self.type_sequence_label_size      )

											__lowerCAmelCase           =	self.get_config()

											return config, pixel_values, labels






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											return VideoMAEConfig(
											    image_size=self.image_size		,      patch_size=self.patch_size		,      num_channels=self.num_channels		,      num_frames=self.num_frames		,      tubelet_size=self.tubelet_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		,      is_decoder=_A		,      initializer_range=self.initializer_range		,      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A      ):




											"""simple docstring"""



											__lowerCAmelCase           =	VideoMAEModel(config=_A      )
											model.to(_A      )
											model.eval()
											__lowerCAmelCase           =	model(_A      )
											self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, self.seq_length, self.hidden_size)      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A      ):




											"""simple docstring"""



											__lowerCAmelCase           =	VideoMAEForPreTraining(_A      )
											model.to(_A      )
											model.eval()
											# important: each video needs to have the same number of masked patches
											# hence we define a single mask, which we then repeat for each example in the batch
											__lowerCAmelCase           =	torch.ones((self.num_masks,)      )
											__lowerCAmelCase           =	torch.cat([mask, torch.zeros(self.seq_length - mask.size(0      )      )]      )
											__lowerCAmelCase           =	mask.expand(self.batch_size		,      -1      ).bool()

											__lowerCAmelCase           =	model(_A		,      _A      )
											# model only returns predictions for masked patches
											__lowerCAmelCase           =	mask.sum().item()
											__lowerCAmelCase           =	3 * self.tubelet_size * self.patch_size**2
											self.parent.assertEqual(result.logits.shape		,      (self.batch_size, num_masked_patches, decoder_num_labels)      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	self.prepare_config_and_inputs()
											__lowerCAmelCase           =	config_and_inputs
											__lowerCAmelCase           =	{"""pixel_values""": pixel_values}
											return config, inputs_dict






@require_torch
class       a__   ( _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    unittest.TestCase				):
						_a							:   Union[str, Any] =   (
						    (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
						)
						_a							:   Union[str, Any] =   (
						    {"""feature-extraction""": VideoMAEModel, """video-classification""": VideoMAEForVideoClassification}
						    if is_torch_available()
						    else {}
						)

						_a							:   List[str] =   False
						_a							:   Dict =   False
						_a							:   Optional[Any] =   False
						_a							:   Dict =   False






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	VideoMAEModelTester(self      )
											__lowerCAmelCase           =	ConfigTester(self		,      config_class=_A		,      has_text_modality=_A		,      hidden_size=3_7      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A=False      ):




											"""simple docstring"""



											__lowerCAmelCase           =	copy.deepcopy(_A      )

											if model_class == VideoMAEForPreTraining:
																# important: each video needs to have the same number of masked patches
																# hence we define a single mask, which we then repeat for each example in the batch
																__lowerCAmelCase           =	torch.ones((self.model_tester.num_masks,)      )
																__lowerCAmelCase           =	torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0      )      )]      )
																__lowerCAmelCase           =	mask.expand(self.model_tester.batch_size		,      -1      ).bool()
																__lowerCAmelCase           =	bool_masked_pos.to(_A      )

											if return_labels:
																if model_class in [
																    *get_values(_A      ),
																]:
																					__lowerCAmelCase           =	torch.zeros(
																					    self.model_tester.batch_size		,      dtype=torch.long		,      device=_A      )

											return inputs_dict






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											self.config_tester.run_common_tests()






						@unittest.skip(reason="VideoMAE does not use inputs_embeds"      )
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											pass






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__lowerCAmelCase           =	model_class(_A      )
																self.assertIsInstance(model.get_input_embeddings()		,      (nn.Module)      )
																__lowerCAmelCase           =	model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(_A		,      nn.Linear      )      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs_for_common()

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

																__lowerCAmelCase           =	["""pixel_values"""]
																self.assertListEqual(arg_names[:1]		,      _A      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_A      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_pretraining(*_A      )






						@slow
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__lowerCAmelCase           =	VideoMAEModel.from_pretrained(_A      )
																self.assertIsNotNone(_A      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											if not self.has_attentions:
																pass

											else:
																__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs_for_common()
																__lowerCAmelCase           =	True

																for model_class in self.all_model_classes:
																					__lowerCAmelCase           =	self.model_tester.seq_length - self.model_tester.num_masks
																					__lowerCAmelCase           =	(
																					    num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
																					)

																					__lowerCAmelCase           =	True
																					__lowerCAmelCase           =	False
																					__lowerCAmelCase           =	True
																					__lowerCAmelCase           =	model_class(_A      )
																					model.to(_A      )
																					model.eval()
																					with torch.no_grad():
																										__lowerCAmelCase           =	model(**self._prepare_for_class(_A		,      _A      )      )
																					__lowerCAmelCase           =	outputs.attentions
																					self.assertEqual(len(_A      )		,      self.model_tester.num_hidden_layers      )

																					# check that output_attentions also work using config
																					del inputs_dict["output_attentions"]
																					__lowerCAmelCase           =	True
																					__lowerCAmelCase           =	model_class(_A      )
																					model.to(_A      )
																					model.eval()
																					with torch.no_grad():
																										__lowerCAmelCase           =	model(**self._prepare_for_class(_A		,      _A      )      )
																					__lowerCAmelCase           =	outputs.attentions
																					self.assertEqual(len(_A      )		,      self.model_tester.num_hidden_layers      )

																					self.assertListEqual(
																					    list(attentions[0].shape[-3:]      )		,      [self.model_tester.num_attention_heads, seq_len, seq_len]		,      )
																					__lowerCAmelCase           =	len(_A      )

																					# Check attention is always last and order is fine
																					__lowerCAmelCase           =	True
																					__lowerCAmelCase           =	True
																					__lowerCAmelCase           =	model_class(_A      )
																					model.to(_A      )
																					model.eval()
																					with torch.no_grad():
																										__lowerCAmelCase           =	model(**self._prepare_for_class(_A		,      _A      )      )

																					self.assertEqual(out_len + 1		,      len(_A      )      )

																					__lowerCAmelCase           =	outputs.attentions

																					self.assertEqual(len(_A      )		,      self.model_tester.num_hidden_layers      )
																					self.assertListEqual(
																					    list(self_attentions[0].shape[-3:]      )		,      [self.model_tester.num_attention_heads, seq_len, seq_len]		,      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											def check_hidden_states_output(_A		,      _A		,      _A      ):
																__lowerCAmelCase           =	model_class(_A      )
																model.to(_A      )
																model.eval()

																with torch.no_grad():
																					__lowerCAmelCase           =	model(**self._prepare_for_class(_A		,      _A      )      )

																__lowerCAmelCase           =	outputs.hidden_states
																__lowerCAmelCase           =	self.model_tester.num_hidden_layers + 1
																self.assertEqual(len(_A      )		,      _A      )

																__lowerCAmelCase           =	self.model_tester.seq_length - self.model_tester.num_masks
																__lowerCAmelCase           =	num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length

																self.assertListEqual(
																    list(hidden_states[0].shape[-2:]      )		,      [seq_length, self.model_tester.hidden_size]		,      )

											__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__lowerCAmelCase           =	True
																check_hidden_states_output(_A		,      _A		,      _A      )

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																__lowerCAmelCase           =	True

																check_hidden_states_output(_A		,      _A		,      _A      )






						@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."      )
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											pass







def      _a				(						):
					__lowerCAmelCase           =	hf_hub_download(
					    repo_id="hf-internal-testing/spaghetti-video"				,				filename="eating_spaghetti.npy"				,				repo_type="dataset"					)
					__lowerCAmelCase           =	np.load(A__					)
					return list(A__					)


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






						@cached_property
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											return (
											    VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]		,      image_std=[0.5, 0.5, 0.5]      )
											    if is_vision_available()
											    else None
											)






						@slow
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics"      ).to(
											    _A      )

											__lowerCAmelCase           =	self.default_image_processor
											__lowerCAmelCase           =	prepare_video()
											__lowerCAmelCase           =	image_processor(_A		,      return_tensors="pt"      ).to(_A      )

											# forward pass
											with torch.no_grad():
																__lowerCAmelCase           =	model(**_A      )

											# verify the logits
											__lowerCAmelCase           =	torch.Size((1, 4_0_0)      )
											self.assertEqual(outputs.logits.shape		,      _A      )

											__lowerCAmelCase           =	torch.tensor([0.36_69, -0.06_88, -0.24_21]      ).to(_A      )

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






						@slow
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short"      ).to(_A      )

											__lowerCAmelCase           =	self.default_image_processor
											__lowerCAmelCase           =	prepare_video()
											__lowerCAmelCase           =	image_processor(_A		,      return_tensors="pt"      ).to(_A      )

											# add boolean mask, indicating which patches to mask
											__lowerCAmelCase           =	hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos"		,      filename="bool_masked_pos.pt"      )
											__lowerCAmelCase           =	torch.load(_A      )

											# forward pass
											with torch.no_grad():
																__lowerCAmelCase           =	model(**_A      )

											# verify the logits
											__lowerCAmelCase           =	torch.Size([1, 1_4_0_8, 1_5_3_6]      )
											__lowerCAmelCase           =	torch.tensor(
											    [[0.79_94, 0.96_12, 0.85_08], [0.74_01, 0.89_58, 0.83_02], [0.58_62, 0.74_68, 0.73_25]]		,      device=_A      )
											self.assertEqual(outputs.logits.shape		,      _A      )
											self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]		,      _A		,      atol=1E-4      )      )

											# verify the loss (`config.norm_pix_loss` = `True`)
											__lowerCAmelCase           =	torch.tensor([0.51_42]		,      device=_A      )
											self.assertTrue(torch.allclose(outputs.loss		,      _A		,      atol=1E-4      )      )

											# verify the loss (`config.norm_pix_loss` = `False`)
											__lowerCAmelCase           =	VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short"		,      norm_pix_loss=_A      ).to(
											    _A      )

											with torch.no_grad():
																__lowerCAmelCase           =	model(**_A      )

											__lowerCAmelCase           =	torch.tensor(torch.tensor([0.64_69]      )		,      device=_A      )
											self.assertTrue(torch.allclose(outputs.loss		,      _A		,      atol=1E-4      )      )










import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


UpperCamelCase__         =      logging.get_logger(__name__)

UpperCamelCase__         =      list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCamelCase__         =      tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class       a__   :
						_a							:   str =   field(
						    default=snake_case__			,    metadata={"""help""": """Model type selected in the list: """ + """, """.join(snake_case__				)}				)
						_a							:   str =   field(
						    default=snake_case__			,    metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}				)
						_a							:   int =   field(
						    default=1_2_8			,    metadata={
						        """help""": (
						            """The maximum total input sequence length after tokenization. Sequences longer """
						            """than this will be truncated, sequences shorter will be padded."""
						        )
						    }			,    )
						_a							:   int =   field(
						    default=1_2_8			,    metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}			,    )
						_a							:   int =   field(
						    default=6_4			,    metadata={
						        """help""": (
						            """The maximum number of tokens for the question. Questions longer than this will """
						            """be truncated to this length."""
						        )
						    }			,    )
						_a							:   int =   field(
						    default=3_0			,    metadata={
						        """help""": (
						            """The maximum length of an answer that can be generated. This is needed because the start """
						            """and end predictions are not conditioned on one another."""
						        )
						    }			,    )
						_a							:   bool =   field(
						    default=snake_case__			,    metadata={"""help""": """Overwrite the cached training and evaluation sets"""}				)
						_a							:   bool =   field(
						    default=snake_case__			,    metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}				)
						_a							:   float =   field(
						    default=0.0			,    metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}				)
						_a							:   int =   field(
						    default=2_0			,    metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}				)
						_a							:   int =   field(
						    default=0			,    metadata={
						        """help""": (
						            """language id of input for language-specific xlm models (see"""
						            """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
						        )
						    }			,    )
						_a							:   int =   field(default=1			,    metadata={"""help""": """multiple threads for converting example to features"""}				)






class       a__   ( snake_case__				):
						_a							:   Any =   """train"""
						_a							:   Union[str, Any] =   """dev"""






class       a__   ( snake_case__				):
						_a							:   SquadDataTrainingArguments
						_a							:   List[SquadFeatures]
						_a							:   Split
						_a							:   bool






						def __init__(       self		,      _A		,      _A		,      _A = None		,      _A = Split.train		,      _A = False		,      _A = None		,      _A = "pt"		,      ):




											"""simple docstring"""



											__lowerCAmelCase           =	args
											__lowerCAmelCase           =	is_language_sensitive
											__lowerCAmelCase           =	SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
											if isinstance(_A		,      _A      ):
																try:
																					__lowerCAmelCase           =	Split[mode]
																except KeyError:
																					raise KeyError("mode is not a valid split name"      )
											__lowerCAmelCase           =	mode
											# Load data features from cache or dataset file
											__lowerCAmelCase           =	"v2" if args.version_2_with_negative else "v1"
											__lowerCAmelCase           =	os.path.join(
											    cache_dir if cache_dir is not None else args.data_dir		,      f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}"""		,      )

											# Make sure only the first process in distributed training processes the dataset,
											# and the others will use the cache.
											__lowerCAmelCase           =	cached_features_file + ".lock"
											with FileLock(_A      ):
																if os.path.exists(_A      ) and not args.overwrite_cache:
																					__lowerCAmelCase           =	time.time()
																					__lowerCAmelCase           =	torch.load(_A      )

																					# Legacy cache files have only features, while new cache files
																					# will have dataset and examples also.
																					__lowerCAmelCase           =	self.old_features["features"]
																					__lowerCAmelCase           =	self.old_features.get("dataset"		,      _A      )
																					__lowerCAmelCase           =	self.old_features.get("examples"		,      _A      )
																					logger.info(
																					    f"""Loading features from cached file {cached_features_file} [took %.3f s]"""		,      time.time() - start      )

																					if self.dataset is None or self.examples is None:
																										logger.warning(
																										    f"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"""
																										    " future run"      )
																else:
																					if mode == Split.dev:
																										__lowerCAmelCase           =	self.processor.get_dev_examples(args.data_dir      )
																					else:
																										__lowerCAmelCase           =	self.processor.get_train_examples(args.data_dir      )

																					__lowerCAmelCase       ,							__lowerCAmelCase           =	squad_convert_examples_to_features(
																					    examples=self.examples		,      tokenizer=_A		,      max_seq_length=args.max_seq_length		,      doc_stride=args.doc_stride		,      max_query_length=args.max_query_length		,      is_training=mode == Split.train		,      threads=args.threads		,      return_dataset=_A		,      )

																					__lowerCAmelCase           =	time.time()
																					torch.save(
																					    {"features": self.features, "dataset": self.dataset, "examples": self.examples}		,      _A		,      )
																					# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
																					logger.info(
																					    f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"""      )






						def __len__(       self      ):




											"""simple docstring"""



											return len(self.features      )






						def __getitem__(       self		,      _A      ):




											"""simple docstring"""



											__lowerCAmelCase           =	self.features[i]

											__lowerCAmelCase           =	torch.tensor(feature.input_ids		,      dtype=torch.long      )
											__lowerCAmelCase           =	torch.tensor(feature.attention_mask		,      dtype=torch.long      )
											__lowerCAmelCase           =	torch.tensor(feature.token_type_ids		,      dtype=torch.long      )
											__lowerCAmelCase           =	torch.tensor(feature.cls_index		,      dtype=torch.long      )
											__lowerCAmelCase           =	torch.tensor(feature.p_mask		,      dtype=torch.float      )
											__lowerCAmelCase           =	torch.tensor(feature.is_impossible		,      dtype=torch.float      )

											__lowerCAmelCase           =	{
											    "input_ids": input_ids,
											    "attention_mask": attention_mask,
											    "token_type_ids": token_type_ids,
											}

											if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
																del inputs["token_type_ids"]

											if self.args.model_type in ["xlnet", "xlm"]:
																inputs.update({"cls_index": cls_index, "p_mask": p_mask}      )
																if self.args.version_2_with_negative:
																					inputs.update({"is_impossible": is_impossible}      )
																if self.is_language_sensitive:
																					inputs.update({"langs": (torch.ones(input_ids.shape		,      dtype=torch.intaa      ) * self.args.lang_id)}      )

											if self.mode == Split.train:
																__lowerCAmelCase           =	torch.tensor(feature.start_position		,      dtype=torch.long      )
																__lowerCAmelCase           =	torch.tensor(feature.end_position		,      dtype=torch.long      )
																inputs.update({"start_positions": start_positions, "end_positions": end_positions}      )

											return inputs




