code: 
  
  
  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				(     UpperCAmelCase				,UpperCAmelCase				,UpperCAmelCase				,UpperCAmelCase=None      )->		Dict:
  
  
  
  
  
  
  
  					'''simple docstring'''
  
  
  
  					SCREAMING_SNAKE_CASE_	      =       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.
  										SCREAMING_SNAKE_CASE_	      =       weight.view(torch.intaa      )
  										SCREAMING_SNAKE_CASE_	      =       '''bfloat16'''
  					SCREAMING_SNAKE_CASE_	      =       weight.cpu().numpy()
  					SCREAMING_SNAKE_CASE_	      =       os.path.join(UpperCAmelCase				,f'''{weight_name}.dat'''      )
  					if index is not None:
  										if dtype is None:
  															SCREAMING_SNAKE_CASE_	      =       str(array.dtype      )
  										SCREAMING_SNAKE_CASE_	      =       {'''dtype''': dtype, '''shape''': list(array.shape      )}
  					if array.ndim == 0:
  										SCREAMING_SNAKE_CASE_	      =       array[None]
  					SCREAMING_SNAKE_CASE_	      =       np.memmap(UpperCAmelCase				,dtype=array.dtype				,mode='''w+'''				,shape=array.shape      )
  					SCREAMING_SNAKE_CASE_	      =       array[:]
  					file_array.flush()
  					return index
  
  
  
  
  
  
  
  def 							UpperCAmelCase				(     UpperCAmelCase				,UpperCAmelCase      )->		List[str]:
  
  
  
  
  
  
  
  					'''simple docstring'''
  
  
  
  					SCREAMING_SNAKE_CASE_	      =       tuple(weight_info['''shape''']      )
  					if shape == ():
  										# NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
  										SCREAMING_SNAKE_CASE_	      =       (1,)
  
  					SCREAMING_SNAKE_CASE_	      =       weight_info['''dtype''']
  					if dtype == "bfloat16":
  										# NumPy does not support bfloat16 so this was saved as a int16
  										SCREAMING_SNAKE_CASE_	      =       '''int16'''
  
  					SCREAMING_SNAKE_CASE_	      =       np.memmap(UpperCAmelCase				,dtype=UpperCAmelCase				,shape=UpperCAmelCase				,mode='''r'''      )
  
  					if len(weight_info['''shape''']      ) == 0:
  										SCREAMING_SNAKE_CASE_	      =       weight[0]
  					SCREAMING_SNAKE_CASE_	      =       torch.tensor(UpperCAmelCase      )
  					if weight_info["dtype"] == "bfloat16":
  										SCREAMING_SNAKE_CASE_	      =       weight.view(torch.bfloataa      )
  
  					return weight
  
  
  
  
  
  
  
  def 							UpperCAmelCase				(     UpperCAmelCase				,UpperCAmelCase      )->		str:
  
  
  
  
  
  
  
  					'''simple docstring'''
  
  
  
  					if index is None or len(UpperCAmelCase      ) == 0:
  										# Nothing to save
  										return
  
  					SCREAMING_SNAKE_CASE_	      =       os.path.join(UpperCAmelCase				,'''index.json'''      )
  					if os.path.isfile(UpperCAmelCase      ):
  										with open(UpperCAmelCase				,'''r'''				,encoding='''utf-8'''      ) as f:
  															SCREAMING_SNAKE_CASE_	      =       json.load(UpperCAmelCase      )
  					else:
  										SCREAMING_SNAKE_CASE_	      =       {}
  					current_index.update(UpperCAmelCase      )
  
  					with open(UpperCAmelCase				,'''w'''				,encoding='''utf-8'''      ) as f:
  										json.dump(UpperCAmelCase				,UpperCAmelCase				,indent=2      )
  
  
  
  
  
  
  
  def 							UpperCAmelCase				(     UpperCAmelCase				,UpperCAmelCase      )->		Optional[Any]:
  
  
  
  
  
  
  
  					'''simple docstring'''
  
  
  
  					os.makedirs(UpperCAmelCase				,exist_ok=UpperCAmelCase      )
  					SCREAMING_SNAKE_CASE_	      =       {}
  					for name, parameter in state_dict.items():
  										SCREAMING_SNAKE_CASE_	      =       offload_weight(UpperCAmelCase				,UpperCAmelCase				,UpperCAmelCase				,index=UpperCAmelCase      )
  
  					# Update index
  					save_offload_index(UpperCAmelCase				,UpperCAmelCase      )
  
  class 						snake_case			(       lowerCAmelCase__	):
  			'''simple docstring'''
  
  			def __init__(	self     :     int							,							lowerCAmelCase_     :     Mapping							,							lowerCAmelCase_     :     str					)					->					Dict:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_	      =       dataset
  								SCREAMING_SNAKE_CASE_	      =       prefix
  
  			def __getitem__(	self     :     Optional[int]							,							lowerCAmelCase_     :     Optional[int]					)					->					Union[str, Any]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								return self.dataset[F'''{self.prefix}{key}''']
  
  			def __iter__(	self     :     Tuple					)					->					str:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								return iter([key for key in self.dataset if key.startswith(self.prefix					)]					)
  
  
  
  
  			def __len__(	self     :     Dict					)					->					Optional[int]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								return len(self.dataset					)
  
  class 						snake_case			(       lowerCAmelCase__	):
  			'''simple docstring'''
  
  			def __init__(	self     :     int							,							lowerCAmelCase_     :     Dict[str, torch.Tensor] = None							,							lowerCAmelCase_     :     Optional[Union[str, os.PathLike]] = None							,							lowerCAmelCase_     :     Mapping = None							,							lowerCAmelCase_     :     int=None							,							)					->					Tuple:
  
  
  
  
  								"""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.'''					)
  
  								SCREAMING_SNAKE_CASE_	      =       {} if state_dict is None else state_dict
  								SCREAMING_SNAKE_CASE_	      =       save_folder
  								if index is None and save_folder is not None:
  													with open(os.path.join(lowerCAmelCase_							,							'''index.json'''					)					) as f:
  																		SCREAMING_SNAKE_CASE_	      =       json.load(lowerCAmelCase_					)
  								SCREAMING_SNAKE_CASE_	      =       {} if index is None else index
  								SCREAMING_SNAKE_CASE_	      =       list(self.state_dict.keys()					)
  								self.all_keys.extend([key for key in self.index if key not in self.all_keys]					)
  								SCREAMING_SNAKE_CASE_	      =       device
  
  			def __getitem__(	self     :     str							,							lowerCAmelCase_     :     str					)					->					Union[str, Any]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								if key in self.state_dict:
  													return self.state_dict[key]
  								SCREAMING_SNAKE_CASE_	      =       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
  
  													SCREAMING_SNAKE_CASE_	      =       '''cpu''' if self.device is None else self.device
  													with safe_open(weight_info['''safetensors_file''']							,							framework='''pt'''							,							device=lowerCAmelCase_					) as f:
  																		SCREAMING_SNAKE_CASE_	      =       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
  
  								SCREAMING_SNAKE_CASE_	      =       os.path.join(self.save_folder							,							F'''{key}.dat'''					)
  								return load_offloaded_weight(lowerCAmelCase_							,							lowerCAmelCase_					)
  
  			def __iter__(	self     :     str					)					->					Optional[int]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								return iter(self.all_keys					)
  
  
  
  
  			def __len__(	self     :     Optional[Any]					)					->					Optional[Any]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								return len(self.all_keys					)
  
  
  
  
  
  
  
  def 							UpperCAmelCase				(     UpperCAmelCase				,UpperCAmelCase      )->		List[str]:
  
  
  
  
  
  
  
  					'''simple docstring'''
  
  
  
  					SCREAMING_SNAKE_CASE_	      =       {}
  					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
  
  
  
style_context: 
  
  
  import tempfile
  import unittest
  
  import torch
  
  from diffusers import UNetaDConditionModel
  from diffusers.training_utils import EMAModel
  from diffusers.utils.testing_utils import enable_full_determinism, skip_mps, torch_device
  
  
  enable_full_determinism()
  
  class 						snake_case			(       unittest.TestCase	):
  			'''simple docstring'''
  
  			UpperCAmelCase       :       Union[str, Any]       = """hf-internal-testing/tiny-stable-diffusion-pipe"""
  			UpperCAmelCase       :       int       = 1
  			UpperCAmelCase       :       Optional[Any]       = 77
  			UpperCAmelCase       :       Any       = 32
  			UpperCAmelCase       :       str       = 4
  			UpperCAmelCase       :       Optional[int]       = 64
  			UpperCAmelCase       :       Tuple       = torch.manual_seed(0	)
  
  			def _lowercase (	self     :     str							,							lowerCAmelCase_     :     str=0.9_999					)					->					int:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_	      =       UNetaDConditionModel.from_pretrained(self.model_id							,							subfolder='''unet'''					)
  								SCREAMING_SNAKE_CASE_	      =       unet.to(lowerCAmelCase_					)
  								SCREAMING_SNAKE_CASE_	      =       EMAModel(unet.parameters()							,							decay=lowerCAmelCase_							,							model_cls=lowerCAmelCase_							,							model_config=unet.config					)
  								return unet, ema_unet
  
  			def _lowercase (	self     :     str					)					->					List[str]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_	      =       torch.randn(
  								    self.batch_size							,							self.num_in_channels							,							self.latent_height							,							self.latent_width							,							generator=self.generator					).to(lowerCAmelCase_					)
  								SCREAMING_SNAKE_CASE_	      =       torch.randint(0							,							1_000							,							size=(self.batch_size,)							,							generator=self.generator					).to(lowerCAmelCase_					)
  								SCREAMING_SNAKE_CASE_	      =       torch.randn(
  								    self.batch_size							,							self.prompt_length							,							self.text_encoder_hidden_dim							,							generator=self.generator					).to(lowerCAmelCase_					)
  								return noisy_latents, timesteps, encoder_hidden_states
  
  			def _lowercase (	self     :     str							,							lowerCAmelCase_     :     Tuple					)					->					str:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_	      =       {}
  								for k, param in unet.state_dict().items():
  													SCREAMING_SNAKE_CASE_	      =       torch.randn_like(lowerCAmelCase_					) + (param * torch.randn_like(lowerCAmelCase_					))
  													updated_state_dict.update({k: updated_param}					)
  								unet.load_state_dict(lowerCAmelCase_					)
  								return unet
  
  			def _lowercase (	self     :     Dict					)					->					str:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_	      =       self.get_models()
  								# Take the first (hypothetical) EMA step.
  								ema_unet.step(unet.parameters()					)
  								assert ema_unet.optimization_step == 1
  
  								# Take two more.
  								for _ in range(2					):
  													ema_unet.step(unet.parameters()					)
  								assert ema_unet.optimization_step == 3
  
  			def _lowercase (	self     :     Union[str, Any]					)					->					List[str]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_	      =       self.get_models()
  								# Since the `unet` is not being updated (i.e., backprop'd)
  								# there won't be any difference between the `params` of `unet`
  								# and `ema_unet` even if we call `ema_unet.step(unet.parameters())`.
  								ema_unet.step(unet.parameters()					)
  								SCREAMING_SNAKE_CASE_	      =       list(unet.parameters()					)
  								for s_param, param in zip(ema_unet.shadow_params							,							lowerCAmelCase_					):
  													assert torch.allclose(lowerCAmelCase_							,							lowerCAmelCase_					)
  
  								# The above holds true even if we call `ema.step()` multiple times since
  								# `unet` params are still not being updated.
  								for _ in range(4					):
  													ema_unet.step(unet.parameters()					)
  								for s_param, param in zip(ema_unet.shadow_params							,							lowerCAmelCase_					):
  													assert torch.allclose(lowerCAmelCase_							,							lowerCAmelCase_					)
  
  			def _lowercase (	self     :     Any					)					->					Union[str, Any]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_	      =       self.get_models()
  								# Here we simulate the parameter updates for `unet`. Since there might
  								# be some parameters which are initialized to zero we take extra care to
  								# initialize their values to something non-zero before the multiplication.
  								SCREAMING_SNAKE_CASE_	      =       self.simulate_backprop(lowerCAmelCase_					)
  
  								# Take the EMA step.
  								ema_unet.step(unet_pseudo_updated_step_one.parameters()					)
  
  								# Now the EMA'd parameters won't be equal to the original model parameters.
  								SCREAMING_SNAKE_CASE_	      =       list(unet_pseudo_updated_step_one.parameters()					)
  								for s_param, param in zip(ema_unet.shadow_params							,							lowerCAmelCase_					):
  													assert ~torch.allclose(lowerCAmelCase_							,							lowerCAmelCase_					)
  
  								# Ensure this is the case when we take multiple EMA steps.
  								for _ in range(4					):
  													ema_unet.step(unet.parameters()					)
  								for s_param, param in zip(ema_unet.shadow_params							,							lowerCAmelCase_					):
  													assert ~torch.allclose(lowerCAmelCase_							,							lowerCAmelCase_					)
  
  			def _lowercase (	self     :     Any					)					->					Tuple:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_	      =       self.get_models()
  
  								# First backprop + EMA
  								SCREAMING_SNAKE_CASE_	      =       self.simulate_backprop(lowerCAmelCase_					)
  								ema_unet.step(unet_step_one.parameters()					)
  								SCREAMING_SNAKE_CASE_	      =       ema_unet.shadow_params
  
  								# Second backprop + EMA
  								SCREAMING_SNAKE_CASE_	      =       self.simulate_backprop(lowerCAmelCase_					)
  								ema_unet.step(unet_step_two.parameters()					)
  								SCREAMING_SNAKE_CASE_	      =       ema_unet.shadow_params
  
  								for step_one, step_two in zip(lowerCAmelCase_							,							lowerCAmelCase_					):
  													assert ~torch.allclose(lowerCAmelCase_							,							lowerCAmelCase_					)
  
  			def _lowercase (	self     :     str					)					->					Optional[Any]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_	      =       self.get_models(decay=0.0					)
  								SCREAMING_SNAKE_CASE_	      =       self.simulate_backprop(lowerCAmelCase_					)
  								ema_unet.step(unet_step_one.parameters()					)
  								SCREAMING_SNAKE_CASE_	      =       ema_unet.shadow_params
  
  								SCREAMING_SNAKE_CASE_	      =       self.simulate_backprop(lowerCAmelCase_					)
  								ema_unet.step(unet_step_two.parameters()					)
  								SCREAMING_SNAKE_CASE_	      =       ema_unet.shadow_params
  
  								for step_one, step_two in zip(lowerCAmelCase_							,							lowerCAmelCase_					):
  													assert torch.allclose(lowerCAmelCase_							,							lowerCAmelCase_					)
  
  
  
  
  			@skip_mps
  			def _lowercase (	self     :     str					)					->					List[Any]:
  
  
  
  
  								"""simple docstring"""
  
  
  
  
  
  
  								SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_	      =       self.get_models()
  								SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_	      =       self.get_dummy_inputs()
  
  								with tempfile.TemporaryDirectory() as tmpdir:
  													ema_unet.save_pretrained(lowerCAmelCase_					)
  													SCREAMING_SNAKE_CASE_	      =       UNetaDConditionModel.from_pretrained(lowerCAmelCase_							,							model_cls=lowerCAmelCase_					)
  													SCREAMING_SNAKE_CASE_	      =       loaded_unet.to(unet.device					)
  
  								# Since no EMA step has been performed the outputs should match.
  								SCREAMING_SNAKE_CASE_	      =       unet(lowerCAmelCase_							,							lowerCAmelCase_							,							lowerCAmelCase_					).sample
  								SCREAMING_SNAKE_CASE_	      =       loaded_unet(lowerCAmelCase_							,							lowerCAmelCase_							,							lowerCAmelCase_					).sample
  
  								assert torch.allclose(lowerCAmelCase_							,							lowerCAmelCase_							,							atol=1e-4					)
  
  
  