'''simple docstring'''






# Copyright 2022 The HuggingFace 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 argparse
import os
import subprocess

from packaging.version import Version, parse

from accelerate.commands.config.config_args import default_config_file, load_config_from_file


_UpperCAmelCase    :     Dict         =       '''Run commands across TPU VMs for initial setup before running `accelerate launch`.'''





def  _SCREAMING_SNAKE_CASE		(      __snake_case							:			Tuple=None				):
     if subparsers is not None:
          _A    		=  subparsers.add_parser('tpu-config'   ,		description=_description				)
     else:
          _A    		=  argparse.ArgumentParser('Accelerate tpu-config command'   ,		description=_description				)
     # Core arguments
     _A    		=  parser.add_argument_group(
         'Config Arguments'   ,		'Arguments that can be configured through `accelerate config`.'				)
     config_args.add_argument(
         '--config_file'   ,		type=__snake_case   ,		default=__snake_case   ,		help='Path to the config file to use for accelerate.'   ,		)
     config_args.add_argument(
         '--tpu_name'   ,		default=__snake_case   ,		help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.'   ,		)
     config_args.add_argument(
         '--tpu_zone'   ,		default=__snake_case   ,		help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.'   ,		)
     _A    		=  parser.add_argument_group('TPU Arguments'   ,		'Arguments for options ran inside the TPU.'				)
     pod_args.add_argument(
         '--use_alpha'   ,		action='store_true'   ,		help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.'   ,		)
     pod_args.add_argument(
         '--command_file'   ,		default=__snake_case   ,		help='The path to the file containing the commands to run on the pod on startup.'   ,		)
     pod_args.add_argument(
         '--command'   ,		action='append'   ,		nargs='+'   ,		help='A command to run on the pod. Can be passed multiple times.'   ,		)
     pod_args.add_argument(
         '--install_accelerate'   ,		action='store_true'   ,		help='Whether to install accelerate on the pod. Defaults to False.'   ,		)
     pod_args.add_argument(
         '--accelerate_version'   ,		default='latest'   ,		help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.'   ,		)
     pod_args.add_argument(
         '--debug'   ,		action='store_true'   ,		help='If set, will print the command that would be run instead of running it.'				)

     if subparsers is not None:
          parser.set_defaults(func=__snake_case				)
     return parser





def  _SCREAMING_SNAKE_CASE		(      __snake_case							:			Union[str, Any]				):
     _A    		=  None

     # Get the default from the config file if it exists.
     if args.config_file is not None or os.path.isfile(__snake_case				):
          _A    		=  load_config_from_file(args.config_file				)
          if not args.command_file and defaults.command_file is not None and not args.command:
               _A    		=  defaults.command_file
          if not args.command and defaults.commands is not None:
               _A    		=  defaults.commands
          if not args.tpu_name:
               _A    		=  defaults.tpu_name
          if not args.tpu_zone:
               _A    		=  defaults.tpu_zone
     if args.accelerate_version == "dev":
          _A    		=  'git+https://github.com/huggingface/accelerate.git'
     elif args.accelerate_version == "latest":
          _A    		=  'accelerate -U'
     elif isinstance(parse(args.accelerate_version				)   ,		__snake_case				):
          _A    		=  F'accelerate=={args.accelerate_version}'

     if not args.command_file and not args.command:
          raise ValueError('You must specify either a command file or a command to run on the pod.'				)

     if args.command_file:
          with open(args.command_file   ,		'r'				) as f:
               _A    		=  [f.read().splitlines()]

    # To turn list of lists into list of strings
     if isinstance(args.command[0]   ,		__snake_case				):
          _A    		=  [line for cmd in args.command for line in cmd]
     # Default to the shared folder and install accelerate
     _A    		=  ['cd /usr/share']
     if args.install_accelerate:
          new_cmd += [F'pip install {args.accelerate_version}']
     new_cmd += args.command
     _A    		=  '; '.join(__snake_case				)

     # Then send it to gcloud
     # Eventually try to use google-api-core to do this instead of subprocess
     _A    		=  ['gcloud']
     if args.use_alpha:
          cmd += ["alpha"]
     cmd += [
         "compute",
         "tpus",
         "tpu-vm",
         "ssh",
         args.tpu_name,
         "--zone",
         args.tpu_zone,
         "--command",
         args.command,
         "--worker",
         "all",
     ]
     if args.debug:
          print(F'Running {" ".join(__snake_case				)}'				)
          return
     subprocess.run(__snake_case				)
     print('Successfully setup pod.'				)





def  _SCREAMING_SNAKE_CASE		(      ):
     _A    		=  tpu_command_parser()
     _A    		=  parser.parse_args()

     tpu_command_launcher(__snake_case				)




'''simple docstring'''






import logging
import random

import ray

from transformers import RagConfig, RagRetriever, RagTokenizer
from transformers.models.rag.retrieval_rag import CustomHFIndex


_UpperCAmelCase    :     int         =       logging.getLogger(__name__)







class lowercase_       :







   """simple docstring"""

   def __init__(      self      :			Tuple     )  ->			int:
        _A    		=  False
   def 	__UpperCAmelCase   (      self      :			Optional[int], UpperCamelCase__      :			str, UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			int, UpperCamelCase__      :			Optional[Any]     )  ->			Any:
        if not self.initialized:
             _A    		=  RagRetriever(
                 UpperCamelCase__, question_encoder_tokenizer=UpperCamelCase__, generator_tokenizer=UpperCamelCase__, index=UpperCamelCase__, init_retrieval=UpperCamelCase__, )
             _A    		=  True
   def 	__UpperCAmelCase   (      self      :			Any     )  ->			List[Any]:
        self.retriever.index.init_index()

   def 	__UpperCAmelCase   (      self      :			int, UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			Dict     )  ->			Optional[Any]:
        _A		,       _A    		=  self.retriever._main_retrieve(UpperCamelCase__, UpperCamelCase__     )
        return doc_ids, retrieved_doc_embeds







class lowercase_       (		_UpperCamelCase			):







   """simple docstring"""

   def __init__(      self      :			Optional[Any], UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			Optional[int], UpperCamelCase__      :			Dict, UpperCamelCase__      :			Union[str, Any], UpperCamelCase__      :			int=None     )  ->			Optional[int]:
        if index is not None and index.is_initialized() and len(UpperCamelCase__     ) > 0:
             raise ValueError(
                 'When using Ray for distributed fine-tuning, '
                 'you\'ll need to provide the paths instead, '
                 'as the dataset and the index are loaded '
                 'separately. More info in examples/rag/use_own_knowledge_dataset.py '     )
        super().__init__(
            UpperCamelCase__, question_encoder_tokenizer=UpperCamelCase__, generator_tokenizer=UpperCamelCase__, index=UpperCamelCase__, init_retrieval=UpperCamelCase__, )
        _A    		=  retrieval_workers
        if len(self.retrieval_workers     ) > 0:
             ray.get(
                 [
                     worker.create_rag_retriever.remote(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__     )
                     for worker in self.retrieval_workers
                 ]     )
   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			int:
        logger.info('initializing retrieval'     )

        if len(self.retrieval_workers     ) > 0:
             ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers]     )
        else:
             # Non-distributed training. Load index into this same process.
             self.index.init_index()
   def 	__UpperCAmelCase   (      self      :			Optional[Any], UpperCamelCase__      :			Dict, UpperCamelCase__      :			Tuple     )  ->			Dict:
        if len(self.retrieval_workers     ) > 0:
             # Select a random retrieval actor.
             _A    		=  self.retrieval_workers[random.randint(0, len(self.retrieval_workers     ) - 1     )]
             _A		,       _A    		=  ray.get(random_worker.retrieve.remote(UpperCamelCase__, UpperCamelCase__     )     )
        else:
             _A		,       _A    		=  self._main_retrieve(UpperCamelCase__, UpperCamelCase__     )
        return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(UpperCamelCase__     )
   @classmethod
   def 	__UpperCAmelCase   (      cls      :			List[str], UpperCamelCase__      :			List[Any], UpperCamelCase__      :			List[Any]=None, **UpperCamelCase__      :			Optional[int]     )  ->			Optional[Any]:
        return super(UpperCamelCase__, cls     ).get_tokenizers(UpperCamelCase__, UpperCamelCase__, **UpperCamelCase__     )

   @classmethod
   def 	__UpperCAmelCase   (      cls      :			Any, UpperCamelCase__      :			Tuple, UpperCamelCase__      :			int, UpperCamelCase__      :			List[Any]=None, **UpperCamelCase__      :			List[str]     )  ->			Tuple:
        _A    		=  kwargs.pop('config', UpperCamelCase__     ) or RagConfig.from_pretrained(UpperCamelCase__, **UpperCamelCase__     )
        _A    		=  RagTokenizer.from_pretrained(UpperCamelCase__, config=UpperCamelCase__     )
        _A    		=  rag_tokenizer.question_encoder
        _A    		=  rag_tokenizer.generator
        if indexed_dataset is not None:
             _A    		=  'custom'
             _A    		=  CustomHFIndex(config.retrieval_vector_size, UpperCamelCase__     )
        else:
             _A    		=  cls._build_index(UpperCamelCase__     )
        return cls(
            UpperCamelCase__, question_encoder_tokenizer=UpperCamelCase__, generator_tokenizer=UpperCamelCase__, retrieval_workers=UpperCamelCase__, index=UpperCamelCase__, )



