import unittest
from typing import Tuple

import torch

from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device
from diffusers.utils.testing_utils import require_torch







@require_torch
class __snake_case       :




   @property
   def 			__a		(					self    :       Optional[int]   ):



     """simple docstring"""






     return self.get_dummy_input()




   @property
   def 			__a		(					self    :       Any   ):



     """simple docstring"""






     if self.block_type == "down":
       return (4, 32, 16, 16)
     elif self.block_type == "mid":
       return (4, 32, 32, 32)
     elif self.block_type == "up":
       return (4, 32, 64, 64)

     raise ValueError(f"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'."""   )




   def 			__a		(					self    :       Dict ,			_lowercase    :       Tuple=True ,			_lowercase    :       List[Any]=False ,			_lowercase    :       int=False ,			_lowercase    :       Dict=False ,			):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   4
     SCREAMING_SNAKE_CASE__    							=   32
     SCREAMING_SNAKE_CASE__    							=   (32, 32)

     SCREAMING_SNAKE_CASE__    							=   torch.manual_seed(0   )
     SCREAMING_SNAKE_CASE__    							=   torch.device(_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   (batch_size, num_channels) + sizes
     SCREAMING_SNAKE_CASE__    							=   randn_tensor(_lowercase ,			generator=_lowercase ,			device=_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   {"""hidden_states""": hidden_states}

     if include_temb:
       SCREAMING_SNAKE_CASE__    							=   1_28
       SCREAMING_SNAKE_CASE__    							=   randn_tensor((batch_size, temb_channels) ,			generator=_lowercase ,			device=_lowercase   )

     if include_res_hidden_states_tuple:
       SCREAMING_SNAKE_CASE__    							=   torch.manual_seed(1   )
       SCREAMING_SNAKE_CASE__    							=   (randn_tensor(_lowercase ,			generator=_lowercase ,			device=_lowercase   ),)

     if include_encoder_hidden_states:
       SCREAMING_SNAKE_CASE__    							=   floats_tensor((batch_size, 32, 32)   ).to(_lowercase   )

     if include_skip_sample:
       SCREAMING_SNAKE_CASE__    							=   randn_tensor(((batch_size, 3) + sizes) ,			generator=_lowercase ,			device=_lowercase   )

     return dummy_input




   def 			__a		(					self    :       Union[str, Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   {
         """in_channels""": 32,
         """out_channels""": 32,
         """temb_channels""": 1_28,
     }
     if self.block_type == "up":
       SCREAMING_SNAKE_CASE__    							=   32

     if self.block_type == "mid":
       init_dict.pop("""out_channels"""   )

     SCREAMING_SNAKE_CASE__    							=   self.dummy_input
     return init_dict, inputs_dict




   def 			__a		(					self    :       Optional[Any] ,			_lowercase    :       Optional[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   self.prepare_init_args_and_inputs_for_common()
     SCREAMING_SNAKE_CASE__    							=   self.block_class(**_lowercase   )
     unet_block.to(_lowercase   )
     unet_block.eval()

     with torch.no_grad():
       SCREAMING_SNAKE_CASE__    							=   unet_block(**_lowercase   )

     if isinstance(_lowercase ,			_lowercase   ):
       SCREAMING_SNAKE_CASE__    							=   output[0]

     self.assertEqual(output.shape ,			self.output_shape   )

     SCREAMING_SNAKE_CASE__    							=   output[0, -1, -3:, -3:]
     SCREAMING_SNAKE_CASE__    							=   torch.tensor(_lowercase   ).to(_lowercase   )
     assert torch_all_close(output_slice.flatten() ,			_lowercase ,			atol=5E-3   )




   @unittest.skipIf(torch_device == """mps""" ,			"""Training is not supported in mps"""   )
   def 			__a		(					self    :       int   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   self.prepare_init_args_and_inputs_for_common()
     SCREAMING_SNAKE_CASE__    							=   self.block_class(**_lowercase   )
     model.to(_lowercase   )
     model.train()
     SCREAMING_SNAKE_CASE__    							=   model(**_lowercase   )

     if isinstance(_lowercase ,			_lowercase   ):
       SCREAMING_SNAKE_CASE__    							=   output[0]

     SCREAMING_SNAKE_CASE__    							=   torch.device(_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   randn_tensor(output.shape ,			device=_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   torch.nn.functional.mse_loss(_lowercase ,			_lowercase   )
     loss.backward()

from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar

__lowerCamelCase    :				List[str]							     =	TypeVar('''KEY''')
__lowerCamelCase    :				int							     =	TypeVar('''VAL''')







@dataclass(frozen=lowerCamelCase_     ,	slots=lowerCamelCase_	)
class __snake_case       (		Generic[KEY, VAL]	):
   lowerCAmelCase_														=							42
   lowerCAmelCase_														=							42







class __snake_case       (		_Item	):




   def __init__(					self    :       List[Any]   ):



     """simple docstring"""






     super().__init__(_lowercase ,			_lowercase   )




   def __bool__(					self    :       List[str]   ):



     """simple docstring"""






     return False





__lowerCamelCase    :				str							     =	_DeletedItem()







class __snake_case       (		MutableMapping[KEY, VAL]	):




   def __init__(					self    :       Optional[int] ,			_lowercase    :       int = 8 ,			_lowercase    :       float = 0.75   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   initial_block_size
     SCREAMING_SNAKE_CASE__    							=   [None] * initial_block_size
     assert 0.0 < capacity_factor < 1.0
     SCREAMING_SNAKE_CASE__    							=   capacity_factor
     SCREAMING_SNAKE_CASE__    							=   0




   def 			__a		(					self    :       Union[str, Any] ,			_lowercase    :       KEY   ):



     """simple docstring"""






     return hash(_lowercase   ) % len(self._buckets   )




   def 			__a		(					self    :       List[str] ,			_lowercase    :       int   ):



     """simple docstring"""






     return (ind + 1) % len(self._buckets   )




   def 			__a		(					self    :       Union[str, Any] ,			_lowercase    :       int ,			_lowercase    :       KEY ,			_lowercase    :       VAL   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self._buckets[ind]
     if not stored:
       SCREAMING_SNAKE_CASE__    							=   _Item(_lowercase ,			_lowercase   )
       self._len += 1
       return True
     elif stored.key == key:
       SCREAMING_SNAKE_CASE__    							=   _Item(_lowercase ,			_lowercase   )
       return True
     else:
       return False




   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   len(self._buckets   ) * self._capacity_factor
     return len(self   ) >= int(_lowercase   )




   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     if len(self._buckets   ) <= self._initial_block_size:
       return False
     SCREAMING_SNAKE_CASE__    							=   len(self._buckets   ) * self._capacity_factor / 2
     return len(self   ) < limit




   def 			__a		(					self    :       List[Any] ,			_lowercase    :       int   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self._buckets
     SCREAMING_SNAKE_CASE__    							=   [None] * new_size
     SCREAMING_SNAKE_CASE__    							=   0
     for item in old_buckets:
       if item:
         self._add_item(item.key ,			item.val   )




   def 			__a		(					self    :       Tuple   ):



     """simple docstring"""






     self._resize(len(self._buckets   ) * 2   )




   def 			__a		(					self    :       Tuple   ):



     """simple docstring"""






     self._resize(len(self._buckets   ) // 2   )




   def 			__a		(					self    :       List[str] ,			_lowercase    :       KEY   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self._get_bucket_index(_lowercase   )
     for _ in range(len(self._buckets   )   ):
       yield ind
       SCREAMING_SNAKE_CASE__    							=   self._get_next_ind(_lowercase   )




   def 			__a		(					self    :       List[str] ,			_lowercase    :       KEY ,			_lowercase    :       VAL   ):



     """simple docstring"""






     for ind in self._iterate_buckets(_lowercase   ):
       if self._try_set(_lowercase ,			_lowercase ,			_lowercase   ):
         break




   def __setitem__(					self    :       List[str] ,			_lowercase    :       KEY ,			_lowercase    :       VAL   ):



     """simple docstring"""






     if self._is_full():
       self._size_up()

     self._add_item(_lowercase ,			_lowercase   )




   def __delitem__(					self    :       Tuple ,			_lowercase    :       KEY   ):



     """simple docstring"""






     for ind in self._iterate_buckets(_lowercase   ):
       SCREAMING_SNAKE_CASE__    							=   self._buckets[ind]
       if item is None:
         raise KeyError(_lowercase   )
       if item is _deleted:
         continue
       if item.key == key:
         SCREAMING_SNAKE_CASE__    							=   _deleted
         self._len -= 1
         break
     if self._is_sparse():
       self._size_down()




   def __getitem__(					self    :       Tuple ,			_lowercase    :       KEY   ):



     """simple docstring"""






     for ind in self._iterate_buckets(_lowercase   ):
       SCREAMING_SNAKE_CASE__    							=   self._buckets[ind]
       if item is None:
         break
       if item is _deleted:
         continue
       if item.key == key:
         return item.val
     raise KeyError(_lowercase   )




   def __len__(					self    :       List[Any]   ):



     """simple docstring"""






     return self._len




   def __iter__(					self    :       List[str]   ):



     """simple docstring"""






     yield from (item.key for item in self._buckets if item)




   def __repr__(					self    :       Optional[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   """ ,""".join(
         f"""{item.key}: {item.val}""" for item in self._buckets if item   )
     return f"""HashMap({val_string})"""
