
import os

import torch

from ..logging import get_logger
from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME
from .versions import is_torch_version


if is_torch_version('>=', FSDP_PYTORCH_VERSION):
    import torch.distributed.checkpoint as dist_cp
    from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner
    from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
    from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
    from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType


__lowerCAmelCase     :	Tuple       			=  get_logger(__name__)

def a__       (			A_,	A_,	A_,	A_,	A_=0   ):






  '''simple docstring'''





  os.makedirs(A_,	exist_ok=A_   )
  with FSDP.state_dict_type(
      A_,	fsdp_plugin.state_dict_type,	fsdp_plugin.state_dict_config,	fsdp_plugin.optim_state_dict_config   ):
    __magic_name__								=			model.state_dict()
    if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
      __magic_name__								=			f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin'''
      __magic_name__								=			os.path.join(A_,	A_   )
      if accelerator.process_index == 0:
        logger.info(f'''Saving model to {output_model_file}'''   )
        torch.save(A_,	A_   )
        logger.info(f'''Model saved to {output_model_file}'''   )
    elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
      __magic_name__								=			(
          f'''{MODEL_NAME}_rank{accelerator.process_index}.bin'''
          if model_index == 0
          else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'''
      )
      __magic_name__								=			os.path.join(A_,	A_   )
      logger.info(f'''Saving model to {output_model_file}'''   )
      torch.save(A_,	A_   )
      logger.info(f'''Model saved to {output_model_file}'''   )
    elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
      __magic_name__								=			os.path.join(A_,	f'''{MODEL_NAME}_{model_index}'''   )
      os.makedirs(A_,	exist_ok=A_   )
      logger.info(f'''Saving model to {ckpt_dir}'''   )
      __magic_name__								=			{"""model""": state_dict}

      dist_cp.save_state_dict(
          state_dict=A_,	storage_writer=dist_cp.FileSystemWriter(A_   ),	planner=DefaultSavePlanner(),	)
      logger.info(f'''Model saved to {ckpt_dir}'''   )

def a__       (			A_,	A_,	A_,	A_,	A_=0   ):






  '''simple docstring'''





  accelerator.wait_for_everyone()
  with FSDP.state_dict_type(
      A_,	fsdp_plugin.state_dict_type,	fsdp_plugin.state_dict_config,	fsdp_plugin.optim_state_dict_config   ):
    if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
      if type(A_   ) != FSDP and accelerator.process_index != 0:
        if not fsdp_plugin.sync_module_states:
          raise ValueError(
              """Set the `sync_module_states` flag to `True` so that model states are synced across processes when """
              """initializing FSDP object"""   )
        return
      __magic_name__								=			f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin'''
      __magic_name__								=			os.path.join(A_,	A_   )
      logger.info(f'''Loading model from {input_model_file}'''   )
      __magic_name__								=			torch.load(A_   )
      logger.info(f'''Model loaded from {input_model_file}'''   )
    elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
      __magic_name__								=			(
          f'''{MODEL_NAME}_rank{accelerator.process_index}.bin'''
          if model_index == 0
          else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'''
      )
      __magic_name__								=			os.path.join(A_,	A_   )
      logger.info(f'''Loading model from {input_model_file}'''   )
      __magic_name__								=			torch.load(A_   )
      logger.info(f'''Model loaded from {input_model_file}'''   )
    elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
      __magic_name__								=			(
          os.path.join(A_,	f'''{MODEL_NAME}_{model_index}'''   )
          if f'''{MODEL_NAME}''' not in input_dir
          else input_dir
      )
      logger.info(f'''Loading model from {ckpt_dir}'''   )
      __magic_name__								=			{"""model""": model.state_dict()}
      dist_cp.load_state_dict(
          state_dict=A_,	storage_reader=dist_cp.FileSystemReader(A_   ),	planner=DefaultLoadPlanner(),	)
      __magic_name__								=			state_dict["""model"""]
      logger.info(f'''Model loaded from {ckpt_dir}'''   )
    model.load_state_dict(A_   )

def a__       (			A_,	A_,	A_,	A_,	A_,	A_=0   ):






  '''simple docstring'''





  os.makedirs(A_,	exist_ok=A_   )
  with FSDP.state_dict_type(
      A_,	fsdp_plugin.state_dict_type,	fsdp_plugin.state_dict_config,	fsdp_plugin.optim_state_dict_config   ):
    __magic_name__								=			FSDP.optim_state_dict(A_,	A_   )
    if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
      if accelerator.process_index == 0:
        __magic_name__								=			(
            f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin'''
        )
        __magic_name__								=			os.path.join(A_,	A_   )
        logger.info(f'''Saving Optimizer state to {output_optimizer_file}'''   )
        torch.save(A_,	A_   )
        logger.info(f'''Optimizer state saved in {output_optimizer_file}'''   )
    else:
      __magic_name__								=			os.path.join(A_,	f'''{OPTIMIZER_NAME}_{optimizer_index}'''   )
      os.makedirs(A_,	exist_ok=A_   )
      logger.info(f'''Saving Optimizer state to {ckpt_dir}'''   )
      dist_cp.save_state_dict(
          state_dict={"""optimizer""": optim_state},	storage_writer=dist_cp.FileSystemWriter(A_   ),	planner=DefaultSavePlanner(),	)
      logger.info(f'''Optimizer state saved in {ckpt_dir}'''   )





def a__       (			A_,	A_,	A_,	A_,	A_,	A_=0   ):






  '''simple docstring'''





  accelerator.wait_for_everyone()
  with FSDP.state_dict_type(
      A_,	fsdp_plugin.state_dict_type,	fsdp_plugin.state_dict_config,	fsdp_plugin.optim_state_dict_config   ):
    if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
      __magic_name__								=			None
      # below check should work but currently it isn't working (mostly opytorch issue),
      # in the meantime disabling it at the cost of excess memory usage
      # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
      __magic_name__								=			(
          f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin'''
      )
      __magic_name__								=			os.path.join(A_,	A_   )
      logger.info(f'''Loading Optimizer state from {input_optimizer_file}'''   )
      __magic_name__								=			torch.load(A_   )
      logger.info(f'''Optimizer state loaded from {input_optimizer_file}'''   )
    else:
      __magic_name__								=			(
          os.path.join(A_,	f'''{OPTIMIZER_NAME}_{optimizer_index}'''   )
          if f'''{OPTIMIZER_NAME}''' not in input_dir
          else input_dir
      )
      logger.info(f'''Loading Optimizer from {ckpt_dir}'''   )
      __magic_name__								=			load_sharded_optimizer_state_dict(
          model_state_dict=model.state_dict(),	optimizer_key="""optimizer""",	storage_reader=dist_cp.FileSystemReader(A_   ),	)
      __magic_name__								=			optim_state["""optimizer"""]
      logger.info(f'''Optimizer loaded from {ckpt_dir}'''   )
    __magic_name__								=			FSDP.optim_state_dict_to_load(A_,	A_,	A_   )
    optimizer.load_state_dict(A_   )



# 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 argparse
import os

from accelerate.utils import ComputeEnvironment

from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file  # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment  # noqa: F401
from .sagemaker import get_sagemaker_input


__lowerCAmelCase     :	Optional[Any]       			=  'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine'

def a__       (			):






  '''simple docstring'''





  __magic_name__								=			_ask_options(
      """In which compute environment are you running?""",	["""This machine""", """AWS (Amazon SageMaker)"""],	_convert_compute_environment,	)
  if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
    __magic_name__								=			get_sagemaker_input()
  else:
    __magic_name__								=			get_cluster_input()
  return config

def a__       (			A_=None   ):






  '''simple docstring'''





  if subparsers is not None:
    __magic_name__								=			subparsers.add_parser("""config""",	description=A_   )
  else:
    __magic_name__								=			argparse.ArgumentParser("""Accelerate config command""",	description=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'."""
      ),	)

  if subparsers is not None:
    parser.set_defaults(func=A_   )
  return parser

def a__       (			A_   ):






  '''simple docstring'''





  __magic_name__								=			get_user_input()
  if args.config_file is not None:
    __magic_name__								=			args.config_file
  else:
    if not os.path.isdir(A_   ):
      os.makedirs(A_   )
    __magic_name__								=			default_yaml_config_file

  if config_file.endswith(""".json"""   ):
    config.to_json_file(A_   )
  else:
    config.to_yaml_file(A_   )
  print(f'''accelerate configuration saved at {config_file}'''   )

def a__       (			):






  '''simple docstring'''





  __magic_name__								=			config_command_parser()
  __magic_name__								=			parser.parse_args()
  config_command(A_   )


if __name__ == "__main__":
    main()

