

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


_SCREAMING_SNAKE_CASE					:  int             =      get_logger(__name__)
def     UpperCAmelCase_       (						_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    ):
          SCREAMING_SNAKE_CASE__   =   model.state_dict()
          if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
               SCREAMING_SNAKE_CASE__   =   F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin'''
               SCREAMING_SNAKE_CASE__   =   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:
               SCREAMING_SNAKE_CASE__   =   (
                   F'''{MODEL_NAME}_rank{accelerator.process_index}.bin'''
                   if model_index == 0
                   else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'''
               )
               SCREAMING_SNAKE_CASE__   =   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:
               SCREAMING_SNAKE_CASE__   =   os.path.join(_A				,		F'''{MODEL_NAME}_{model_index}'''    )
               os.makedirs(_A				,		exist_ok=_A    )
               logger.info(F'''Saving model to {ckpt_dir}'''    )
               SCREAMING_SNAKE_CASE__   =   {'''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     UpperCAmelCase_       (						_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
               SCREAMING_SNAKE_CASE__   =   F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin'''
               SCREAMING_SNAKE_CASE__   =   os.path.join(_A				,		_A    )
               logger.info(F'''Loading model from {input_model_file}'''    )
               SCREAMING_SNAKE_CASE__   =   torch.load(_A    )
               logger.info(F'''Model loaded from {input_model_file}'''    )
          elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
               SCREAMING_SNAKE_CASE__   =   (
                   F'''{MODEL_NAME}_rank{accelerator.process_index}.bin'''
                   if model_index == 0
                   else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'''
               )
               SCREAMING_SNAKE_CASE__   =   os.path.join(_A				,		_A    )
               logger.info(F'''Loading model from {input_model_file}'''    )
               SCREAMING_SNAKE_CASE__   =   torch.load(_A    )
               logger.info(F'''Model loaded from {input_model_file}'''    )
          elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
               SCREAMING_SNAKE_CASE__   =   (
                   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}'''    )
               SCREAMING_SNAKE_CASE__   =   {'''model''': model.state_dict()}
               dist_cp.load_state_dict(
                   state_dict=_A				,		storage_reader=dist_cp.FileSystemReader(_A    )				,		planner=DefaultLoadPlanner()				,		)
               SCREAMING_SNAKE_CASE__   =   state_dict['''model''']
               logger.info(F'''Model loaded from {ckpt_dir}'''    )
          model.load_state_dict(_A    )
def     UpperCAmelCase_       (						_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    ):
          SCREAMING_SNAKE_CASE__   =   FSDP.optim_state_dict(_A				,		_A    )
          if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
               if accelerator.process_index == 0:
                    SCREAMING_SNAKE_CASE__   =   (
                        F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin'''
                    )
                    SCREAMING_SNAKE_CASE__   =   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:
               SCREAMING_SNAKE_CASE__   =   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     UpperCAmelCase_       (						_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:
               SCREAMING_SNAKE_CASE__   =   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:
               SCREAMING_SNAKE_CASE__   =   (
                   F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin'''
               )
               SCREAMING_SNAKE_CASE__   =   os.path.join(_A				,		_A    )
               logger.info(F'''Loading Optimizer state from {input_optimizer_file}'''    )
               SCREAMING_SNAKE_CASE__   =   torch.load(_A    )
               logger.info(F'''Optimizer state loaded from {input_optimizer_file}'''    )
          else:
               SCREAMING_SNAKE_CASE__   =   (
                   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}'''    )
               SCREAMING_SNAKE_CASE__   =   load_sharded_optimizer_state_dict(
                   model_state_dict=model.state_dict()				,		optimizer_key='''optimizer'''				,		storage_reader=dist_cp.FileSystemReader(_A    )				,		)
               SCREAMING_SNAKE_CASE__   =   optim_state['''optimizer''']
               logger.info(F'''Optimizer loaded from {ckpt_dir}'''    )
          SCREAMING_SNAKE_CASE__   =   FSDP.optim_state_dict_to_load(_A				,		_A				,		_A    )
          optimizer.load_state_dict(_A    )





import argparse
import copy
def     UpperCAmelCase_       (						_A    ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__   =   {}

     with open(_A    ) as f:
          for line in f:
               if line.split()[0] not in dict_of_neighbours:
                    SCREAMING_SNAKE_CASE__   =   []
                    _list.append([line.split()[1], line.split()[2]]    )
                    SCREAMING_SNAKE_CASE__   =   _list
               else:
                    dict_of_neighbours[line.split()[0]].append(
                        [line.split()[1], line.split()[2]]    )
               if line.split()[1] not in dict_of_neighbours:
                    SCREAMING_SNAKE_CASE__   =   []
                    _list.append([line.split()[0], line.split()[2]]    )
                    SCREAMING_SNAKE_CASE__   =   _list
               else:
                    dict_of_neighbours[line.split()[1]].append(
                        [line.split()[0], line.split()[2]]    )

     return dict_of_neighbours
def     UpperCAmelCase_       (						_A				,		_A    ):





     '''simple docstring'''




     with open(_A    ) as f:
          SCREAMING_SNAKE_CASE__   =   f.read(1    )
     SCREAMING_SNAKE_CASE__   =   start_node

     SCREAMING_SNAKE_CASE__   =   []

     SCREAMING_SNAKE_CASE__   =   start_node

     SCREAMING_SNAKE_CASE__   =   0
     while visiting not in first_solution:
          SCREAMING_SNAKE_CASE__   =   1_00_00
          for k in dict_of_neighbours[visiting]:
               if int(k[1]    ) < int(_A    ) and k[0] not in first_solution:
                    SCREAMING_SNAKE_CASE__   =   k[1]
                    SCREAMING_SNAKE_CASE__   =   k[0]

          first_solution.append(_A    )
          SCREAMING_SNAKE_CASE__   =   distance_of_first_solution + int(_A    )
          SCREAMING_SNAKE_CASE__   =   best_node

     first_solution.append(_A    )

     SCREAMING_SNAKE_CASE__   =   0
     for k in dict_of_neighbours[first_solution[-2]]:
          if k[0] == start_node:
               break
          position += 1

     SCREAMING_SNAKE_CASE__   =   (
         distance_of_first_solution
         + int(dict_of_neighbours[first_solution[-2]][position][1]    )
         - 1_00_00
     )
     return first_solution, distance_of_first_solution
def     UpperCAmelCase_       (						_A				,		_A    ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__   =   []

     for n in solution[1:-1]:
          SCREAMING_SNAKE_CASE__   =   solution.index(_A    )
          for kn in solution[1:-1]:
               SCREAMING_SNAKE_CASE__   =   solution.index(_A    )
               if n == kn:
                    continue

               SCREAMING_SNAKE_CASE__   =   copy.deepcopy(_A    )
               SCREAMING_SNAKE_CASE__   =   kn
               SCREAMING_SNAKE_CASE__   =   n

               SCREAMING_SNAKE_CASE__   =   0

               for k in _tmp[:-1]:
                    SCREAMING_SNAKE_CASE__   =   _tmp[_tmp.index(_A    ) + 1]
                    for i in dict_of_neighbours[k]:
                         if i[0] == next_node:
                              SCREAMING_SNAKE_CASE__   =   distance + int(i[1]    )
               _tmp.append(_A    )

               if _tmp not in neighborhood_of_solution:
                    neighborhood_of_solution.append(_tmp    )

     SCREAMING_SNAKE_CASE__   =   len(neighborhood_of_solution[0]    ) - 1

     neighborhood_of_solution.sort(key=lambda _A    : x[index_of_last_item_in_the_list]    )
     return neighborhood_of_solution
def     UpperCAmelCase_       (						_A				,		_A				,		_A				,		_A				,		_A    ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__   =   1
     SCREAMING_SNAKE_CASE__   =   first_solution
     SCREAMING_SNAKE_CASE__   =   []
     SCREAMING_SNAKE_CASE__   =   distance_of_first_solution
     SCREAMING_SNAKE_CASE__   =   solution

     while count <= iters:
          SCREAMING_SNAKE_CASE__   =   find_neighborhood(_A				,		_A    )
          SCREAMING_SNAKE_CASE__   =   0
          SCREAMING_SNAKE_CASE__   =   neighborhood[index_of_best_solution]
          SCREAMING_SNAKE_CASE__   =   len(_A    ) - 1

          SCREAMING_SNAKE_CASE__   =   False
          while not found:
               SCREAMING_SNAKE_CASE__   =   0
               while i < len(_A    ):
                    if best_solution[i] != solution[i]:
                         SCREAMING_SNAKE_CASE__   =   best_solution[i]
                         SCREAMING_SNAKE_CASE__   =   solution[i]
                         break
                    SCREAMING_SNAKE_CASE__   =   i + 1

               if [first_exchange_node, second_exchange_node] not in tabu_list and [
                   second_exchange_node,
                   first_exchange_node,
               ] not in tabu_list:
                    tabu_list.append([first_exchange_node, second_exchange_node]    )
                    SCREAMING_SNAKE_CASE__   =   True
                    SCREAMING_SNAKE_CASE__   =   best_solution[:-1]
                    SCREAMING_SNAKE_CASE__   =   neighborhood[index_of_best_solution][best_cost_index]
                    if cost < best_cost:
                         SCREAMING_SNAKE_CASE__   =   cost
                         SCREAMING_SNAKE_CASE__   =   solution
               else:
                    SCREAMING_SNAKE_CASE__   =   index_of_best_solution + 1
                    SCREAMING_SNAKE_CASE__   =   neighborhood[index_of_best_solution]

          if len(_A    ) >= size:
               tabu_list.pop(0    )

          SCREAMING_SNAKE_CASE__   =   count + 1

     return best_solution_ever, best_cost
def     UpperCAmelCase_       (						_A=None    ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__   =   generate_neighbours(args.File    )

     SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__   =   generate_first_solution(
         args.File				,		_A    )

     SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__   =   tabu_search(
         _A				,		_A				,		_A				,		args.Iterations				,		args.Size				,		)

     print(F'''Best solution: {best_sol}, with total distance: {best_cost}.'''    )


if __name__ == "__main__":
       _SCREAMING_SNAKE_CASE					:  Tuple             =      argparse.ArgumentParser(description='''Tabu Search''')
       parser.add_argument(
           '''-f''',
           '''--File''',
           type=str,
           help='''Path to the file containing the data''',
           required=True,
       )
       parser.add_argument(
           '''-i''',
           '''--Iterations''',
           type=int,
           help='''How many iterations the algorithm should perform''',
           required=True,
       )
       parser.add_argument(
           '''-s''', '''--Size''', type=int, help='''Size of the tabu list''', required=True
       )

       # Pass the arguments to main method
       main(parser.parse_args())


