






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

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


__UpperCamelCase   :							Optional[int]         =   """Create a default config file for Accelerate with only a few flags set."""



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						int="no",       SCREAMING_SNAKE_CASE__:						str = default_json_config_file,       SCREAMING_SNAKE_CASE__:						bool = False     )	->      List[str]:

   """simple docstring"""
   __a					  =     Path(SCREAMING_SNAKE_CASE__     )
   path.parent.mkdir(parents=SCREAMING_SNAKE_CASE__,       exist_ok=SCREAMING_SNAKE_CASE__     )
   if path.exists():
      print(
          f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."""     )
      return False
   __a					  =     mixed_precision.lower()
   if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
      raise ValueError(
          f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"""     )
   __a					  =     {
       'compute_environment': 'LOCAL_MACHINE',
       'mixed_precision': mixed_precision,
   }
   if torch.cuda.is_available():
      __a					  =     torch.cuda.device_count()
      __a					  =     num_gpus
      __a					  =     False
      if num_gpus > 1:
         __a					  =     'MULTI_GPU'
      else:
         __a					  =     'NO'
   elif is_xpu_available() and use_xpu:
      __a					  =     torch.xpu.device_count()
      __a					  =     num_xpus
      __a					  =     False
      if num_xpus > 1:
         __a					  =     'MULTI_XPU'
      else:
         __a					  =     'NO'
   elif is_npu_available():
      __a					  =     torch.npu.device_count()
      __a					  =     num_npus
      __a					  =     False
      if num_npus > 1:
         __a					  =     'MULTI_NPU'
      else:
         __a					  =     'NO'
   else:
      __a					  =     0
      __a					  =     True
      __a					  =     1
      __a					  =     'NO'
   __a					  =     ClusterConfig(**SCREAMING_SNAKE_CASE__     )
   config.to_json_file(SCREAMING_SNAKE_CASE__     )
   return path



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						int,       SCREAMING_SNAKE_CASE__:						List[str]     )	->      Optional[Any]:

   """simple docstring"""
   __a					  =     parser.add_parser('default',       parents=SCREAMING_SNAKE_CASE__,       help=SCREAMING_SNAKE_CASE__,       formatter_class=SCREAMING_SNAKE_CASE__     )
   parser.add_argument(
       '--config_file',       default=SCREAMING_SNAKE_CASE__,       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\'.'
       ),       dest='save_location',       )

   parser.add_argument(
       '--mixed_precision',       choices=['no', 'fp16', 'bf16'],       type=SCREAMING_SNAKE_CASE__,       help='Whether or not to use mixed precision training. '
       'Choose between FP16 and BF16 (bfloat16) training. '
       'BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.',       default='no',       )
   parser.set_defaults(func=SCREAMING_SNAKE_CASE__     )
   return parser



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Union[str, Any]     )	->      Union[str, Any]:

   """simple docstring"""
   __a					  =     write_basic_config(args.mixed_precision,       args.save_location     )
   if config_file:
      print(f"""accelerate configuration saved at {config_file}"""     )







'''simple docstring'''



from multiprocessing import Lock, Pipe, Process

# lock used to ensure that two processes do not access a pipe at the same time
__UpperCamelCase   :							Optional[int]         =   Lock()



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Tuple,       SCREAMING_SNAKE_CASE__:						Any,       SCREAMING_SNAKE_CASE__:						Tuple,       SCREAMING_SNAKE_CASE__:						str,       SCREAMING_SNAKE_CASE__:						Optional[Any],       SCREAMING_SNAKE_CASE__:						Any,       SCREAMING_SNAKE_CASE__:						List[Any]     )	->      int:

   """simple docstring"""
   global process_lock

   # we perform n swaps since after n swaps we know we are sorted
   # we *could* stop early if we are sorted already, but it takes as long to
   # find out we are sorted as it does to sort the list with this algorithm
   for i in range(0,       10     ):
      if (i + position) % 2 == 0 and r_send is not None:
         # send your value to your right neighbor
         process_lock.acquire()
         r_send[1].send(SCREAMING_SNAKE_CASE__     )
         process_lock.release()

         # receive your right neighbor's value
         process_lock.acquire()
         __a					  =     rr_cv[0].recv()
         process_lock.release()

         # take the lower value since you are on the left
         __a					  =     min(SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__     )
      elif (i + position) % 2 != 0 and l_send is not None:
         # send your value to your left neighbor
         process_lock.acquire()
         l_send[1].send(SCREAMING_SNAKE_CASE__     )
         process_lock.release()

         # receive your left neighbor's value
         process_lock.acquire()
         __a					  =     lr_cv[0].recv()
         process_lock.release()

         # take the higher value since you are on the right
         __a					  =     max(SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__     )
    # after all swaps are performed, send the values back to main
   result_pipe[1].send(SCREAMING_SNAKE_CASE__     )



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Tuple     )	->      Optional[Any]:

   """simple docstring"""
   __a					  =     []
   __a					  =     []
   # initialize the list of pipes where the values will be retrieved
   for _ in arr:
      result_pipe.append(Pipe()     )
   # creates the processes
   # the first and last process only have one neighbor so they are made outside
   # of the loop
   __a					  =     Pipe()
   __a					  =     Pipe()
   process_array_.append(
       Process(
           target=SCREAMING_SNAKE_CASE__,       args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]),       )     )
   __a					  =     temp_rs
   __a					  =     temp_rr

   for i in range(1,       len(SCREAMING_SNAKE_CASE__     ) - 1     ):
      __a					  =     Pipe()
      __a					  =     Pipe()
      process_array_.append(
          Process(
              target=SCREAMING_SNAKE_CASE__,       args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]),       )     )
      __a					  =     temp_rs
      __a					  =     temp_rr

   process_array_.append(
       Process(
           target=SCREAMING_SNAKE_CASE__,       args=(
               len(SCREAMING_SNAKE_CASE__     ) - 1,
               arr[len(SCREAMING_SNAKE_CASE__     ) - 1],
               temp_ls,
               None,
               temp_lr,
               None,
               result_pipe[len(SCREAMING_SNAKE_CASE__     ) - 1],
           ),       )     )

   # start the processes
   for p in process_array_:
      p.start()

   # wait for the processes to end and write their values to the list
   for p in range(0,       len(SCREAMING_SNAKE_CASE__     )     ):
      __a					  =     result_pipe[p][0].recv()
      process_array_[p].join()
   return arr



def  __UpperCAmelCase						(					)	->      Any:

   """simple docstring"""
   __a					  =     list(range(10,       0,       -1     )     )
   print('Initial List'     )
   print(*SCREAMING_SNAKE_CASE__     )
   __a					  =     odd_even_transposition(SCREAMING_SNAKE_CASE__     )
   print('Sorted List\n'     )
   print(*SCREAMING_SNAKE_CASE__     )


if __name__ == "__main__":
 main()