
import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO
)
UpperCamelCase_						:     Optional[Any]	       =							logging.getLogger(__name__)



def 		UpperCamelCase     (       _UpperCAmelCase  :   Union[str, Any] ,			_UpperCAmelCase  :   Tuple  )   ->			List[str]:






						'''simple docstring'''

						_lowercase       :	str           =   np.argmax(_UpperCAmelCase ,			axis=1  )
						return np.sum(outputs == labels  )



def 		UpperCamelCase     (       _UpperCAmelCase  :   Optional[int]  )   ->			Any:






						'''simple docstring'''

						with open(_UpperCAmelCase ,			encoding="utf_8"  ) as f:
												_lowercase       :	int           =   csv.reader(_UpperCAmelCase  )
												_lowercase       :	List[Any]           =   []
												next(_UpperCAmelCase  )  # skip the first line
												for line in tqdm(_UpperCAmelCase  ):
																		output.append((" ".join(line[1:5]  ), line[5], line[6], int(line[-1]  ) - 1)  )
						return output



def 		UpperCamelCase     (       _UpperCAmelCase  :   List[str] ,			_UpperCAmelCase  :   Dict ,			_UpperCAmelCase  :   Tuple ,			_UpperCAmelCase  :   List[Any] ,			_UpperCAmelCase  :   Optional[int] ,			_UpperCAmelCase  :   Optional[Any]  )   ->			Optional[Any]:






						'''simple docstring'''

						_lowercase       :	Any           =   []
						for dataset in encoded_datasets:
												_lowercase       :	Tuple           =   len(_UpperCAmelCase  )
												_lowercase       :	List[str]           =   np.zeros((n_batch, 2, input_len) ,			dtype=np.intaa  )
												_lowercase       :	int           =   np.zeros((n_batch, 2) ,			dtype=np.intaa  )
												_lowercase       :	List[Any]           =   np.full((n_batch, 2, input_len) ,			fill_value=-100 ,			dtype=np.intaa  )
												_lowercase       :	List[Any]           =   np.zeros((n_batch,) ,			dtype=np.intaa  )
												for (
												    i,
												    (story, conta, conta, mc_label),
												) in enumerate(_UpperCAmelCase  ):
																		_lowercase       :	Union[str, Any]           =   [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
																		_lowercase       :	str           =   [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
																		_lowercase       :	Tuple           =   with_conta
																		_lowercase       :	List[str]           =   with_conta
																		_lowercase       :	Any           =   len(_UpperCAmelCase  ) - 1
																		_lowercase       :	Any           =   len(_UpperCAmelCase  ) - 1
																		_lowercase       :	str           =   with_conta
																		_lowercase       :	Tuple           =   with_conta
																		_lowercase       :	Tuple           =   mc_label
												_lowercase       :	List[Any]           =   (input_ids, mc_token_ids, lm_labels, mc_labels)
												tensor_datasets.append(tuple(torch.tensor(_UpperCAmelCase  ) for t in all_inputs  )  )
						return tensor_datasets



def 		UpperCamelCase     (       )   ->			List[Any]:






						'''simple docstring'''

						_lowercase       :	Optional[int]           =   argparse.ArgumentParser()
						parser.add_argument("--model_name" ,			type=_UpperCAmelCase ,			default="openai-gpt" ,			help="pretrained model name"  )
						parser.add_argument("--do_train" ,			action="store_true" ,			help="Whether to run training."  )
						parser.add_argument("--do_eval" ,			action="store_true" ,			help="Whether to run eval on the dev set."  )
						parser.add_argument(
						    "--output_dir" ,			default=_UpperCAmelCase ,			type=_UpperCAmelCase ,			required=_UpperCAmelCase ,			help="The output directory where the model predictions and checkpoints will be written." ,			)
						parser.add_argument("--train_dataset" ,			type=_UpperCAmelCase ,			default=""  )
						parser.add_argument("--eval_dataset" ,			type=_UpperCAmelCase ,			default=""  )
						parser.add_argument("--seed" ,			type=_UpperCAmelCase ,			default=42  )
						parser.add_argument("--num_train_epochs" ,			type=_UpperCAmelCase ,			default=3  )
						parser.add_argument("--train_batch_size" ,			type=_UpperCAmelCase ,			default=8  )
						parser.add_argument("--eval_batch_size" ,			type=_UpperCAmelCase ,			default=16  )
						parser.add_argument("--adam_epsilon" ,			default=1e-8 ,			type=_UpperCAmelCase ,			help="Epsilon for Adam optimizer."  )
						parser.add_argument("--max_grad_norm" ,			type=_UpperCAmelCase ,			default=1  )
						parser.add_argument(
						    "--max_steps" ,			default=-1 ,			type=_UpperCAmelCase ,			help=(
						        "If > 0: set total number of training                         steps to perform. Override num_train_epochs."
						    ) ,			)
						parser.add_argument(
						    "--gradient_accumulation_steps" ,			type=_UpperCAmelCase ,			default=1 ,			help="Number of updates steps to accumulate before                        performing a backward/update pass." ,			)
						parser.add_argument("--learning_rate" ,			type=_UpperCAmelCase ,			default=6.25e-5  )
						parser.add_argument("--warmup_steps" ,			default=0 ,			type=_UpperCAmelCase ,			help="Linear warmup over warmup_steps."  )
						parser.add_argument("--lr_schedule" ,			type=_UpperCAmelCase ,			default="warmup_linear"  )
						parser.add_argument("--weight_decay" ,			type=_UpperCAmelCase ,			default=0.01  )
						parser.add_argument("--lm_coef" ,			type=_UpperCAmelCase ,			default=0.9  )
						parser.add_argument("--n_valid" ,			type=_UpperCAmelCase ,			default=374  )

						parser.add_argument("--server_ip" ,			type=_UpperCAmelCase ,			default="" ,			help="Can be used for distant debugging."  )
						parser.add_argument("--server_port" ,			type=_UpperCAmelCase ,			default="" ,			help="Can be used for distant debugging."  )
						_lowercase       :	Dict           =   parser.parse_args()
						print(_UpperCAmelCase  )

						if args.server_ip and args.server_port:
												# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
												import ptvsd

												print("Waiting for debugger attach"  )
												ptvsd.enable_attach(address=(args.server_ip, args.server_port) ,			redirect_output=_UpperCAmelCase  )
												ptvsd.wait_for_attach()

						random.seed(args.seed  )
						np.random.seed(args.seed  )
						torch.manual_seed(args.seed  )
						torch.cuda.manual_seed_all(args.seed  )

						_lowercase       :	Union[str, Any]           =   torch.device("cuda" if torch.cuda.is_available() else "cpu"  )
						_lowercase       :	List[Any]           =   torch.cuda.device_count()
						logger.info("device: {}, n_gpu {}".format(_UpperCAmelCase ,			_UpperCAmelCase  )  )

						if not args.do_train and not args.do_eval:
												raise ValueError("At least one of `do_train` or `do_eval` must be True."  )

						if not os.path.exists(args.output_dir  ):
												os.makedirs(args.output_dir  )

						# Load tokenizer and model
						# This loading functions also add new tokens and embeddings called `special tokens`
						# These new embeddings will be fine-tuned on the RocStories dataset
						_lowercase       :	List[Any]           =   ["_start_", "_delimiter_", "_classify_"]
						_lowercase       :	Optional[int]           =   OpenAIGPTTokenizer.from_pretrained(args.model_name  )
						tokenizer.add_tokens(_UpperCAmelCase  )
						_lowercase       :	Union[str, Any]           =   tokenizer.convert_tokens_to_ids(_UpperCAmelCase  )
						_lowercase       :	Dict           =   OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name  )
						model.resize_token_embeddings(len(_UpperCAmelCase  )  )
						model.to(_UpperCAmelCase  )

						# Load and encode the datasets
						def tokenize_and_encode(_UpperCAmelCase  :   Tuple  ):
												if isinstance(_UpperCAmelCase ,			_UpperCAmelCase  ):
																		return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_UpperCAmelCase  )  )
												elif isinstance(_UpperCAmelCase ,			_UpperCAmelCase  ):
																		return obj
												return [tokenize_and_encode(_UpperCAmelCase  ) for o in obj]

						logger.info("Encoding dataset..."  )
						_lowercase       :	int           =   load_rocstories_dataset(args.train_dataset  )
						_lowercase       :	int           =   load_rocstories_dataset(args.eval_dataset  )
						_lowercase       :	int           =   (train_dataset, eval_dataset)
						_lowercase       :	Any           =   tokenize_and_encode(_UpperCAmelCase  )

						# Compute the max input length for the Transformer
						_lowercase       :	str           =   model.config.n_positions // 2 - 2
						_lowercase       :	Optional[Any]           =   max(
						    len(story[:max_length]  ) + max(len(conta[:max_length]  ) ,			len(conta[:max_length]  )  ) + 3
						    for dataset in encoded_datasets
						    for story, conta, conta, _ in dataset  )
						_lowercase       :	Dict           =   min(_UpperCAmelCase ,			model.config.n_positions  )  # Max size of input for the pre-trained model

						# Prepare inputs tensors and dataloaders
						_lowercase       :	str           =   pre_process_datasets(_UpperCAmelCase ,			_UpperCAmelCase ,			_UpperCAmelCase ,			*_UpperCAmelCase  )
						_lowercase      ,    _lowercase       :	Dict           =   tensor_datasets[0], tensor_datasets[1]

						_lowercase       :	str           =   TensorDataset(*_UpperCAmelCase  )
						_lowercase       :	Optional[Any]           =   RandomSampler(_UpperCAmelCase  )
						_lowercase       :	Tuple           =   DataLoader(_UpperCAmelCase ,			sampler=_UpperCAmelCase ,			batch_size=args.train_batch_size  )

						_lowercase       :	List[Any]           =   TensorDataset(*_UpperCAmelCase  )
						_lowercase       :	Optional[Any]           =   SequentialSampler(_UpperCAmelCase  )
						_lowercase       :	Any           =   DataLoader(_UpperCAmelCase ,			sampler=_UpperCAmelCase ,			batch_size=args.eval_batch_size  )

						# Prepare optimizer
						if args.do_train:
												if args.max_steps > 0:
																		_lowercase       :	Optional[Any]           =   args.max_steps
																		_lowercase       :	str           =   args.max_steps // (len(_UpperCAmelCase  ) // args.gradient_accumulation_steps) + 1
												else:
																		_lowercase       :	Tuple           =   len(_UpperCAmelCase  ) // args.gradient_accumulation_steps * args.num_train_epochs

												_lowercase       :	Any           =   list(model.named_parameters()  )
												_lowercase       :	Tuple           =   ["bias", "LayerNorm.bias", "LayerNorm.weight"]
												_lowercase       :	Any           =   [
												    {
												        "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay  )],
												        "weight_decay": args.weight_decay,
												    },
												    {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay  )], "weight_decay": 0.0},
												]
												_lowercase       :	List[Any]           =   AdamW(_UpperCAmelCase ,			lr=args.learning_rate ,			eps=args.adam_epsilon  )
												_lowercase       :	Dict           =   get_linear_schedule_with_warmup(
												    _UpperCAmelCase ,			num_warmup_steps=args.warmup_steps ,			num_training_steps=_UpperCAmelCase  )

						if args.do_train:
												_lowercase      ,    _lowercase      ,    _lowercase       :	Any           =   0, 0, None
												model.train()
												for _ in trange(int(args.num_train_epochs  ) ,			desc="Epoch"  ):
																		_lowercase       :	Union[str, Any]           =   0
																		_lowercase       :	int           =   0
																		_lowercase       :	Any           =   tqdm(_UpperCAmelCase ,			desc="Training"  )
																		for step, batch in enumerate(_UpperCAmelCase  ):
																								_lowercase       :	Dict           =   tuple(t.to(_UpperCAmelCase  ) for t in batch  )
																								_lowercase      ,    _lowercase      ,    _lowercase      ,    _lowercase       :	Union[str, Any]           =   batch
																								_lowercase       :	Optional[int]           =   model(_UpperCAmelCase ,			mc_token_ids=_UpperCAmelCase ,			lm_labels=_UpperCAmelCase ,			mc_labels=_UpperCAmelCase  )
																								_lowercase       :	Dict           =   args.lm_coef * losses[0] + losses[1]
																								loss.backward()
																								optimizer.step()
																								scheduler.step()
																								optimizer.zero_grad()
																								tr_loss += loss.item()
																								_lowercase       :	Union[str, Any]           =   (
																								    loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
																								)
																								nb_tr_steps += 1
																								_lowercase       :	Any           =   "Training loss: {:.2e} lr: {:.2e}".format(_UpperCAmelCase ,			scheduler.get_lr()[0]  )

    # Save a trained model
						if args.do_train:
												# Save a trained model, configuration and tokenizer
												_lowercase       :	Dict           =   model.module if hasattr(_UpperCAmelCase ,			"module"  ) else model  # Only save the model itself

												# If we save using the predefined names, we can load using `from_pretrained`
												_lowercase       :	Dict           =   os.path.join(args.output_dir ,			_UpperCAmelCase  )
												_lowercase       :	Optional[int]           =   os.path.join(args.output_dir ,			_UpperCAmelCase  )

												torch.save(model_to_save.state_dict() ,			_UpperCAmelCase  )
												model_to_save.config.to_json_file(_UpperCAmelCase  )
												tokenizer.save_vocabulary(args.output_dir  )

												# Load a trained model and vocabulary that you have fine-tuned
												_lowercase       :	List[Any]           =   OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir  )
												_lowercase       :	Dict           =   OpenAIGPTTokenizer.from_pretrained(args.output_dir  )
												model.to(_UpperCAmelCase  )

						if args.do_eval:
												model.eval()
												_lowercase      ,    _lowercase       :	str           =   0, 0
												_lowercase      ,    _lowercase       :	Optional[Any]           =   0, 0
												for batch in tqdm(_UpperCAmelCase ,			desc="Evaluating"  ):
																		_lowercase       :	Dict           =   tuple(t.to(_UpperCAmelCase  ) for t in batch  )
																		_lowercase      ,    _lowercase      ,    _lowercase      ,    _lowercase       :	Optional[Any]           =   batch
																		with torch.no_grad():
																								_lowercase      ,    _lowercase      ,    _lowercase      ,    _lowercase       :	Tuple           =   model(
																								    _UpperCAmelCase ,			mc_token_ids=_UpperCAmelCase ,			lm_labels=_UpperCAmelCase ,			mc_labels=_UpperCAmelCase  )

																		_lowercase       :	Tuple           =   mc_logits.detach().cpu().numpy()
																		_lowercase       :	Dict           =   mc_labels.to("cpu"  ).numpy()
																		_lowercase       :	Optional[int]           =   accuracy(_UpperCAmelCase ,			_UpperCAmelCase  )

																		eval_loss += mc_loss.mean().item()
																		eval_accuracy += tmp_eval_accuracy

																		nb_eval_examples += input_ids.size(0  )
																		nb_eval_steps += 1

												_lowercase       :	int           =   eval_loss / nb_eval_steps
												_lowercase       :	Union[str, Any]           =   eval_accuracy / nb_eval_examples
												_lowercase       :	List[Any]           =   tr_loss / nb_tr_steps if args.do_train else None
												_lowercase       :	Union[str, Any]           =   {"eval_loss": eval_loss, "eval_accuracy": eval_accuracy, "train_loss": train_loss}

												_lowercase       :	Tuple           =   os.path.join(args.output_dir ,			"eval_results.txt"  )
												with open(_UpperCAmelCase ,			"w"  ) as writer:
																		logger.info("***** Eval results *****"  )
																		for key in sorted(result.keys()  ):
																								logger.info("  %s = %s" ,			_UpperCAmelCase ,			str(result[key]  )  )
																								writer.write("%s = %s\n" % (key, str(result[key]  ))  )


if __name__ == "__main__":
							main()






from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
							import numpy
							import tensorflow as tf

							from transformers import (
							    TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
							    TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
							    TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
							    BertConfig,
							    DPRConfig,
							    TFDPRContextEncoder,
							    TFDPRQuestionEncoder,
							    TFDPRReader,
							)




class   __lowercase						:






	def __init__(self				: Dict      ,	snake_case				: Dict      ,	snake_case				: List[Any]=13      ,	snake_case				: int=7      ,	snake_case				: List[str]=True      ,	snake_case				: List[Any]=True      ,	snake_case				: Union[str, Any]=True      ,	snake_case				: Dict=True      ,	snake_case				: Optional[Any]=99      ,	snake_case				: str=32      ,	snake_case				: Any=2      ,	snake_case				: Optional[Any]=4      ,	snake_case				: int=37      ,	snake_case				: Dict="gelu"      ,	snake_case				: Dict=0.1      ,	snake_case				: Dict=0.1      ,	snake_case				: Optional[int]=512      ,	snake_case				: Dict=16      ,	snake_case				: Union[str, Any]=2      ,	snake_case				: Dict=0.02      ,	snake_case				: str=3      ,	snake_case				: str=4      ,	snake_case				: Optional[Any]=None      ,	snake_case				: str=0      ,	) ->			Optional[Any]:
							_lowercase       :	int           =   parent
							_lowercase       :	Tuple           =   batch_size
							_lowercase       :	str           =   seq_length
							_lowercase       :	Optional[Any]           =   is_training
							_lowercase       :	List[Any]           =   use_input_mask
							_lowercase       :	Tuple           =   use_token_type_ids
							_lowercase       :	List[Any]           =   use_labels
							_lowercase       :	List[str]           =   vocab_size
							_lowercase       :	Dict           =   hidden_size
							_lowercase       :	str           =   num_hidden_layers
							_lowercase       :	Tuple           =   num_attention_heads
							_lowercase       :	Dict           =   intermediate_size
							_lowercase       :	List[Any]           =   hidden_act
							_lowercase       :	Optional[Any]           =   hidden_dropout_prob
							_lowercase       :	Dict           =   attention_probs_dropout_prob
							_lowercase       :	int           =   max_position_embeddings
							_lowercase       :	Tuple           =   type_vocab_size
							_lowercase       :	List[str]           =   type_sequence_label_size
							_lowercase       :	str           =   initializer_range
							_lowercase       :	Tuple           =   num_labels
							_lowercase       :	List[Any]           =   num_choices
							_lowercase       :	Dict           =   scope
							_lowercase       :	Optional[Any]           =   projection_dim






	def       _a(self				: Tuple    ) ->			List[str]:
							_lowercase       :	Optional[int]           =   ids_tensor([self.batch_size, self.seq_length]      ,	self.vocab_size    )

							_lowercase       :	Optional[int]           =   None
							if self.use_input_mask:
													# follow test_modeling_tf_ctrl.py
													_lowercase       :	List[Any]           =   random_attention_mask([self.batch_size, self.seq_length]    )

							_lowercase       :	List[Any]           =   None
							if self.use_token_type_ids:
													_lowercase       :	List[Any]           =   ids_tensor([self.batch_size, self.seq_length]      ,	self.type_vocab_size    )

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

							_lowercase       :	Union[str, Any]           =   BertConfig(
							    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      ,	is_decoder=snake_case      ,	initializer_range=self.initializer_range      ,	)
							_lowercase       :	Any           =   DPRConfig(projection_dim=self.projection_dim      ,	**config.to_dict()    )

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






	def       _a(self				: Union[str, Any]      ,	snake_case				: Any      ,	snake_case				: Tuple      ,	snake_case				: str      ,	snake_case				: str      ,	snake_case				: Union[str, Any]      ,	snake_case				: Tuple      ,	snake_case				: str    ) ->			List[str]:
							_lowercase       :	List[Any]           =   TFDPRContextEncoder(config=snake_case    )
							_lowercase       :	Dict           =   model(snake_case      ,	attention_mask=snake_case      ,	token_type_ids=snake_case    )
							_lowercase       :	Optional[int]           =   model(snake_case      ,	token_type_ids=snake_case    )
							_lowercase       :	Union[str, Any]           =   model(snake_case    )
							self.parent.assertEqual(result.pooler_output.shape      ,	(self.batch_size, self.projection_dim or self.hidden_size)    )






	def       _a(self				: List[Any]      ,	snake_case				: List[str]      ,	snake_case				: Tuple      ,	snake_case				: Any      ,	snake_case				: int      ,	snake_case				: Optional[int]      ,	snake_case				: Any      ,	snake_case				: Union[str, Any]    ) ->			int:
							_lowercase       :	Optional[Any]           =   TFDPRQuestionEncoder(config=snake_case    )
							_lowercase       :	int           =   model(snake_case      ,	attention_mask=snake_case      ,	token_type_ids=snake_case    )
							_lowercase       :	str           =   model(snake_case      ,	token_type_ids=snake_case    )
							_lowercase       :	str           =   model(snake_case    )
							self.parent.assertEqual(result.pooler_output.shape      ,	(self.batch_size, self.projection_dim or self.hidden_size)    )






	def       _a(self				: Union[str, Any]      ,	snake_case				: Any      ,	snake_case				: int      ,	snake_case				: List[str]      ,	snake_case				: Union[str, Any]      ,	snake_case				: Tuple      ,	snake_case				: Optional[Any]      ,	snake_case				: Union[str, Any]    ) ->			Any:
							_lowercase       :	Any           =   TFDPRReader(config=snake_case    )
							_lowercase       :	Optional[Any]           =   model(snake_case      ,	attention_mask=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)    )
							self.parent.assertEqual(result.relevance_logits.shape      ,	(self.batch_size,)    )






	def       _a(self				: int    ) ->			Optional[Any]:
							_lowercase       :	Union[str, Any]           =   self.prepare_config_and_inputs()
							(
							    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    
							)       :	int           =   config_and_inputs
							_lowercase       :	int           =   {"input_ids": input_ids}
							return config, inputs_dict




@require_tf
class   __lowercase						(						__snake_case   , __snake_case   , unittest.TestCase       ):
	_A       =   (
	    (
	        TFDPRContextEncoder,
	        TFDPRQuestionEncoder,
	        TFDPRReader,
	    )
	    if is_tf_available()
	    else ()
	)
	_A       =   {"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {}

	_A       =   False
	_A       =   False
	_A       =   False
	_A       =   False
	_A       =   False






	def       _a(self				: str    ) ->			List[str]:
							_lowercase       :	List[Any]           =   TFDPRModelTester(self    )
							_lowercase       :	Any           =   ConfigTester(self      ,	config_class=snake_case      ,	hidden_size=37    )






	def       _a(self				: str    ) ->			Union[str, Any]:
							self.config_tester.run_common_tests()






	def       _a(self				: Any    ) ->			Tuple:
							_lowercase       :	List[str]           =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_dpr_context_encoder(*snake_case    )






	def       _a(self				: Dict    ) ->			Optional[Any]:
							_lowercase       :	str           =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_dpr_question_encoder(*snake_case    )






	def       _a(self				: List[Any]    ) ->			Any:
							_lowercase       :	Optional[Any]           =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_dpr_reader(*snake_case    )






	@slow
	def       _a(self				: int    ) ->			str:
							for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_lowercase       :	str           =   TFDPRContextEncoder.from_pretrained(snake_case    )
													self.assertIsNotNone(snake_case    )

							for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_lowercase       :	List[str]           =   TFDPRContextEncoder.from_pretrained(snake_case    )
													self.assertIsNotNone(snake_case    )

							for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_lowercase       :	int           =   TFDPRQuestionEncoder.from_pretrained(snake_case    )
													self.assertIsNotNone(snake_case    )

							for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_lowercase       :	Any           =   TFDPRReader.from_pretrained(snake_case    )
													self.assertIsNotNone(snake_case    )




@require_tf
class   __lowercase						(						unittest.TestCase       ):






	@slow
	def       _a(self				: Dict    ) ->			Any:
							_lowercase       :	Any           =   TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base"    )

							_lowercase       :	Optional[int]           =   tf.constant(
							    [[101, 7592, 1010, 2003, 2026, 3899, 1_0140, 1029, 102]]    )  # [CLS] hello, is my dog cute? [SEP]
							_lowercase       :	List[Any]           =   model(snake_case    )[0]  # embedding shape = (1, 768)
							# compare the actual values for a slice.
							_lowercase       :	Optional[Any]           =   tf.constant(
							    [
							        [
							            0.03_23_62_53,
							            0.12_75_33_35,
							            0.16_81_85_09,
							            0.00_27_97_86,
							            0.3_89_69_33,
							            0.24_26_49_45,
							            0.2_17_89_71,
							            -0.02_33_52_27,
							            -0.08_48_19_59,
							            -0.14_32_41_17,
							        ]
							    ]    )
							self.assertTrue(numpy.allclose(output[:, :10].numpy()      ,	expected_slice.numpy()      ,	atol=1e-4    )    )




