





'''simple docstring'''






import argparse
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing the checkpointing capability,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################

A :			Tuple							   =      16
A :			Union[str, Any]							   =      32





def    lowercase_   (		lowercase__					,	lowercase__ = 16    ) ->Any:
						_snake_case: Any	       =		AutoTokenizer.from_pretrained('bert-base-cased'    )
						_snake_case: Tuple	       =		load_dataset('glue'					,	'mrpc'    )

						def tokenize_function(lowercase__    ):
												# max_length=None => use the model max length (it's actually the default)
												_snake_case: Optional[int]	       =		tokenizer(examples['sentence1']					,	examples['sentence2']					,	truncation=snake_case__					,	max_length=snake_case__    )
												return outputs

						# Apply the method we just defined to all the examples in all the splits of the dataset
						# starting with the main process first:
						with accelerator.main_process_first():
												_snake_case: Any	       =		datasets.map(
												    snake_case__					,	batched=snake_case__					,	remove_columns=['idx', 'sentence1', 'sentence2']					,	)

						# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
						# transformers library
						_snake_case: str	       =		tokenized_datasets.rename_column('label'					,	'labels'    )

						def collate_fn(lowercase__    ):
												# On TPU it's best to pad everything to the same length or training will be very slow.
												_snake_case: Dict	       =		128 if accelerator.distributed_type == DistributedType.TPU else None
												# When using mixed precision we want round multiples of 8/16
												if accelerator.mixed_precision == "fp8":
																		_snake_case: Optional[Any]	       =		16
												elif accelerator.mixed_precision != "no":
																		_snake_case: int	       =		8
												else:
																		_snake_case: Dict	       =		None

												return tokenizer.pad(
												    snake_case__					,	padding='longest'					,	max_length=snake_case__					,	pad_to_multiple_of=snake_case__					,	return_tensors='pt'					,	)

						# Instantiate dataloaders.
						_snake_case: List[Any]	       =		DataLoader(
						    tokenized_datasets['train']					,	shuffle=snake_case__					,	collate_fn=snake_case__					,	batch_size=snake_case__    )
						_snake_case: List[Any]	       =		DataLoader(
						    tokenized_datasets['validation']					,	shuffle=snake_case__					,	collate_fn=snake_case__					,	batch_size=snake_case__    )

						return train_dataloader, eval_dataloader


# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
		from accelerate.test_utils.training import mocked_dataloaders

		A :			List[Any]							   =      mocked_dataloaders  # noqa: F811





def    lowercase_   (		lowercase__					,	lowercase__    ) ->Optional[Any]:
						# For testing only
						if os.environ.get('TESTING_MOCKED_DATALOADERS'					,	snake_case__    ) == "1":
												_snake_case: List[str]	       =		2
						# Initialize accelerator
						_snake_case: Tuple	       =		Accelerator(cpu=args.cpu					,	mixed_precision=args.mixed_precision    )
						# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
						_snake_case: List[str]	       =		config["lr"]
						_snake_case: Union[str, Any]	       =		int(config['num_epochs']    )
						_snake_case: Any	       =		int(config['seed']    )
						_snake_case: List[Any]	       =		int(config['batch_size']    )

						# New Code #
						# Parse out whether we are saving every epoch or after a certain number of batches
						if hasattr(args.checkpointing_steps					,	'isdigit'    ):
												if args.checkpointing_steps == "epoch":
																		_snake_case: Dict	       =		args.checkpointing_steps
												elif args.checkpointing_steps.isdigit():
																		_snake_case: Dict	       =		int(args.checkpointing_steps    )
												else:
																		raise ValueError(
																		    F'''Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.'''    )
						else:
												_snake_case: List[str]	       =		None

						set_seed(snake_case__    )

						_snake_case: List[Any]	       =		get_dataloaders(snake_case__					,	snake_case__    )
						_snake_case: Optional[Any]	       =		evaluate.load('glue'					,	'mrpc'    )

						# If the batch size is too big we use gradient accumulation
						_snake_case: Dict	       =		1
						if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
												_snake_case: List[Any]	       =		batch_size // MAX_GPU_BATCH_SIZE
												_snake_case: Tuple	       =		MAX_GPU_BATCH_SIZE

						# Instantiate the model (we build the model here so that the seed also control new weights initialization)
						_snake_case: str	       =		AutoModelForSequenceClassification.from_pretrained('bert-base-cased'					,	return_dict=snake_case__    )

						# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
						# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
						# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
						_snake_case: Optional[Any]	       =		model.to(accelerator.device    )

						# Instantiate optimizer
						_snake_case: str	       =		AdamW(params=model.parameters()					,	lr=snake_case__    )

						# Instantiate scheduler
						_snake_case: Optional[int]	       =		get_linear_schedule_with_warmup(
						    optimizer=snake_case__					,	num_warmup_steps=100					,	num_training_steps=(len(snake_case__    ) * num_epochs) // gradient_accumulation_steps					,	)

						# Prepare everything
						# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
						# prepare method.
						_snake_case: List[str]	       =		accelerator.prepare(
						    snake_case__					,	snake_case__					,	snake_case__					,	snake_case__					,	snake_case__    )

						# New Code #
						# We need to keep track of how many total steps we have iterated over
						_snake_case: Union[str, Any]	       =		0
						# We also need to keep track of the stating epoch so files are named properly
						_snake_case: List[Any]	       =		0

						# We need to load the checkpoint back in before training here with `load_state`
						# The total number of epochs is adjusted based on where the state is being loaded from,
						# as we assume continuation of the same training script
						if args.resume_from_checkpoint:
												if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
																		accelerator.print(F'''Resumed from checkpoint: {args.resume_from_checkpoint}'''    )
																		accelerator.load_state(args.resume_from_checkpoint    )
																		_snake_case: Any	       =		os.path.basename(args.resume_from_checkpoint    )
												else:
																		# Get the most recent checkpoint
																		_snake_case: Any	       =		[f.name for f in os.scandir(os.getcwd()    ) if f.is_dir()]
																		dirs.sort(key=os.path.getctime    )
																		_snake_case: Tuple	       =		dirs[-1]  # Sorts folders by date modified, most recent checkpoint is the last
												# Extract `epoch_{i}` or `step_{i}`
												_snake_case: List[str]	       =		os.path.splitext(snake_case__    )[0]

												if "epoch" in training_difference:
																		_snake_case: List[str]	       =		int(training_difference.replace('epoch_'					,	''    )    ) + 1
																		_snake_case: Dict	       =		None
												else:
																		_snake_case: Optional[Any]	       =		int(training_difference.replace('step_'					,	''    )    )
																		_snake_case: Union[str, Any]	       =		resume_step // len(snake_case__    )
																		resume_step -= starting_epoch * len(snake_case__    )

    # Now we train the model
						for epoch in range(snake_case__					,	snake_case__    ):
												model.train()
												# New Code #
												if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
																		# We need to skip steps until we reach the resumed step
																		_snake_case: str	       =		accelerator.skip_first_batches(snake_case__					,	snake_case__    )
																		overall_step += resume_step
												else:
																		# After the first iteration though, we need to go back to the original dataloader
																		_snake_case: Tuple	       =		train_dataloader
												for step, batch in enumerate(snake_case__    ):
																		# We could avoid this line since we set the accelerator with `device_placement=True`.
																		batch.to(accelerator.device    )
																		_snake_case: int	       =		model(**snake_case__    )
																		_snake_case: str	       =		outputs.loss
																		_snake_case: Union[str, Any]	       =		loss / gradient_accumulation_steps
																		accelerator.backward(snake_case__    )
																		if step % gradient_accumulation_steps == 0:
																								optimizer.step()
																								lr_scheduler.step()
																								optimizer.zero_grad()
																		# New Code #
																		overall_step += 1

																		# New Code #
																		# We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
																		# These are saved to folders named `step_{overall_step}`
																		# Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
																		# If mixed precision was used, will also save a "scalar.bin" file
																		if isinstance(snake_case__					,	snake_case__    ):
																								_snake_case: Any	       =		F'''step_{overall_step}'''
																								if overall_step % checkpointing_steps == 0:
																														if args.output_dir is not None:
																																				_snake_case: str	       =		os.path.join(args.output_dir					,	snake_case__    )
																														accelerator.save_state(snake_case__    )

												model.eval()
												for step, batch in enumerate(snake_case__    ):
																		# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
																		batch.to(accelerator.device    )
																		with torch.no_grad():
																								_snake_case: Optional[Any]	       =		model(**snake_case__    )
																		_snake_case: Optional[int]	       =		outputs.logits.argmax(dim=-1    )
																		_snake_case: List[Any]	       =		accelerator.gather_for_metrics((predictions, batch['labels'])    )
																		metric.add_batch(
																		    predictions=snake_case__					,	references=snake_case__					,	)

												_snake_case: Union[str, Any]	       =		metric.compute()
												# Use accelerator.print to print only on the main process.
												accelerator.print(F'''epoch {epoch}:'''					,	snake_case__    )

												# New Code #
												# We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
												# These are saved to folders named `epoch_{epoch}`
												# Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
												# If mixed precision was used, will also save a "scalar.bin" file
												if checkpointing_steps == "epoch":
																		_snake_case: List[str]	       =		F'''epoch_{epoch}'''
																		if args.output_dir is not None:
																								_snake_case: Optional[Any]	       =		os.path.join(args.output_dir					,	snake_case__    )
																		accelerator.save_state(snake_case__    )





def    lowercase_   (		) ->Dict:
						_snake_case: Optional[int]	       =		argparse.ArgumentParser(description='Simple example of training script.'    )
						parser.add_argument(
						    '--mixed_precision'					,	type=snake_case__					,	default=snake_case__					,	choices=['no', 'fp16', 'bf16', 'fp8']					,	help='Whether to use mixed precision. Choose'
						    'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'
						    'and an Nvidia Ampere GPU.'					,	)
						parser.add_argument('--cpu'					,	action='store_true'					,	help='If passed, will train on the CPU.'    )
						parser.add_argument(
						    '--checkpointing_steps'					,	type=snake_case__					,	default=snake_case__					,	help='Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.'					,	)
						parser.add_argument(
						    '--output_dir'					,	type=snake_case__					,	default='.'					,	help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.'					,	)
						parser.add_argument(
						    '--resume_from_checkpoint'					,	type=snake_case__					,	default=snake_case__					,	help='If the training should continue from a checkpoint folder.'					,	)
						_snake_case: Tuple	       =		parser.parse_args()
						_snake_case: str	       =		{"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
						training_function(snake_case__					,	snake_case__    )


if __name__ == "__main__":
		main()











'''simple docstring'''






import tempfile
import unittest

from transformers import DPRConfig, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import DPRContextEncoder, DPRQuestionEncoder, DPRReader, DPRReaderTokenizer
				from transformers.models.dpr.modeling_dpr import (
				    DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
				)



class    A						:




				'''simple docstring'''





				def __init__(self					,    _UpperCAmelCase					,    _UpperCAmelCase=1_3					,    _UpperCAmelCase=7					,    _UpperCAmelCase=False					,    _UpperCAmelCase=True					,    _UpperCAmelCase=True					,    _UpperCAmelCase=True					,    _UpperCAmelCase=9_9					,    _UpperCAmelCase=3_2					,    _UpperCAmelCase=5					,    _UpperCAmelCase=4					,    _UpperCAmelCase=3_7					,    _UpperCAmelCase="gelu"					,    _UpperCAmelCase=0.1					,    _UpperCAmelCase=0.1					,    _UpperCAmelCase=5_1_2					,    _UpperCAmelCase=1_6					,    _UpperCAmelCase=2					,    _UpperCAmelCase=0.02					,    _UpperCAmelCase=3					,    _UpperCAmelCase=4					,    _UpperCAmelCase=None					,    _UpperCAmelCase=0					,    )      ->			List[Any]:
							__UpperCamelCase :     List[str]										=  parent
							__UpperCamelCase :     Optional[int]										=  batch_size
							__UpperCamelCase :     Union[str, Any]										=  seq_length
							__UpperCamelCase :     List[Any]										=  is_training
							__UpperCamelCase :     Union[str, Any]										=  use_input_mask
							__UpperCamelCase :     int										=  use_token_type_ids
							__UpperCamelCase :     Any										=  use_labels
							__UpperCamelCase :     Union[str, Any]										=  vocab_size
							__UpperCamelCase :     Any										=  hidden_size
							__UpperCamelCase :     Dict										=  num_hidden_layers
							__UpperCamelCase :     List[Any]										=  num_attention_heads
							__UpperCamelCase :     Union[str, Any]										=  intermediate_size
							__UpperCamelCase :     Tuple										=  hidden_act
							__UpperCamelCase :     int										=  hidden_dropout_prob
							__UpperCamelCase :     Optional[Any]										=  attention_probs_dropout_prob
							__UpperCamelCase :     List[str]										=  max_position_embeddings
							__UpperCamelCase :     str										=  type_vocab_size
							__UpperCamelCase :     str										=  type_sequence_label_size
							__UpperCamelCase :     List[str]										=  initializer_range
							__UpperCamelCase :     List[str]										=  num_labels
							__UpperCamelCase :     Any										=  num_choices
							__UpperCamelCase :     List[Any]										=  scope
							__UpperCamelCase :     Tuple										=  projection_dim
				def 			a_			(self     )      ->			Any:
							__UpperCamelCase :     str										=  ids_tensor([self.batch_size, self.seq_length]					,    self.vocab_size     )

							__UpperCamelCase :     Dict										=  None
							if self.use_input_mask:
										__UpperCamelCase :     List[str]										=  random_attention_mask([self.batch_size, self.seq_length]     )

							__UpperCamelCase :     Tuple										=  None
							if self.use_token_type_ids:
										__UpperCamelCase :     Optional[int]										=  ids_tensor([self.batch_size, self.seq_length]					,    self.type_vocab_size     )

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

							__UpperCamelCase :     Optional[int]										=  self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
				def 			a_			(self     )      ->			Optional[Any]:
							return DPRConfig(
							    projection_dim=self.projection_dim					,    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 			a_			(self					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase     )      ->			str:
							__UpperCamelCase :     Optional[int]										=  DPRContextEncoder(config=_UpperCAmelCase     )
							model.to(_UpperCAmelCase     )
							model.eval()
							__UpperCamelCase :     Optional[int]										=  model(_UpperCAmelCase					,    attention_mask=_UpperCAmelCase					,    token_type_ids=_UpperCAmelCase     )
							__UpperCamelCase :     Optional[int]										=  model(_UpperCAmelCase					,    token_type_ids=_UpperCAmelCase     )
							__UpperCamelCase :     int										=  model(_UpperCAmelCase     )
							self.parent.assertEqual(result.pooler_output.shape					,    (self.batch_size, self.projection_dim or self.hidden_size)     )
				def 			a_			(self					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase     )      ->			Optional[int]:
							__UpperCamelCase :     int										=  DPRQuestionEncoder(config=_UpperCAmelCase     )
							model.to(_UpperCAmelCase     )
							model.eval()
							__UpperCamelCase :     Optional[int]										=  model(_UpperCAmelCase					,    attention_mask=_UpperCAmelCase					,    token_type_ids=_UpperCAmelCase     )
							__UpperCamelCase :     List[str]										=  model(_UpperCAmelCase					,    token_type_ids=_UpperCAmelCase     )
							__UpperCamelCase :     Optional[Any]										=  model(_UpperCAmelCase     )
							self.parent.assertEqual(result.pooler_output.shape					,    (self.batch_size, self.projection_dim or self.hidden_size)     )
				def 			a_			(self					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase     )      ->			str:
							__UpperCamelCase :     Optional[int]										=  DPRReader(config=_UpperCAmelCase     )
							model.to(_UpperCAmelCase     )
							model.eval()
							__UpperCamelCase :     Optional[Any]										=  model(
							    _UpperCAmelCase					,    attention_mask=_UpperCAmelCase					,    )

							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     )      ->			List[Any]:
							__UpperCamelCase :     Tuple										=  self.prepare_config_and_inputs()
							(
							    (
							    __UpperCamelCase
							)						,   (
							    __UpperCamelCase
							)						,   (
							    __UpperCamelCase
							)						,   (
							    __UpperCamelCase
							)						,   (
							    __UpperCamelCase
							)						,   (
							    __UpperCamelCase
							)						,   (
							    __UpperCamelCase
							)						,   
							) :     Optional[int]										=  config_and_inputs
							__UpperCamelCase :     Dict										=  {"input_ids": input_ids}
							return config, inputs_dict







@require_torch
class    A						(					SCREAMING_SNAKE_CASE__     ,				SCREAMING_SNAKE_CASE__     ,				unittest.TestCase						):




				'''simple docstring'''





				A       =							(
				    (
				        DPRContextEncoder,
				        DPRQuestionEncoder,
				        DPRReader,
				    )
				    if is_torch_available()
				    else ()
				)
				A       =							{"feature-extraction": DPRQuestionEncoder} if is_torch_available() else {}

				A       =							False
				A       =							False  # why?
				A       =							False
				A       =							False
				def 			a_			(self     )      ->			Union[str, Any]:
							__UpperCamelCase :     Dict										=  DPRModelTester(self     )
							__UpperCamelCase :     Tuple										=  ConfigTester(self					,    config_class=_UpperCAmelCase					,    hidden_size=3_7     )
				def 			a_			(self     )      ->			List[str]:
							self.config_tester.run_common_tests()
				def 			a_			(self     )      ->			Optional[int]:
							__UpperCamelCase :     List[Any]										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_context_encoder(*_UpperCAmelCase     )
				def 			a_			(self     )      ->			str:
							__UpperCamelCase :     int										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_question_encoder(*_UpperCAmelCase     )
				def 			a_			(self     )      ->			Any:
							__UpperCamelCase :     List[Any]										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_reader(*_UpperCAmelCase     )
				def 			a_			(self     )      ->			Optional[Any]:
							__UpperCamelCase :     List[Any]										=  self.model_tester.prepare_config_and_inputs()[0]

							__UpperCamelCase :     Union[str, Any]										=  DPRQuestionEncoder(config=_UpperCAmelCase     )
							model.to(_UpperCAmelCase     )
							model.eval()

							with tempfile.TemporaryDirectory() as tmp_dirname:
										model.save_pretrained(_UpperCAmelCase     )
										__UpperCamelCase :     Tuple										=  DPRQuestionEncoder.from_pretrained(_UpperCAmelCase					,    projection_dim=5_1_2     )

							self.assertIsNotNone(_UpperCAmelCase     )





				@slow
				def 			a_			(self     )      ->			Optional[Any]:
							for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										__UpperCamelCase :     Union[str, Any]										=  DPRContextEncoder.from_pretrained(_UpperCAmelCase     )
										self.assertIsNotNone(_UpperCAmelCase     )

							for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										__UpperCamelCase :     Tuple										=  DPRContextEncoder.from_pretrained(_UpperCAmelCase     )
										self.assertIsNotNone(_UpperCAmelCase     )

							for model_name in DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										__UpperCamelCase :     Union[str, Any]										=  DPRQuestionEncoder.from_pretrained(_UpperCAmelCase     )
										self.assertIsNotNone(_UpperCAmelCase     )

							for model_name in DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										__UpperCamelCase :     Optional[int]										=  DPRReader.from_pretrained(_UpperCAmelCase     )
										self.assertIsNotNone(_UpperCAmelCase     )







@require_torch
class    A						(					unittest.TestCase						):




				'''simple docstring'''





				@slow
				def 			a_			(self     )      ->			Dict:
							__UpperCamelCase :     int										=  DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base"					,    return_dict=_UpperCAmelCase     )
							model.to(_UpperCAmelCase     )

							__UpperCamelCase :     Optional[int]										=  torch.tensor(
							    [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]]					,    dtype=torch.long					,    device=_UpperCAmelCase     )  # [CLS] hello, is my dog cute? [SEP]
							__UpperCamelCase :     Dict										=  model(_UpperCAmelCase     )[0]  # embedding shape = (1, 768)
							# compare the actual values for a slice.
							__UpperCamelCase :     Union[str, Any]										=  torch.tensor(
							    [
							        [
							            0.03_236_253,
							            0.12_753_335,
							            0.16_818_509,
							            0.00_279_786,
							            0.3_896_933,
							            0.24_264_945,
							            0.2_178_971,
							            -0.02_335_227,
							            -0.08_481_959,
							            -0.14_324_117,
							        ]
							    ]					,    dtype=torch.float					,    device=_UpperCAmelCase					,    )
							self.assertTrue(torch.allclose(output[:, :1_0]					,    _UpperCAmelCase					,    atol=1E-4     )     )





				@slow
				def 			a_			(self     )      ->			List[str]:
							__UpperCamelCase :     Any										=  DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base"     )
							__UpperCamelCase :     str										=  DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base"     )
							model.to(_UpperCAmelCase     )

							__UpperCamelCase :     Optional[int]										=  tokenizer(
							    questions="What is love ?"					,    titles="Haddaway"					,    texts="What Is Love is a song recorded by the artist Haddaway"					,    padding=_UpperCAmelCase					,    return_tensors="pt"					,    )
							encoded_inputs.to(_UpperCAmelCase     )

							__UpperCamelCase :     int										=  model(**_UpperCAmelCase     )

							# compare the actual values for a slice.
							__UpperCamelCase :     Dict										=  torch.tensor(
							    [[-10.3_005, -10.7_765, -11.4_872, -11.6_841, -11.9_312, -10.3_002, -9.8_544, -11.7_378, -12.0_821, -10.2_975]]					,    dtype=torch.float					,    device=_UpperCAmelCase					,    )

							__UpperCamelCase :     Optional[Any]										=  torch.tensor(
							    [[-11.0_684, -11.7_041, -11.5_397, -10.3_465, -10.8_791, -6.8_443, -11.9_959, -11.0_364, -10.0_096, -6.8_405]]					,    dtype=torch.float					,    device=_UpperCAmelCase					,    )
							self.assertTrue(torch.allclose(outputs.start_logits[:, :1_0]					,    _UpperCAmelCase					,    atol=1E-4     )     )
							self.assertTrue(torch.allclose(outputs.end_logits[:, :1_0]					,    _UpperCAmelCase					,    atol=1E-4     )     )



