






'''simple docstring'''







from __future__ import annotations

UpperCamelCase_					=				"Alexander Joslin"






def  lowerCAmelCase__		(					a_  :     int			)   -> int:

       if number <= 0:
              UpperCAmelCase__	:   Tuple												=	f"""n must be greater than 0. Got n = {number}"""
              raise ValueError(a_			)

       UpperCAmelCase__	:   str												=	[number + 1] * (number + 1)

       # starting position
       UpperCAmelCase__	:   str												=	0
       for i in range(1			,						a_			):
              UpperCAmelCase__	:   Tuple												=	min(table[i + 1]			,						table[i] + 1			)
              # check if out of bounds
              if i * 2 <= number:
                     UpperCAmelCase__	:   List[str]												=	min(table[i * 2]			,						table[i] + 1			)
              # check if out of bounds
              if i * 3 <= number:
                     UpperCAmelCase__	:   Optional[int]												=	min(table[i * 3]			,						table[i] + 1			)
       return table[number]


if __name__ == "__main__":
  import doctest

  doctest.testmod()







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


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  lowerCAmelCase__		(					a_  :     List[Any]			)   -> Optional[Any]:
       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:
              UpperCAmelCase__	:   Dict												=	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
                     ):
                            UpperCAmelCase__	:   Optional[Any]												=	ClusterConfig
                     else:
                            UpperCAmelCase__	:   Dict												=	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
                     ):
                            UpperCAmelCase__	:   Dict												=	ClusterConfig
                     else:
                            UpperCAmelCase__	:   int												=	SageMakerConfig
                     return config_class.from_yaml_file(yaml_file=a_			)




@dataclass
class 					__UpperCAmelCase :

      '''simple docstring'''





      SCREAMING_SNAKE_CASE				:    ComputeEnvironment
      SCREAMING_SNAKE_CASE				:    Union[DistributedType, SageMakerDistributedType]
      SCREAMING_SNAKE_CASE				:    str
      SCREAMING_SNAKE_CASE				:    bool




      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   List[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						):
                           UpperCAmelCase__	:   Union[str, Any]												=	value.value
                    if isinstance(_UpperCAmelCase  ,		_UpperCAmelCase						) and not bool(_UpperCAmelCase						):
                           UpperCAmelCase__	:   Optional[int]												=	None
             UpperCAmelCase__	:   Optional[Any]												=	{k: v for k, v in result.items() if v is not None}
             return result




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




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase						):
             with open(_UpperCAmelCase  ,		'''w'''  ,		encoding='''utf-8'''						) as f:
                    UpperCAmelCase__	:   Any												=	json.dumps(self.to_dict()  ,		indent=2  ,		sort_keys=_UpperCAmelCase						) + '''\n'''
                    f.write(_UpperCAmelCase						)




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

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




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




      def 							lowerCamelCase     (					self						):
             if isinstance(self.compute_environment  ,		_UpperCAmelCase						):
                    UpperCAmelCase__	:   Tuple												=	ComputeEnvironment(self.compute_environment						)
             if isinstance(self.distributed_type  ,		_UpperCAmelCase						):
                    if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                           UpperCAmelCase__	:   Optional[Any]												=	SageMakerDistributedType(self.distributed_type						)
                    else:
                           UpperCAmelCase__	:   Dict												=	DistributedType(self.distributed_type						)
             if self.dynamo_config is None:
                    UpperCAmelCase__	:   Optional[Any]												=	{}




@dataclass
class 					__UpperCAmelCase (		UpperCamelCase__	):

      '''simple docstring'''





      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 							lowerCamelCase     (					self						):
             if self.deepspeed_config is None:
                    UpperCAmelCase__	:   Union[str, Any]												=	{}
             if self.fsdp_config is None:
                    UpperCAmelCase__	:   Any												=	{}
             if self.megatron_lm_config is None:
                    UpperCAmelCase__	:   Tuple												=	{}
             if self.ipex_config is None:
                    UpperCAmelCase__	:   List[str]												=	{}
             return super().__post_init__()




@dataclass
class 					__UpperCAmelCase (		UpperCamelCase__	):

      '''simple docstring'''





      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