



"""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__ :							Union[str, Any]       ,  lowerCAmelCase__ :							int       ,  lowerCAmelCase__ :							int       ,  lowerCAmelCase__ :							Union[str, Any]=None		)		->  Any:

  """simple docstring"""




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

def 							UpperCamelCase_       (       lowerCAmelCase__ :							Dict       ,  lowerCAmelCase__ :							Union[str, Any]		)		->  List[Any]:

  """simple docstring"""




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

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

  lowerCAmelCase_  :							Union[str, Any]								=					np.memmap(lowerCAmelCase__       ,  dtype=lowerCAmelCase__       ,  shape=lowerCAmelCase__       ,  mode='r'		)

  if len(weight_info['shape']		) == 0:
    lowerCAmelCase_  :							Tuple								=					weight[0]
  lowerCAmelCase_  :							Tuple								=					torch.tensor(lowerCAmelCase__		)
  if weight_info["dtype"] == "bfloat16":
    lowerCAmelCase_  :							str								=					weight.view(torch.bfloataa		)

  return weight

def 							UpperCamelCase_       (       lowerCAmelCase__ :							Dict       ,  lowerCAmelCase__ :							Optional[Any]		)		->  Any:

  """simple docstring"""




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

  lowerCAmelCase_  :							Any								=					os.path.join(lowerCAmelCase__       ,  'index.json'		)
  if os.path.isfile(lowerCAmelCase__		):
    with open(lowerCAmelCase__       ,  'r'       ,  encoding='utf-8'		) as f:
      lowerCAmelCase_  :							int								=					json.load(lowerCAmelCase__		)
  else:
    lowerCAmelCase_  :							Tuple								=					{}
  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]		)		->  Tuple:

  """simple docstring"""




  os.makedirs(lowerCAmelCase__       ,  exist_ok=lowerCAmelCase__		)
  lowerCAmelCase_  :							List[str]								=					{}
  for name, parameter in state_dict.items():
    lowerCAmelCase_  :							str								=					offload_weight(lowerCAmelCase__       ,  lowerCAmelCase__       ,  lowerCAmelCase__       ,  index=lowerCAmelCase__		)

  # Update index
  save_offload_index(lowerCAmelCase__       ,  lowerCAmelCase__		)







class  UpperCamelCase__  (      lowercase_    ):




      """simple docstring"""




      def __init__( self							: List[Any]       ,     SCREAMING_SNAKE_CASE_							: Mapping       ,     SCREAMING_SNAKE_CASE_							: str			):
        lowerCAmelCase_  :							str								=					dataset
        lowerCAmelCase_  :							str								=					prefix



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



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





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







class  UpperCamelCase__  (      lowercase_    ):




      """simple docstring"""




      def __init__( self							: List[str]       ,     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_							: List[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.'			)

        lowerCAmelCase_  :							str								=					{} if state_dict is None else state_dict
        lowerCAmelCase_  :							str								=					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_  :							Union[str, Any]								=					json.load(SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							List[str]								=					{} if index is None else index
        lowerCAmelCase_  :							Any								=					list(self.state_dict.keys()			)
        self.all_keys.extend([key for key in self.index if key not in self.all_keys]			)
        lowerCAmelCase_  :							List[Any]								=					device



      def __getitem__( self							: List[str]       ,     SCREAMING_SNAKE_CASE_							: str			):
        # State dict gets priority
        if key in self.state_dict:
          return self.state_dict[key]
        lowerCAmelCase_  :							List[Any]								=					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_  :							int								=					'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_  :							Any								=					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_  :							List[str]								=					os.path.join(self.save_folder       ,     F"{key}.dat"			)
        return load_offloaded_weight(SCREAMING_SNAKE_CASE_       ,     SCREAMING_SNAKE_CASE_			)



      def __iter__( self							: List[str]			):
        return iter(self.all_keys			)





      def __len__( self							: int			):
        return len(self.all_keys			)




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

  """simple docstring"""




  lowerCAmelCase_  :							Union[str, Any]								=					{}
  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 inspect

from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
     import jax







@require_flax
class  UpperCamelCase__  :




      """simple docstring"""




      def 	SCREAMING_SNAKE_CASE__					( self							: Optional[int]			):
        lowerCAmelCase_		,lowerCAmelCase_  :							Any								=					self.prepare_init_args_and_inputs_for_common()

        lowerCAmelCase_  :							List[str]								=					self.model_class(**SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							Any								=					model.init(inputs_dict['prng_key']       ,     inputs_dict['sample']			)
        jax.lax.stop_gradient(SCREAMING_SNAKE_CASE_			)

        lowerCAmelCase_  :							Tuple								=					model.apply(SCREAMING_SNAKE_CASE_       ,     inputs_dict['sample']			)

        if isinstance(SCREAMING_SNAKE_CASE_       ,     SCREAMING_SNAKE_CASE_			):
          lowerCAmelCase_  :							str								=					output.sample

        self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							Any								=					inputs_dict['sample'].shape
        self.assertEqual(output.shape       ,     SCREAMING_SNAKE_CASE_       ,     'Input and output shapes do not match'			)



      def 	SCREAMING_SNAKE_CASE__					( self							: List[str]			):
        lowerCAmelCase_		,lowerCAmelCase_  :							Union[str, Any]								=					self.prepare_init_args_and_inputs_for_common()

        lowerCAmelCase_  :							Tuple								=					1_6
        lowerCAmelCase_  :							Dict								=					(1_6, 3_2)

        lowerCAmelCase_  :							Any								=					self.model_class(**SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							Optional[Any]								=					model.init(inputs_dict['prng_key']       ,     inputs_dict['sample']			)
        jax.lax.stop_gradient(SCREAMING_SNAKE_CASE_			)

        lowerCAmelCase_  :							Optional[Any]								=					model.apply(SCREAMING_SNAKE_CASE_       ,     inputs_dict['sample']			)

        if isinstance(SCREAMING_SNAKE_CASE_       ,     SCREAMING_SNAKE_CASE_			):
          lowerCAmelCase_  :							Dict								=					output.sample

        self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							Optional[Any]								=					inputs_dict['sample'].shape
        self.assertEqual(output.shape       ,     SCREAMING_SNAKE_CASE_       ,     'Input and output shapes do not match'			)





      def 	SCREAMING_SNAKE_CASE__					( self							: List[Any]			):
        lowerCAmelCase_  :							List[str]								=					'kwargs' in inspect.signature(self.model_class.__init__			).parameters
        lowerCAmelCase_  :							Optional[Any]								=					len(self.model_class._deprecated_kwargs			) > 0

        if has_kwarg_in_model_class and not has_deprecated_kwarg:
          raise ValueError(
              F"{self.model_class} has `**kwargs` in its __init__ method but has not defined any deprecated kwargs"
              ' under the `_deprecated_kwargs` class attribute. Make sure to either remove `**kwargs` if there are'
              ' no deprecated arguments or add the deprecated argument with `_deprecated_kwargs ='
              ' [<deprecated_argument>]`'			)

        if not has_kwarg_in_model_class and has_deprecated_kwarg:
          raise ValueError(
              F"{self.model_class} doesn't have `**kwargs` in its __init__ method but has defined deprecated kwargs"
              ' under the `_deprecated_kwargs` class attribute. Make sure to either add the `**kwargs` argument to'
              F" {self.model_class}.__init__ if there are deprecated arguments or remove the deprecated argument"
              ' from `_deprecated_kwargs = [<deprecated_argument>]`'			)





