






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


a_							=    logging.getLogger(__name__)
torch.set_grad_enabled(False)
a_							=    '''cuda''' if torch.cuda.is_available() else '''cpu'''


def        _a  (     UpperCamelCase_					:				str    ,   UpperCamelCase_					:				Optional[int]=100    ,   UpperCamelCase_					:				Union[str, Any]=" "   ) ->   List[str]:
						"""simple docstring"""







						lowerCAmelCase__       =						text.split(UpperCamelCase_   )
						return [character.join(text[i : i + n]   ).strip() for i in range(0    ,   len(UpperCamelCase_   )    ,   UpperCamelCase_   )]


def        _a  (     UpperCamelCase_					:				dict   ) ->   dict:
						"""simple docstring"""







						lowerCAmelCase__      ,							lowerCAmelCase__       =						[], []
						for title, text in zip(documents["title"]    ,   documents["text"]   ):
												if text is not None:
																		for passage in split_text(UpperCamelCase_   ):
																								titles.append(title if title is not None else ""   )
																								texts.append(UpperCamelCase_   )
						return {"title": titles, "text": texts}


def        _a  (     UpperCamelCase_					:				dict    ,   UpperCamelCase_					:				DPRContextEncoder    ,   UpperCamelCase_					:				DPRContextEncoderTokenizerFast   ) ->   dict:
						"""simple docstring"""







						lowerCAmelCase__       =						ctx_tokenizer(
						    documents["title"]    ,   documents["text"]    ,   truncation=UpperCamelCase_    ,   padding="longest"    ,   return_tensors="pt"   )["input_ids"]
						lowerCAmelCase__       =						ctx_encoder(input_ids.to(device=UpperCamelCase_   )    ,   return_dict=UpperCamelCase_   ).pooler_output
						return {"embeddings": embeddings.detach().cpu().numpy()}


def        _a  (     UpperCamelCase_					:				"RagExampleArguments"    ,   UpperCamelCase_					:				"ProcessingArguments"    ,   UpperCamelCase_					:				"IndexHnswArguments"    ,   ) ->   Any:
						"""simple docstring"""







						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
						lowerCAmelCase__       =						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
						lowerCAmelCase__       =						dataset.map(UpperCamelCase_    ,   batched=UpperCamelCase_    ,   num_proc=processing_args.num_proc   )

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

						# And finally save your dataset
						lowerCAmelCase__       =						os.path.join(rag_example_args.output_dir    ,   "my_knowledge_dataset"   )
						dataset.save_to_disk(UpperCamelCase_   )
						# 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
						lowerCAmelCase__       =						faiss.IndexHNSWFlat(index_hnsw_args.d    ,   index_hnsw_args.m    ,   faiss.METRIC_INNER_PRODUCT   )
						dataset.add_faiss_index("embeddings"    ,   custom_index=UpperCamelCase_   )

						# And save the index
						lowerCAmelCase__       =						os.path.join(rag_example_args.output_dir    ,   "my_knowledge_dataset_hnsw_index.faiss"   )
						dataset.get_index("embeddings"   ).save(UpperCamelCase_   )
						# dataset.load_faiss_index("embeddings", index_path)  # to reload the index


@dataclass
class      lowercase__     :
	a_         =field(
	    default=str(Path(_UpperCAmelCase	).parent / """test_run""" / """dummy-kb""" / """my_knowledge_dataset.csv"""	),					metadata={"""help""": """Path to a tab-separated csv file with columns 'title' and 'text'"""},					)
	a_         =field(
	    default=_UpperCAmelCase,					metadata={"""help""": """Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."""},					)
	a_         =field(
	    default="""facebook/rag-sequence-nq""",					metadata={"""help""": """The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"""},					)
	a_         =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_         =field(
	    default=str(Path(_UpperCAmelCase	).parent / """test_run""" / """dummy-kb"""	),					metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""},					)





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





@dataclass
class      lowercase__     :
	a_         =field(
	    default=768,					metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""},					)
	a_         =field(
	    default=128,					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)

					a_							=    HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
					a_,						a_,						a_							=    parser.parse_args_into_dataclasses()
					with TemporaryDirectory() as tmp_dir:
										a_							=    rag_example_args.output_dir or tmp_dir
										main(rag_example_args, processing_args, index_hnsw_args)














from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


a_							=    logging.get_logger(__name__)


a_							=    {
    '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''',
    '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''',
    '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''',
    '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''',
    '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''',
    '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''',
    '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''',
    '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''',
    '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''',
    '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''',
    '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''',
    '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''',
}


class      lowercase__     (			_UpperCAmelCase	):
	a_         ="""codegen"""
	a_         ={
	    """max_position_embeddings""": """n_positions""",
	    """hidden_size""": """n_embd""",
	    """num_attention_heads""": """n_head""",
	    """num_hidden_layers""": """n_layer""",
	}

	def __init__(							self		,    __UpperCAmelCase=50400		,    __UpperCAmelCase=2048		,    __UpperCAmelCase=2048		,    __UpperCAmelCase=4096		,    __UpperCAmelCase=28		,    __UpperCAmelCase=16		,    __UpperCAmelCase=64		,    __UpperCAmelCase=None		,    __UpperCAmelCase="gelu_new"		,    __UpperCAmelCase=0.0		,    __UpperCAmelCase=0.0		,    __UpperCAmelCase=0.0		,    __UpperCAmelCase=1E-5		,    __UpperCAmelCase=0.02		,    __UpperCAmelCase=True		,    __UpperCAmelCase=50256		,    __UpperCAmelCase=50256		,    __UpperCAmelCase=False		,    **__UpperCAmelCase		,    )->					Optional[int]:







							'''simple docstring'''





							lowerCAmelCase__       =						vocab_size
							lowerCAmelCase__       =						n_ctx
							lowerCAmelCase__       =						n_positions
							lowerCAmelCase__       =						n_embd
							lowerCAmelCase__       =						n_layer
							lowerCAmelCase__       =						n_head
							lowerCAmelCase__       =						n_inner
							lowerCAmelCase__       =						rotary_dim
							lowerCAmelCase__       =						activation_function
							lowerCAmelCase__       =						resid_pdrop
							lowerCAmelCase__       =						embd_pdrop
							lowerCAmelCase__       =						attn_pdrop
							lowerCAmelCase__       =						layer_norm_epsilon
							lowerCAmelCase__       =						initializer_range
							lowerCAmelCase__       =						use_cache

							lowerCAmelCase__       =						bos_token_id
							lowerCAmelCase__       =						eos_token_id

							super().__init__(
							    bos_token_id=__UpperCAmelCase		,    eos_token_id=__UpperCAmelCase		,    tie_word_embeddings=__UpperCAmelCase		,    **__UpperCAmelCase       )





class      lowercase__     (			_UpperCAmelCase	):

	def __init__(							self		,    __UpperCAmelCase		,    __UpperCAmelCase = "default"		,    __UpperCAmelCase = None		,    __UpperCAmelCase = False		,    )->					Any:







							'''simple docstring'''





							super().__init__(__UpperCAmelCase		,    task=__UpperCAmelCase		,    patching_specs=__UpperCAmelCase		,    use_past=__UpperCAmelCase       )
							if not getattr(self._config		,    "pad_token_id"		,    __UpperCAmelCase       ):
													# TODO: how to do that better?
													lowerCAmelCase__       =						0

	@property
	def 		UpperCAmelCase  (							self       )->					Mapping[str, Mapping[int, str]]:







							'''simple docstring'''





							lowerCAmelCase__       =						OrderedDict({"input_ids": {0: "batch", 1: "sequence"}}       )
							if self.use_past:
													self.fill_with_past_key_values_(__UpperCAmelCase		,    direction="inputs"       )
													lowerCAmelCase__       =						{0: "batch", 1: "past_sequence + sequence"}
							else:
													lowerCAmelCase__       =						{0: "batch", 1: "sequence"}

							return common_inputs

	@property
	def 		UpperCAmelCase  (							self       )->					int:







							'''simple docstring'''





							return self._config.n_layer

	@property
	def 		UpperCAmelCase  (							self       )->					int:







							'''simple docstring'''





							return self._config.n_head

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase		,    __UpperCAmelCase = -1		,    __UpperCAmelCase = -1		,    __UpperCAmelCase = False		,    __UpperCAmelCase = None		,    )->					Mapping[str, Any]:







							'''simple docstring'''





							lowerCAmelCase__       =						super(__UpperCAmelCase		,    self       ).generate_dummy_inputs(
							    __UpperCAmelCase		,    batch_size=__UpperCAmelCase		,    seq_length=__UpperCAmelCase		,    is_pair=__UpperCAmelCase		,    framework=__UpperCAmelCase       )

							# We need to order the input in the way they appears in the forward()
							lowerCAmelCase__       =						OrderedDict({"input_ids": common_inputs["input_ids"]}       )

							# Need to add the past_keys
							if self.use_past:
													if not is_torch_available():
																			raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."       )
													else:
																			import torch

																			lowerCAmelCase__      ,							lowerCAmelCase__       =						common_inputs["input_ids"].shape
																			# Not using the same length for past_key_values
																			lowerCAmelCase__       =						seqlen + 2
																			lowerCAmelCase__       =						(
																			    batch,
																			    self.num_attention_heads,
																			    past_key_values_length,
																			    self._config.hidden_size // self.num_attention_heads,
																			)
																			lowerCAmelCase__       =						[
																			    (torch.zeros(__UpperCAmelCase       ), torch.zeros(__UpperCAmelCase       )) for _ in range(self.num_layers       )
																			]

							lowerCAmelCase__       =						common_inputs["attention_mask"]
							if self.use_past:
													lowerCAmelCase__       =						ordered_inputs["attention_mask"].dtype
													lowerCAmelCase__       =						torch.cat(
													    [ordered_inputs["attention_mask"], torch.ones(__UpperCAmelCase		,    __UpperCAmelCase		,    dtype=__UpperCAmelCase       )]		,    dim=1       )

							return ordered_inputs


	@property
	def 		UpperCAmelCase  (							self       )->					int:







							'''simple docstring'''





							return 13






