
"""simple docstring"""

# Copyright 2021 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 json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


_A				=					os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
_A				=					os.path.join(hf_cache_home, 'accelerate')
_A				=					os.path.join(cache_dir, 'default_config.yaml')
_A				=					os.path.join(cache_dir, 'default_config.yaml')

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
					_A				=					default_yaml_config_file
else:
					_A				=					default_json_config_file
def 						UpperCAmelCase   (						a_     ):





		'''simple docstring'''


		if config_file is not None:
				if not os.path.isfile(a_     ):
						raise FileNotFoundError(
						    F"""The passed configuration file `{config_file}` does not exist. """
						    'Please pass an existing file to `accelerate launch`, or use the the default one '
						    'created through `accelerate config` and run `accelerate launch` '
						    'without the `--config_file` argument.'     )
		else:
				lowerCamelCase	:     Optional[Any]            =       default_config_file
		with open(a_,		'r',		encoding='utf-8'     ) as f:
				if config_file.endswith('.json'     ):
						if (
						    json.load(a_     ).get('compute_environment',		ComputeEnvironment.LOCAL_MACHINE     )
						    == ComputeEnvironment.LOCAL_MACHINE
						):
								lowerCamelCase	:     Tuple            =       ClusterConfig
						else:
								lowerCamelCase	:     str            =       SageMakerConfig
						return config_class.from_json_file(json_file=a_     )
				else:
						if (
						    yaml.safe_load(a_     ).get('compute_environment',		ComputeEnvironment.LOCAL_MACHINE     )
						    == ComputeEnvironment.LOCAL_MACHINE
						):
								lowerCamelCase	:     List[Any]            =       ClusterConfig
						else:
								lowerCamelCase	:     Tuple            =       SageMakerConfig
						return config_class.from_yaml_file(yaml_file=a_     )






@dataclass
class 			_lowercase  :
	lowercase_								=      42
	lowercase_								=      42
	lowercase_								=      42
	lowercase_								=      42




	def      _UpperCamelCase       (					self   )						->				Optional[Any]:
			lowerCamelCase	:     Union[str, Any]            =       self.__dict__
			# For serialization, it's best to convert Enums to strings (or their underlying value type).
			for key, value in result.items():
					if isinstance(UpperCAmelCase_						,					UpperCAmelCase_   ):
							lowerCamelCase	:     Tuple            =       value.value
					if isinstance(UpperCAmelCase_						,					UpperCAmelCase_   ) and not bool(UpperCAmelCase_   ):
							lowerCamelCase	:     Optional[int]            =       None
			lowerCamelCase	:     str            =       {k: v for k, v in result.items() if v is not None}
			return result




	@classmethod
	def      _UpperCamelCase       (					cls						,					UpperCAmelCase_=None   )						->				Dict:
			lowerCamelCase	:     str            =       default_json_config_file if json_file is None else json_file
			with open(UpperCAmelCase_						,					'r'						,					encoding='utf-8'   ) as f:
					lowerCamelCase	:     Union[str, Any]            =       json.load(UpperCAmelCase_   )
			if "compute_environment" not in config_dict:
					lowerCamelCase	:     List[str]            =       ComputeEnvironment.LOCAL_MACHINE
			if "mixed_precision" not in config_dict:
					lowerCamelCase	:     str            =       'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
			if "fp16" in config_dict:  # Convert the config to the new format.
					del config_dict["fp16"]
			if "dynamo_backend" in config_dict:  # Convert the config to the new format.
					lowerCamelCase	:     Union[str, Any]            =       config_dict.pop('dynamo_backend'   )
					lowerCamelCase	:     str            =       {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
			if "use_cpu" not in config_dict:
					lowerCamelCase	:     List[str]            =       False
			return cls(**UpperCAmelCase_   )




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_   )						->				Union[str, Any]:
			with open(UpperCAmelCase_						,					'w'						,					encoding='utf-8'   ) as f:
					lowerCamelCase	:     Union[str, Any]            =       json.dumps(self.to_dict()						,					indent=2						,					sort_keys=UpperCAmelCase_   ) + '\n'
					f.write(UpperCAmelCase_   )




	@classmethod
	def      _UpperCamelCase       (					cls						,					UpperCAmelCase_=None   )						->				str:
			lowerCamelCase	:     List[Any]            =       default_yaml_config_file if yaml_file is None else yaml_file
			with open(UpperCAmelCase_						,					'r'						,					encoding='utf-8'   ) as f:
					lowerCamelCase	:     int            =       yaml.safe_load(UpperCAmelCase_   )
			if "compute_environment" not in config_dict:
					lowerCamelCase	:     Optional[int]            =       ComputeEnvironment.LOCAL_MACHINE

			if "mixed_precision" not in config_dict:
					lowerCamelCase	:     Any            =       'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
			if isinstance(config_dict['mixed_precision']						,					UpperCAmelCase_   ) and not config_dict["mixed_precision"]:
					lowerCamelCase	:     str            =       'no'
			if "fp16" in config_dict:  # Convert the config to the new format.
					del config_dict["fp16"]
			if "dynamo_backend" in config_dict:  # Convert the config to the new format.
					lowerCamelCase	:     Dict            =       config_dict.pop('dynamo_backend'   )
					lowerCamelCase	:     Optional[int]            =       {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
			if "use_cpu" not in config_dict:
					lowerCamelCase	:     Dict            =       False
			return cls(**UpperCAmelCase_   )




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_   )						->				str:
			with open(UpperCAmelCase_						,					'w'						,					encoding='utf-8'   ) as f:
					yaml.safe_dump(self.to_dict()						,					UpperCAmelCase_   )




	def      _UpperCamelCase       (					self   )						->				List[str]:
			if isinstance(self.compute_environment						,					UpperCAmelCase_   ):
					lowerCamelCase	:     str            =       ComputeEnvironment(self.compute_environment   )
			if isinstance(self.distributed_type						,					UpperCAmelCase_   ):
					if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
							lowerCamelCase	:     int            =       SageMakerDistributedType(self.distributed_type   )
					else:
							lowerCamelCase	:     int            =       DistributedType(self.distributed_type   )
			if self.dynamo_config is None:
					lowerCamelCase	:     Optional[int]            =       {}






@dataclass
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      42
	lowercase_								=      0
	lowercase_								=      1
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      "static"
	lowercase_								=      False
	lowercase_								=      "main"

	# args for deepspeed_plugin
	lowercase_								=      None
	# args for fsdp
	lowercase_								=      None
	# args for megatron_lm
	lowercase_								=      None
	# args for ipex
	lowercase_								=      None
	# args for TPU
	lowercase_								=      False

	# args for TPU pods
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      False
	lowercase_								=      False
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      None

	# args for dynamo
	lowercase_								=      None




	def      _UpperCamelCase       (					self   )						->				Tuple:
			if self.deepspeed_config is None:
					lowerCamelCase	:     Dict            =       {}
			if self.fsdp_config is None:
					lowerCamelCase	:     Any            =       {}
			if self.megatron_lm_config is None:
					lowerCamelCase	:     Union[str, Any]            =       {}
			if self.ipex_config is None:
					lowerCamelCase	:     Dict            =       {}
			return super().__post_init__()






@dataclass
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      42
	lowercase_								=      42
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      "us-east-1"
	lowercase_								=      1
	lowercase_								=      "all"
	lowercase_								=      F"""accelerate-sagemaker-{num_machines}"""
	lowercase_								=      SAGEMAKER_PYTORCH_VERSION
	lowercase_								=      SAGEMAKER_TRANSFORMERS_VERSION
	lowercase_								=      SAGEMAKER_PYTHON_VERSION
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      None
	lowercase_								=      None








"""simple docstring"""

import os
from typing import Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ... import AutoTokenizer
from ...utils import logging


_A				=					'block_records.npy'


_A				=					logging.get_logger(__name__)
def 						UpperCAmelCase   (						a_,		a_     ):





		'''simple docstring'''


		import tensorflow.compat.va as tf

		lowerCamelCase	:     Union[str, Any]            =       tf.data.TFRecordDataset(a_,		buffer_size=512 * 1024 * 1024     )
		lowerCamelCase	:     Union[str, Any]            =       blocks_dataset.batch(a_,		drop_remainder=a_     )
		lowerCamelCase	:     Union[str, Any]            =       next(blocks_dataset.take(1     ).as_numpy_iterator()     )

		return np_record






class 			_lowercase  :




	def __init__(					self						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_=2						,					UpperCAmelCase_=1000						,					UpperCAmelCase_=100						,					UpperCAmelCase_=100000						,					)						->				List[Any]:
			from scann.scann_ops.py.scann_ops_pybind import builder as Builder

			lowerCamelCase	:     int            =       Builder(db=UpperCAmelCase_						,					num_neighbors=UpperCAmelCase_						,					distance_measure='dot_product'   )
			lowerCamelCase	:     Optional[int]            =       builder.tree(
			    num_leaves=UpperCAmelCase_						,					num_leaves_to_search=UpperCAmelCase_						,					training_sample_size=UpperCAmelCase_   )
			lowerCamelCase	:     Union[str, Any]            =       builder.score_ah(dimensions_per_block=UpperCAmelCase_   )

			lowerCamelCase	:     List[Any]            =       builder.build()




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_   )						->				Optional[int]:
			lowerCamelCase      ,       lowerCamelCase	:     List[Any]            =       self.searcher.search_batched(question_projection.detach().cpu()   )
			return retrieved_block_ids.astype('int64'   )






class 			_lowercase  :




	def __init__(					self						,					UpperCAmelCase_						,					UpperCAmelCase_   )						->				Optional[Any]:
			super().__init__()
			lowerCamelCase	:     Tuple            =       block_records
			lowerCamelCase	:     Any            =       tokenizer




	def __call__(					self						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_=None						,					UpperCAmelCase_="pt"   )						->				Tuple:
			lowerCamelCase	:     List[str]            =       np.take(self.block_records						,					indices=UpperCAmelCase_						,					axis=0   )

			lowerCamelCase	:     Any            =       self.tokenizer.decode(question_input_ids[0]						,					skip_special_tokens=UpperCAmelCase_   )

			lowerCamelCase	:     int            =       []
			lowerCamelCase	:     Optional[int]            =       []
			for retrieved_block in retrieved_blocks:
					text.append(UpperCAmelCase_   )
					text_pair.append(retrieved_block.decode()   )

			lowerCamelCase	:     Union[str, Any]            =       self.tokenizer(
			    UpperCAmelCase_						,					UpperCAmelCase_						,					padding=UpperCAmelCase_						,					truncation=UpperCAmelCase_						,					return_special_tokens_mask=UpperCAmelCase_						,					max_length=UpperCAmelCase_   )
			lowerCamelCase	:     str            =       concat_inputs.convert_to_tensors(UpperCAmelCase_   )

			if answer_ids is not None:
					return self.block_has_answer(UpperCAmelCase_						,					UpperCAmelCase_   ) + (concat_inputs_tensors,)
			else:
					return (None, None, None, concat_inputs_tensors)




	@classmethod
	def      _UpperCamelCase       (					cls						,					UpperCAmelCase_						,					*UpperCAmelCase_						,					**UpperCAmelCase_   )						->				Dict:
			if os.path.isdir(UpperCAmelCase_   ):
					lowerCamelCase	:     str            =       os.path.join(UpperCAmelCase_						,					_REALM_BLOCK_RECORDS_FILENAME   )
			else:
					lowerCamelCase	:     Tuple            =       hf_hub_download(
					    repo_id=UpperCAmelCase_						,					filename=_REALM_BLOCK_RECORDS_FILENAME						,					**UpperCAmelCase_   )
			lowerCamelCase	:     Dict            =       np.load(UpperCAmelCase_						,					allow_pickle=UpperCAmelCase_   )

			lowerCamelCase	:     Union[str, Any]            =       AutoTokenizer.from_pretrained(UpperCAmelCase_						,					*UpperCAmelCase_						,					**UpperCAmelCase_   )

			return cls(UpperCAmelCase_						,					UpperCAmelCase_   )




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_   )						->				Union[str, Any]:
			# save block records
			np.save(os.path.join(UpperCAmelCase_						,					_REALM_BLOCK_RECORDS_FILENAME   )						,					self.block_records   )
			# save tokenizer
			self.tokenizer.save_pretrained(UpperCAmelCase_   )




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_   )						->				Tuple:
			lowerCamelCase	:     List[Any]            =       []
			lowerCamelCase	:     Any            =       []
			lowerCamelCase	:     int            =       []
			lowerCamelCase	:     Union[str, Any]            =       0

			for input_id in concat_inputs.input_ids:
					lowerCamelCase	:     Optional[Any]            =       input_id.tolist()
					# Check answers between two [SEP] tokens
					lowerCamelCase	:     Tuple            =       input_id_list.index(self.tokenizer.sep_token_id   )
					lowerCamelCase	:     Any            =       first_sep_idx + 1 + input_id_list[first_sep_idx + 1 :].index(self.tokenizer.sep_token_id   )

					start_pos.append([]   )
					end_pos.append([]   )
					for answer in answer_ids:
							for idx in range(first_sep_idx + 1						,					UpperCAmelCase_   ):
									if answer[0] == input_id_list[idx]:
											if input_id_list[idx : idx + len(UpperCAmelCase_   )] == answer:
													start_pos[-1].append(UpperCAmelCase_   )
													end_pos[-1].append(idx + len(UpperCAmelCase_   ) - 1   )

					if len(start_pos[-1]   ) == 0:
							has_answers.append(UpperCAmelCase_   )
					else:
							has_answers.append(UpperCAmelCase_   )
							if len(start_pos[-1]   ) > max_answers:
									lowerCamelCase	:     List[str]            =       len(start_pos[-1]   )

        # Pad -1 to max_answers
			for start_pos_, end_pos_ in zip(UpperCAmelCase_						,					UpperCAmelCase_   ):
					if len(start_pos_   ) < max_answers:
							lowerCamelCase	:     Optional[int]            =       [-1] * (max_answers - len(start_pos_   ))
							start_pos_ += padded
							end_pos_ += padded
			return has_answers, start_pos, end_pos






