"""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


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





def  lowerCAmelCase__     (      _UpperCamelCase							:					Dict       )       ->					str:





						"""simple docstring"""






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



@dataclass
class 	lowerCAmelCase_     :



				"""simple docstring"""
				_lowerCAmelCase  :     ComputeEnvironment
				_lowerCAmelCase  :     Union[DistributedType, SageMakerDistributedType]
				_lowerCAmelCase  :     str
				_lowerCAmelCase  :     bool

				def 		snake_case			(					self     ):






										"""simple docstring"""

										snake_case             =      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(lowerCAmelCase		,     lowerCAmelCase     ):
																						snake_case             =      value.value
																if isinstance(lowerCAmelCase		,     lowerCAmelCase     ) and not bool(lowerCAmelCase     ):
																						snake_case             =      None
										snake_case             =      {k: v for k, v in result.items() if v is not None}
										return result

				@classmethod
				def 		snake_case			(					cls		,     lowerCAmelCase=None     ):






										"""simple docstring"""

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

				def 		snake_case			(					self		,     lowerCAmelCase     ):






										"""simple docstring"""

										with open(lowerCAmelCase		,     'w'		,     encoding='utf-8'     ) as f:
																snake_case             =      json.dumps(self.to_dict()		,     indent=2		,     sort_keys=lowerCAmelCase     ) + '\n'
																f.write(lowerCAmelCase     )

				@classmethod
				def 		snake_case			(					cls		,     lowerCAmelCase=None     ):






										"""simple docstring"""

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

										if "mixed_precision" not in config_dict:
																snake_case             =      'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
										if isinstance(config_dict['mixed_precision']		,     lowerCAmelCase     ) and not config_dict["mixed_precision"]:
																snake_case             =      '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.
																snake_case             =      config_dict.pop('dynamo_backend'     )
																snake_case             =      {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
										if "use_cpu" not in config_dict:
																snake_case             =      False
										return cls(**lowerCAmelCase     )

				def 		snake_case			(					self		,     lowerCAmelCase     ):






										"""simple docstring"""

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

				def 		snake_case			(					self     ):






										"""simple docstring"""

										if isinstance(self.compute_environment		,     lowerCAmelCase     ):
																snake_case             =      ComputeEnvironment(self.compute_environment     )
										if isinstance(self.distributed_type		,     lowerCAmelCase     ):
																if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																						snake_case             =      SageMakerDistributedType(self.distributed_type     )
																else:
																						snake_case             =      DistributedType(self.distributed_type     )
										if self.dynamo_config is None:
																snake_case             =      {}





@dataclass
class 	lowerCAmelCase_     (      lowerCAmelCase       ):



				"""simple docstring"""
				_lowerCAmelCase  :     int
				_lowerCAmelCase  :     int      	=    0
				_lowerCAmelCase  :     int      	=    1
				_lowerCAmelCase  :     Optional[str]      	=    None
				_lowerCAmelCase  :     Optional[str]      	=    None
				_lowerCAmelCase  :     Optional[int]      	=    None
				_lowerCAmelCase  :     Optional[str]      	=    "static"
				_lowerCAmelCase  :     Optional[bool]      	=    False
				_lowerCAmelCase  :     str      	=    "main"

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

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

				# args for dynamo
				_lowerCAmelCase  :     dict      	=    None

				def 		snake_case			(					self     ):






										"""simple docstring"""

										if self.deepspeed_config is None:
																snake_case             =      {}
										if self.fsdp_config is None:
																snake_case             =      {}
										if self.megatron_lm_config is None:
																snake_case             =      {}
										if self.ipex_config is None:
																snake_case             =      {}
										return super().__post_init__()





@dataclass
class 	lowerCAmelCase_     (      lowerCAmelCase       ):



				"""simple docstring"""
				_lowerCAmelCase  :     str
				_lowerCAmelCase  :     str
				_lowerCAmelCase  :     Optional[str]      	=    None
				_lowerCAmelCase  :     Optional[str]      	=    None
				_lowerCAmelCase  :     str      	=    "us-east-1"
				_lowerCAmelCase  :     int      	=    1
				_lowerCAmelCase  :     str      	=    "all"
				_lowerCAmelCase  :     str      	=    F"""accelerate-sagemaker-{num_machines}"""
				_lowerCAmelCase  :     str      	=    SAGEMAKER_PYTORCH_VERSION
				_lowerCAmelCase  :     str      	=    SAGEMAKER_TRANSFORMERS_VERSION
				_lowerCAmelCase  :     str      	=    SAGEMAKER_PYTHON_VERSION
				_lowerCAmelCase  :     str      	=    None
				_lowerCAmelCase  :     str      	=    None
				_lowerCAmelCase  :     dict      	=    None
				_lowerCAmelCase  :     dict      	=    None



"""simple docstring"""
import math
from collections.abc import Generator





def  lowerCAmelCase__     (      _UpperCamelCase							:					int       )       ->					Generator[int, None, None]:





						"""simple docstring"""






						snake_case             =      (i for i in range(1			,      (max_n + 1)       ))
						for i in (n for n in numbers if n > 1):
												for j in range(2			,      _UpperCamelCase       ):
																		if (i % j) == 0:
																								break
												else:
																		yield i





def  lowerCAmelCase__     (      _UpperCamelCase							:					int       )       ->					Generator[int, None, None]:





						"""simple docstring"""






						snake_case             =      (i for i in range(1			,      (max_n + 1)       ))
						for i in (n for n in numbers if n > 1):
												# only need to check for factors up to sqrt(i)
												snake_case             =      int(math.sqrt(_UpperCamelCase       )       ) + 1
												for j in range(2			,      _UpperCamelCase       ):
																		if (i % j) == 0:
																								break
												else:
																		yield i





def  lowerCAmelCase__     (      _UpperCamelCase							:					int       )       ->					Generator[int, None, None]:





						"""simple docstring"""






						snake_case             =      (i for i in range(1			,      (max_n + 1)			,      2       ))
						# It's useless to test even numbers as they will not be prime
						if max_n > 2:
												yield 2  # Because 2 will not be tested, it's necessary to yield it now
						for i in (n for n in numbers if n > 1):
												snake_case             =      int(math.sqrt(_UpperCamelCase       )       ) + 1
												for j in range(3			,      _UpperCamelCase			,      2       ):
																		# As we removed the even numbers, we don't need them now
																		if (i % j) == 0:
																								break
												else:
																		yield i





def  lowerCAmelCase__     (      )       ->					List[str]:





						"""simple docstring"""






						from timeit import timeit

						snake_case             =      'from __main__ import slow_primes, primes, fast_primes'
						print(timeit('slow_primes(1_000_000_000_000)'			,      setup=_UpperCamelCase			,      number=1_0_0_0_0_0_0       )       )
						print(timeit('primes(1_000_000_000_000)'			,      setup=_UpperCamelCase			,      number=1_0_0_0_0_0_0       )       )
						print(timeit('fast_primes(1_000_000_000_000)'			,      setup=_UpperCamelCase			,      number=1_0_0_0_0_0_0       )       )


if __name__ == "__main__":
					SCREAMING_SNAKE_CASE__       =	int(input("Calculate primes up to:\n>> ").strip())
					for ret in primes(number):
										print(ret)
					benchmark()


