

"""simple docstring"""






from __future__ import annotations

import unittest

from transformers import OpenAIGPTConfig, 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 tensorflow as tf

						from transformers.models.openai.modeling_tf_openai import (
						    TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
						    TFOpenAIGPTDoubleHeadsModel,
						    TFOpenAIGPTForSequenceClassification,
						    TFOpenAIGPTLMHeadModel,
						    TFOpenAIGPTModel,
						)






class       _UpperCAmelCase     :
			def __init__(						self ,						_A ,						)      ->      Tuple:






				'''simple docstring'''







				_UpperCAmelCase      :							Optional[int]       =   parent
				_UpperCAmelCase      :							Any       =   13
				_UpperCAmelCase      :							str       =   7
				_UpperCAmelCase      :							int       =   True
				_UpperCAmelCase      :							Optional[int]       =   True
				_UpperCAmelCase      :							Tuple       =   True
				_UpperCAmelCase      :							List[Any]       =   True
				_UpperCAmelCase      :							Any       =   True
				_UpperCAmelCase      :							Optional[Any]       =   99
				_UpperCAmelCase      :							Optional[Any]       =   32
				_UpperCAmelCase      :							Dict       =   2
				_UpperCAmelCase      :							str       =   4
				_UpperCAmelCase      :							Tuple       =   37
				_UpperCAmelCase      :							Dict       =   """gelu"""
				_UpperCAmelCase      :							Optional[int]       =   0.1
				_UpperCAmelCase      :							Tuple       =   0.1
				_UpperCAmelCase      :							List[str]       =   5_12
				_UpperCAmelCase      :							List[str]       =   16
				_UpperCAmelCase      :							List[Any]       =   2
				_UpperCAmelCase      :							Dict       =   0.02
				_UpperCAmelCase      :							Union[str, Any]       =   3
				_UpperCAmelCase      :							Dict       =   4
				_UpperCAmelCase      :							int       =   None
				_UpperCAmelCase      :							str       =   self.vocab_size - 1
			def 							__snake_case	(						self       )      ->      List[str]:






				'''simple docstring'''







				_UpperCAmelCase      :							Dict       =   ids_tensor([self.batch_size, self.seq_length] ,						self.vocab_size       )

				_UpperCAmelCase      :							Union[str, Any]       =   None
				if self.use_input_mask:
					_UpperCAmelCase      :							Union[str, Any]       =   random_attention_mask([self.batch_size, self.seq_length]       )

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

				_UpperCAmelCase      :							int       =   None
				if self.use_mc_token_ids:
					_UpperCAmelCase      :							Optional[Any]       =   ids_tensor([self.batch_size, self.num_choices] ,						self.seq_length       )

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

				_UpperCAmelCase      :							Tuple       =   OpenAIGPTConfig(
				    vocab_size=self.vocab_size ,						n_embd=self.hidden_size ,						n_layer=self.num_hidden_layers ,						n_head=self.num_attention_heads ,						n_positions=self.max_position_embeddings ,						pad_token_id=self.pad_token_id ,						)

				_UpperCAmelCase      :							Any       =   ids_tensor([self.num_hidden_layers, self.num_attention_heads] ,						2       )

				return (
				    config,
				    input_ids,
				    input_mask,
				    head_mask,
				    token_type_ids,
				    mc_token_ids,
				    sequence_labels,
				    token_labels,
				    choice_labels,
				)
			def 							__snake_case	(						self ,						_A ,						_A ,						_A ,						_A ,						_A ,						*_A       )      ->      Optional[int]:






				'''simple docstring'''







				_UpperCAmelCase      :							Dict       =   TFOpenAIGPTModel(config=_A       )
				_UpperCAmelCase      :							Dict       =   {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
				_UpperCAmelCase      :							str       =   model(_A       )

				_UpperCAmelCase      :							Optional[int]       =   [input_ids, input_mask]
				_UpperCAmelCase      :							Optional[int]       =   model(_A       )

				_UpperCAmelCase      :							Tuple       =   model(_A       )

				self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, self.seq_length, self.hidden_size)       )
			def 							__snake_case	(						self ,						_A ,						_A ,						_A ,						_A ,						_A ,						*_A       )      ->      Dict:






				'''simple docstring'''







				_UpperCAmelCase      :							List[Any]       =   TFOpenAIGPTLMHeadModel(config=_A       )
				_UpperCAmelCase      :							int       =   {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
				_UpperCAmelCase      :							int       =   model(_A       )
				self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.seq_length, self.vocab_size)       )
			def 							__snake_case	(						self ,						_A ,						_A ,						_A ,						_A ,						_A ,						_A ,						*_A       )      ->      List[str]:






				'''simple docstring'''







				_UpperCAmelCase      :							List[Any]       =   TFOpenAIGPTDoubleHeadsModel(config=_A       )

				_UpperCAmelCase      :							Optional[int]       =   tf.tile(tf.expand_dims(_A ,						1       ) ,						(1, self.num_choices, 1)       )
				_UpperCAmelCase      :							Dict       =   tf.tile(tf.expand_dims(_A ,						1       ) ,						(1, self.num_choices, 1)       )
				_UpperCAmelCase      :							int       =   tf.tile(tf.expand_dims(_A ,						1       ) ,						(1, self.num_choices, 1)       )

				_UpperCAmelCase      :							List[Any]       =   {
				    """input_ids""": multiple_choice_inputs_ids,
				    """mc_token_ids""": mc_token_ids,
				    """attention_mask""": multiple_choice_input_mask,
				    """token_type_ids""": multiple_choice_token_type_ids,
				}
				_UpperCAmelCase      :							str       =   model(_A       )
				self.parent.assertEqual(
				    result.logits.shape ,						(self.batch_size, self.num_choices, self.seq_length, self.vocab_size)       )
				self.parent.assertEqual(result.mc_logits.shape ,						(self.batch_size, self.num_choices)       )
			def 							__snake_case	(						self ,						_A ,						_A ,						_A ,						_A ,						_A ,						*_A       )      ->      Tuple:






				'''simple docstring'''







				_UpperCAmelCase      :							int       =   self.num_labels
				_UpperCAmelCase      :							Optional[int]       =   ids_tensor([self.batch_size] ,						self.type_sequence_label_size       )
				_UpperCAmelCase      :							List[str]       =   {
				    """input_ids""": input_ids,
				    """attention_mask""": input_mask,
				    """token_type_ids""": token_type_ids,
				    """labels""": sequence_labels,
				}
				_UpperCAmelCase      :							Union[str, Any]       =   TFOpenAIGPTForSequenceClassification(_A       )
				_UpperCAmelCase      :							Optional[Any]       =   model(_A       )
				self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.num_labels)       )
			def 							__snake_case	(						self       )      ->      List[Any]:






				'''simple docstring'''







				_UpperCAmelCase      :							Optional[int]       =   self.prepare_config_and_inputs()

				(
				    (
				    _UpperCAmelCase
				)  ,				(
				    _UpperCAmelCase
				)  ,				(
				    _UpperCAmelCase
				)  ,				(
				    _UpperCAmelCase
				)  ,				(
				    _UpperCAmelCase
				)  ,				(
				    _UpperCAmelCase
				)  ,				(
				    _UpperCAmelCase
				)  ,				(
				    _UpperCAmelCase
				)  ,				(
				    _UpperCAmelCase
				)  ,				
				)      :							List[Any]       =   config_and_inputs

				_UpperCAmelCase      :							Dict       =   {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
				return config, inputs_dict






@require_tf
class       _UpperCAmelCase     (						__a      ,       __a      ,       unittest.TestCase):
			__a	:    Union[str, Any]			   =							(
			    (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification)
			    if is_tf_available()
			    else ()
			)
			__a	:    Any			   =							(
			    (TFOpenAIGPTLMHeadModel,) if is_tf_available() else ()
			)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
			__a	:    List[Any]			   =							(
			    {
			        """feature-extraction""": TFOpenAIGPTModel,
			        """text-classification""": TFOpenAIGPTForSequenceClassification,
			        """text-generation""": TFOpenAIGPTLMHeadModel,
			        """zero-shot""": TFOpenAIGPTForSequenceClassification,
			    }
			    if is_tf_available()
			    else {}
			)
			__a	:    Optional[Any]			   =							False
			__a	:    Optional[Any]			   =							False
			def 							__snake_case	(						self ,						_A ,						_A ,						_A ,						_A ,						_A       )      ->      List[Any]:






				'''simple docstring'''







				if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
					# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
					# `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
					# tiny config could not be created.
					return True

				return False
			def 							__snake_case	(						self       )      ->      Any:






				'''simple docstring'''







				_UpperCAmelCase      :							Union[str, Any]       =   TFOpenAIGPTModelTester(self       )
				_UpperCAmelCase      :							Optional[int]       =   ConfigTester(self ,						config_class=_A ,						n_embd=37       )
			def 							__snake_case	(						self       )      ->      Tuple:






				'''simple docstring'''







				self.config_tester.run_common_tests()
			def 							__snake_case	(						self       )      ->      Tuple:






				'''simple docstring'''







				_UpperCAmelCase      :							List[str]       =   self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_openai_gpt_model(*_A       )
			def 							__snake_case	(						self       )      ->      List[str]:






				'''simple docstring'''







				_UpperCAmelCase      :							Union[str, Any]       =   self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_openai_gpt_lm_head(*_A       )
			def 							__snake_case	(						self       )      ->      str:






				'''simple docstring'''







				_UpperCAmelCase      :							Union[str, Any]       =   self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_openai_gpt_double_head(*_A       )
			def 							__snake_case	(						self       )      ->      Any:






				'''simple docstring'''







				_UpperCAmelCase      :							Union[str, Any]       =   self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_A       )
			@slow
			def 							__snake_case	(						self       )      ->      List[Any]:






				'''simple docstring'''







				for model_name in TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					_UpperCAmelCase      :							Union[str, Any]       =   TFOpenAIGPTModel.from_pretrained(_A       )
					self.assertIsNotNone(_A       )






@require_tf
class       _UpperCAmelCase     (						unittest.TestCase):
			@slow
			def 							__snake_case	(						self       )      ->      List[str]:






				'''simple docstring'''







				_UpperCAmelCase      :							List[str]       =   TFOpenAIGPTLMHeadModel.from_pretrained("""openai-gpt"""       )
				_UpperCAmelCase      :							Dict       =   tf.convert_to_tensor([[4_81, 47_35, 5_44]] ,						dtype=tf.intaa       )  # the president is
				_UpperCAmelCase      :							List[Any]       =   [
				    4_81,
				    47_35,
				    5_44,
				    2_46,
				    9_63,
				    8_70,
				    7_62,
				    2_39,
				    2_44,
				    4_04_77,
				    2_44,
				    2_49,
				    7_19,
				    8_81,
				    4_87,
				    5_44,
				    2_40,
				    2_44,
				    6_03,
				    4_81,
				]  # the president is a very good man. " \n " i\'m sure he is, " said the

				_UpperCAmelCase      :							Optional[Any]       =   model.generate(_A ,						do_sample=_A       )
				self.assertListEqual(output_ids[0].numpy().tolist() ,						_A       )








"""simple docstring"""






import logging
import os
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import List, Optional

import faiss
import torch
from datasets import Features, Sequence, Value, load_dataset

from transformers import (
    DPRContextEncoder,
    DPRContextEncoderTokenizerFast,
    HfArgumentParser,
    RagRetriever,
    RagSequenceForGeneration,
    RagTokenizer,
)


lowerCamelCase__			:					int							  =					logging.getLogger(__name__)
torch.set_grad_enabled(False)
lowerCamelCase__			:					int							  =					'''cuda''' if torch.cuda.is_available() else '''cpu'''
def  UpperCamelCase   (     _lowerCAmelCase       :  str,					_lowerCAmelCase       :  int=100,					_lowerCAmelCase       :  List[str]=" "	)			->     List[str]:
	_UpperCAmelCase      :							Tuple       =   text.split(_lowerCAmelCase	)
	return [character.join(text[i : i + n]	).strip() for i in range(0,					len(_lowerCAmelCase	),					_lowerCAmelCase	)]
def  UpperCamelCase   (     _lowerCAmelCase       :  dict	)			->     dict:
	_UpperCAmelCase  ,				_UpperCAmelCase      :							List[str]       =   [], []
	for title, text in zip(documents["""title"""],					documents["""text"""]	):
		if text is not None:
			for passage in split_text(_lowerCAmelCase	):
				titles.append(title if title is not None else """"""	)
				texts.append(_lowerCAmelCase	)
	return {"title": titles, "text": texts}
def  UpperCamelCase   (     _lowerCAmelCase       :  dict,					_lowerCAmelCase       :  DPRContextEncoder,					_lowerCAmelCase       :  DPRContextEncoderTokenizerFast	)			->     dict:
	_UpperCAmelCase      :							int       =   ctx_tokenizer(
	    documents["""title"""],					documents["""text"""],					truncation=_lowerCAmelCase,					padding="""longest""",					return_tensors="""pt"""	)["""input_ids"""]
	_UpperCAmelCase      :							Optional[Any]       =   ctx_encoder(input_ids.to(device=_lowerCAmelCase	),					return_dict=_lowerCAmelCase	).pooler_output
	return {"embeddings": embeddings.detach().cpu().numpy()}
def  UpperCamelCase   (     _lowerCAmelCase       :  "RagExampleArguments",					_lowerCAmelCase       :  "ProcessingArguments",					_lowerCAmelCase       :  "IndexHnswArguments",					)			->     int:
	######################################
	logger.info("""Step 1 - Create the dataset"""	)
	######################################

	# The dataset needed for RAG must have three columns:
	# - title (string): title of the document
	# - text (string): text of a passage of the document
	# - embeddings (array of dimension d): DPR representation of the passage

	# Let's say you have documents in tab-separated csv files with columns "title" and "text"
	assert os.path.isfile(rag_example_args.csv_path	), "Please provide a valid path to a csv file"

	# You can load a Dataset object this way
	_UpperCAmelCase      :							Optional[int]       =   load_dataset(
	    """csv""",					data_files=[rag_example_args.csv_path],					split="""train""",					delimiter="""\t""",					column_names=["""title""", """text"""]	)

	# More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files

	# Then split the documents into passages of 100 words
	_UpperCAmelCase      :							List[str]       =   dataset.map(_lowerCAmelCase,					batched=_lowerCAmelCase,					num_proc=processing_args.num_proc	)

	# And compute the embeddings
	_UpperCAmelCase      :							Optional[Any]       =   DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name	).to(device=_lowerCAmelCase	)
	_UpperCAmelCase      :							Tuple       =   DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name	)
	_UpperCAmelCase      :							int       =   Features(
	    {"""text""": Value("""string"""	), """title""": Value("""string"""	), """embeddings""": Sequence(Value("""float32"""	)	)}	)  # optional, save as float32 instead of float64 to save space
	_UpperCAmelCase      :							Any       =   dataset.map(
	    partial(_lowerCAmelCase,					ctx_encoder=_lowerCAmelCase,					ctx_tokenizer=_lowerCAmelCase	),					batched=_lowerCAmelCase,					batch_size=processing_args.batch_size,					features=_lowerCAmelCase,					)

	# And finally save your dataset
	_UpperCAmelCase      :							Dict       =   os.path.join(rag_example_args.output_dir,					"""my_knowledge_dataset"""	)
	dataset.save_to_disk(_lowerCAmelCase	)
	# from datasets import load_from_disk
	# dataset = load_from_disk(passages_path)  # to reload the dataset

	######################################
	logger.info("""Step 2 - Index the dataset"""	)
	######################################

	# Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search
	_UpperCAmelCase      :							List[Any]       =   faiss.IndexHNSWFlat(index_hnsw_args.d,					index_hnsw_args.m,					faiss.METRIC_INNER_PRODUCT	)
	dataset.add_faiss_index("""embeddings""",					custom_index=_lowerCAmelCase	)

	# And save the index
	_UpperCAmelCase      :							List[str]       =   os.path.join(rag_example_args.output_dir,					"""my_knowledge_dataset_hnsw_index.faiss"""	)
	dataset.get_index("""embeddings"""	).save(_lowerCAmelCase	)
	# dataset.load_faiss_index("embeddings", index_path)  # to reload the index

	######################################
	logger.info("""Step 3 - Load RAG"""	)
	######################################

	# Easy way to load the model
	_UpperCAmelCase      :							List[Any]       =   RagRetriever.from_pretrained(
	    rag_example_args.rag_model_name,					index_name="""custom""",					indexed_dataset=_lowerCAmelCase	)
	_UpperCAmelCase      :							Dict       =   RagSequenceForGeneration.from_pretrained(rag_example_args.rag_model_name,					retriever=_lowerCAmelCase	)
	_UpperCAmelCase      :							Tuple       =   RagTokenizer.from_pretrained(rag_example_args.rag_model_name	)

	# For distributed fine-tuning you'll need to provide the paths instead, as the dataset and the index are loaded separately.
	# retriever = RagRetriever.from_pretrained(rag_model_name, index_name="custom", passages_path=passages_path, index_path=index_path)

	######################################
	logger.info("""Step 4 - Have fun"""	)
	######################################

	_UpperCAmelCase      :							List[Any]       =   rag_example_args.question or """What does Moses' rod turn into ?"""
	_UpperCAmelCase      :							List[Any]       =   tokenizer.question_encoder(_lowerCAmelCase,					return_tensors="""pt"""	)["""input_ids"""]
	_UpperCAmelCase      :							Dict       =   model.generate(_lowerCAmelCase	)
	_UpperCAmelCase      :							int       =   tokenizer.batch_decode(_lowerCAmelCase,					skip_special_tokens=_lowerCAmelCase	)[0]
	logger.info("""Q: """ + question	)
	logger.info("""A: """ + generated_string	)






@dataclass
class       _UpperCAmelCase     :
			__a	:    str			   =							field(
			    default=str(Path(__a).parent / """test_data""" / """my_knowledge_dataset.csv""")      ,       metadata={"""help""": """Path to a tab-separated csv file with columns 'title' and 'text'"""}      ,       )
			__a	:    Optional[str]			   =							field(
			    default=__a      ,       metadata={"""help""": """Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."""}      ,       )
			__a	:    str			   =							field(
			    default="""facebook/rag-sequence-nq"""      ,       metadata={"""help""": """The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"""}      ,       )
			__a	:    str			   =							field(
			    default="""facebook/dpr-ctx_encoder-multiset-base"""      ,       metadata={
			        """help""": (
			            """The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or"""
			            """ 'facebook/dpr-ctx_encoder-multiset-base'"""
			        )
			    }      ,       )
			__a	:    Optional[str]			   =							field(
			    default=__a      ,       metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""}      ,       )






@dataclass
class       _UpperCAmelCase     :
			__a	:    Optional[int]			   =							field(
			    default=__a      ,       metadata={
			        """help""": """The number of processes to use to split the documents into passages. Default is single process."""
			    }      ,       )
			__a	:    int			   =							field(
			    default=1_6      ,       metadata={
			        """help""": """The batch size to use when computing the passages embeddings using the DPR context encoder."""
			    }      ,       )






@dataclass
class       _UpperCAmelCase     :
			__a	:    int			   =							field(
			    default=7_6_8      ,       metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""}      ,       )
			__a	:    int			   =							field(
			    default=1_2_8      ,       metadata={
			        """help""": (
			            """The number of bi-directional links created for every new element during the HNSW index construction."""
			        )
			    }      ,       )


if __name__ == "__main__":
						logging.basicConfig(level=logging.WARNING)
						logger.setLevel(logging.INFO)

						lowerCamelCase__			:					Tuple							  =					HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
						lowerCamelCase__  ,					lowerCamelCase__  ,					lowerCamelCase__			:					Dict							  =					parser.parse_args_into_dataclasses()
						with TemporaryDirectory() as tmp_dir:
												lowerCamelCase__			:					List[str]							  =					rag_example_args.output_dir or tmp_dir
												main(rag_example_args, processing_args, index_hnsw_args)





