





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









'''simple docstring'''


class    a_     :





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





        """simple docstring"""




        lowercase_    :List[str]					    =				val
        # Number of nodes in left subtree
        lowercase_    :Optional[int]					    =				0
        lowercase_    :List[str]					    =				None
        lowercase_    :List[Any]					    =				None
        lowercase_    :Optional[Any]					    =				None







     def 							lowercase__   (				self	:      Union[str, Any]			,   lowercase	:      Dict		):





        """simple docstring"""




        assert self.left_tree_size == other.left_tree_size, "Unequal Sizes of Blocks"

        if self.val < other.val:
           lowercase_    :List[Any]					    =				self.right
           lowercase_    :str					    =				None
           if self.right:
              lowercase_    :Optional[int]					    =				other
           lowercase_    :Optional[Any]					    =				other
           lowercase_    :str					    =				self.left_tree_size * 2 + 1
           return self
        else:
           lowercase_    :Any					    =				other.right
           lowercase_    :Any					    =				None
           if other.right:
              lowercase_    :List[Any]					    =				self
           lowercase_    :Union[str, Any]					    =				self
           lowercase_    :Optional[int]					    =				other.left_tree_size * 2 + 1
           return other







class    a_     :





     def __init__(				self	:      Optional[Any]			,   lowercase	:      Any=None			,   lowercase	:      Optional[Any]=None			,   lowercase	:      int=0		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				heap_size
        lowercase_    :List[str]					    =				bottom_root
        lowercase_    :Dict					    =				min_node





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





        """simple docstring"""




        if other.size == 0:
           return None
        if self.size == 0:
           lowercase_    :Dict					    =				other.size
           lowercase_    :int					    =				other.bottom_root
           lowercase_    :Tuple					    =				other.min_node
           return None
        # Update size
        lowercase_    :Optional[int]					    =				self.size + other.size

        # Update min.node
        if self.min_node.val > other.min_node.val:
           lowercase_    :int					    =				other.min_node
        # Merge

        # Order roots by left_subtree_size
        lowercase_    :Any					    =				[]
        lowercase_    ,							lowercase_    :List[str]					    =				self.bottom_root, other.bottom_root
        while i or j:
           if i and ((not j) or i.left_tree_size < j.left_tree_size):
              combined_roots_list.append((i, True)		)
              lowercase_    :str					    =				i.parent
           else:
              combined_roots_list.append((j, False)		)
              lowercase_    :Dict					    =				j.parent
        # Insert links between them
        for i in range(len(lowercase		) - 1		):
           if combined_roots_list[i][1] != combined_roots_list[i + 1][1]:
              lowercase_    :Dict					    =				combined_roots_list[i + 1][0]
              lowercase_    :str					    =				combined_roots_list[i][0]
        # Consecutively merge roots with same left_tree_size
        lowercase_    :int					    =				combined_roots_list[0][0]
        while i.parent:
           if (
               (i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent)
           ) or (
               i.left_tree_size == i.parent.left_tree_size
               and i.left_tree_size != i.parent.parent.left_tree_size
           ):
              # Neighbouring Nodes
              lowercase_    :List[Any]					    =				i.left
              lowercase_    :Any					    =				i.parent.parent

              # Merging trees
              lowercase_    :Any					    =				i.merge_trees(i.parent		)

              # Updating links
              lowercase_    :List[Any]					    =				previous_node
              lowercase_    :int					    =				next_node
              if previous_node:
                 lowercase_    :int					    =				i
              if next_node:
                 lowercase_    :str					    =				i
           else:
              lowercase_    :str					    =				i.parent
        # Updating self.bottom_root
        while i.left:
           lowercase_    :List[str]					    =				i.left
        lowercase_    :List[str]					    =				i

        # Update other
        lowercase_    :Any					    =				self.size
        lowercase_    :Optional[Any]					    =				self.bottom_root
        lowercase_    :int					    =				self.min_node

        # Return the merged heap
        return self





     def 							lowercase__   (				self	:      int			,   lowercase	:      List[Any]		):





        """simple docstring"""




        if self.size == 0:
           lowercase_    :Dict					    =				Node(lowercase		)
           lowercase_    :Optional[Any]					    =				1
           lowercase_    :Optional[Any]					    =				self.bottom_root
        else:
           # Create new node
           lowercase_    :Union[str, Any]					    =				Node(lowercase		)

           # Update size
           self.size += 1

           # update min_node
           if val < self.min_node.val:
              lowercase_    :Union[str, Any]					    =				new_node
           # Put new_node as a bottom_root in heap
           lowercase_    :int					    =				new_node
           lowercase_    :List[str]					    =				self.bottom_root
           lowercase_    :Any					    =				new_node

           # Consecutively merge roots with same left_tree_size
           while (
               self.bottom_root.parent
               and self.bottom_root.left_tree_size
               == self.bottom_root.parent.left_tree_size
           ):
              # Next node
              lowercase_    :int					    =				self.bottom_root.parent.parent

              # Merge
              lowercase_    :Union[str, Any]					    =				self.bottom_root.merge_trees(self.bottom_root.parent		)

              # Update Links
              lowercase_    :Optional[Any]					    =				next_node
              lowercase_    :Any					    =				None
              if next_node:
                 lowercase_    :Union[str, Any]					    =				self.bottom_root





     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        return self.min_node.val





     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




        return self.size == 0





     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        lowercase_    :str					    =				self.min_node.val

        # Last element in heap corner case
        if self.size == 1:
           # Update size
           lowercase_    :Dict					    =				0

           # Update bottom root
           lowercase_    :int					    =				None

           # Update min_node
           lowercase_    :Tuple					    =				None

           return min_value
        # No right subtree corner case
        # The structure of the tree implies that this should be the bottom root
        # and there is at least one other root
        if self.min_node.right is None:
           # Update size
           self.size -= 1

           # Update bottom root
           lowercase_    :Optional[Any]					    =				self.bottom_root.parent
           lowercase_    :Tuple					    =				None

           # Update min_node
           lowercase_    :Dict					    =				self.bottom_root
           lowercase_    :List[str]					    =				self.bottom_root.parent
           while i:
              if i.val < self.min_node.val:
                 lowercase_    :Union[str, Any]					    =				i
              lowercase_    :Dict					    =				i.parent
           return min_value
        # General case
        # Find the BinomialHeap of the right subtree of min_node
        lowercase_    :List[str]					    =				self.min_node.right
        lowercase_    :Dict					    =				None
        lowercase_    :str					    =				bottom_of_new
        lowercase_    :Optional[int]					    =				1

        # Size, min_node and bottom_root
        while bottom_of_new.left:
           lowercase_    :List[Any]					    =				size_of_new * 2 + 1
           lowercase_    :Union[str, Any]					    =				bottom_of_new.left
           if bottom_of_new.val < min_of_new.val:
              lowercase_    :Optional[int]					    =				bottom_of_new
        # Corner case of single root on top left path
        if (not self.min_node.left) and (not self.min_node.parent):
           lowercase_    :Optional[int]					    =				size_of_new
           lowercase_    :Union[str, Any]					    =				bottom_of_new
           lowercase_    :Dict					    =				min_of_new
           # print("Single root, multiple nodes case")
           return min_value
        # Remaining cases
        # Construct heap of right subtree
        lowercase_    :Tuple					    =				BinomialHeap(
            bottom_root=lowercase			,   min_node=lowercase			,   heap_size=lowercase		)

        # Update size
        lowercase_    :Dict					    =				self.size - 1 - size_of_new

        # Neighbour nodes
        lowercase_    :Optional[Any]					    =				self.min_node.left
        lowercase_    :str					    =				self.min_node.parent

        # Initialize new bottom_root and min_node
        lowercase_    :int					    =				previous_node or next_node
        lowercase_    :Any					    =				next_node

        # Update links of previous_node and search below for new min_node and
        # bottom_root
        if previous_node:
           lowercase_    :int					    =				next_node

           # Update bottom_root and search for min_node below
           lowercase_    :str					    =				previous_node
           lowercase_    :List[Any]					    =				previous_node
           while self.bottom_root.left:
              lowercase_    :List[str]					    =				self.bottom_root.left
              if self.bottom_root.val < self.min_node.val:
                 lowercase_    :List[Any]					    =				self.bottom_root
        if next_node:
           lowercase_    :List[Any]					    =				previous_node

           # Search for new min_node above min_node
           lowercase_    :Dict					    =				next_node
           while i:
              if i.val < self.min_node.val:
                 lowercase_    :Optional[Any]					    =				i
              lowercase_    :str					    =				i.parent
        # Merge heaps
        self.merge_heaps(lowercase		)

        return min_value





     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				self.bottom_root
        while top_root.parent:
           lowercase_    :int					    =				top_root.parent
        # preorder
        lowercase_    :List[str]					    =				[]
        self.__traversal(lowercase			,   lowercase		)
        return heap_pre_order





     def 							lowercase__   (				self	:      Union[str, Any]			,   lowercase	:      List[Any]			,   lowercase	:      List[str]			,   lowercase	:      Dict=0		):





        """simple docstring"""




        if curr_node:
           preorder.append((curr_node.val, level)		)
           self.__traversal(curr_node.left			,   lowercase			,   level + 1		)
           self.__traversal(curr_node.right			,   lowercase			,   level + 1		)
        else:
           preorder.append(("#", level)		)







     def __str__(				self	:      Optional[int]		):





        """simple docstring"""




        if self.is_empty():
           return ""
        lowercase_    :int					    =				self.pre_order()

        return "\n".join(("-" * level + str(lowercase		)) for value, level in preorder_heap		)


# Unit Tests
if __name__ == "__main__":
 import doctest

 doctest.testmod()


