code: 
  
  
  
  
  
  
  '''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
  
  
  UpperCAmelCase__      =							get_logger(__name__)
  
  
  
  
  
  
  def 	UpperCAmelCase__(							_SCREAMING_SNAKE_CASE				:   str,_SCREAMING_SNAKE_CASE				:   List[dict],_SCREAMING_SNAKE_CASE				:   list,_SCREAMING_SNAKE_CASE				:   list,_SCREAMING_SNAKE_CASE				:   int,_SCREAMING_SNAKE_CASE				:   GradScaler = None,):
  
  
  
  
  
  
  			"""simple docstring"""
  
  
  
  
  			for i, state in enumerate(a_   ):
  						__A=  f"""{MODEL_NAME}.bin""" if i == 0 else f"""{MODEL_NAME}_{i}.bin"""
  						__A=  os.path.join(a_,a_   )
  						save(a_,a_   )
  						logger.info(f"""Model weights saved in {output_model_file}"""   )
  			# Optimizer states
  			for i, opt in enumerate(a_   ):
  						__A=  opt.state_dict()
  						__A=  f"""{OPTIMIZER_NAME}.bin""" if i == 0 else f"""{OPTIMIZER_NAME}_{i}.bin"""
  						__A=  os.path.join(a_,a_   )
  						save(a_,a_   )
  						logger.info(f"""Optimizer state saved in {output_optimizer_file}"""   )
  			# Scheduler states
  			for i, scheduler in enumerate(a_   ):
  						__A=  scheduler.state_dict()
  						__A=  f"""{SCHEDULER_NAME}.bin""" if i == 0 else f"""{SCHEDULER_NAME}_{i}.bin"""
  						__A=  os.path.join(a_,a_   )
  						save(a_,a_   )
  						logger.info(f"""Scheduler state saved in {output_scheduler_file}"""   )
  			# GradScaler state
  			if scaler is not None:
  						__A=  scaler.state_dict()
  						__A=  os.path.join(a_,a_   )
  						torch.save(a_,a_   )
  						logger.info(f"""Gradient scaler state saved in {output_scaler_file}"""   )
  			# Random number generator states
  			__A=  {}
  			__A=  f"""{RNG_STATE_NAME}_{process_index}.pkl"""
  			__A=  random.getstate()
  			__A=  np.random.get_state()
  			__A=  torch.get_rng_state()
  			if is_xpu_available():
  						__A=  torch.xpu.get_rng_state_all()
  			else:
  						__A=  torch.cuda.get_rng_state_all()
  			if is_tpu_available():
  						__A=  xm.get_rng_state()
  			__A=  os.path.join(a_,a_   )
  			torch.save(a_,a_   )
  			logger.info(f"""Random states saved in {output_states_file}"""   )
  			return output_dir
  
  
  
  
  
  
  def 	UpperCAmelCase__(							_SCREAMING_SNAKE_CASE				:   Optional[int],_SCREAMING_SNAKE_CASE				:   int,_SCREAMING_SNAKE_CASE				:   Any,_SCREAMING_SNAKE_CASE				:   Tuple,_SCREAMING_SNAKE_CASE				:   Optional[Any],_SCREAMING_SNAKE_CASE				:   Tuple=None,_SCREAMING_SNAKE_CASE				:   Union[str, Any]=None,**_SCREAMING_SNAKE_CASE				:   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:
  						__A=  'cpu'
  			elif map_location == "on_device":
  						__A=  PartialState().device
  			# Model states
  			for i, model in enumerate(a_   ):
  						__A=  f"""{MODEL_NAME}.bin""" if i == 0 else f"""{MODEL_NAME}_{i}.bin"""
  						__A=  os.path.join(a_,a_   )
  						models[i].load_state_dict(torch.load(a_,map_location=a_   ),**a_   )
  			logger.info('All model weights loaded successfully'   )
  
  			# Optimizer states
  			for i, opt in enumerate(a_   ):
  						__A=  f"""{OPTIMIZER_NAME}.bin""" if i == 0 else f"""{OPTIMIZER_NAME}_{i}.bin"""
  						__A=  os.path.join(a_,a_   )
  						__A=  torch.load(a_,map_location=a_   )
  						optimizers[i].load_state_dict(a_   )
  			logger.info('All optimizer states loaded successfully'   )
  
  			# Scheduler states
  			for i, scheduler in enumerate(a_   ):
  						__A=  f"""{SCHEDULER_NAME}.bin""" if i == 0 else f"""{SCHEDULER_NAME}_{i}.bin"""
  						__A=  os.path.join(a_,a_   )
  						scheduler.load_state_dict(torch.load(a_   )   )
  			logger.info('All scheduler states loaded successfully'   )
  
  			# GradScaler state
  			if scaler is not None:
  						__A=  os.path.join(a_,a_   )
  						scaler.load_state_dict(torch.load(a_   )   )
  						logger.info('GradScaler state loaded successfully'   )
  
  			# Random states
  			try:
  						__A=  torch.load(os.path.join(a_,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 	UpperCAmelCase__(							_SCREAMING_SNAKE_CASE				:   int,_SCREAMING_SNAKE_CASE				:   str,_SCREAMING_SNAKE_CASE				:   int = 0   ):
  
  
  
  
  
  
  			"""simple docstring"""
  
  
  
  
  			__A=  Path(a_   ) / f"""custom_checkpoint_{index}.pkl"""
  			logger.info(f"""Saving the state of {get_pretty_name(a_   )} to {save_location}"""   )
  			torch.save(obj.state_dict(),a_   )
  
  
  
  
  
  
  def 	UpperCAmelCase__(							_SCREAMING_SNAKE_CASE				:   Tuple,_SCREAMING_SNAKE_CASE				:   List[Any],_SCREAMING_SNAKE_CASE				:   int = 0   ):
  
  
  
  
  
  
  			"""simple docstring"""
  
  
  
  
  			__A=  f"""{path}/custom_checkpoint_{index}.pkl"""
  			logger.info(f"""Loading the state of {get_pretty_name(a_   )} from {load_location}"""   )
  			obj.load_state_dict(torch.load(a_,map_location='cpu'   )   )
  
  
  
  
style_context: 
  
  
  '''simple docstring'''
  
  
  
  
  
  import numpy as np
  from cva import destroyAllWindows, imread, imshow, waitKey
  class 	a__				:
  
  
  
  
  
  			'''simple docstring'''
  
  			def __init__(     self       : Dict ,						lowerCAmelCase_       : Optional[Any] ,						lowerCAmelCase_       : int  )			->		Optional[int]:
  						__A=  0
  						# max greyscale value for #FFFFFF
  						__A=  int(self.get_greyscale(255 ,						255 ,						255  )  )
  
  						if not self.min_threshold < threshold < self.max_threshold:
  									__A=  F"""Factor value should be from 0 to {self.max_threshold}"""
  									raise ValueError(lowerCAmelCase_  )
  
  						__A=  input_img
  						__A=  threshold
  						__A,  __A=  self.input_img.shape[1], self.input_img.shape[0]
  
  						# error table size (+4 columns and +1 row) greater than input image because of
  						# lack of if statements
  						__A=  [
  						    [0 for _ in range(self.height + 4  )] for __ in range(self.width + 1  )
  						]
  						__A=  np.ones((self.width, self.height, 3) ,						np.uinta  ) * 255
  			@classmethod
  			def 				lowerCAmelCase    (     cls       : Tuple ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : int ,						lowerCAmelCase_       : int  )			->		float:
  						return 0.1_14 * blue + 0.5_87 * green + 0.21_26 * red
  
  			def 				lowerCAmelCase    (     self       : str  )			->		None:
  						for y in range(self.height  ):
  									for x in range(self.width  ):
  												__A=  int(self.get_greyscale(*self.input_img[y][x]  )  )
  												if self.threshold > greyscale + self.error_table[y][x]:
  															__A=  (0, 0, 0)
  															__A=  greyscale + self.error_table[x][y]
  												else:
  															__A=  (255, 255, 255)
  															__A=  greyscale + self.error_table[x][y] - 255
  												self.error_table[y][x + 1] += int(8 / 32 * current_error  )
  												self.error_table[y][x + 2] += int(4 / 32 * current_error  )
  												self.error_table[y + 1][x] += int(8 / 32 * current_error  )
  												self.error_table[y + 1][x + 1] += int(4 / 32 * current_error  )
  												self.error_table[y + 1][x + 2] += int(2 / 32 * current_error  )
  												self.error_table[y + 1][x - 1] += int(4 / 32 * current_error  )
  												self.error_table[y + 1][x - 2] += int(2 / 32 * current_error  )
  
  
  if __name__ == "__main__":
  					# create Burke's instances with original images in greyscale
  					UpperCAmelCase__      =							[
  					    Burkes(imread('''image_data/lena.jpg''', 1), threshold)
  					    for threshold in (1, 1_2_6, 1_3_0, 1_4_0)
  					]
  
  					for burkes in burkes_instances:
  										burkes.process()
  
  					for burkes in burkes_instances:
  										imshow(
  										    F"""Original image with dithering threshold: {burkes.threshold}""",
  										    burkes.output_img,
  										)
  
  					waitKey(0)
  					destroyAllWindows()
  
  
  
  