'''simple docstring'''


import os
import random
from pathlib import Path
from typing import List

import numpy as np
import torch
from torch.cuda.amp import GradScaler

from .utils import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    get_pretty_name,
    is_tpu_available,
    is_xpu_available,
    save,
)


if is_tpu_available(check_device=False):
 import torch_xla.core.xla_model as xm

from .logging import get_logger
from .state import PartialState


snake_case__	:     List[str]      =    get_logger(__name__)


def    _lowerCamelCase       ( lowerCamelCase_   :				str      ,	lowerCamelCase_   :				List[dict]      ,	lowerCamelCase_   :				list      ,	lowerCamelCase_   :				list      ,	lowerCamelCase_   :				int      ,	lowerCamelCase_   :				GradScaler = None      ,	):



     """simple docstring"""





     for i, state in enumerate(lowerCamelCase_  ):
          UpperCAmelCase_				:  Tuple  = F'''{MODEL_NAME}.bin''' if i == 0 else F'''{MODEL_NAME}_{i}.bin'''
          UpperCAmelCase_				:  int  = os.path.join(lowerCamelCase_      ,	lowerCamelCase_  )
          save(lowerCamelCase_      ,	lowerCamelCase_  )
          logger.info(F'''Model weights saved in {output_model_file}'''  )
     # Optimizer states
     for i, opt in enumerate(lowerCamelCase_  ):
          UpperCAmelCase_				:  str  = opt.state_dict()
          UpperCAmelCase_				:  Optional[Any]  = F'''{OPTIMIZER_NAME}.bin''' if i == 0 else F'''{OPTIMIZER_NAME}_{i}.bin'''
          UpperCAmelCase_				:  List[str]  = os.path.join(lowerCamelCase_      ,	lowerCamelCase_  )
          save(lowerCamelCase_      ,	lowerCamelCase_  )
          logger.info(F'''Optimizer state saved in {output_optimizer_file}'''  )
     # Scheduler states
     for i, scheduler in enumerate(lowerCamelCase_  ):
          UpperCAmelCase_				:  Tuple  = scheduler.state_dict()
          UpperCAmelCase_				:  Union[str, Any]  = F'''{SCHEDULER_NAME}.bin''' if i == 0 else F'''{SCHEDULER_NAME}_{i}.bin'''
          UpperCAmelCase_				:  int  = os.path.join(lowerCamelCase_      ,	lowerCamelCase_  )
          save(lowerCamelCase_      ,	lowerCamelCase_  )
          logger.info(F'''Scheduler state saved in {output_scheduler_file}'''  )
     # GradScaler state
     if scaler is not None:
          UpperCAmelCase_				:  Dict  = scaler.state_dict()
          UpperCAmelCase_				:  Dict  = os.path.join(lowerCamelCase_      ,	lowerCamelCase_  )
          torch.save(lowerCamelCase_      ,	lowerCamelCase_  )
          logger.info(F'''Gradient scaler state saved in {output_scaler_file}'''  )
     # Random number generator states
     UpperCAmelCase_				:  Dict  = {}
     UpperCAmelCase_				:  int  = F'''{RNG_STATE_NAME}_{process_index}.pkl'''
     UpperCAmelCase_				:  Dict  = random.getstate()
     UpperCAmelCase_				:  List[str]  = np.random.get_state()
     UpperCAmelCase_				:  Any  = torch.get_rng_state()
     if is_xpu_available():
          UpperCAmelCase_				:  Optional[int]  = torch.xpu.get_rng_state_all()
     else:
          UpperCAmelCase_				:  Dict  = torch.cuda.get_rng_state_all()
     if is_tpu_available():
          UpperCAmelCase_				:  int  = xm.get_rng_state()
     UpperCAmelCase_				:  Any  = os.path.join(lowerCamelCase_      ,	lowerCamelCase_  )
     torch.save(lowerCamelCase_      ,	lowerCamelCase_  )
     logger.info(F'''Random states saved in {output_states_file}'''  )
     return output_dir


def    _lowerCamelCase       ( lowerCamelCase_   :				List[Any]      ,	lowerCamelCase_   :				List[Any]      ,	lowerCamelCase_   :				Dict      ,	lowerCamelCase_   :				Dict      ,	lowerCamelCase_   :				Dict      ,	lowerCamelCase_   :				Any=None      ,	lowerCamelCase_   :				int=None      ,	**lowerCamelCase_   :				Dict      ,	):



     """simple docstring"""





     if map_location not in [None, "cpu", "on_device"]:
          raise TypeError(
              'Unsupported optimizer map location passed, please choose one of `None`, `\'cpu\'`, or `\'on_device\'`'  )
     if map_location is None:
          UpperCAmelCase_				:  str  = 'cpu'
     elif map_location == "on_device":
          UpperCAmelCase_				:  Optional[int]  = PartialState().device
     # Model states
     for i, model in enumerate(lowerCamelCase_  ):
          UpperCAmelCase_				:  Union[str, Any]  = F'''{MODEL_NAME}.bin''' if i == 0 else F'''{MODEL_NAME}_{i}.bin'''
          UpperCAmelCase_				:  Any  = os.path.join(lowerCamelCase_      ,	lowerCamelCase_  )
          models[i].load_state_dict(torch.load(lowerCamelCase_      ,	map_location=lowerCamelCase_  )      ,	**lowerCamelCase_  )
     logger.info('All model weights loaded successfully'  )

     # Optimizer states
     for i, opt in enumerate(lowerCamelCase_  ):
          UpperCAmelCase_				:  List[Any]  = F'''{OPTIMIZER_NAME}.bin''' if i == 0 else F'''{OPTIMIZER_NAME}_{i}.bin'''
          UpperCAmelCase_				:  List[Any]  = os.path.join(lowerCamelCase_      ,	lowerCamelCase_  )
          UpperCAmelCase_				:  str  = torch.load(lowerCamelCase_      ,	map_location=lowerCamelCase_  )
          optimizers[i].load_state_dict(lowerCamelCase_  )
     logger.info('All optimizer states loaded successfully'  )

     # Scheduler states
     for i, scheduler in enumerate(lowerCamelCase_  ):
          UpperCAmelCase_				:  Any  = F'''{SCHEDULER_NAME}.bin''' if i == 0 else F'''{SCHEDULER_NAME}_{i}.bin'''
          UpperCAmelCase_				:  List[Any]  = os.path.join(lowerCamelCase_      ,	lowerCamelCase_  )
          scheduler.load_state_dict(torch.load(lowerCamelCase_  )  )
     logger.info('All scheduler states loaded successfully'  )

     # GradScaler state
     if scaler is not None:
          UpperCAmelCase_				:  Dict  = os.path.join(lowerCamelCase_      ,	lowerCamelCase_  )
          scaler.load_state_dict(torch.load(lowerCamelCase_  )  )
          logger.info('GradScaler state loaded successfully'  )

     # Random states
     try:
          UpperCAmelCase_				:  Union[str, Any]  = torch.load(os.path.join(lowerCamelCase_      ,	F'''{RNG_STATE_NAME}_{process_index}.pkl'''  )  )
          random.setstate(states['random_state']  )
          np.random.set_state(states['numpy_random_seed']  )
          torch.set_rng_state(states['torch_manual_seed']  )
          if is_xpu_available():
               torch.xpu.set_rng_state_all(states['torch_xpu_manual_seed']  )
          else:
               torch.cuda.set_rng_state_all(states['torch_cuda_manual_seed']  )
          if is_tpu_available():
               xm.set_rng_state(states['xm_seed']  )
          logger.info('All random states loaded successfully'  )
     except Exception:
          logger.info('Could not load random states'  )


def    _lowerCamelCase       ( lowerCamelCase_   :				str      ,	lowerCamelCase_   :				str      ,	lowerCamelCase_   :				int = 0  ):



     """simple docstring"""





     UpperCAmelCase_				:  Any  = Path(lowerCamelCase_  ) / F'''custom_checkpoint_{index}.pkl'''
     logger.info(F'''Saving the state of {get_pretty_name(lowerCamelCase_  )} to {save_location}'''  )
     torch.save(obj.state_dict()      ,	lowerCamelCase_  )





def    _lowerCamelCase       ( lowerCamelCase_   :				List[str]      ,	lowerCamelCase_   :				Dict      ,	lowerCamelCase_   :				int = 0  ):



     """simple docstring"""





     UpperCAmelCase_				:  Tuple  = F'''{path}/custom_checkpoint_{index}.pkl'''
     logger.info(F'''Loading the state of {get_pretty_name(lowerCamelCase_  )} from {load_location}'''  )
     obj.load_state_dict(torch.load(lowerCamelCase_      ,	map_location='cpu'  )  )









from __future__ import annotations

from collections import Counter



def  snake_case_(_UpperCamelCase	)				->      list[int]:



  """simple docstring"""






  _snake_case		=				[True] * n
  _snake_case		=				False
  _snake_case		=				False
  _snake_case		=				True

  for i in range(3					,			int(n**0.5 + 1	)					,			2	):
    _snake_case		=				i * 2
    while index < n:
      _snake_case		=				False
      _snake_case		=				index + i

  _snake_case		=				[2]

  for i in range(3					,			_UpperCamelCase					,			2	):
    if is_prime[i]:
      primes.append(_UpperCamelCase	)

  return primes



def  snake_case_(_UpperCamelCase	)				->      list[list[int]]:



  """simple docstring"""






  _snake_case		=				str(_UpperCamelCase	)
  _snake_case		=				[]
  _snake_case		=				['''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''']

  for duplicate in Counter(_UpperCamelCase	) - Counter(set(_UpperCamelCase	)	):
    _snake_case		=				[int(number_str.replace(_UpperCamelCase					,			_UpperCamelCase	)	) for digit in digits]
    replacements.append(_UpperCamelCase	)

  return replacements



def  snake_case_(_UpperCamelCase = 8	)				->      int:



  """simple docstring"""






  _snake_case		=				set()

  # Filter primes with less than 3 replaceable digits
  _snake_case		=				{
      x for x in set(prime_sieve(1_000_000	)	) if len(str(_UpperCamelCase	)	) - len(set(str(_UpperCamelCase	)	)	) >= 3
  }

  for prime in primes:
    if prime in numbers_checked:
      continue

    _snake_case		=				digit_replacements(_UpperCamelCase	)

    for family in replacements:
      numbers_checked.update(_UpperCamelCase	)
      _snake_case		=				primes.intersection(_UpperCamelCase	)

      if len(_UpperCamelCase	) != family_length:
        continue

      return min(_UpperCamelCase	)

  return -1


if __name__ == "__main__":
 print(solution())

