



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  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase=None):
					UpperCamelCase_			= 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.
										UpperCamelCase_			= weight.view(torch.intaa)
										UpperCamelCase_			= "bfloat16"
					UpperCamelCase_			= weight.cpu().numpy()
					UpperCamelCase_			= os.path.join(_lowerCAmelCase ,						f"""{weight_name}.dat""")
					if index is not None:
										if dtype is None:
															UpperCamelCase_			= str(array.dtype)
										UpperCamelCase_			= {"dtype": dtype, "shape": list(array.shape)}
					if array.ndim == 0:
										UpperCamelCase_			= array[None]
					UpperCamelCase_			= np.memmap(_lowerCAmelCase ,						dtype=array.dtype ,						mode="w+" ,						shape=array.shape)
					UpperCamelCase_			= array[:]
					file_array.flush()
					return index



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase):
					UpperCamelCase_			= tuple(weight_info["shape"])
					if shape == ():
										# NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
										UpperCamelCase_			= (1,)

					UpperCamelCase_			= weight_info["dtype"]
					if dtype == "bfloat16":
										# NumPy does not support bfloat16 so this was saved as a int16
										UpperCamelCase_			= "int16"

					UpperCamelCase_			= np.memmap(_lowerCAmelCase ,						dtype=_lowerCAmelCase ,						shape=_lowerCAmelCase ,						mode="r")

					if len(weight_info["shape"]) == 0:
										UpperCamelCase_			= weight[0]
					UpperCamelCase_			= torch.tensor(_lowerCAmelCase)
					if weight_info["dtype"] == "bfloat16":
										UpperCamelCase_			= weight.view(torch.bfloataa)

					return weight



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase):
					if index is None or len(_lowerCAmelCase) == 0:
										# Nothing to save
										return

					UpperCamelCase_			= os.path.join(_lowerCAmelCase ,						"index.json")
					if os.path.isfile(_lowerCAmelCase):
										with open(_lowerCAmelCase ,						"r" ,						encoding="utf-8") as f:
															UpperCamelCase_			= json.load(_lowerCAmelCase)
					else:
										UpperCamelCase_			= {}
					current_index.update(_lowerCAmelCase)

					with open(_lowerCAmelCase ,						"w" ,						encoding="utf-8") as f:
										json.dump(_lowerCAmelCase ,						_lowerCAmelCase ,						indent=2)



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase):
					os.makedirs(_lowerCAmelCase ,						exist_ok=_lowerCAmelCase)
					UpperCamelCase_			= {}
					for name, parameter in state_dict.items():
										UpperCamelCase_			= offload_weight(_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase ,						index=_lowerCAmelCase)

					# Update index
					save_offload_index(_lowerCAmelCase ,						_lowerCAmelCase)


class    _lowercase (a_   ):
				'''simple docstring'''







				def __init__(			self  ,			snake_case__  ,			snake_case__     ):

									'''simple docstring'''


									UpperCamelCase_			= dataset
									UpperCamelCase_			= prefix

				def __getitem__(			self  ,			snake_case__     ):

									'''simple docstring'''


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

				def __iter__(			self     ):

									'''simple docstring'''


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

				def __len__(			self     ):

									'''simple docstring'''


									return len(self.dataset     )




class    _lowercase (a_   ):
				'''simple docstring'''







				def __init__(			self  ,			snake_case__ = None  ,			snake_case__ = None  ,			snake_case__ = None  ,			snake_case__=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."     )

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

				def __getitem__(			self  ,			snake_case__     ):

									'''simple docstring'''


									if key in self.state_dict:
														return self.state_dict[key]
									UpperCamelCase_			= 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

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

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

									UpperCamelCase_			= os.path.join(self.save_folder  ,			F"""{key}.dat"""     )
									return load_offloaded_weight(snake_case__  ,			snake_case__     )

				def __iter__(			self     ):

									'''simple docstring'''


									return iter(self.all_keys     )

				def __len__(			self     ):

									'''simple docstring'''


									return len(self.all_keys     )




def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase):
					UpperCamelCase_			= {}
					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





UpperCAmelCase :				Optional[int]							="""
# Diffusers installation
! pip install diffusers transformers datasets accelerate
# To install from source instead of the last release, comment the command above and uncomment the following one.
# ! pip install git+https://github.com/huggingface/diffusers.git
"""

UpperCAmelCase :				List[Any]							=[{"""type""": """code""", """content""": INSTALL_CONTENT}]
