





import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
    import torch_xla.core.xla_model as xm
def  __UpperCamelCase    (						snake_case							,			snake_case = False      )    ->		Optional[Any]:


   '''simple docstring'''







   if device_specific:
      seed += AcceleratorState().process_index
   random.seed(snake_case      )
   np.random.seed(snake_case      )
   torch.manual_seed(snake_case      )
   if is_xpu_available():
      torch.xpu.manual_seed_all(snake_case      )
   elif is_npu_available():
      torch.npu.manual_seed_all(snake_case      )
   else:
      torch.cuda.manual_seed_all(snake_case      )
   # ^^ safe to call this function even if cuda is not available
   if is_tpu_available():
      xm.set_rng_state(snake_case      )
def  __UpperCamelCase    (						snake_case = None							,			snake_case = None      )    ->		Optional[int]:


   '''simple docstring'''







   if rng_type == RNGType.TORCH:
      __A    =  torch.get_rng_state()
   elif rng_type == RNGType.CUDA:
      __A    =  torch.cuda.get_rng_state()
   elif rng_type == RNGType.XLA:
      assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
      __A    =  torch.tensor(xm.get_rng_state()      )
   elif rng_type == RNGType.NPU:
      assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
      __A    =  torch.npu.get_rng_state()
   elif rng_type == RNGType.XPU:
      assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
      __A    =  torch.xpu.get_rng_state()
   elif rng_type == RNGType.GENERATOR:
      assert generator is not None, "Need a generator to synchronize its seed."
      __A    =  generator.get_state()

   # Broadcast the rng state from device 0 to other devices
   __A    =  AcceleratorState()
   if state.distributed_type == DistributedType.TPU:
      __A    =  rng_state.to(xm.xla_device()      )
      xm.collective_broadcast([rng_state]      )
      xm.mark_step()
      __A    =  rng_state.cpu()
   elif (
       state.distributed_type in CUDA_DISTRIBUTED_TYPES
       or state.distributed_type == DistributedType.MULTI_NPU
       or state.distributed_type == DistributedType.MULTI_XPU
   ):
      __A    =  rng_state.to(state.device      )
      torch.distributed.broadcast(snake_case							,			0      )
      __A    =  rng_state.cpu()
   elif state.distributed_type == DistributedType.MULTI_CPU:
      torch.distributed.broadcast(snake_case							,			0      )

   # Set the broadcast rng state
   if rng_type == RNGType.TORCH:
      torch.set_rng_state(snake_case      )
   elif rng_type == RNGType.CUDA:
      torch.cuda.set_rng_state(snake_case      )
   elif rng_type == RNGType.NPU:
      torch.npu.set_rng_state(snake_case      )
   elif rng_type == RNGType.XPU:
      torch.xpu.set_rng_state(snake_case      )
   elif rng_type == RNGType.XLA:
      xm.set_rng_state(rng_state.item()      )
   elif rng_type == RNGType.GENERATOR:
      generator.set_state(snake_case      )
def  __UpperCamelCase    (						snake_case							,			snake_case = None      )    ->		Optional[int]:


   '''simple docstring'''







   for rng_type in rng_types:
      synchronize_rng_state(RNGType(snake_case      )							,			generator=snake_case      )








class 		_lowerCAmelCase:

  """simple docstring"""







  def __init__(   self      )->   None:
     # numbermap keys are the number and its values are lists of indexes sorted
     # in ascending order
     __A    =  {}
     # indexmap keys are an index and it's values are the number at that index
     __A    =  {}

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   list[int]:
     if isinstance(UpperCAmelCase    ,							(range, str)      ):
        __A    =  list(UpperCAmelCase      )
     elif not isinstance(UpperCAmelCase    ,							UpperCAmelCase      ):
        raise TypeError(
            '''binary_search_delete() only accepts either a list, range or str'''      )

     __A    =  0
     __A    =  len(UpperCAmelCase      ) - 1

     while low <= high:
        __A    =  (low + high) // 2
        if array[mid] == item:
           array.pop(UpperCAmelCase      )
           return array
        elif array[mid] < item:
           __A    =  mid + 1
        else:
           __A    =  mid - 1
     raise ValueError(
         '''Either the item is not in the array or the array was unsorted'''      )

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   list[int]:
     if isinstance(UpperCAmelCase    ,							(range, str)      ):
        __A    =  list(UpperCAmelCase      )
     elif not isinstance(UpperCAmelCase    ,							UpperCAmelCase      ):
        raise TypeError(
            '''binary_search_insert() only accepts either a list, range or str'''      )

     __A    =  0
     __A    =  len(UpperCAmelCase      ) - 1

     while low <= high:
        __A    =  (low + high) // 2
        if array[mid] == index:
           # If the item already exists in the array,
           # insert it after the existing item
           array.insert(mid + 1    ,							UpperCAmelCase      )
           return array
        elif array[mid] < index:
           __A    =  mid + 1
        else:
           __A    =  mid - 1

        # If the item doesn't exist in the array, insert it at the appropriate position
     array.insert(UpperCAmelCase    ,							UpperCAmelCase      )
     return array

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   None:
     # Remove previous index
     if index in self.indexmap:
        __A    =  self.indexmap[index]
        if len(self.numbermap[n]      ) == 1:
           del self.numbermap[n]
        else:
           __A    =  self.binary_search_delete(self.numbermap[n]    ,							UpperCAmelCase      )

        # Set new index
     __A    =  number

     # Number not seen before or empty so insert number value
     if number not in self.numbermap:
        __A    =  [index]

     # Here we need to perform a binary search insertion in order to insert
     # The item in the correct place
     else:
        __A    =  self.binary_search_insert(
            self.numbermap[number]    ,							UpperCAmelCase      )





  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase      )->   int:
     return self.numbermap.get(UpperCAmelCase    ,							[-1]      )[0]


if __name__ == "__main__":
    import doctest

    doctest.testmod()

