


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







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

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

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

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

							return weight







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

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

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







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

							# Update index
							save_offload_index(UpperCamelCase_	,     UpperCamelCase_   )






class 				__lowerCAmelCase      (      lowercase	):

						"""simple docstring"""






						def __init__(     self       :			Union[str, Any]   ,     lowerCAmelCase       :			Mapping   ,     lowerCAmelCase       :			str  ):
													A_ 						=		dataset
													A_ 						=		prefix






						def __getitem__(     self       :			List[str]   ,     lowerCAmelCase       :			Union[str, Any]  ):
													return self.dataset[F"{self.prefix}{key}"]






						def __iter__(     self       :			Optional[int]  ):
													return iter([key for key in self.dataset if key.startswith(self.prefix  )]  )






						def __len__(     self       :			Any  ):
													return len(self.dataset  )






class 				__lowerCAmelCase      (      lowercase	):

						"""simple docstring"""






						def __init__(     self       :			Union[str, Any]   ,     lowerCAmelCase       :			Dict[str, torch.Tensor] = None   ,     lowerCAmelCase       :			Optional[Union[str, os.PathLike]] = None   ,     lowerCAmelCase       :			Mapping = None   ,     lowerCAmelCase       :			Any=None   ,     ):
													if state_dict is None and save_folder is None:
																				raise ValueError("Need either a `state_dict` or a `save_folder` containing offloaded weights."  )

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






						def __getitem__(     self       :			List[str]   ,     lowerCAmelCase       :			str  ):
													# State dict gets priority
													if key in self.state_dict:
																				return self.state_dict[key]
													A_ 						=		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

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

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

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






						def __iter__(     self       :			Union[str, Any]  ):
													return iter(self.all_keys  )






						def __len__(     self       :			Optional[Any]  ):
													return len(self.all_keys  )







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









'''simple docstring'''
def 			a_							(  UpperCamelCase_	,     UpperCamelCase_ = 1_0_0_0   ):
							if (not isinstance(UpperCamelCase_	,     UpperCamelCase_   )) or (digit_position <= 0):
														raise ValueError("Digit position must be a positive integer"   )
							elif (not isinstance(UpperCamelCase_	,     UpperCamelCase_   )) or (precision < 0):
														raise ValueError("Precision must be a nonnegative integer"   )

							# compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly
							# accurate
							A_ 						=		(
							    4 * _subsum(UpperCamelCase_	,     1	,     UpperCamelCase_   )
							    - 2 * _subsum(UpperCamelCase_	,     4	,     UpperCamelCase_   )
							    - _subsum(UpperCamelCase_	,     5	,     UpperCamelCase_   )
							    - _subsum(UpperCamelCase_	,     6	,     UpperCamelCase_   )
							)

							# return the first hex digit of the fractional part of the result
							return hex(int((sum_result % 1) * 1_6   )   )[2:]







def 			a_							(  UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_   ):
							A_ 						=		0.0
							for sum_index in range(digit_pos_to_extract + precision   ):
														A_ 						=		8 * sum_index + denominator_addend
														if sum_index < digit_pos_to_extract:
																					# if the exponential term is an integer and we mod it by the denominator
																					# before dividing, only the integer part of the sum will change;
																					# the fractional part will not
																					A_ 						=		pow(
																					    1_6	,     digit_pos_to_extract - 1 - sum_index	,     UpperCamelCase_   )
														else:
																					A_ 						=		pow(1_6	,     digit_pos_to_extract - 1 - sum_index   )
														total += exponential_term / denominator
							return total


if __name__ == "__main__":
							import doctest

							doctest.testmod()





