


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      :			Tuple      				=   get_logger(__name__)
def       UpperCAmelCase__						(UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_=0    ):



     """simple docstring"""






     os.makedirs(UpperCamelCase_							,exist_ok=UpperCamelCase_    )
     with FSDP.state_dict_type(
         UpperCamelCase_							,fsdp_plugin.state_dict_type							,fsdp_plugin.state_dict_config							,fsdp_plugin.optim_state_dict_config    ):
          snake_case					=    model.state_dict()
          if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
               snake_case					=    F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin'''
               snake_case					=    os.path.join(UpperCamelCase_							,UpperCamelCase_    )
               if accelerator.process_index == 0:
                    logger.info(F'''Saving model to {output_model_file}'''    )
                    torch.save(UpperCamelCase_							,UpperCamelCase_    )
                    logger.info(F'''Model saved to {output_model_file}'''    )
          elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
               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'''
               )
               snake_case					=    os.path.join(UpperCamelCase_							,UpperCamelCase_    )
               logger.info(F'''Saving model to {output_model_file}'''    )
               torch.save(UpperCamelCase_							,UpperCamelCase_    )
               logger.info(F'''Model saved to {output_model_file}'''    )
          elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
               snake_case					=    os.path.join(UpperCamelCase_							,F'''{MODEL_NAME}_{model_index}'''    )
               os.makedirs(UpperCamelCase_							,exist_ok=UpperCamelCase_    )
               logger.info(F'''Saving model to {ckpt_dir}'''    )
               snake_case					=    {'''model''': state_dict}

               dist_cp.save_state_dict(
                   state_dict=UpperCamelCase_							,storage_writer=dist_cp.FileSystemWriter(UpperCamelCase_    )							,planner=DefaultSavePlanner()							,)
               logger.info(F'''Model saved to {ckpt_dir}'''    )
def       UpperCAmelCase__						(UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_=0    ):



     """simple docstring"""






     accelerator.wait_for_everyone()
     with FSDP.state_dict_type(
         UpperCamelCase_							,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(UpperCamelCase_    ) != 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
               snake_case					=    F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin'''
               snake_case					=    os.path.join(UpperCamelCase_							,UpperCamelCase_    )
               logger.info(F'''Loading model from {input_model_file}'''    )
               snake_case					=    torch.load(UpperCamelCase_    )
               logger.info(F'''Model loaded from {input_model_file}'''    )
          elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
               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'''
               )
               snake_case					=    os.path.join(UpperCamelCase_							,UpperCamelCase_    )
               logger.info(F'''Loading model from {input_model_file}'''    )
               snake_case					=    torch.load(UpperCamelCase_    )
               logger.info(F'''Model loaded from {input_model_file}'''    )
          elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
               snake_case					=    (
                   os.path.join(UpperCamelCase_							,F'''{MODEL_NAME}_{model_index}'''    )
                   if F'''{MODEL_NAME}''' not in input_dir
                   else input_dir
               )
               logger.info(F'''Loading model from {ckpt_dir}'''    )
               snake_case					=    {'''model''': model.state_dict()}
               dist_cp.load_state_dict(
                   state_dict=UpperCamelCase_							,storage_reader=dist_cp.FileSystemReader(UpperCamelCase_    )							,planner=DefaultLoadPlanner()							,)
               snake_case					=    state_dict['''model''']
               logger.info(F'''Model loaded from {ckpt_dir}'''    )
          model.load_state_dict(UpperCamelCase_    )
def       UpperCAmelCase__						(UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_=0    ):



     """simple docstring"""






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

def       UpperCAmelCase__						(UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_=0    ):



     """simple docstring"""






     accelerator.wait_for_everyone()
     with FSDP.state_dict_type(
         UpperCamelCase_							,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:
               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:
               snake_case					=    (
                   F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin'''
               )
               snake_case					=    os.path.join(UpperCamelCase_							,UpperCamelCase_    )
               logger.info(F'''Loading Optimizer state from {input_optimizer_file}'''    )
               snake_case					=    torch.load(UpperCamelCase_    )
               logger.info(F'''Optimizer state loaded from {input_optimizer_file}'''    )
          else:
               snake_case					=    (
                   os.path.join(UpperCamelCase_							,F'''{OPTIMIZER_NAME}_{optimizer_index}'''    )
                   if F'''{OPTIMIZER_NAME}''' not in input_dir
                   else input_dir
               )
               logger.info(F'''Loading Optimizer from {ckpt_dir}'''    )
               snake_case					=    load_sharded_optimizer_state_dict(
                   model_state_dict=model.state_dict()							,optimizer_key='''optimizer'''							,storage_reader=dist_cp.FileSystemReader(UpperCamelCase_    )							,)
               snake_case					=    optim_state['''optimizer''']
               logger.info(F'''Optimizer loaded from {ckpt_dir}'''    )
          snake_case					=    FSDP.optim_state_dict_to_load(UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_    )
          optimizer.load_state_dict(UpperCamelCase_    )








import argparse
import copy
def       UpperCAmelCase__						(UpperCamelCase_    ):



     """simple docstring"""






     snake_case					=    {}

     with open(UpperCamelCase_    ) as f:
          for line in f:
               if line.split()[0] not in dict_of_neighbours:
                    snake_case					=    []
                    _list.append([line.split()[1], line.split()[2]]    )
                    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:
                    snake_case					=    []
                    _list.append([line.split()[0], line.split()[2]]    )
                    snake_case					=    _list
               else:
                    dict_of_neighbours[line.split()[1]].append(
                        [line.split()[0], line.split()[2]]    )

     return dict_of_neighbours
def       UpperCAmelCase__						(UpperCamelCase_							,UpperCamelCase_    ):



     """simple docstring"""






     with open(UpperCamelCase_    ) as f:
          snake_case					=    f.read(1    )
     snake_case					=    start_node

     snake_case					=    []

     snake_case					=    start_node

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

          first_solution.append(UpperCamelCase_    )
          snake_case					=    distance_of_first_solution + int(UpperCamelCase_    )
          snake_case					=    best_node

     first_solution.append(UpperCamelCase_    )

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

     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__						(UpperCamelCase_							,UpperCamelCase_    ):



     """simple docstring"""






     snake_case					=    []

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

               snake_case					=    copy.deepcopy(UpperCamelCase_    )
               snake_case					=    kn
               snake_case					=    n

               snake_case					=    0

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

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

     snake_case					=    len(neighborhood_of_solution[0]    ) - 1

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



     """simple docstring"""






     snake_case					=    1
     snake_case					=    first_solution
     snake_case					=    []
     snake_case					=    distance_of_first_solution
     snake_case					=    solution

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

          snake_case					=    False
          while not found:
               snake_case					=    0
               while i < len(UpperCamelCase_    ):
                    if best_solution[i] != solution[i]:
                         snake_case					=    best_solution[i]
                         snake_case					=    solution[i]
                         break
                    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]    )
                    snake_case					=    True
                    snake_case					=    best_solution[:-1]
                    snake_case					=    neighborhood[index_of_best_solution][best_cost_index]
                    if cost < best_cost:
                         snake_case					=    cost
                         snake_case					=    solution
               else:
                    snake_case					=    index_of_best_solution + 1
                    snake_case					=    neighborhood[index_of_best_solution]

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

          snake_case					=    count + 1

     return best_solution_ever, best_cost
def       UpperCAmelCase__						(UpperCamelCase_=None    ):



     """simple docstring"""






     snake_case					=    generate_neighbours(args.File    )

     snake_case			,  snake_case					=    generate_first_solution(
         args.File							,UpperCamelCase_    )

     snake_case			,  snake_case					=    tabu_search(
         UpperCamelCase_							,UpperCamelCase_							,UpperCamelCase_							,args.Iterations							,args.Size							,)

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


if __name__ == "__main__":
 _SCREAMING_SNAKE_CASE      :			Optional[Any]      				=   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())




