






'''simple docstring'''
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


_UpperCamelCase											=			os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
_UpperCamelCase											=			os.path.join(hf_cache_home, '''accelerate''')
_UpperCamelCase											=			os.path.join(cache_dir, '''default_config.yaml''')
_UpperCamelCase											=			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):
					_UpperCamelCase											=			default_yaml_config_file
else:
					_UpperCamelCase											=			default_json_config_file


def   lowercase_	(   lowerCAmelCase__	:  Dict ):

			"""simple docstring"""





			if config_file is not None:
						if not os.path.isfile(lowerCAmelCase__ ):
									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:
						__UpperCAmelCase   :      List[str]										=     default_config_file
			with open(lowerCAmelCase__			,							"""r"""			,							encoding="""utf-8""" ) as f:
						if config_file.endswith(""".json""" ):
									if (
									    json.load(lowerCAmelCase__ ).get("""compute_environment"""			,							ComputeEnvironment.LOCAL_MACHINE )
									    == ComputeEnvironment.LOCAL_MACHINE
									):
												__UpperCAmelCase   :      List[str]										=     ClusterConfig
									else:
												__UpperCAmelCase   :      Tuple										=     SageMakerConfig
									return config_class.from_json_file(json_file=lowerCAmelCase__ )
						else:
									if (
									    yaml.safe_load(lowerCAmelCase__ ).get("""compute_environment"""			,							ComputeEnvironment.LOCAL_MACHINE )
									    == ComputeEnvironment.LOCAL_MACHINE
									):
												__UpperCAmelCase   :      Any										=     ClusterConfig
									else:
												__UpperCAmelCase   :      Tuple										=     SageMakerConfig
									return config_class.from_yaml_file(yaml_file=lowerCAmelCase__ )



@dataclass
class _A  :
		_SCREAMING_SNAKE_CASE					:    ComputeEnvironment
		_SCREAMING_SNAKE_CASE					:    Union[DistributedType, SageMakerDistributedType]
		_SCREAMING_SNAKE_CASE					:    str
		_SCREAMING_SNAKE_CASE					:    bool





		def 							__A       (     self				)       ->     Dict:

					'''simple docstring'''
					__UpperCAmelCase   :      List[str]										=     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				):
											__UpperCAmelCase   :      List[Any]										=     value.value
								if isinstance(__UpperCAmelCase ,       __UpperCAmelCase				) and not bool(__UpperCAmelCase				):
											__UpperCAmelCase   :      Dict										=     None
					__UpperCAmelCase   :      Any										=     {k: v for k, v in result.items() if v is not None}
					return result





		@classmethod
		def 							__A       (     cls ,       __UpperCAmelCase=None				)       ->     Dict:

					'''simple docstring'''
					__UpperCAmelCase   :      Any										=     default_json_config_file if json_file is None else json_file
					with open(__UpperCAmelCase ,       """r""" ,       encoding="""utf-8"""				) as f:
								__UpperCAmelCase   :      Optional[Any]										=     json.load(__UpperCAmelCase				)
					if "compute_environment" not in config_dict:
								__UpperCAmelCase   :      Tuple										=     ComputeEnvironment.LOCAL_MACHINE
					if "mixed_precision" not in config_dict:
								__UpperCAmelCase   :      List[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.
								__UpperCAmelCase   :      Tuple										=     config_dict.pop("""dynamo_backend"""				)
								__UpperCAmelCase   :      Any										=     {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
					if "use_cpu" not in config_dict:
								__UpperCAmelCase   :      Dict										=     False
					return cls(**__UpperCAmelCase				)





		def 							__A       (     self ,       __UpperCAmelCase				)       ->     str:

					'''simple docstring'''
					with open(__UpperCAmelCase ,       """w""" ,       encoding="""utf-8"""				) as f:
								__UpperCAmelCase   :      int										=     json.dumps(self.to_dict() ,       indent=2 ,       sort_keys=__UpperCAmelCase				) + """\n"""
								f.write(__UpperCAmelCase				)





		@classmethod
		def 							__A       (     cls ,       __UpperCAmelCase=None				)       ->     Optional[int]:

					'''simple docstring'''
					__UpperCAmelCase   :      str										=     default_yaml_config_file if yaml_file is None else yaml_file
					with open(__UpperCAmelCase ,       """r""" ,       encoding="""utf-8"""				) as f:
								__UpperCAmelCase   :      int										=     yaml.safe_load(__UpperCAmelCase				)
					if "compute_environment" not in config_dict:
								__UpperCAmelCase   :      int										=     ComputeEnvironment.LOCAL_MACHINE

					if "mixed_precision" not in config_dict:
								__UpperCAmelCase   :      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"]:
								__UpperCAmelCase   :      Optional[int]										=     """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.
								__UpperCAmelCase   :      List[str]										=     config_dict.pop("""dynamo_backend"""				)
								__UpperCAmelCase   :      Optional[int]										=     {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
					if "use_cpu" not in config_dict:
								__UpperCAmelCase   :      Any										=     False
					return cls(**__UpperCAmelCase				)





		def 							__A       (     self ,       __UpperCAmelCase				)       ->     Optional[int]:

					'''simple docstring'''
					with open(__UpperCAmelCase ,       """w""" ,       encoding="""utf-8"""				) as f:
								yaml.safe_dump(self.to_dict() ,       __UpperCAmelCase				)





		def 							__A       (     self				)       ->     str:

					'''simple docstring'''
					if isinstance(self.compute_environment ,       __UpperCAmelCase				):
								__UpperCAmelCase   :      Dict										=     ComputeEnvironment(self.compute_environment				)
					if isinstance(self.distributed_type ,       __UpperCAmelCase				):
								if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
											__UpperCAmelCase   :      Union[str, Any]										=     SageMakerDistributedType(self.distributed_type				)
								else:
											__UpperCAmelCase   :      Tuple										=     DistributedType(self.distributed_type				)
					if self.dynamo_config is None:
								__UpperCAmelCase   :      List[str]										=     {}



@dataclass
class _A  (    __SCREAMING_SNAKE_CASE    ):
		_SCREAMING_SNAKE_CASE					:    int
		_SCREAMING_SNAKE_CASE					:    int						      =			0
		_SCREAMING_SNAKE_CASE					:    int						      =			1
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    Optional[int]						      =			None
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			"static"
		_SCREAMING_SNAKE_CASE					:    Optional[bool]						      =			False
		_SCREAMING_SNAKE_CASE					:    str						      =			"main"

		# args for deepspeed_plugin
		_SCREAMING_SNAKE_CASE					:    dict						      =			None
		# args for fsdp
		_SCREAMING_SNAKE_CASE					:    dict						      =			None
		# args for megatron_lm
		_SCREAMING_SNAKE_CASE					:    dict						      =			None
		# args for ipex
		_SCREAMING_SNAKE_CASE					:    dict						      =			None
		# args for TPU
		_SCREAMING_SNAKE_CASE					:    bool						      =			False

		# args for TPU pods
		_SCREAMING_SNAKE_CASE					:    str						      =			None
		_SCREAMING_SNAKE_CASE					:    str						      =			None
		_SCREAMING_SNAKE_CASE					:    bool						      =			False
		_SCREAMING_SNAKE_CASE					:    bool						      =			False
		_SCREAMING_SNAKE_CASE					:    str						      =			None
		_SCREAMING_SNAKE_CASE					:    List[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    List[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    List[str]						      =			None

		# args for dynamo
		_SCREAMING_SNAKE_CASE					:    dict						      =			None





		def 							__A       (     self				)       ->     Union[str, Any]:

					'''simple docstring'''
					if self.deepspeed_config is None:
								__UpperCAmelCase   :      Tuple										=     {}
					if self.fsdp_config is None:
								__UpperCAmelCase   :      List[str]										=     {}
					if self.megatron_lm_config is None:
								__UpperCAmelCase   :      Optional[Any]										=     {}
					if self.ipex_config is None:
								__UpperCAmelCase   :      Tuple										=     {}
					return super().__post_init__()



@dataclass
class _A  (    __SCREAMING_SNAKE_CASE    ):
		_SCREAMING_SNAKE_CASE					:    str
		_SCREAMING_SNAKE_CASE					:    str
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    str						      =			"us-east-1"
		_SCREAMING_SNAKE_CASE					:    int						      =			1
		_SCREAMING_SNAKE_CASE					:    str						      =			"all"
		_SCREAMING_SNAKE_CASE					:    str						      =			f'''accelerate-sagemaker-{num_machines}'''
		_SCREAMING_SNAKE_CASE					:    str						      =			SAGEMAKER_PYTORCH_VERSION
		_SCREAMING_SNAKE_CASE					:    str						      =			SAGEMAKER_TRANSFORMERS_VERSION
		_SCREAMING_SNAKE_CASE					:    str						      =			SAGEMAKER_PYTHON_VERSION
		_SCREAMING_SNAKE_CASE					:    str						      =			None
		_SCREAMING_SNAKE_CASE					:    str						      =			None
		_SCREAMING_SNAKE_CASE					:    dict						      =			None
		_SCREAMING_SNAKE_CASE					:    dict						      =			None









'''simple docstring'''
import torch

from transformers import AutoTokenizer



class _A  (    __SCREAMING_SNAKE_CASE    ):





		def __init__(     self ,       __UpperCAmelCase				)       ->     Union[str, Any]:

					'''simple docstring'''
					__UpperCAmelCase   :      Any										=     AutoTokenizer.from_pretrained(__UpperCAmelCase				)





		def 							__A       (     self ,       __UpperCAmelCase				)       ->     Any:

					'''simple docstring'''

					if isinstance(__UpperCAmelCase ,       __UpperCAmelCase				) and all(isinstance(_x ,       __UpperCAmelCase				) for _x in x				):
								__UpperCAmelCase   :      Dict										=     None
								for l in x:
											__UpperCAmelCase   :      Dict										=     self.tokenizer(
											    __UpperCAmelCase ,       padding="""max_length""" ,       max_length=384 ,       truncation=__UpperCAmelCase ,       return_tensors="""pt""" ,       )
											__UpperCAmelCase   :      Union[str, Any]										=     torch.tensor([len(__UpperCAmelCase				)]				)
											if d is not None:
														for k in d.keys():
																	__UpperCAmelCase   :      Dict										=     torch.cat((d[k], t[k]) ,       0				)
											else:
														__UpperCAmelCase   :      List[str]										=     t

								__UpperCAmelCase   :      Union[str, Any]										=     torch.tensor(self.tokenizer.convert_tokens_to_ids("""[E]"""				)				)
								__UpperCAmelCase   :      Any										=     torch.tensor(self.tokenizer.convert_tokens_to_ids("""[/E]"""				)				)

					elif isinstance(__UpperCAmelCase ,       __UpperCAmelCase				) and all(isinstance(_x ,       __UpperCAmelCase				) for _x in x				):
								__UpperCAmelCase   :      int										=     self.tokenizer(
								    __UpperCAmelCase ,       padding="""max_length""" ,       max_length=384 ,       truncation=__UpperCAmelCase ,       return_tensors="""pt""" ,       )

					else:
								raise Exception(
								    """Type of parameter x was not recognized! Only `list of strings` for query or `list of lists of"""
								    """ strings` for supports are supported."""				)

					return d





		def 							__A       (     self ,       __UpperCAmelCase ,       __UpperCAmelCase ,       __UpperCAmelCase ,       __UpperCAmelCase ,       __UpperCAmelCase=0.70				)       ->     Dict:

					'''simple docstring'''
					__UpperCAmelCase   :      Tuple										=     []
					for idx in range(len(W_query["""input_ids"""]				)				):
								__UpperCAmelCase   :      Optional[int]										=     range(p_start.shape[1]				)

								__UpperCAmelCase   :      Union[str, Any]										=     []
								for start_id in start_indexes:
											for end_id in end_indexes:
														if start_id < end_id:
																	output.append(
																	    (
																	        start_id,
																	        end_id,
																	        p_start[idx][start_id].item(),
																	        p_end[idx][end_id].item(),
																	    )				)

								output.sort(key=lambda __UpperCAmelCase				: (tup[2] * tup[3]) ,       reverse=__UpperCAmelCase				)
								__UpperCAmelCase   :      Optional[Any]										=     []
								for k in range(len(__UpperCAmelCase				)				):
											if output[k][2] * output[k][3] >= thresh:
														__UpperCAmelCase				,  __UpperCAmelCase   :      Tuple										=     output[k][0], output[k][1]
														__UpperCAmelCase   :      int										=     self.tokenizer.decode(W_query["""input_ids"""][idx][c_start_pos:c_end_pos]				)
														temp.append((decoded, output[k][2] * output[k][3])				)

								final_outputs.append(__UpperCAmelCase				)

					return final_outputs




