

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


lowerCAmelCase     :   Union[str, Any]						     =  logging.getLogger(__name__)
torch.set_grad_enabled(False)
lowerCAmelCase     :   List[Any]						     =  """cuda""" if torch.cuda.is_available() else """cpu"""

def    A_  (							a					,   a=1_0_0					,   a=" "  ):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     text.split(a  )
      return [character.join(text[i : i + n]  ).strip() for i in range(0					,   len(a  )					,   a  )]

def    A_  (							a  ):

      """simple docstring"""



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

def    A_  (							a					,   a					,   a  ):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_				:  Any           =     ctx_tokenizer(
          documents['title']					,   documents['text']					,   truncation=a					,   padding='longest'					,   return_tensors='pt'  )['input_ids']
      SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     ctx_encoder(input_ids.to(device=a  )					,   return_dict=a  ).pooler_output
      return {"embeddings": embeddings.detach().cpu().numpy()}

def    A_  (							a					,   a					,   a					,   ):

      """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
      SCREAMING_SNAKE_CASE_				:  List[Any]           =     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
      SCREAMING_SNAKE_CASE_				:  Tuple           =     dataset.map(a					,   batched=a					,   num_proc=processing_args.num_proc  )

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

      # And finally save your dataset
      SCREAMING_SNAKE_CASE_				:  str           =     os.path.join(rag_example_args.output_dir					,   'my_knowledge_dataset'  )
      dataset.save_to_disk(a  )
      # 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
      SCREAMING_SNAKE_CASE_				:  int           =     faiss.IndexHNSWFlat(index_hnsw_args.d					,   index_hnsw_args.m					,   faiss.METRIC_INNER_PRODUCT  )
      dataset.add_faiss_index('embeddings'					,   custom_index=a  )

      # And save the index
      SCREAMING_SNAKE_CASE_				:  Optional[int]           =     os.path.join(rag_example_args.output_dir					,   'my_knowledge_dataset_hnsw_index.faiss'  )
      dataset.get_index('embeddings'  ).save(a  )
      # dataset.load_faiss_index("embeddings", index_path)  # to reload the index
@dataclass
class  _A		:
  SCREAMING_SNAKE_CASE    :      str       =  field(
      default=str(Path(_lowerCAmelCase).parent / '''test_run''' / '''dummy-kb''' / '''my_knowledge_dataset.csv''')   ,     metadata={'''help''': '''Path to a tab-separated csv file with columns \'title\' and \'text\''''}   ,     )
  SCREAMING_SNAKE_CASE    :      Optional[str]       =  field(
      default=_lowerCAmelCase   ,     metadata={'''help''': '''Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'''}   ,     )
  SCREAMING_SNAKE_CASE    :      str       =  field(
      default='''facebook/rag-sequence-nq'''   ,     metadata={'''help''': '''The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''''}   ,     )
  SCREAMING_SNAKE_CASE    :      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\''''
          )
      }   ,     )
  SCREAMING_SNAKE_CASE    :      Optional[str]       =  field(
      default=str(Path(_lowerCAmelCase).parent / '''test_run''' / '''dummy-kb''')   ,     metadata={'''help''': '''Path to a directory where the dataset passages and the index will be saved'''}   ,     )

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

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

    lowerCAmelCase     :   str						     =  HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
    lowerCAmelCase     :   Optional[Any]						     =  parser.parse_args_into_dataclasses()
    with TemporaryDirectory() as tmp_dir:
        lowerCAmelCase     :   str						     =  rag_example_args.output_dir or tmp_dir
        main(rag_example_args, processing_args, index_hnsw_args)






# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
    import torch


lowerCAmelCase     :   Optional[int]						     =  logging.get_logger(__name__)
@dataclass
class  _A		:

  def __init__(				self ,					_SCREAMING_SNAKE_CASE=False ,					_SCREAMING_SNAKE_CASE=False ,					_SCREAMING_SNAKE_CASE=6.0 ,					_SCREAMING_SNAKE_CASE=None ,					_SCREAMING_SNAKE_CASE=False ,					_SCREAMING_SNAKE_CASE=False ,					_SCREAMING_SNAKE_CASE=None ,					_SCREAMING_SNAKE_CASE="fp4" ,					_SCREAMING_SNAKE_CASE=False ,					**_SCREAMING_SNAKE_CASE ,					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  str           =     load_in_abit
        SCREAMING_SNAKE_CASE_				:  Tuple           =     load_in_abit
        SCREAMING_SNAKE_CASE_				:  Dict           =     llm_inta_threshold
        SCREAMING_SNAKE_CASE_				:  Tuple           =     llm_inta_skip_modules
        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     llm_inta_enable_fpaa_cpu_offload
        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     llm_inta_has_fpaa_weight
        SCREAMING_SNAKE_CASE_				:  List[str]           =     bnb_abit_quant_type
        SCREAMING_SNAKE_CASE_				:  int           =     bnb_abit_use_double_quant

        if bnb_abit_compute_dtype is None:
              SCREAMING_SNAKE_CASE_				:  List[Any]           =     torch.floataa
        elif isinstance(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):
              SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     getattr(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)
        elif isinstance(_SCREAMING_SNAKE_CASE ,					torch.dtype					):
              SCREAMING_SNAKE_CASE_				:  Optional[int]           =     bnb_abit_compute_dtype
        else:
              raise ValueError('bnb_4bit_compute_dtype must be a string or a torch.dtype'					)

        self.post_init()

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        if not isinstance(self.llm_inta_threshold ,					_SCREAMING_SNAKE_CASE					):
              raise ValueError('llm_int8_threshold must be a float'					)

        if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules ,					_SCREAMING_SNAKE_CASE					):
              raise ValueError('llm_int8_skip_modules must be a list of strings'					)
        if not isinstance(self.llm_inta_enable_fpaa_cpu_offload ,					_SCREAMING_SNAKE_CASE					):
              raise ValueError('llm_int8_enable_fp32_cpu_offload must be a boolean'					)

        if not isinstance(self.llm_inta_has_fpaa_weight ,					_SCREAMING_SNAKE_CASE					):
              raise ValueError('llm_int8_has_fp16_weight must be a boolean'					)

        if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype ,					torch.dtype					):
              raise ValueError('bnb_4bit_compute_dtype must be torch.dtype'					)

        if not isinstance(self.bnb_abit_quant_type ,					_SCREAMING_SNAKE_CASE					):
              raise ValueError('bnb_4bit_quant_type must be a string'					)

        if not isinstance(self.bnb_abit_use_double_quant ,					_SCREAMING_SNAKE_CASE					):
              raise ValueError('bnb_4bit_use_double_quant must be a boolean'					)

        if self.load_in_abit and not version.parse(importlib.metadata.version('bitsandbytes'					)					) >= version.parse(
            '0.39.0'					):
              raise ValueError(
                  '4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version'					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        return self.load_in_abit or self.load_in_abit

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        if self.load_in_abit:
              return "llm_int8"
        elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
              return "fp4"
        elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
              return "nf4"
        else:
              return None

  @classmethod
  def  UpperCAmelCase    (				cls ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					**_SCREAMING_SNAKE_CASE					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     cls(**_SCREAMING_SNAKE_CASE					)

        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     []
        for key, value in kwargs.items():
              if hasattr(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):
                    setattr(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)
                    to_remove.append(_SCREAMING_SNAKE_CASE					)
        for key in to_remove:
              kwargs.pop(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)

        if return_unused_kwargs:
              return config, kwargs
        else:
              return config

  def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE					):





        """simple docstring"""







        with open(_SCREAMING_SNAKE_CASE ,					'w' ,					encoding='utf-8'					) as writer:
              SCREAMING_SNAKE_CASE_				:  Optional[int]           =     self.to_dict()
              SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     json.dumps(_SCREAMING_SNAKE_CASE ,					indent=2 ,					sort_keys=_SCREAMING_SNAKE_CASE					) + '\n'

              writer.write(_SCREAMING_SNAKE_CASE					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  str           =     copy.deepcopy(self.__dict__					)
        SCREAMING_SNAKE_CASE_				:  str           =     str(output['bnb_4bit_compute_dtype']					).split('.'					)[1]

        return output

  def __repr__(				self					):





        """simple docstring"""







        return f"{self.__class__.__name__} {self.to_json_string()}"

  def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE = True					):





        """simple docstring"""







        if use_diff is True:
              SCREAMING_SNAKE_CASE_				:  int           =     self.to_diff_dict()
        else:
              SCREAMING_SNAKE_CASE_				:  List[str]           =     self.to_dict()
        return json.dumps(_SCREAMING_SNAKE_CASE ,					indent=2 ,					sort_keys=_SCREAMING_SNAKE_CASE					) + "\n"



  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  int           =     self.to_dict()

        # get the default config dict
        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     BitsAndBytesConfig().to_dict()

        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     {}

        # only serialize values that differ from the default config
        for key, value in config_dict.items():
              if value != default_config_dict[key]:
                    SCREAMING_SNAKE_CASE_				:  int           =     value

        return serializable_config_dict






