





'''simple docstring'''


import argparse
import json

import torch

from diffusers import AutoencoderKL, DDPMPipeline, DDPMScheduler, UNetaDModel, VQModel
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Any			,__lowerCamelCase      :      int=1				):
   if n_shave_prefix_segments >= 0:
      return ".".join(path.split("."				)[n_shave_prefix_segments:]				)
   else:
      return ".".join(path.split("."				)[:n_shave_prefix_segments]				)
def 							UpperCAmelCase_						(		__lowerCamelCase      :      List[str]			,__lowerCamelCase      :      List[Any]=0				):
   lowercase_    :str					    =				[]
   for old_item in old_list:
      lowercase_    :Optional[int]					    =				old_item
      lowercase_    :Union[str, Any]					    =				new_item.replace("block."			,"resnets."				)
      lowercase_    :Any					    =				new_item.replace("conv_shorcut"			,"conv1"				)
      lowercase_    :Optional[int]					    =				new_item.replace("in_shortcut"			,"conv_shortcut"				)
      lowercase_    :Dict					    =				new_item.replace("temb_proj"			,"time_emb_proj"				)

      lowercase_    :Any					    =				shave_segments(__lowerCamelCase			,n_shave_prefix_segments=__lowerCamelCase				)

      mapping.append({"old": old_item, "new": new_item}				)

   return mapping
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Union[str, Any]			,__lowerCamelCase      :      Optional[int]=0			,__lowerCamelCase      :      int=False				):
   lowercase_    :Tuple					    =				[]
   for old_item in old_list:
      lowercase_    :Optional[int]					    =				old_item

      # In `model.mid`, the layer is called `attn`.
      if not in_mid:
         lowercase_    :Dict					    =				new_item.replace("attn"			,"attentions"				)
      lowercase_    :Any					    =				new_item.replace(".k."			,".key."				)
      lowercase_    :Any					    =				new_item.replace(".v."			,".value."				)
      lowercase_    :int					    =				new_item.replace(".q."			,".query."				)

      lowercase_    :int					    =				new_item.replace("proj_out"			,"proj_attn"				)
      lowercase_    :Any					    =				new_item.replace("norm"			,"group_norm"				)

      lowercase_    :str					    =				shave_segments(__lowerCamelCase			,n_shave_prefix_segments=__lowerCamelCase				)
      mapping.append({"old": old_item, "new": new_item}				)

   return mapping
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Tuple			,__lowerCamelCase      :      Union[str, Any]			,__lowerCamelCase      :      List[Any]			,__lowerCamelCase      :      List[Any]=None			,__lowerCamelCase      :      Tuple=None			,__lowerCamelCase      :      Dict=None				):
   assert isinstance(__lowerCamelCase			,__lowerCamelCase				), "Paths should be a list of dicts containing 'old' and 'new' keys."

   if attention_paths_to_split is not None:
      if config is None:
         raise ValueError("Please specify the config if setting 'attention_paths_to_split' to 'True'."				)

      for path, path_map in attention_paths_to_split.items():
         lowercase_    :Optional[Any]					    =				old_checkpoint[path]
         lowercase_    :List[Any]					    =				old_tensor.shape[0] // 3

         lowercase_    :Optional[Any]					    =				(-1, channels) if len(old_tensor.shape				) == 3 else (-1)

         lowercase_    :Dict					    =				old_tensor.shape[0] // config.get("num_head_channels"			,1				) // 3

         lowercase_    :str					    =				old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:]				)
         lowercase_    ,							lowercase_    ,							lowercase_    :List[Any]					    =				old_tensor.split(channels // num_heads			,dim=1				)

         lowercase_    :List[str]					    =				query.reshape(__lowerCamelCase				).squeeze()
         lowercase_    :int					    =				key.reshape(__lowerCamelCase				).squeeze()
         lowercase_    :Union[str, Any]					    =				value.reshape(__lowerCamelCase				).squeeze()

   for path in paths:
      lowercase_    :str					    =				path["new"]

      if attention_paths_to_split is not None and new_path in attention_paths_to_split:
         continue

      lowercase_    :Tuple					    =				new_path.replace("down."			,"down_blocks."				)
      lowercase_    :Tuple					    =				new_path.replace("up."			,"up_blocks."				)

      if additional_replacements is not None:
         for replacement in additional_replacements:
            lowercase_    :List[str]					    =				new_path.replace(replacement["old"]			,replacement["new"]				)

      if "attentions" in new_path:
         lowercase_    :int					    =				old_checkpoint[path["old"]].squeeze()
      else:
         lowercase_    :List[Any]					    =				old_checkpoint[path["old"]]
def 							UpperCAmelCase_						(		__lowerCamelCase      :      List[str]			,__lowerCamelCase      :      Tuple				):
   lowercase_    :Optional[int]					    =				{}

   lowercase_    :List[Any]					    =				checkpoint["temb.dense.0.weight"]
   lowercase_    :Dict					    =				checkpoint["temb.dense.0.bias"]
   lowercase_    :Optional[int]					    =				checkpoint["temb.dense.1.weight"]
   lowercase_    :Optional[int]					    =				checkpoint["temb.dense.1.bias"]

   lowercase_    :List[Any]					    =				checkpoint["norm_out.weight"]
   lowercase_    :Dict					    =				checkpoint["norm_out.bias"]

   lowercase_    :Dict					    =				checkpoint["conv_in.weight"]
   lowercase_    :Optional[Any]					    =				checkpoint["conv_in.bias"]
   lowercase_    :Dict					    =				checkpoint["conv_out.weight"]
   lowercase_    :Union[str, Any]					    =				checkpoint["conv_out.bias"]

   lowercase_    :int					    =				len({".".join(layer.split("."				)[:2]				) for layer in checkpoint if "down" in layer}				)
   lowercase_    :List[Any]					    =				{
       layer_id: [key for key in checkpoint if F'down.{layer_id}' in key] for layer_id in range(__lowerCamelCase				)
   }

   lowercase_    :List[Any]					    =				len({".".join(layer.split("."				)[:2]				) for layer in checkpoint if "up" in layer}				)
   lowercase_    :List[Any]					    =				{layer_id: [key for key in checkpoint if F'up.{layer_id}' in key] for layer_id in range(__lowerCamelCase				)}

   for i in range(__lowerCamelCase				):
      lowercase_    :Optional[Any]					    =				(i - 1) // (config["layers_per_block"] + 1)

      if any("downsample" in layer for layer in down_blocks[i]				):
         lowercase_    :Dict					    =				checkpoint[
             F'down.{i}.downsample.op.weight'
         ]
         lowercase_    :Union[str, Any]					    =				checkpoint[F'down.{i}.downsample.op.bias']
      #            new_checkpoint[f'down_blocks.{i}.downsamplers.0.op.weight'] = checkpoint[f'down.{i}.downsample.conv.weight']
      #            new_checkpoint[f'down_blocks.{i}.downsamplers.0.op.bias'] = checkpoint[f'down.{i}.downsample.conv.bias']

      if any("block" in layer for layer in down_blocks[i]				):
         lowercase_    :Any					    =				len(
             {".".join(shave_segments(__lowerCamelCase			,2				).split("."				)[:2]				) for layer in down_blocks[i] if "block" in layer}				)
         lowercase_    :str					    =				{
             layer_id: [key for key in down_blocks[i] if F'block.{layer_id}' in key]
             for layer_id in range(__lowerCamelCase				)
         }

         if num_blocks > 0:
            for j in range(config["layers_per_block"]				):
               lowercase_    :List[str]					    =				renew_resnet_paths(blocks[j]				)
               assign_to_checkpoint(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase				)

      if any("attn" in layer for layer in down_blocks[i]				):
         lowercase_    :Union[str, Any]					    =				len(
             {".".join(shave_segments(__lowerCamelCase			,2				).split("."				)[:2]				) for layer in down_blocks[i] if "attn" in layer}				)
         lowercase_    :List[Any]					    =				{
             layer_id: [key for key in down_blocks[i] if F'attn.{layer_id}' in key]
             for layer_id in range(__lowerCamelCase				)
         }

         if num_attn > 0:
            for j in range(config["layers_per_block"]				):
               lowercase_    :Union[str, Any]					    =				renew_attention_paths(attns[j]				)
               assign_to_checkpoint(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,config=__lowerCamelCase				)

   lowercase_    :Optional[Any]					    =				[key for key in checkpoint if "mid.block_1" in key]
   lowercase_    :List[str]					    =				[key for key in checkpoint if "mid.block_2" in key]
   lowercase_    :Optional[Any]					    =				[key for key in checkpoint if "mid.attn_1" in key]

   # Mid new 2
   lowercase_    :Dict					    =				renew_resnet_paths(__lowerCamelCase				)
   assign_to_checkpoint(
       __lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "block_1", "new": "resnets.0"}]			,)

   lowercase_    :Union[str, Any]					    =				renew_resnet_paths(__lowerCamelCase				)
   assign_to_checkpoint(
       __lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "block_2", "new": "resnets.1"}]			,)

   lowercase_    :List[str]					    =				renew_attention_paths(__lowerCamelCase			,in_mid=__lowerCamelCase				)
   assign_to_checkpoint(
       __lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "attn_1", "new": "attentions.0"}]			,)

   for i in range(__lowerCamelCase				):
      lowercase_    :Any					    =				num_up_blocks - 1 - i

      if any("upsample" in layer for layer in up_blocks[i]				):
         lowercase_    :int					    =				checkpoint[
             F'up.{i}.upsample.conv.weight'
         ]
         lowercase_    :Union[str, Any]					    =				checkpoint[F'up.{i}.upsample.conv.bias']

      if any("block" in layer for layer in up_blocks[i]				):
         lowercase_    :Tuple					    =				len(
             {".".join(shave_segments(__lowerCamelCase			,2				).split("."				)[:2]				) for layer in up_blocks[i] if "block" in layer}				)
         lowercase_    :List[str]					    =				{
             layer_id: [key for key in up_blocks[i] if F'block.{layer_id}' in key] for layer_id in range(__lowerCamelCase				)
         }

         if num_blocks > 0:
            for j in range(config["layers_per_block"] + 1				):
               lowercase_    :Optional[Any]					    =				{"old": F'up_blocks.{i}', "new": F'up_blocks.{block_id}'}
               lowercase_    :Dict					    =				renew_resnet_paths(blocks[j]				)
               assign_to_checkpoint(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[replace_indices]				)

      if any("attn" in layer for layer in up_blocks[i]				):
         lowercase_    :Tuple					    =				len(
             {".".join(shave_segments(__lowerCamelCase			,2				).split("."				)[:2]				) for layer in up_blocks[i] if "attn" in layer}				)
         lowercase_    :List[str]					    =				{
             layer_id: [key for key in up_blocks[i] if F'attn.{layer_id}' in key] for layer_id in range(__lowerCamelCase				)
         }

         if num_attn > 0:
            for j in range(config["layers_per_block"] + 1				):
               lowercase_    :Optional[Any]					    =				{"old": F'up_blocks.{i}', "new": F'up_blocks.{block_id}'}
               lowercase_    :str					    =				renew_attention_paths(attns[j]				)
               assign_to_checkpoint(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[replace_indices]				)

   lowercase_    :List[Any]					    =				{k.replace("mid_new_2"			,"mid_block"				): v for k, v in new_checkpoint.items()}
   return new_checkpoint
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Optional[Any]			,__lowerCamelCase      :      Any				):
   lowercase_    :List[Any]					    =				{}

   lowercase_    :Any					    =				checkpoint["encoder.norm_out.weight"]
   lowercase_    :Optional[int]					    =				checkpoint["encoder.norm_out.bias"]

   lowercase_    :Dict					    =				checkpoint["encoder.conv_in.weight"]
   lowercase_    :Tuple					    =				checkpoint["encoder.conv_in.bias"]
   lowercase_    :Tuple					    =				checkpoint["encoder.conv_out.weight"]
   lowercase_    :Optional[int]					    =				checkpoint["encoder.conv_out.bias"]

   lowercase_    :Any					    =				checkpoint["decoder.norm_out.weight"]
   lowercase_    :int					    =				checkpoint["decoder.norm_out.bias"]

   lowercase_    :Optional[Any]					    =				checkpoint["decoder.conv_in.weight"]
   lowercase_    :Union[str, Any]					    =				checkpoint["decoder.conv_in.bias"]
   lowercase_    :str					    =				checkpoint["decoder.conv_out.weight"]
   lowercase_    :str					    =				checkpoint["decoder.conv_out.bias"]

   lowercase_    :str					    =				len({".".join(layer.split("."				)[:3]				) for layer in checkpoint if "down" in layer}				)
   lowercase_    :int					    =				{
       layer_id: [key for key in checkpoint if F'down.{layer_id}' in key] for layer_id in range(__lowerCamelCase				)
   }

   lowercase_    :int					    =				len({".".join(layer.split("."				)[:3]				) for layer in checkpoint if "up" in layer}				)
   lowercase_    :List[str]					    =				{layer_id: [key for key in checkpoint if F'up.{layer_id}' in key] for layer_id in range(__lowerCamelCase				)}

   for i in range(__lowerCamelCase				):
      lowercase_    :Optional[int]					    =				(i - 1) // (config["layers_per_block"] + 1)

      if any("downsample" in layer for layer in down_blocks[i]				):
         lowercase_    :Tuple					    =				checkpoint[
             F'encoder.down.{i}.downsample.conv.weight'
         ]
         lowercase_    :List[str]					    =				checkpoint[
             F'encoder.down.{i}.downsample.conv.bias'
         ]

      if any("block" in layer for layer in down_blocks[i]				):
         lowercase_    :Optional[Any]					    =				len(
             {".".join(shave_segments(__lowerCamelCase			,3				).split("."				)[:3]				) for layer in down_blocks[i] if "block" in layer}				)
         lowercase_    :List[str]					    =				{
             layer_id: [key for key in down_blocks[i] if F'block.{layer_id}' in key]
             for layer_id in range(__lowerCamelCase				)
         }

         if num_blocks > 0:
            for j in range(config["layers_per_block"]				):
               lowercase_    :Dict					    =				renew_resnet_paths(blocks[j]				)
               assign_to_checkpoint(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase				)

      if any("attn" in layer for layer in down_blocks[i]				):
         lowercase_    :str					    =				len(
             {".".join(shave_segments(__lowerCamelCase			,3				).split("."				)[:3]				) for layer in down_blocks[i] if "attn" in layer}				)
         lowercase_    :Optional[Any]					    =				{
             layer_id: [key for key in down_blocks[i] if F'attn.{layer_id}' in key]
             for layer_id in range(__lowerCamelCase				)
         }

         if num_attn > 0:
            for j in range(config["layers_per_block"]				):
               lowercase_    :str					    =				renew_attention_paths(attns[j]				)
               assign_to_checkpoint(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,config=__lowerCamelCase				)

   lowercase_    :str					    =				[key for key in checkpoint if "mid.block_1" in key]
   lowercase_    :Union[str, Any]					    =				[key for key in checkpoint if "mid.block_2" in key]
   lowercase_    :Union[str, Any]					    =				[key for key in checkpoint if "mid.attn_1" in key]

   # Mid new 2
   lowercase_    :Union[str, Any]					    =				renew_resnet_paths(__lowerCamelCase				)
   assign_to_checkpoint(
       __lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "block_1", "new": "resnets.0"}]			,)

   lowercase_    :Optional[int]					    =				renew_resnet_paths(__lowerCamelCase				)
   assign_to_checkpoint(
       __lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "block_2", "new": "resnets.1"}]			,)

   lowercase_    :str					    =				renew_attention_paths(__lowerCamelCase			,in_mid=__lowerCamelCase				)
   assign_to_checkpoint(
       __lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "attn_1", "new": "attentions.0"}]			,)

   for i in range(__lowerCamelCase				):
      lowercase_    :int					    =				num_up_blocks - 1 - i

      if any("upsample" in layer for layer in up_blocks[i]				):
         lowercase_    :Dict					    =				checkpoint[
             F'decoder.up.{i}.upsample.conv.weight'
         ]
         lowercase_    :Optional[int]					    =				checkpoint[
             F'decoder.up.{i}.upsample.conv.bias'
         ]

      if any("block" in layer for layer in up_blocks[i]				):
         lowercase_    :Tuple					    =				len(
             {".".join(shave_segments(__lowerCamelCase			,3				).split("."				)[:3]				) for layer in up_blocks[i] if "block" in layer}				)
         lowercase_    :int					    =				{
             layer_id: [key for key in up_blocks[i] if F'block.{layer_id}' in key] for layer_id in range(__lowerCamelCase				)
         }

         if num_blocks > 0:
            for j in range(config["layers_per_block"] + 1				):
               lowercase_    :Optional[Any]					    =				{"old": F'up_blocks.{i}', "new": F'up_blocks.{block_id}'}
               lowercase_    :int					    =				renew_resnet_paths(blocks[j]				)
               assign_to_checkpoint(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[replace_indices]				)

      if any("attn" in layer for layer in up_blocks[i]				):
         lowercase_    :Any					    =				len(
             {".".join(shave_segments(__lowerCamelCase			,3				).split("."				)[:3]				) for layer in up_blocks[i] if "attn" in layer}				)
         lowercase_    :int					    =				{
             layer_id: [key for key in up_blocks[i] if F'attn.{layer_id}' in key] for layer_id in range(__lowerCamelCase				)
         }

         if num_attn > 0:
            for j in range(config["layers_per_block"] + 1				):
               lowercase_    :int					    =				{"old": F'up_blocks.{i}', "new": F'up_blocks.{block_id}'}
               lowercase_    :Optional[Any]					    =				renew_attention_paths(attns[j]				)
               assign_to_checkpoint(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,additional_replacements=[replace_indices]				)

   lowercase_    :Optional[Any]					    =				{k.replace("mid_new_2"			,"mid_block"				): v for k, v in new_checkpoint.items()}
   lowercase_    :List[Any]					    =				checkpoint["quant_conv.weight"]
   lowercase_    :Dict					    =				checkpoint["quant_conv.bias"]
   if "quantize.embedding.weight" in checkpoint:
      lowercase_    :Tuple					    =				checkpoint["quantize.embedding.weight"]
   lowercase_    :List[str]					    =				checkpoint["post_quant_conv.weight"]
   lowercase_    :Dict					    =				checkpoint["post_quant_conv.bias"]

   return new_checkpoint


if __name__ == "__main__":
 lowerCAmelCase      :  Any      							=argparse.ArgumentParser()

 parser.add_argument(
     '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.'''
 )

 parser.add_argument(
     '''--config_file''',
     default=None,
     type=str,
     required=True,
     help='''The config json file corresponding to the architecture.''',
 )

 parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''')

 lowerCAmelCase      :  Union[str, Any]      							=parser.parse_args()
 lowerCAmelCase      :  str      							=torch.load(args.checkpoint_path)

 with open(args.config_file) as f:
  lowerCAmelCase      :  List[str]      							=json.loads(f.read())

 # unet case
 lowerCAmelCase      :  Optional[int]      							={key.split('''.''')[0] for key in checkpoint.keys()}
 if "encoder" in key_prefix_set and "decoder" in key_prefix_set:
  lowerCAmelCase      :  int      							=convert_vq_autoenc_checkpoint(checkpoint, config)
 else:
  lowerCAmelCase      :  Optional[Any]      							=convert_ddpm_checkpoint(checkpoint, config)

 if "ddpm" in config:
  del config["ddpm"]

 if config["_class_name"] == "VQModel":
  lowerCAmelCase      :  List[str]      							=VQModel(**config)
  model.load_state_dict(converted_checkpoint)
  model.save_pretrained(args.dump_path)
 elif config["_class_name"] == "AutoencoderKL":
  lowerCAmelCase      :  Optional[Any]      							=AutoencoderKL(**config)
  model.load_state_dict(converted_checkpoint)
  model.save_pretrained(args.dump_path)
 else:
  lowerCAmelCase      :  Union[str, Any]      							=UNetaDModel(**config)
  model.load_state_dict(converted_checkpoint)

  lowerCAmelCase      :  Dict      							=DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1]))

  lowerCAmelCase      :  str      							=DDPMPipeline(unet=model, scheduler=scheduler)
  pipe.save_pretrained(args.dump_path)









'''simple docstring'''


import json
import os
from collections.abc import Mapping
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from .imports import is_safetensors_available
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Optional[int]			,__lowerCamelCase      :      Union[str, Any]			,__lowerCamelCase      :      List[Any]			,__lowerCamelCase      :      str=None				):
   lowercase_    :List[Any]					    =				None
   # Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
   if str(weight.dtype				) == "torch.bfloat16":
      # Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
      lowercase_    :int					    =				weight.view(torch.intaa				)
      lowercase_    :List[Any]					    =				"bfloat16"
   lowercase_    :Optional[Any]					    =				weight.cpu().numpy()
   lowercase_    :Optional[int]					    =				os.path.join(__lowerCamelCase			,F'{weight_name}.dat'				)
   if index is not None:
      if dtype is None:
         lowercase_    :str					    =				str(array.dtype				)
      lowercase_    :int					    =				{"dtype": dtype, "shape": list(array.shape				)}
   if array.ndim == 0:
      lowercase_    :int					    =				array[None]
   lowercase_    :List[Any]					    =				np.memmap(__lowerCamelCase			,dtype=array.dtype			,mode="w+"			,shape=array.shape				)
   lowercase_    :List[Any]					    =				array[:]
   file_array.flush()
   return index
def 							UpperCAmelCase_						(		__lowerCamelCase      :      int			,__lowerCamelCase      :      Dict				):
   lowercase_    :int					    =				tuple(weight_info["shape"]				)
   if shape == ():
      # NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
      lowercase_    :List[str]					    =				(1,)

   lowercase_    :List[str]					    =				weight_info["dtype"]
   if dtype == "bfloat16":
      # NumPy does not support bfloat16 so this was saved as a int16
      lowercase_    :Optional[Any]					    =				"int16"

   lowercase_    :str					    =				np.memmap(__lowerCamelCase			,dtype=__lowerCamelCase			,shape=__lowerCamelCase			,mode="r"				)

   if len(weight_info["shape"]				) == 0:
      lowercase_    :Union[str, Any]					    =				weight[0]
   lowercase_    :str					    =				torch.tensor(__lowerCamelCase				)
   if weight_info["dtype"] == "bfloat16":
      lowercase_    :Any					    =				weight.view(torch.bfloataa				)

   return weight
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Dict			,__lowerCamelCase      :      List[str]				):
   if index is None or len(__lowerCamelCase				) == 0:
      # Nothing to save
      return

   lowercase_    :List[Any]					    =				os.path.join(__lowerCamelCase			,"index.json"				)
   if os.path.isfile(__lowerCamelCase				):
      with open(__lowerCamelCase			,"r"			,encoding="utf-8"				) as f:
         lowercase_    :Any					    =				json.load(__lowerCamelCase				)
   else:
      lowercase_    :Union[str, Any]					    =				{}
   current_index.update(__lowerCamelCase				)

   with open(__lowerCamelCase			,"w"			,encoding="utf-8"				) as f:
      json.dump(__lowerCamelCase			,__lowerCamelCase			,indent=2				)
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Union[str, os.PathLike]			,__lowerCamelCase      :      Dict[str, torch.Tensor]				):
   os.makedirs(__lowerCamelCase			,exist_ok=__lowerCamelCase				)
   lowercase_    :List[Any]					    =				{}
   for name, parameter in state_dict.items():
      lowercase_    :Tuple					    =				offload_weight(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,index=__lowerCamelCase				)

   # Update index
   save_offload_index(__lowerCamelCase			,__lowerCamelCase				)
class    a_     (       _lowerCAmelCase							):





     def __init__(				self	:      int			,   lowercase	:      Mapping			,   lowercase	:      str		):





        """simple docstring"""




        lowercase_    :Union[str, Any]					    =				dataset
        lowercase_    :List[str]					    =				prefix





     def __getitem__(				self	:      Any			,   lowercase	:      List[str]		):





        """simple docstring"""




        return self.dataset[F'{self.prefix}{key}']





     def __iter__(				self	:      Optional[int]		):





        """simple docstring"""




        return iter([key for key in self.dataset if key.startswith(self.prefix		)]		)







     def __len__(				self	:      Any		):





        """simple docstring"""




        return len(self.dataset		)







class    a_     (       _lowerCAmelCase							):





     def __init__(				self	:      Tuple			,   lowercase	:      Dict[str, torch.Tensor] = None			,   lowercase	:      Optional[Union[str, os.PathLike]] = None			,   lowercase	:      Mapping = None			,   lowercase	:      Optional[Any]=None			,   ):





        """simple docstring"""




        if state_dict is None and save_folder is None:
           raise ValueError("Need either a `state_dict` or a `save_folder` containing offloaded weights."		)

        lowercase_    :Optional[int]					    =				{} if state_dict is None else state_dict
        lowercase_    :str					    =				save_folder
        if index is None and save_folder is not None:
           with open(os.path.join(lowercase			,   "index.json"		)		) as f:
              lowercase_    :Any					    =				json.load(lowercase		)
        lowercase_    :str					    =				{} if index is None else index
        lowercase_    :List[str]					    =				list(self.state_dict.keys()		)
        self.all_keys.extend([key for key in self.index if key not in self.all_keys]		)
        lowercase_    :List[Any]					    =				device





     def __getitem__(				self	:      Any			,   lowercase	:      str		):





        """simple docstring"""




        if key in self.state_dict:
           return self.state_dict[key]
        lowercase_    :int					    =				self.index[key]
        if weight_info.get("safetensors_file"		) is not None:
           if not is_safetensors_available():
              raise ImportError("These offloaded weights require the use of safetensors: `pip install safetensors`."		)

           from safetensors import safe_open

           lowercase_    :Dict					    =				"cpu" if self.device is None else self.device
           with safe_open(weight_info["safetensors_file"]			,   framework="pt"			,   device=lowercase		) as f:
              lowercase_    :Tuple					    =				f.get_tensor(weight_info.get("weight_name"			,   lowercase		)		)

           if "dtype" in weight_info:
              return tensor.to(getattr(lowercase			,   weight_info["dtype"]		)		)
           else:
              return tensor

        lowercase_    :str					    =				os.path.join(self.save_folder			,   F'{key}.dat'		)
        return load_offloaded_weight(lowercase			,   lowercase		)





     def __iter__(				self	:      Optional[int]		):





        """simple docstring"""




        return iter(self.all_keys		)







     def __len__(				self	:      Tuple		):





        """simple docstring"""




        return len(self.all_keys		)







def 							UpperCAmelCase_						(		__lowerCamelCase      :      Dict[str, torch.Tensor]			,__lowerCamelCase      :      List[str]				):
   lowercase_    :List[str]					    =				{}
   for module_name in submodule_names:
      # We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
      # submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
      result.update(
          {
              key: param
              for key, param in state_dict.items()
              if key == module_name or key.startswith(module_name + "."				)
          }				)
   return result


