


'''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.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


__UpperCAmelCase       =							'''Create a default config file for Accelerate with only a few flags set.'''


def  _snake_case       (					A="no"			,   A = default_json_config_file			,   A = False	)						->   Dict:
							lowerCAmelCase__	       =     Path(A	)
							path.parent.mkdir(parents=A			,   exist_ok=A	)
							if path.exists():
														print(
														    F"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."""	)
														return False
							lowerCAmelCase__	       =     mixed_precision.lower()
							if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
														raise ValueError(
														    F"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"""	)
							lowerCAmelCase__	       =     {
							    '''compute_environment''': '''LOCAL_MACHINE''',
							    '''mixed_precision''': mixed_precision,
							}
							if torch.cuda.is_available():
														lowerCAmelCase__	       =     torch.cuda.device_count()
														lowerCAmelCase__	       =     num_gpus
														lowerCAmelCase__	       =     False
														if num_gpus > 1:
																					lowerCAmelCase__	       =     '''MULTI_GPU'''
														else:
																					lowerCAmelCase__	       =     '''NO'''
							elif is_xpu_available() and use_xpu:
														lowerCAmelCase__	       =     torch.xpu.device_count()
														lowerCAmelCase__	       =     num_xpus
														lowerCAmelCase__	       =     False
														if num_xpus > 1:
																					lowerCAmelCase__	       =     '''MULTI_XPU'''
														else:
																					lowerCAmelCase__	       =     '''NO'''
							elif is_npu_available():
														lowerCAmelCase__	       =     torch.npu.device_count()
														lowerCAmelCase__	       =     num_npus
														lowerCAmelCase__	       =     False
														if num_npus > 1:
																					lowerCAmelCase__	       =     '''MULTI_NPU'''
														else:
																					lowerCAmelCase__	       =     '''NO'''
							else:
														lowerCAmelCase__	       =     0
														lowerCAmelCase__	       =     True
														lowerCAmelCase__	       =     1
														lowerCAmelCase__	       =     '''NO'''
							lowerCAmelCase__	       =     ClusterConfig(**A	)
							config.to_json_file(A	)
							return path


def  _snake_case       (					A			,   A	)						->   Optional[int]:
							lowerCAmelCase__	       =     parser.add_parser('''default'''			,   parents=A			,   help=A			,   formatter_class=A	)
							parser.add_argument(
							    '''--config_file'''			,   default=A			,   help=(
							        '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
							        '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
							        '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
							        '''with \'huggingface\'.'''
							    )			,   dest='''save_location'''			,   )

							parser.add_argument(
							    '''--mixed_precision'''			,   choices=['''no''', '''fp16''', '''bf16''']			,   type=A			,   help='''Whether or not to use mixed precision training. '''
							    '''Choose between FP16 and BF16 (bfloat16) training. '''
							    '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.'''			,   default='''no'''			,   )
							parser.set_defaults(func=A	)
							return parser






def  _snake_case       (					A	)						->   int:
							lowerCAmelCase__	       =     write_basic_config(args.mixed_precision			,   args.save_location	)
							if config_file:
														print(F"""accelerate configuration saved at {config_file}"""	)



'''simple docstring'''






import os
from typing import Optional

import fsspec
from fsspec.archive import AbstractArchiveFileSystem
from fsspec.utils import DEFAULT_BLOCK_SIZE




class 		a__    (							a__  ):





							'''simple docstring'''






							lowercase__      :       Dict     						=				""
							lowercase__      :       str     						=				(
							    None  # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz
							)
							lowercase__      :       str     						=				None  # compression type in fsspec. ex: "gzip"
							lowercase__      :       str     						=				None  # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz







							def __init__(		self ,   lowerCamelCase_ = "" ,   lowerCamelCase_ = None ,   lowerCamelCase_ = None ,   **lowerCamelCase_       )	->							Any:
														super().__init__(self ,   **lowerCamelCase_       )
														# always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode
														lowerCAmelCase__	       =     fsspec.open(
														    lowerCamelCase_ ,   mode='''rb''' ,   protocol=lowerCamelCase_ ,   compression=self.compression ,   client_kwargs={
														        '''requote_redirect_url''': False,  # see https://github.com/huggingface/datasets/pull/5459
														        '''trust_env''': True,  # Enable reading proxy env variables.
														        **(target_options or {}).pop('''client_kwargs''' ,   {}       ),  # To avoid issues if it was already passed.
														    } ,   **(target_options or {}) ,   )
														lowerCAmelCase__	       =     os.path.basename(self.file.path.split('''::'''       )[0]       )
														lowerCAmelCase__	       =     (
														    self.compressed_name[: self.compressed_name.rindex('''.'''       )]
														    if '''.''' in self.compressed_name
														    else self.compressed_name
														)
														lowerCAmelCase__	       =     None







							@classmethod
							def   __SCREAMING_SNAKE_CASE							(		cls ,   lowerCamelCase_       )	->							Any:
														# compressed file paths are always relative to the archive root
														return super()._strip_protocol(lowerCamelCase_       ).lstrip('''/'''       )







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Optional[int]:
														if self.dir_cache is None:
																					lowerCAmelCase__	       =     {**self.file.fs.info(self.file.path       ), '''name''': self.uncompressed_name}
																					lowerCAmelCase__	       =     {f['''name''']: f}







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_       )	->							List[Any]:
														return self.file.open().read()







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_ ,   lowerCamelCase_ = "rb" ,   lowerCamelCase_=None ,   lowerCamelCase_=True ,   lowerCamelCase_=None ,   **lowerCamelCase_ ,   )	->							List[str]:
														lowerCAmelCase__	       =     self._strip_protocol(lowerCamelCase_       )
														if mode != "rb":
																					raise ValueError(F"""Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'"""       )
														return self.file.open()




class 		a__    (							a__  ):





							'''simple docstring'''






							lowercase__      :       Optional[Any]     						=				"bz2"
							lowercase__      :       str     						=				"bz2"
							lowercase__      :       Optional[int]     						=				".bz2"




class 		a__    (							a__  ):





							'''simple docstring'''






							lowercase__      :       Any     						=				"gzip"
							lowercase__      :       int     						=				"gzip"
							lowercase__      :       int     						=				".gz"




class 		a__    (							a__  ):





							'''simple docstring'''






							lowercase__      :       Tuple     						=				"lz4"
							lowercase__      :       Optional[Any]     						=				"lz4"
							lowercase__      :       int     						=				".lz4"




class 		a__    (							a__  ):





							'''simple docstring'''






							lowercase__      :       Optional[int]     						=				"xz"
							lowercase__      :       str     						=				"xz"
							lowercase__      :       List[Any]     						=				".xz"




class 		a__    (							a__  ):





							'''simple docstring'''






							lowercase__      :       Union[str, Any]     						=				"zstd"
							lowercase__      :       Union[str, Any]     						=				"zstd"
							lowercase__      :       Dict     						=				".zst"







							def __init__(		self ,   lowerCamelCase_ ,   lowerCamelCase_ = "rb" ,   lowerCamelCase_ = None ,   lowerCamelCase_ = None ,   lowerCamelCase_ = DEFAULT_BLOCK_SIZE ,   **lowerCamelCase_ ,   )	->							List[Any]:
														super().__init__(
														    fo=lowerCamelCase_ ,   mode=lowerCamelCase_ ,   target_protocol=lowerCamelCase_ ,   target_options=lowerCamelCase_ ,   block_size=lowerCamelCase_ ,   **lowerCamelCase_ ,   )
														# We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2:
														#
														# File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open
														#     out.close = close
														# AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only
														#
														# see https://github.com/intake/filesystem_spec/issues/725
														lowerCAmelCase__	       =     self.file.__enter__




														class 		a__    :





																					'''simple docstring'''






																					def __init__(		self ,   lowerCamelCase_       )	->							List[str]:
																												lowerCAmelCase__	       =     file_







																					def __enter__(		self       )	->							Tuple:
																												self._file.__enter__()
																												return self







																					def __exit__(		self ,   *lowerCamelCase_ ,   **lowerCamelCase_       )	->							str:
																												self._file.__exit__(*lowerCamelCase_ ,   **lowerCamelCase_       )







																					def __iter__(		self       )	->							Any:
																												return iter(self._file       )







																					def   __SCREAMING_SNAKE_CASE							(		self       )	->							Union[str, Any]:
																												return next(self._file       )







																					def __getattr__(		self ,   lowerCamelCase_       )	->							str:
																												return getattr(self._file ,   lowerCamelCase_       )

														def fixed_enter(*lowerCamelCase_ ,   **lowerCamelCase_       ):
																					return WrappedFile(_enter(*lowerCamelCase_ ,   **lowerCamelCase_       )       )

														lowerCAmelCase__	       =     fixed_enter