'''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_						( snake_case_	:	Tuple						,		snake_case_	:	List[str]						,		snake_case_	:	str						,		snake_case_	:	List[Any]=None			) ->					List[str]:






 '''simple docstring'''

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







def 					UpperCamelCase_						( snake_case_	:	Optional[int]						,		snake_case_	:	List[str]			) ->					Any:






 '''simple docstring'''

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

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

 __lowerCAmelCase    							=						np.memmap(snake_case_						,		dtype=snake_case_						,		shape=snake_case_						,		mode="""r"""			)

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

 return weight







def 					UpperCamelCase_						( snake_case_	:	Optional[int]						,		snake_case_	:	Union[str, Any]			) ->					List[str]:






 '''simple docstring'''

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

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

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







def 					UpperCamelCase_						( snake_case_	:	Union[str, os.PathLike]						,		snake_case_	:	Dict[str, torch.Tensor]			) ->					Optional[int]:






 '''simple docstring'''

 os.makedirs(snake_case_						,		exist_ok=snake_case_			)
 __lowerCAmelCase    							=						{}
 for name, parameter in state_dict.items():
  __lowerCAmelCase    							=						offload_weight(snake_case_						,		snake_case_						,		snake_case_						,		index=snake_case_			)

 # Update index
 save_offload_index(snake_case_						,		snake_case_			)







class     _lowercase					(    UpperCAmelCase__      ):


 '''simple docstring'''






 def __init__(				self       :     Optional[Any]				,	SCREAMING_SNAKE_CASE__       :     Mapping				,	SCREAMING_SNAKE_CASE__       :     str							)  ->   Any:
  __lowerCAmelCase    							=						dataset
  __lowerCAmelCase    							=						prefix
 def __getitem__(				self       :     int				,	SCREAMING_SNAKE_CASE__       :     str							)  ->   List[str]:
  return self.dataset[f"""{self.prefix}{key}"""]
 def __iter__(				self       :     Dict							)  ->   str:
  return iter([key for key in self.dataset if key.startswith(self.prefix							)]							)





 def __len__(				self       :     Union[str, Any]							)  ->   Union[str, Any]:
  return len(self.dataset							)







class     _lowercase					(    UpperCAmelCase__      ):


 '''simple docstring'''






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

  __lowerCAmelCase    							=						{} if state_dict is None else state_dict
  __lowerCAmelCase    							=						save_folder
  if index is None and save_folder is not None:
   with open(os.path.join(SCREAMING_SNAKE_CASE__				,	"""index.json"""							)							) as f:
    __lowerCAmelCase    							=						json.load(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						{} if index is None else index
  __lowerCAmelCase    							=						list(self.state_dict.keys()							)
  self.all_keys.extend([key for key in self.index if key not in self.all_keys]							)
  __lowerCAmelCase    							=						device
 def __getitem__(				self       :     List[Any]				,	SCREAMING_SNAKE_CASE__       :     str							)  ->   List[Any]:
  # State dict gets priority
  if key in self.state_dict:
   return self.state_dict[key]
  __lowerCAmelCase    							=						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

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

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

  __lowerCAmelCase    							=						os.path.join(self.save_folder				,	f"""{key}.dat"""							)
  return load_offloaded_weight(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)
 def __iter__(				self       :     List[Any]							)  ->   Tuple:
  return iter(self.all_keys							)





 def __len__(				self       :     Dict							)  ->   int:
  return len(self.all_keys							)







def 					UpperCamelCase_						( snake_case_	:	Dict[str, torch.Tensor]						,		snake_case_	:	List[str]			) ->					str:






 '''simple docstring'''

 __lowerCAmelCase    							=						{}
 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'''

import math

import torch
from torch import nn
from torch.nn import init

from .binarizer import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer







class     _lowercase					(    nn.Linear      ):


 '''simple docstring'''






 def __init__(				self       :     List[str]				,	SCREAMING_SNAKE_CASE__       :     int				,	SCREAMING_SNAKE_CASE__       :     int				,	SCREAMING_SNAKE_CASE__       :     bool = True				,	SCREAMING_SNAKE_CASE__       :     str = "constant"				,	SCREAMING_SNAKE_CASE__       :     float = 0.0				,	SCREAMING_SNAKE_CASE__       :     str = "topK"				,	)  ->   Any:
  super(SCREAMING_SNAKE_CASE__				,	self							).__init__(in_features=SCREAMING_SNAKE_CASE__				,	out_features=SCREAMING_SNAKE_CASE__				,	bias=SCREAMING_SNAKE_CASE__							)
  assert pruning_method in ["topK", "threshold", "sigmoied_threshold", "magnitude", "l0"]
  __lowerCAmelCase    							=						pruning_method

  if self.pruning_method in ["topK", "threshold", "sigmoied_threshold", "l0"]:
   __lowerCAmelCase    							=						mask_scale
   __lowerCAmelCase    							=						mask_init
   __lowerCAmelCase    							=						nn.Parameter(torch.empty(self.weight.size()							)							)
   self.init_mask()
 def a (				self       :     Union[str, Any]							)  ->   int:
  if self.mask_init == "constant":
   init.constant_(self.mask_scores				,	val=self.mask_scale							)
  elif self.mask_init == "uniform":
   init.uniform_(self.mask_scores				,	a=-self.mask_scale				,	b=self.mask_scale							)
  elif self.mask_init == "kaiming":
   init.kaiming_uniform_(self.mask_scores				,	a=math.sqrt(5							)							)





 def a (				self       :     Any				,	SCREAMING_SNAKE_CASE__       :     torch.tensor				,	SCREAMING_SNAKE_CASE__       :     float							)  ->   Tuple:
  # Get the mask
  if self.pruning_method == "topK":
   __lowerCAmelCase    							=						TopKBinarizer.apply(self.mask_scores				,	SCREAMING_SNAKE_CASE__							)
  elif self.pruning_method in ["threshold", "sigmoied_threshold"]:
   __lowerCAmelCase    							=						"""sigmoied""" in self.pruning_method
   __lowerCAmelCase    							=						ThresholdBinarizer.apply(self.mask_scores				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)
  elif self.pruning_method == "magnitude":
   __lowerCAmelCase    							=						MagnitudeBinarizer.apply(self.weight				,	SCREAMING_SNAKE_CASE__							)
  elif self.pruning_method == "l0":
   __lowerCAmelCase							,	__lowerCAmelCase							,	__lowerCAmelCase    							=						-0.1, 1.1, 2 / 3
   if self.training:
    __lowerCAmelCase    							=						torch.zeros_like(self.mask_scores							).uniform_().clamp(0.0_0_0_1				,	0.9_9_9_9							)
    __lowerCAmelCase    							=						torch.sigmoid((u.log() - (1 - u).log() + self.mask_scores) / b							)
   else:
    __lowerCAmelCase    							=						torch.sigmoid(self.mask_scores							)
   __lowerCAmelCase    							=						s * (r - l) + l
   __lowerCAmelCase    							=						s_bar.clamp(min=0.0				,	max=1.0							)
  # Mask weights with computed mask
  __lowerCAmelCase    							=						mask * self.weight
  # Compute output (linear layer) with masked weights
  return nn.functional.linear(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	self.bias							)






