"""simple docstring"""




import glob
import os
from typing import Dict, List, Union

import torch

from diffusers.utils import is_safetensors_available


if is_safetensors_available():
				import safetensors.torch

from huggingface_hub import snapshot_download

from diffusers import DiffusionPipeline, __version__
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils import CONFIG_NAME, DIFFUSERS_CACHE, ONNX_WEIGHTS_NAME, WEIGHTS_NAME
class      UpperCamelCase__(      __lowerCAmelCase			):





						def __init__(							self  )       ->					List[Any]:
													self.register_to_config()
													super().__init__()





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					Tuple:





													if dicta == dicta:
																				return True
													else:
																				A__						  =				self._remove_meta_keys(__UpperCAmelCase  )
																				A__						  =				self._remove_meta_keys(__UpperCAmelCase  )
																				if configa == configa:
																											print(f'''Warning !: Mismatch in keys {meta_keysa} and {meta_keysa}.'''  )
																											return True
													return False





						def 					snake_case__						(							self		,__UpperCAmelCase  )       ->					Optional[Any]:
													A__						  =				[]
													A__						  =				config_dict.copy()
													for key in config_dict.keys():
																				if key.startswith('_'  ):
																											temp_dict.pop(__UpperCAmelCase  )
																											meta_keys.append(__UpperCAmelCase  )
													return (temp_dict, meta_keys)





						@torch.no_grad()
						def 					snake_case__						(							self		,__UpperCAmelCase		,**__UpperCAmelCase  )       ->					int:
													A__						  =				kwargs.pop('cache_dir'		,__UpperCAmelCase  )
													A__						  =				kwargs.pop('resume_download'		,__UpperCAmelCase  )
													A__						  =				kwargs.pop('force_download'		,__UpperCAmelCase  )
													A__						  =				kwargs.pop('proxies'		,__UpperCAmelCase  )
													A__						  =				kwargs.pop('local_files_only'		,__UpperCAmelCase  )
													A__						  =				kwargs.pop('use_auth_token'		,__UpperCAmelCase  )
													A__						  =				kwargs.pop('revision'		,__UpperCAmelCase  )
													A__						  =				kwargs.pop('torch_dtype'		,__UpperCAmelCase  )
													A__						  =				kwargs.pop('device_map'		,__UpperCAmelCase  )

													A__						  =				kwargs.pop('alpha'		,0.5  )
													A__						  =				kwargs.pop('interp'		,__UpperCAmelCase  )

													print('Received list'		,__UpperCAmelCase  )
													print(f'''Combining with alpha={alpha}, interpolation mode={interp}'''  )

													A__						  =				len(__UpperCAmelCase  )
													# Ignore result from model_index_json comparision of the two checkpoints
													A__						  =				kwargs.pop('force'		,__UpperCAmelCase  )

													# If less than 2 checkpoints, nothing to merge. If more than 3, not supported for now.
													if checkpoint_count > 3 or checkpoint_count < 2:
																				raise ValueError(
																				    'Received incorrect number of checkpoints to merge. Ensure that either 2 or 3 checkpoints are being'
																				    ' passed.'  )

													print('Received the right number of checkpoints'  )
													# chkpt0, chkpt1 = pretrained_model_name_or_path_list[0:2]
													# chkpt2 = pretrained_model_name_or_path_list[2] if checkpoint_count == 3 else None

													# Validate that the checkpoints can be merged
													# Step 1: Load the model config and compare the checkpoints. We'll compare the model_index.json first while ignoring the keys starting with '_'
													A__						  =				[]
													for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
																				A__						  =				DiffusionPipeline.load_config(
																				    __UpperCAmelCase		,cache_dir=__UpperCAmelCase		,resume_download=__UpperCAmelCase		,force_download=__UpperCAmelCase		,proxies=__UpperCAmelCase		,local_files_only=__UpperCAmelCase		,use_auth_token=__UpperCAmelCase		,revision=__UpperCAmelCase		,)
																				config_dicts.append(__UpperCAmelCase  )

													A__						  =				True
													for idx in range(1		,len(__UpperCAmelCase  )  ):
																				comparison_result &= self._compare_model_configs(config_dicts[idx - 1]		,config_dicts[idx]  )
																				if not force and comparison_result is False:
																											raise ValueError('Incompatible checkpoints. Please check model_index.json for the models.'  )
																											print(config_dicts[0]		,config_dicts[1]  )
													print('Compatible model_index.json files found'  )
													# Step 2: Basic Validation has succeeded. Let's download the models and save them into our local files.
													A__						  =				[]
													for pretrained_model_name_or_path, config_dict in zip(__UpperCAmelCase		,__UpperCAmelCase  ):
																				A__						  =				[k for k in config_dict.keys() if not k.startswith('_'  )]
																				A__						  =				[os.path.join(__UpperCAmelCase		,'*'  ) for k in folder_names]
																				allow_patterns += [
																				    WEIGHTS_NAME,
																				    SCHEDULER_CONFIG_NAME,
																				    CONFIG_NAME,
																				    ONNX_WEIGHTS_NAME,
																				    DiffusionPipeline.config_name,
																				]
																				A__						  =				config_dict.get('_class_name'  )
																				A__						  =				{'diffusers': __version__, 'pipeline_class': requested_pipeline_class}

																				A__						  =				(
																				    pretrained_model_name_or_path
																				    if os.path.isdir(__UpperCAmelCase  )
																				    else snapshot_download(
																				        __UpperCAmelCase		,cache_dir=__UpperCAmelCase		,resume_download=__UpperCAmelCase		,proxies=__UpperCAmelCase		,local_files_only=__UpperCAmelCase		,use_auth_token=__UpperCAmelCase		,revision=__UpperCAmelCase		,allow_patterns=__UpperCAmelCase		,user_agent=__UpperCAmelCase		,)
																				)
																				print('Cached Folder'		,__UpperCAmelCase  )
																				cached_folders.append(__UpperCAmelCase  )

													# Step 3:-
													# Load the first checkpoint as a diffusion pipeline and modify its module state_dict in place
													A__						  =				DiffusionPipeline.from_pretrained(
													    cached_folders[0]		,torch_dtype=__UpperCAmelCase		,device_map=__UpperCAmelCase  )
													final_pipe.to(self.device  )

													A__						  =				None
													if len(__UpperCAmelCase  ) > 2:
																				A__						  =				os.path.join(cached_folders[2]  )

													if interp == "sigmoid":
																				A__						  =				CheckpointMergerPipeline.sigmoid
													elif interp == "inv_sigmoid":
																				A__						  =				CheckpointMergerPipeline.inv_sigmoid
													elif interp == "add_diff":
																				A__						  =				CheckpointMergerPipeline.add_difference
													else:
																				A__						  =				CheckpointMergerPipeline.weighted_sum

													# Find each module's state dict.
													for attr in final_pipe.config.keys():
																				if not attr.startswith('_'  ):
																											A__						  =				os.path.join(cached_folders[1]		,__UpperCAmelCase  )
																											if os.path.exists(__UpperCAmelCase  ):
																																		A__						  =				[
																																		    *glob.glob(os.path.join(__UpperCAmelCase		,'*.safetensors'  )  ),
																																		    *glob.glob(os.path.join(__UpperCAmelCase		,'*.bin'  )  ),
																																		]
																																		A__						  =				files[0] if len(__UpperCAmelCase  ) > 0 else None
																											if len(__UpperCAmelCase  ) < 3:
																																		A__						  =				None
																											else:
																																		A__						  =				os.path.join(cached_folders[2]		,__UpperCAmelCase  )
																																		if os.path.exists(__UpperCAmelCase  ):
																																									A__						  =				[
																																									    *glob.glob(os.path.join(__UpperCAmelCase		,'*.safetensors'  )  ),
																																									    *glob.glob(os.path.join(__UpperCAmelCase		,'*.bin'  )  ),
																																									]
																																									A__						  =				files[0] if len(__UpperCAmelCase  ) > 0 else None
																																									# For an attr if both checkpoint_path_1 and 2 are None, ignore.
																																									# If atleast one is present, deal with it according to interp method, of course only if the state_dict keys match.
																											if checkpoint_path_a is None and checkpoint_path_a is None:
																																		print(f'''Skipping {attr}: not present in 2nd or 3d model'''  )
																																		continue
																											try:
																																		A__						  =				getattr(__UpperCAmelCase		,__UpperCAmelCase  )
																																		if isinstance(__UpperCAmelCase		,__UpperCAmelCase  ):  # ignore requires_safety_checker boolean
																																									continue
																																		A__						  =				getattr(__UpperCAmelCase		,'state_dict'  )
																																		A__						  =				theta_a()

																																		A__						  =				getattr(__UpperCAmelCase		,'load_state_dict'  )
																																		A__						  =				(
																																		    safetensors.torch.load_file(__UpperCAmelCase  )
																																		    if (is_safetensors_available() and checkpoint_path_a.endswith('.safetensors'  ))
																																		    else torch.load(__UpperCAmelCase		,map_location='cpu'  )
																																		)
																																		A__						  =				None
																																		if checkpoint_path_a:
																																									A__						  =				(
																																									    safetensors.torch.load_file(__UpperCAmelCase  )
																																									    if (is_safetensors_available() and checkpoint_path_a.endswith('.safetensors'  ))
																																									    else torch.load(__UpperCAmelCase		,map_location='cpu'  )
																																									)

																																		if not theta_a.keys() == theta_a.keys():
																																									print(f'''Skipping {attr}: key mismatch'''  )
																																									continue
																																		if theta_a and not theta_a.keys() == theta_a.keys():
																																									print(f'''Skipping {attr}:y mismatch'''  )
																											except Exception as e:
																																		print(f'''Skipping {attr} do to an unexpected error: {str(__UpperCAmelCase  )}'''  )
																																		continue
																											print(f'''MERGING {attr}'''  )

																											for key in theta_a.keys():
																																		if theta_a:
																																									A__						  =				theta_func(theta_a[key]		,theta_a[key]		,theta_a[key]		,__UpperCAmelCase  )
																																		else:
																																									A__						  =				theta_func(theta_a[key]		,theta_a[key]		,__UpperCAmelCase		,__UpperCAmelCase  )

																											del theta_a
																											del theta_a
																											update_theta_a(__UpperCAmelCase  )

																											del theta_a
													return final_pipe





						@staticmethod
						def 					snake_case__						(							__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					str:
													return ((1 - alpha) * thetaa) + (alpha * thetaa)





						@staticmethod
						def 					snake_case__						(							__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					str:
													A__						  =				alpha * alpha * (3 - (2 * alpha))
													return thetaa + ((thetaa - thetaa) * alpha)





						@staticmethod
						def 					snake_case__						(							__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					Optional[Any]:
													import math

													A__						  =				0.5 - math.sin(math.asin(1.0 - 2.0 * alpha  ) / 3.0  )
													return thetaa + ((thetaa - thetaa) * alpha)





						@staticmethod
						def 					snake_case__						(							__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					List[Any]:
													return thetaa + (thetaa - thetaa) * (1.0 - alpha)






"""simple docstring"""
import importlib.util
import weakref
from functools import partialmethod

from .dependency_versions_check import dep_version_check
from .utils import is_accelerate_available, is_torch_available, logging


if is_torch_available():
 import torch

lowercase__   			=      logging.get_logger(__name__)







def 		__a  (      )      ->Dict:
  return importlib.util.find_spec('deepspeed'  ) is not None


if is_accelerate_available() and is_deepspeed_available():
 from accelerate.utils.deepspeed import HfDeepSpeedConfig as DeepSpeedConfig
else:
 # Inherits from a dummy `object` if accelerate is not available, so that python succeeds to import this file.
 # Deepspeed glue code will never inherit this dummy object as it checks if accelerate is available.
 from builtins import object as DeepSpeedConfig




class   __snake_case			(	__lowerCAmelCase							):



      def __init__(		self       ,     lowercase)      ->     int:





        '''simple docstring'''





        set_hf_deepspeed_config(self)
        dep_version_check('accelerate')
        dep_version_check('deepspeed')
        super().__init__(lowercase)







class   __snake_case			(	__lowerCAmelCase							):



      def __init__(		self       ,     lowercase)      ->     List[Any]:





        '''simple docstring'''





        super().__init__(lowercase)
        a__:	List[Any]     				=      None
        a__:	int     				=      []



      def     lowerCamelCase_  (		self)      ->     Any:





        '''simple docstring'''





        if self._dtype is None:
          raise ValueError('trainer_config_process() wasn\'t called yet to tell dtype')
        return self._dtype



      def     lowerCamelCase_  (		self       ,     lowercase)      ->     Optional[Any]:





        '''simple docstring'''





        a__:	Optional[int]     				=      self.get_value(lowercase)
        if val is None:
          return False
        else:
          return val == "auto"



      def     lowerCamelCase_  (		self       ,     lowercase       ,     lowercase       ,     lowercase=None       ,     lowercase=True)      ->     int:





        '''simple docstring'''





        a__				,       a__:	int     				=      self.find_config_node(lowercase)
        if config is None:
          return

        if config.get(lowercase) == "auto":
          a__:	Optional[int]     				=      hf_val
          return

        if not must_match:
          return

        a__:	List[Any]     				=      config.get(lowercase)
        if ds_val is not None and ds_val != hf_val:
          self.mismatches.append(f'- ds {ds_key_long}={ds_val} vs hf {hf_key}={hf_val}')

      a__								=						partialmethod(__lowerCAmelCase			, must_match=__lowerCAmelCase							)



      def     lowerCamelCase_  (		self       ,     lowercase)      ->     Dict:





        '''simple docstring'''





        a__:	str     				=      args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps
        self.fill_match(
            'train_micro_batch_size_per_gpu'       ,     args.per_device_train_batch_size       ,     'per_device_train_batch_size')
        self.fill_match('gradient_accumulation_steps'       ,     args.gradient_accumulation_steps       ,     'gradient_accumulation_steps')
        self.fill_match('train_batch_size'       ,     lowercase       ,     'train_batch_size (calculated)')
        self.fill_match('gradient_clipping'       ,     args.max_grad_norm       ,     'max_grad_norm')

        self.fill_match('optimizer.params.lr'       ,     args.learning_rate       ,     'learning_rate')
        self.fill_match('optimizer.params.betas'       ,     [args.adam_betaa, args.adam_betaa]       ,     'adam_beta1+adam_beta2')
        self.fill_match('optimizer.params.eps'       ,     args.adam_epsilon       ,     'adam_epsilon')
        self.fill_match('optimizer.params.weight_decay'       ,     args.weight_decay       ,     'weight_decay')

        self.fill_only('scheduler.params.warmup_min_lr'       ,     0)  # not a trainer arg
        self.fill_match('scheduler.params.warmup_max_lr'       ,     args.learning_rate       ,     'learning_rate')
        # total_num_steps - will get set in trainer_config_finalize

        # fp16
        if args.fpaa or args.fpaa_full_eval:
          a__:	Tuple     				=      'apex' if args.fpaa_backend == 'apex' else 'amp'
        else:
          a__:	Optional[int]     				=      None

        if args.save_on_each_node:
          # deepspeed uses shared storage by default. Let's override this setting if save_on_each_node == True
          a__:	Union[str, Any]     				=      self.config.get('checkpoint'       ,     {})
          a__:	Tuple     				=      args.save_on_each_node

        # amp: similar to the pytorch native amp - it has a bunch of optional params but we won't set
        # any here unless the user did the work
        self.fill_match(
            'fp16.enabled'       ,     ((args.fpaa or args.fpaa_full_eval) and fpaa_backend == 'amp')       ,     'fp16|fp16_full_eval+fp16_backend(amp)'       ,     )

        # apex: delegates amp work to apex (which needs to be available), but it cannot be used with any
        # ZeRO features
        self.fill_match('amp.enabled'       ,     fpaa_backend == 'apex'       ,     'fp16+fp16_backend(apex)')
        self.fill_match('amp.opt_level'       ,     args.fpaa_opt_level       ,     'fp16_opt_level')

        self.fill_match('bf16.enabled'       ,     (args.bfaa or args.bfaa_full_eval)       ,     'bf16|bf16_full_eval')

        # deepspeed's default mode is fp16 unless there is a config that says differently
        if self.is_true('bf16.enabled'):
          a__:	Optional[int]     				=      torch.bfloataa
        elif self.is_false('fp16.enabled'):
          a__:	Tuple     				=      torch.floataa
        else:
          a__:	Tuple     				=      torch.floataa



      def     lowerCamelCase_  (		self       ,     lowercase       ,     lowercase       ,     lowercase)      ->     Any:





        '''simple docstring'''





        a__:	List[Any]     				=      [
            'zero_optimization.reduce_bucket_size',
            'zero_optimization.stage3_prefetch_bucket_size',
            'zero_optimization.stage3_param_persistence_threshold',
        ]
        a__:	Union[str, Any]     				=      [x for x in hidden_size_based_keys if self.is_auto(lowercase)]

        if len(lowercase) > 0:
          if hasattr(model.config       ,     'hidden_size'):
            a__:	Any     				=      model.config.hidden_size
          elif hasattr(model.config       ,     'hidden_sizes'):
            # if there are many hidden sizes pick the largest one
            a__:	List[str]     				=      max(model.config.hidden_sizes)
          else:
            raise ValueError(
                'The model\'s config file has neither `hidden_size` nor `hidden_sizes` entry, '
                'therefore it\'s not possible to automatically fill out the following `auto` entries '
                f'in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing '
                '`auto` values for these keys with an integer value of your choice.')

          self.fill_only('zero_optimization.reduce_bucket_size'       ,     hidden_size * hidden_size)
          if self.is_zeroa():
            # automatically assign the optimal config values based on model config
            self.fill_only('zero_optimization.stage3_prefetch_bucket_size'       ,     0.9 * hidden_size * hidden_size)
            self.fill_only('zero_optimization.stage3_param_persistence_threshold'       ,     10 * hidden_size)

        # scheduler
        self.fill_match('scheduler.params.total_num_steps'       ,     lowercase       ,     'num_training_steps (calculated)')
        self.fill_match('scheduler.params.warmup_num_steps'       ,     args.get_warmup_steps(lowercase)       ,     'warmup_steps')

        if len(self.mismatches) > 0:
          a__:	int     				=      '\n'.join(self.mismatches)
          raise ValueError(
              'Please correct the following DeepSpeed config values that mismatch TrainingArguments'
              f' values:\n{mismatches}\nThe easiest method is to set these DeepSpeed config values to \'auto\'.')







lowercase__   			=      None







def 		__a  (      _SCREAMING_SNAKE_CASE  )      ->List[Any]:
  # this is a special weakref global object to allow us to get to Deepspeed config from APIs
  # that don't have an easy way to get to the Deepspeed config outside of the Trainer domain.
  global _hf_deepspeed_config_weak_ref
  # will go away automatically when HfDeepSpeedConfig is destroyed (when TrainingArguments is destroyed)
  a__:	Any     				=      weakref.ref(_SCREAMING_SNAKE_CASE  )







def 		__a  (      )      ->List[Any]:
  # useful for unit tests to ensure the global state doesn't leak - call from `tearDown` method
  global _hf_deepspeed_config_weak_ref
  a__:	Any     				=      None







def 		__a  (      )      ->Union[str, Any]:
  if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
    return _hf_deepspeed_config_weak_ref().is_zeroa()
  else:
    return False







def 		__a  (      )      ->Tuple:
  if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
    return _hf_deepspeed_config_weak_ref().config
  else:
    return None







def 		__a  (      _SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE  )      ->Dict:
  from accelerate.utils import DummyOptim, DummyScheduler

  a__:	Optional[Any]     				=      hf_deepspeed_config.config

  # Optimizer + Scheduler
  # Currently supported combos:
  # 1. DS scheduler + DS optimizer: Yes
  # 2. HF scheduler + HF optimizer: Yes
  # 3. DS scheduler + HF optimizer: Yes
  # 4. HF scheduler + DS optimizer: No
  #
  # Unless Offload is enabled in which case it's:
  # 1. DS scheduler + DS optimizer: Yes
  # 2. HF scheduler + HF optimizer: Mostly*
  # 3. DS scheduler + HF optimizer: Mostly*
  # 4. HF scheduler + DS optimizer: No
  #
  # Mostly*: All non-native DeepSpeed optimizers that have both CPU and GPU implementation should work (except LAMB)

  a__:	Dict     				=      None
  if "optimizer" in config:
    if args.adafactor:
      raise ValueError(
          '--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. '
          'Only one optimizer can be configured.'  )
    a__:	str     				=      DummyOptim(params=_SCREAMING_SNAKE_CASE  )
  else:
    if hf_deepspeed_config.is_offload():
      logger.info(
          'Detected ZeRO Offload and non-DeepSpeed optimizers: This combination should work as long as the'
          ' custom optimizer has both CPU and GPU implementation (except LAMB)'  )

    # ds supports Adam, OneBitAdam, and Lamb optimizers and can import other optimizers from torch.
    # But trainer uses AdamW by default.
    a__:	Any     				=      trainer.create_optimizer()
    # To use other optimizers requires voiding warranty with: `zero_allow_untested_optimizer`
    a__:	str     				=      True

  a__:	Dict     				=      None
  if "scheduler" in config:
    a__:	List[str]     				=      DummyScheduler(_SCREAMING_SNAKE_CASE  )
  else:
    if isinstance(_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE  ):
      raise ValueError(
          'Found `optimizer` configured in the DeepSpeed config, but no `scheduler`. '
          'Please configure a scheduler in the DeepSpeed config.'  )
    a__:	Tuple     				=      trainer.create_scheduler(num_training_steps=_SCREAMING_SNAKE_CASE						,	optimizer=_SCREAMING_SNAKE_CASE  )

  return optimizer, lr_scheduler







def 		__a  (      _SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE=False  )      ->Dict:
  from deepspeed.utils import logger as ds_logger

  a__:	Optional[int]     				=      trainer.model
  a__:	List[Any]     				=      trainer.args

  a__:	Optional[int]     				=      trainer.accelerator.state.deepspeed_plugin.hf_ds_config

  # resume config update - some bits like `model` and `num_training_steps` only become available during train
  hf_deepspeed_config.trainer_config_finalize(_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE  )

  # set the Deepspeed log level consistent with the Trainer
  ds_logger.setLevel(args.get_process_log_level()  )

  if inference:
    # only Z3 makes sense for the inference
    if not hf_deepspeed_config.is_zeroa():
      raise ValueError('ZeRO inference only makes sense with ZeRO Stage 3 - please adjust your config'  )

    # in case the training config is re-used for inference
    hf_deepspeed_config.del_config_sub_tree('optimizer'  )
    hf_deepspeed_config.del_config_sub_tree('lr_scheduler'  )
    a__				,       a__:	Optional[int]     				=      None, None
    a__:	Union[str, Any]     				=      None
  else:
    a__:	List[Any]     				=      None  # important for when deepspeed_init is used as re-init
    a__:	Union[str, Any]     				=      list(filter(lambda _SCREAMING_SNAKE_CASE  : p.requires_grad						,	model.parameters()  )  )
    a__				,       a__:	Optional[int]     				=      deepspeed_optim_sched(
        _SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE  )

  # keep for quick debug:
  # from pprint import pprint; pprint(config)

  return optimizer, lr_scheduler







def 		__a  (      _SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE  )      ->int:
  # it's possible that the user is trying to resume from model_path, which doesn't necessarily
  # contain a deepspeed checkpoint. e.g. examples just check if the dir exists and assume it's
  # a resume from a checkpoint and not just a local pretrained weight. So we check here if the
  # path contains what looks like a deepspeed checkpoint
  import glob

  a__:	Tuple     				=      sorted(glob.glob(F'{checkpoint_path}/global_step*'  )  )

  if len(_SCREAMING_SNAKE_CASE  ) > 0:
    logger.info(F'Attempting to resume from {checkpoint_path}'  )
    # this magically updates self.optimizer and self.lr_scheduler
    a__				,       a__:	Union[str, Any]     				=      deepspeed_engine.load_checkpoint(
        _SCREAMING_SNAKE_CASE						,	load_optimizer_states=_SCREAMING_SNAKE_CASE						,	load_lr_scheduler_states=_SCREAMING_SNAKE_CASE  )
    if load_path is None:
      raise ValueError(F'[deepspeed] failed to resume from checkpoint {checkpoint_path}'  )
  else:
    raise ValueError(F'Can\'t find a valid checkpoint at {checkpoint_path}'  )


