


import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image

from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
a					:				Optional[Any]       =      logging.get_logger(__name__)






def  _UpperCAmelCase						( )		->Dict:


 '''simple docstring'''
 snake_case :			List[str]							=   DetaConfig(
     num_queries=900			,  encoder_ffn_dim=2048			,  decoder_ffn_dim=2048			,  num_feature_levels=5			,  assign_first_stage=UpperCAmelCase__			,  with_box_refine=UpperCAmelCase__			,  two_stage=UpperCAmelCase__			,  )

 # set labels
 snake_case :			str							=   91
 snake_case :			List[str]							=   """huggingface/label-files"""
 snake_case :			Any							=   """coco-detection-id2label.json"""
 snake_case :			int							=   json.load(open(cached_download(hf_hub_url(UpperCAmelCase__			,  UpperCAmelCase__			,  repo_type='''dataset'''							)							)			,  '''r'''							)							)
 snake_case :			Optional[int]							=   {int(UpperCAmelCase__							): v for k, v in idalabel.items()}
 snake_case :			Optional[int]							=   idalabel
 snake_case :			List[str]							=   {v: k for k, v in idalabel.items()}

 return config






def  _UpperCAmelCase						( __lowerCamelCase							)		->Any:


 '''simple docstring'''
 snake_case :			str							=   []

 # stem
 # fmt: off
 rename_keys.append(('''backbone.0.body.conv1.weight''', '''model.backbone.model.embedder.embedder.convolution.weight''')							)
 rename_keys.append(('''backbone.0.body.bn1.weight''', '''model.backbone.model.embedder.embedder.normalization.weight''')							)
 rename_keys.append(('''backbone.0.body.bn1.bias''', '''model.backbone.model.embedder.embedder.normalization.bias''')							)
 rename_keys.append(('''backbone.0.body.bn1.running_mean''', '''model.backbone.model.embedder.embedder.normalization.running_mean''')							)
 rename_keys.append(('''backbone.0.body.bn1.running_var''', '''model.backbone.model.embedder.embedder.normalization.running_var''')							)
 # stages
 for stage_idx in range(len(config.backbone_config.depths							)							):
  for layer_idx in range(config.backbone_config.depths[stage_idx]							):
   # shortcut
   if layer_idx == 0:
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight''',
        )							)
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight''',
        )							)
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias''',
        )							)
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean''',
        )							)
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var''',
        )							)
   # 3 convs
   for i in range(3							):
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight''',
        )							)
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight''',
        )							)
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias''',
        )							)
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean''',
        )							)
    rename_keys.append(
        (
            f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var''',
            f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var''',
        )							)
    # transformer encoder
 for i in range(config.encoder_layers							):
  rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', f'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', f'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', f'''model.encoder.layers.{i}.self_attn.attention_weights.weight''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', f'''model.encoder.layers.{i}.self_attn.attention_weights.bias''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', f'''model.encoder.layers.{i}.self_attn.value_proj.weight''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', f'''model.encoder.layers.{i}.self_attn.value_proj.bias''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', f'''model.encoder.layers.{i}.self_attn.output_proj.weight''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', f'''model.encoder.layers.{i}.self_attn.output_proj.bias''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.norm1.weight''', f'''model.encoder.layers.{i}.self_attn_layer_norm.weight''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.norm1.bias''', f'''model.encoder.layers.{i}.self_attn_layer_norm.bias''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.linear1.weight''', f'''model.encoder.layers.{i}.fc1.weight''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.linear1.bias''', f'''model.encoder.layers.{i}.fc1.bias''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.linear2.weight''', f'''model.encoder.layers.{i}.fc2.weight''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.linear2.bias''', f'''model.encoder.layers.{i}.fc2.bias''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.norm2.weight''', f'''model.encoder.layers.{i}.final_layer_norm.weight''')							)
  rename_keys.append((f'''transformer.encoder.layers.{i}.norm2.bias''', f'''model.encoder.layers.{i}.final_layer_norm.bias''')							)

 # transformer decoder
 for i in range(config.decoder_layers							):
  rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', f'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', f'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', f'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', f'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', f'''model.decoder.layers.{i}.encoder_attn.value_proj.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', f'''model.decoder.layers.{i}.encoder_attn.value_proj.bias''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', f'''model.decoder.layers.{i}.encoder_attn.output_proj.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', f'''model.decoder.layers.{i}.encoder_attn.output_proj.bias''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.norm1.weight''', f'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.norm1.bias''', f'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', f'''model.decoder.layers.{i}.self_attn.out_proj.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', f'''model.decoder.layers.{i}.self_attn.out_proj.bias''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.norm2.weight''', f'''model.decoder.layers.{i}.self_attn_layer_norm.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.norm2.bias''', f'''model.decoder.layers.{i}.self_attn_layer_norm.bias''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.linear1.weight''', f'''model.decoder.layers.{i}.fc1.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.linear1.bias''', f'''model.decoder.layers.{i}.fc1.bias''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.linear2.weight''', f'''model.decoder.layers.{i}.fc2.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.linear2.bias''', f'''model.decoder.layers.{i}.fc2.bias''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.norm3.weight''', f'''model.decoder.layers.{i}.final_layer_norm.weight''')							)
  rename_keys.append((f'''transformer.decoder.layers.{i}.norm3.bias''', f'''model.decoder.layers.{i}.final_layer_norm.bias''')							)

 # fmt: on

 return rename_keys






def  _UpperCAmelCase						( __lowerCamelCase			,  __lowerCamelCase			,  __lowerCamelCase							)		->List[str]:


 '''simple docstring'''
 snake_case :			List[Any]							=   dct.pop(UpperCAmelCase__							)
 snake_case :			List[str]							=   val






def  _UpperCAmelCase						( __lowerCamelCase			,  __lowerCamelCase							)		->Optional[Any]:


 '''simple docstring'''
 # transformer decoder self-attention layers
 snake_case :			Any							=   config.d_model
 for i in range(config.decoder_layers							):
  # read in weights + bias of input projection layer of self-attention
  snake_case :			int							=   state_dict.pop(f'''transformer.decoder.layers.{i}.self_attn.in_proj_weight'''							)
  snake_case :			Any							=   state_dict.pop(f'''transformer.decoder.layers.{i}.self_attn.in_proj_bias'''							)
  # next, add query, keys and values (in that order) to the state dict
  snake_case :			Union[str, Any]							=   in_proj_weight[:hidden_size, :]
  snake_case :			Optional[int]							=   in_proj_bias[:hidden_size]
  snake_case :			List[Any]							=   in_proj_weight[
      hidden_size : hidden_size * 2, :
  ]
  snake_case :			Union[str, Any]							=   in_proj_bias[hidden_size : hidden_size * 2]
  snake_case :			str							=   in_proj_weight[-hidden_size:, :]
  snake_case :			str							=   in_proj_bias[-hidden_size:]






def  _UpperCAmelCase						( )		->Dict:


 '''simple docstring'''
 snake_case :			Optional[Any]							=   """http://images.cocodataset.org/val2017/000000039769.jpg"""
 snake_case :			Dict							=   Image.open(requests.get(UpperCAmelCase__			,  stream=UpperCAmelCase__							).raw							)

 return im






@torch.no_grad()
def  _UpperCAmelCase						( __lowerCamelCase			,  __lowerCamelCase			,  __lowerCamelCase							)		->int:


 '''simple docstring'''
 snake_case :			List[str]							=   get_deta_config()

 # load original state dict
 if model_name == "deta-resnet-50":
  snake_case :			Union[str, Any]							=   """adet_checkpoint0011.pth"""
 elif model_name == "deta-resnet-50-24-epochs":
  snake_case :			List[str]							=   """adet_2x_checkpoint0023.pth"""
 else:
  raise ValueError(f'''Model name {model_name} not supported'''							)
 snake_case :			Optional[int]							=   hf_hub_download(repo_id='''nielsr/deta-checkpoints'''			,  filename=UpperCAmelCase__							)
 snake_case :			int							=   torch.load(UpperCAmelCase__			,  map_location='''cpu'''							)["""model"""]

 # rename keys
 snake_case :			Union[str, Any]							=   create_rename_keys(UpperCAmelCase__							)
 for src, dest in rename_keys:
  rename_key(UpperCAmelCase__			,  UpperCAmelCase__			,  UpperCAmelCase__							)
 read_in_decoder_q_k_v(UpperCAmelCase__			,  UpperCAmelCase__							)

 # fix some prefixes
 for key in state_dict.copy().keys():
  if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
   snake_case :			Dict							=   state_dict.pop(UpperCAmelCase__							)
   snake_case :			Optional[int]							=   val
  if "input_proj" in key:
   snake_case :			Union[str, Any]							=   state_dict.pop(UpperCAmelCase__							)
   snake_case :			str							=   val
  if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
   snake_case :			List[Any]							=   state_dict.pop(UpperCAmelCase__							)
   snake_case :			Any							=   val

    # finally, create HuggingFace model and load state dict
 snake_case :			str							=   DetaForObjectDetection(UpperCAmelCase__							)
 model.load_state_dict(UpperCAmelCase__							)
 model.eval()

 snake_case :			Tuple							=   """cuda""" if torch.cuda.is_available() else """cpu"""
 model.to(UpperCAmelCase__							)

 # load image processor
 snake_case :			int							=   DetaImageProcessor(format='''coco_detection'''							)

 # verify our conversion on image
 snake_case :			List[Any]							=   prepare_img()
 snake_case :			List[str]							=   processor(images=UpperCAmelCase__			,  return_tensors='''pt'''							)
 snake_case :			Optional[Any]							=   encoding["""pixel_values"""]
 snake_case :			Any							=   model(pixel_values.to(UpperCAmelCase__							)							)

 # verify logits
 if model_name == "deta-resnet-50":
  snake_case :			str							=   torch.tensor(
      [[-7.3978, -2.5406, -4.1668], [-8.2684, -3.9933, -3.8096], [-7.0515, -3.7973, -5.8516]]							)
  snake_case :			Dict							=   torch.tensor([[0.5043, 0.4973, 0.9998], [0.2542, 0.5489, 0.4748], [0.5490, 0.2765, 0.0570]]							)
 elif model_name == "deta-resnet-50-24-epochs":
  snake_case :			List[Any]							=   torch.tensor(
      [[-7.1688, -2.4857, -4.8669], [-7.8630, -3.8154, -4.2674], [-7.2730, -4.1865, -5.5323]]							)
  snake_case :			Tuple							=   torch.tensor([[0.5021, 0.4971, 0.9994], [0.2546, 0.5486, 0.4731], [0.1686, 0.1986, 0.2142]]							)

 assert torch.allclose(outputs.logits[0, :3, :3]			,  expected_logits.to(UpperCAmelCase__							)			,  atol=1E-4							)
 assert torch.allclose(outputs.pred_boxes[0, :3, :3]			,  expected_boxes.to(UpperCAmelCase__							)			,  atol=1E-4							)
 print('''Everything ok!'''							)

 if pytorch_dump_folder_path:
  # Save model and processor
  logger.info(f'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...'''							)
  Path(UpperCAmelCase__							).mkdir(exist_ok=UpperCAmelCase__							)
  model.save_pretrained(UpperCAmelCase__							)
  processor.save_pretrained(UpperCAmelCase__							)

 # Push to hub
 if push_to_hub:
  print('''Pushing model and processor to hub...'''							)
  model.push_to_hub(f'''jozhang97/{model_name}'''							)
  processor.push_to_hub(f'''jozhang97/{model_name}'''							)


if __name__ == "__main__":
  a					:				Optional[int]       =      argparse.ArgumentParser()

  parser.add_argument(
      '--model_name',
      type=str,
      default='deta-resnet-50',
      choices=['deta-resnet-50', 'deta-resnet-50-24-epochs'],
      help='Name of the model you\'d like to convert.',
  )
  parser.add_argument(
      '--pytorch_dump_folder_path',
      default=None,
      type=str,
      help='Path to the folder to output PyTorch model.',
  )
  parser.add_argument(
      '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
  )
  a					:				List[Any]       =      parser.parse_args()
  convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)














"""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


A_     =				get_logger(__name__)




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




def   _lowerCAmelCase		(				UpperCAmelCase__							:       Any,    UpperCAmelCase__							:       Union[str, Any],    UpperCAmelCase__							:       Union[str, Any],    UpperCAmelCase__							:       Dict,    UpperCAmelCase__							:       Tuple,    UpperCAmelCase__							:       Optional[Any]=None,    UpperCAmelCase__							:       str=None,    **UpperCAmelCase__							:       Optional[int],    )		->List[str]:
						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__    :	Union[str, Any]			=	"""cpu"""
						elif map_location == "on_device":
												A__    :	Any			=	PartialState().device
						# Model states
						for i, model in enumerate(UpperCAmelCase__   ):
												A__    :	Any			=	f'{MODEL_NAME}.bin' if i == 0 else f'{MODEL_NAME}_{i}.bin'
												A__    :	List[str]			=	os.path.join(UpperCAmelCase__,    UpperCAmelCase__   )
												models[i].load_state_dict(torch.load(UpperCAmelCase__,    map_location=UpperCAmelCase__   ),    **UpperCAmelCase__   )
						logger.info("""All model weights loaded successfully"""   )

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

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

						# GradScaler state
						if scaler is not None:
												A__    :	List[str]			=	os.path.join(UpperCAmelCase__,    UpperCAmelCase__   )
												scaler.load_state_dict(torch.load(UpperCAmelCase__   )   )
												logger.info("""GradScaler state loaded successfully"""   )

						# Random states
						try:
												A__    :	Any			=	torch.load(os.path.join(UpperCAmelCase__,    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		(				UpperCAmelCase__							:       Tuple,    UpperCAmelCase__							:       Dict,    UpperCAmelCase__							:       int = 0   )		->Dict:
						A__    :	Dict			=	Path(UpperCAmelCase__   ) / f'custom_checkpoint_{index}.pkl'
						logger.info(f'Saving the state of {get_pretty_name(UpperCAmelCase__   )} to {save_location}'   )
						torch.save(obj.state_dict(),    UpperCAmelCase__   )




def   _lowerCAmelCase		(				UpperCAmelCase__							:       Tuple,    UpperCAmelCase__							:       str,    UpperCAmelCase__							:       int = 0   )		->str:
						A__    :	Optional[int]			=	f'{path}/custom_checkpoint_{index}.pkl'
						logger.info(f'Loading the state of {get_pretty_name(UpperCAmelCase__   )} from {load_location}'   )
						obj.load_state_dict(torch.load(UpperCAmelCase__,    map_location="""cpu"""   )   )






