






"""simple docstring"""







import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
	import torch

	__a							:						str   							=			True
except ImportError:
	__a							:						Tuple   							=			False


try:
	from torch.hub import _get_torch_home

	__a							:						Tuple   							=			_get_torch_home()
except ImportError:
	__a							:						Union[str, Any]   							=			os.path.expanduser(
	    os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
	)

__a							:						Optional[Any]   							=			os.path.join(torch_cache_home, 'transformers')

__a							:						List[str]   							=			'https://cdn.huggingface.co'
__a							:						Optional[Any]   							=			'https://s3.amazonaws.com/models.huggingface.co/bert'
__a							:						Any   							=			'/'.join(str(Path(__file__).resolve()).split('/')[:-1])
__a							:						List[Any]   							=			os.path.join(PATH, 'config.yaml')
__a							:						str   							=			os.path.join(PATH, 'attributes.txt')
__a							:						str   							=			os.path.join(PATH, 'objects.txt')
__a							:						Optional[Any]   							=			os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
__a							:						Any   							=			os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
__a							:						str   							=			os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
__a							:						Tuple   							=			'pytorch_model.bin'
__a							:						Dict   							=			'config.yaml'





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_=OBJECTS			,  lowerCamelCase_=ATTRIBUTES):
					a__ 							=	[]
					with open(lowerCamelCase_) as f:
										for object in f.readlines():
															vg_classes.append(object.split(''',''')[0].lower().strip())

					a__ 							=	[]
					with open(lowerCamelCase_) as f:
										for object in f.readlines():
															vg_attrs.append(object.split(''',''')[0].lower().strip())
					return vg_classes, vg_attrs





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_):
					a__ 							=	OrderedDict()
					with open(lowerCamelCase_			,  '''rb''') as f:
										a__ 							=	pkl.load(lowerCamelCase_)['''model''']
					for k in copy.deepcopy(list(ckp.keys())):
										a__ 							=	ckp.pop(lowerCamelCase_)
										if isinstance(lowerCamelCase_			,  np.ndarray):
															a__ 							=	torch.tensor(lowerCamelCase_)
										else:
															assert isinstance(lowerCamelCase_			,  torch.tensor), type(lowerCamelCase_)
										a__ 							=	v
					return r







class 							_SCREAMING_SNAKE_CASE    :





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE     ={}




							def __init__( self:  Union[str, Any]					,		__A:  dict					,		__A:  str = "root"					,		__A:  Optional[Any]=0     ):

												'''simple docstring'''

												a__ 							=	name
												a__ 							=	level
												a__ 							=	{}
												for k, v in dictionary.items():
																	if v is None:
																						raise ValueError()
																	a__ 							=	copy.deepcopy(__A     )
																	a__ 							=	copy.deepcopy(__A     )
																	if isinstance(__A					,		__A     ):
																						a__ 							=	Config(__A					,		name=__A					,		level=level + 1     )
																	a__ 							=	v
																	setattr(self					,		__A					,		__A     )

												a__ 							=	d




							def __repr__( self:  int     ):

												'''simple docstring'''

												return str(list((self._pointer.keys())     )     )




							def __setattr__( self:  List[Any]					,		__A:  Optional[int]					,		__A:  Optional[int]     ):

												'''simple docstring'''

												a__ 							=	val
												a__ 							=	val
												a__ 							=	key.split('''.'''     )
												a__ 							=	len(__A     ) - 1
												a__ 							=	self._pointer
												if len(__A     ) > 1:
																	for i, l in enumerate(__A     ):
																						if hasattr(self					,		__A     ) and isinstance(getattr(self					,		__A     )					,		__A     ):
																											setattr(getattr(self					,		__A     )					,		'''.'''.join(levels[i:]     )					,		__A     )
																						if l == last_level:
																											a__ 							=	val
																						else:
																											a__ 							=	pointer[l]




							def 			lowercase		( self:  int     ):

												'''simple docstring'''

												return self._pointer




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

												'''simple docstring'''

												with open(F'{file_name}'					,		'''w'''     ) as stream:
																	dump(__A					,		__A     )




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

												'''simple docstring'''

												with open(F'{file_name}'					,		'''w'''     ) as stream:
																	json.dump(__A					,		__A     )




							@staticmethod
							def 			lowercase		( __A:  List[str]     ):

												'''simple docstring'''

												with open(__A     ) as stream:
																	a__ 							=	load(__A					,		Loader=__A     )
												return data




							def __str__( self:  Any     ):

												'''simple docstring'''

												a__ 							=	'''    '''
												if self._name != "root":
																	a__ 							=	F'{t * (self._level-1)}{self._name}:\n'
												else:
																	a__ 							=	''''''
												a__ 							=	self._level
												for i, (k, v) in enumerate(self._pointer.items()     ):
																	if isinstance(__A					,		__A     ):
																						r += F'{t * (self._level)}{v}\n'
																						self._level += 1
																	else:
																						r += F'{t * (self._level)}{k}: {v} ({type(__A     ).__name__})\n'
																	a__ 							=	level
												return r[:-1]




							@classmethod
							def 			lowercase		( cls:  int					,		__A:  str					,		**__A:  Any     ):

												'''simple docstring'''

												a__							,a__ 							=	cls.get_config_dict(__A					,		**__A     )
												return cls(__A     )





							@classmethod
							def 			lowercase		( cls:  Any					,		__A:  str					,		**__A:  List[str]     ):

												'''simple docstring'''

												a__ 							=	kwargs.pop('''cache_dir'''					,		__A     )
												a__ 							=	kwargs.pop('''force_download'''					,		__A     )
												a__ 							=	kwargs.pop('''resume_download'''					,		__A     )
												a__ 							=	kwargs.pop('''proxies'''					,		__A     )
												a__ 							=	kwargs.pop('''local_files_only'''					,		__A     )

												if os.path.isdir(__A     ):
																	a__ 							=	os.path.join(__A					,		__A     )
												elif os.path.isfile(__A     ) or is_remote_url(__A     ):
																	a__ 							=	pretrained_model_name_or_path
												else:
																	a__ 							=	hf_bucket_url(__A					,		filename=__A					,		use_cdn=__A     )

												try:
																	# Load from URL or cache if already cached
																	a__ 							=	cached_path(
																	    __A					,		cache_dir=__A					,		force_download=__A					,		proxies=__A					,		resume_download=__A					,		local_files_only=__A					,		)
																	# Load config dict
																	if resolved_config_file is None:
																						raise EnvironmentError

																	a__ 							=	Config.load_yaml(__A     )

												except EnvironmentError:
																	a__ 							=	'''Can\'t load config for'''
																	raise EnvironmentError(__A     )

												if resolved_config_file == config_file:
																	print('''loading configuration file from path'''     )
												else:
																	print('''loading configuration file cache'''     )

												return Config.load_yaml(__A     ), kwargs





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_):
					a__ 							=	torch.load('''dump.pt'''			,  map_location=in_tensor.device)
					a__ 							=	in_tensor.numpy()
					a__ 							=	out_tensor.numpy()[0]
					print(na.shape			,  na[0, 0, :5])
					print(na.shape			,  na[0, 0, :5])
					assert np.allclose(lowerCamelCase_			,  lowerCamelCase_			,  rtol=0.01			,  atol=0.1), (
					    f'{sum([1 for x in np.isclose(lowerCamelCase_			,  lowerCamelCase_			,  rtol=0.01			,  atol=0.1).flatten() if x is False])/len(na.flatten())*100:.4f} %'
					    " element-wise mismatch"
					)
					raise Exception('''tensors are all good''')

					# Hugging face functions below





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_):
					a__ 							=	urlparse(lowerCamelCase_)
					return parsed.scheme in ("http", "https")





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_			,  lowerCamelCase_=True):
					a__ 							=	CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
					a__ 							=	'''/''' not in model_id
					if legacy_format:
										return f'{endpoint}/{model_id}-{filename}'
					else:
										return f'{endpoint}/{model_id}/{filename}'





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_			,  lowerCamelCase_=None			,  lowerCamelCase_=0			,  lowerCamelCase_=None			,  ):
					a__ 							=	'''python/{}'''.format(sys.version.split()[0])
					if _torch_available:
										ua += "; torch/{}".format(torch.__version__)
					if isinstance(lowerCamelCase_			,  lowerCamelCase_):
										ua += "; " + "; ".join('''{}/{}'''.format(lowerCamelCase_			,  lowerCamelCase_) for k, v in user_agent.items())
					elif isinstance(lowerCamelCase_			,  lowerCamelCase_):
										ua += "; " + user_agent
					a__ 							=	{'''user-agent''': ua}
					if resume_size > 0:
										a__ 							=	'''bytes=%d-''' % (resume_size,)
					a__ 							=	requests.get(lowerCamelCase_			,  stream=lowerCamelCase_			,  proxies=lowerCamelCase_			,  headers=lowerCamelCase_)
					if response.status_code == 416:  # Range not satisfiable
										return
					a__ 							=	response.headers.get('''Content-Length''')
					a__ 							=	resume_size + int(lowerCamelCase_) if content_length is not None else None
					a__ 							=	tqdm(
					    unit='''B'''			,  unit_scale=lowerCamelCase_			,  total=lowerCamelCase_			,  initial=lowerCamelCase_			,  desc='''Downloading'''			,  )
					for chunk in response.iter_content(chunk_size=1024):
										if chunk:  # filter out keep-alive new chunks
															progress.update(len(lowerCamelCase_))
															temp_file.write(lowerCamelCase_)
					progress.close()





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_=None			,  lowerCamelCase_=False			,  lowerCamelCase_=None			,  lowerCamelCase_=10			,  lowerCamelCase_=False			,  lowerCamelCase_=None			,  lowerCamelCase_=False			,  ):
					if cache_dir is None:
										a__ 							=	TRANSFORMERS_CACHE
					if isinstance(lowerCamelCase_			,  lowerCamelCase_):
										a__ 							=	str(lowerCamelCase_)

					os.makedirs(lowerCamelCase_			,  exist_ok=lowerCamelCase_)

					a__ 							=	None
					if not local_files_only:
										try:
															a__ 							=	requests.head(lowerCamelCase_			,  allow_redirects=lowerCamelCase_			,  proxies=lowerCamelCase_			,  timeout=lowerCamelCase_)
															if response.status_code == 200:
																				a__ 							=	response.headers.get('''ETag''')
										except (EnvironmentError, requests.exceptions.Timeout):
															# etag is already None
															pass

					a__ 							=	url_to_filename(lowerCamelCase_			,  lowerCamelCase_)

					# get cache path to put the file
					a__ 							=	os.path.join(lowerCamelCase_			,  lowerCamelCase_)

					# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
					# try to get the last downloaded one
					if etag is None:
										if os.path.exists(lowerCamelCase_):
															return cache_path
										else:
															a__ 							=	[
															    file
															    for file in fnmatch.filter(os.listdir(lowerCamelCase_)			,  filename + '''.*''')
															    if not file.endswith('''.json''') and not file.endswith('''.lock''')
															]
															if len(lowerCamelCase_) > 0:
																				return os.path.join(lowerCamelCase_			,  matching_files[-1])
															else:
																				# If files cannot be found and local_files_only=True,
																				# the models might've been found if local_files_only=False
																				# Notify the user about that
																				if local_files_only:
																									raise ValueError(
																									    '''Cannot find the requested files in the cached path and outgoing traffic has been'''
																									    ''' disabled. To enable model look-ups and downloads online, set \'local_files_only\''''
																									    ''' to False.''')
																				return None

    # From now on, etag is not None.
					if os.path.exists(lowerCamelCase_) and not force_download:
										return cache_path

					# Prevent parallel downloads of the same file with a lock.
					a__ 							=	cache_path + '''.lock'''
					with FileLock(lowerCamelCase_):
										# If the download just completed while the lock was activated.
										if os.path.exists(lowerCamelCase_) and not force_download:
															# Even if returning early like here, the lock will be released.
															return cache_path

										if resume_download:
															a__ 							=	cache_path + '''.incomplete'''

															@contextmanager
															def _resumable_file_manager():
																				with open(lowerCamelCase_			,  '''a+b''') as f:
																									yield f

															a__ 							=	_resumable_file_manager
															if os.path.exists(lowerCamelCase_):
																				a__ 							=	os.stat(lowerCamelCase_).st_size
															else:
																				a__ 							=	0
										else:
															a__ 							=	partial(tempfile.NamedTemporaryFile			,  dir=lowerCamelCase_			,  delete=lowerCamelCase_)
															a__ 							=	0

										# Download to temporary file, then copy to cache dir once finished.
										# Otherwise you get corrupt cache entries if the download gets interrupted.
										with temp_file_manager() as temp_file:
															print(
															    '''%s not found in cache or force_download set to True, downloading to %s'''			,  lowerCamelCase_			,  temp_file.name			,  )

															http_get(
															    lowerCamelCase_			,  lowerCamelCase_			,  proxies=lowerCamelCase_			,  resume_size=lowerCamelCase_			,  user_agent=lowerCamelCase_			,  )

										os.replace(temp_file.name			,  lowerCamelCase_)

										a__ 							=	{'''url''': url, '''etag''': etag}
										a__ 							=	cache_path + '''.json'''
										with open(lowerCamelCase_			,  '''w''') as meta_file:
															json.dump(lowerCamelCase_			,  lowerCamelCase_)

					return cache_path





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_=None):
					a__ 							=	url.encode('''utf-8''')
					a__ 							=	shaaaa(lowerCamelCase_)
					a__ 							=	url_hash.hexdigest()

					if etag:
										a__ 							=	etag.encode('''utf-8''')
										a__ 							=	shaaaa(lowerCamelCase_)
										filename += "." + etag_hash.hexdigest()

					if url.endswith('''.h5'''):
										filename += ".h5"

					return filename





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_=None			,  lowerCamelCase_=False			,  lowerCamelCase_=None			,  lowerCamelCase_=False			,  lowerCamelCase_=None			,  lowerCamelCase_=False			,  lowerCamelCase_=False			,  lowerCamelCase_=False			,  ):
					if cache_dir is None:
										a__ 							=	TRANSFORMERS_CACHE
					if isinstance(lowerCamelCase_			,  lowerCamelCase_):
										a__ 							=	str(lowerCamelCase_)
					if isinstance(lowerCamelCase_			,  lowerCamelCase_):
										a__ 							=	str(lowerCamelCase_)

					if is_remote_url(lowerCamelCase_):
										# URL, so get it from the cache (downloading if necessary)
										a__ 							=	get_from_cache(
										    lowerCamelCase_			,  cache_dir=lowerCamelCase_			,  force_download=lowerCamelCase_			,  proxies=lowerCamelCase_			,  resume_download=lowerCamelCase_			,  user_agent=lowerCamelCase_			,  local_files_only=lowerCamelCase_			,  )
					elif os.path.exists(lowerCamelCase_):
										# File, and it exists.
										a__ 							=	url_or_filename
					elif urlparse(lowerCamelCase_).scheme == "":
										# File, but it doesn't exist.
										raise EnvironmentError('''file {} not found'''.format(lowerCamelCase_))
					else:
										# Something unknown
										raise ValueError('''unable to parse {} as a URL or as a local path'''.format(lowerCamelCase_))

					if extract_compressed_file:
										if not is_zipfile(lowerCamelCase_) and not tarfile.is_tarfile(lowerCamelCase_):
															return output_path

										# Path where we extract compressed archives
										# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
										a__							,a__ 							=	os.path.split(lowerCamelCase_)
										a__ 							=	output_file.replace('''.'''			,  '''-''') + '''-extracted'''
										a__ 							=	os.path.join(lowerCamelCase_			,  lowerCamelCase_)

										if os.path.isdir(lowerCamelCase_) and os.listdir(lowerCamelCase_) and not force_extract:
															return output_path_extracted

										# Prevent parallel extractions
										a__ 							=	output_path + '''.lock'''
										with FileLock(lowerCamelCase_):
															shutil.rmtree(lowerCamelCase_			,  ignore_errors=lowerCamelCase_)
															os.makedirs(lowerCamelCase_)
															if is_zipfile(lowerCamelCase_):
																				with ZipFile(lowerCamelCase_			,  '''r''') as zip_file:
																									zip_file.extractall(lowerCamelCase_)
																									zip_file.close()
															elif tarfile.is_tarfile(lowerCamelCase_):
																				a__ 							=	tarfile.open(lowerCamelCase_)
																				tar_file.extractall(lowerCamelCase_)
																				tar_file.close()
															else:
																				raise EnvironmentError('''Archive format of {} could not be identified'''.format(lowerCamelCase_))

										return output_path_extracted

					return output_path





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_=","):
					assert isinstance(lowerCamelCase_			,  lowerCamelCase_)
					if os.path.isfile(lowerCamelCase_):
										with open(lowerCamelCase_) as f:
															a__ 							=	eval(f.read())
					else:
										a__ 							=	requests.get(lowerCamelCase_)
										try:
															a__ 							=	requests.json()
										except Exception:
															a__ 							=	req.content.decode()
															assert data is not None, "could not connect"
															try:
																				a__ 							=	eval(lowerCamelCase_)
															except Exception:
																				a__ 							=	data.split('''\n''')
										req.close()
					return data





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_):
					a__ 							=	requests.get(lowerCamelCase_)
					a__ 							=	np.array(Image.open(BytesIO(response.content)))
					return img





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_):
					a__ 							=	url.split('''/''')[-1]
					if fn not in os.listdir(os.getcwd()):
										wget.download(lowerCamelCase_)
					with open(lowerCamelCase_			,  '''rb''') as stream:
										a__ 							=	pkl.load(lowerCamelCase_)
					a__ 							=	weights.pop('''model''')
					a__ 							=	{}
					for k, v in model.items():
										a__ 							=	torch.from_numpy(lowerCamelCase_)
										if "running_var" in k:
															a__ 							=	torch.tensor([0])
															a__ 							=	k.replace('''running_var'''			,  '''num_batches_tracked''')
															a__ 							=	zero
					return new





def 							SCREAMING_SNAKE_CASE							(   ):
					print(f'{os.path.abspath(os.path.join(lowerCamelCase_			,  os.pardir))}/demo.ipynb')





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_="RGB"):
					assert isinstance(lowerCamelCase_			,  lowerCamelCase_)
					if os.path.isfile(lowerCamelCase_):
										a__ 							=	cva.imread(lowerCamelCase_)
					else:
										a__ 							=	get_image_from_url(lowerCamelCase_)
										assert img is not None, f'could not connect to: {im}'
					a__ 							=	cva.cvtColor(lowerCamelCase_			,  cva.COLOR_BGR2RGB)
					if input_format == "RGB":
										a__ 							=	img[:, :, ::-1]
					return img





def 							SCREAMING_SNAKE_CASE							(   lowerCamelCase_			,  lowerCamelCase_=1):
					return (images[i : i + batch] for i in range(0			,  len(lowerCamelCase_)			,  lowerCamelCase_))










"""simple docstring"""







import unittest

import torch

from diffusers import UNetaDModel
from diffusers.utils import floats_tensor, slow, torch_device

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin







class 							_SCREAMING_SNAKE_CASE    (	__snake_case							,			__snake_case							,			unittest.TestCase				):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE     =UNetaDModel
							_SCREAMING_SNAKE_CASE     ='sample'




							@property
							def 			lowercase		( self:  Any     ):

												'''simple docstring'''

												a__ 							=	4
												a__ 							=	14
												a__ 							=	16

												a__ 							=	floats_tensor((batch_size, num_features, seq_len)     ).to(__A     )
												a__ 							=	torch.tensor([10] * batch_size     ).to(__A     )

												return {"sample": noise, "timestep": time_step}




							@property
							def 			lowercase		( self:  List[Any]     ):

												'''simple docstring'''

												return (4, 14, 16)




							@property
							def 			lowercase		( self:  List[Any]     ):

												'''simple docstring'''

												return (4, 14, 16)




							def 			lowercase		( self:  Optional[Any]     ):

												'''simple docstring'''

												pass




							def 			lowercase		( self:  Any     ):

												'''simple docstring'''

												pass




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  Optional[int]     ):

												'''simple docstring'''

												super().test_determinism()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  Optional[Any]     ):

												'''simple docstring'''

												super().test_outputs_equivalence()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  Tuple     ):

												'''simple docstring'''

												super().test_from_save_pretrained()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  int     ):

												'''simple docstring'''

												super().test_from_save_pretrained_variant()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  int     ):

												'''simple docstring'''

												super().test_model_from_pretrained()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  Tuple     ):

												'''simple docstring'''

												super().test_output()




							def 			lowercase		( self:  Optional[Any]     ):

												'''simple docstring'''

												a__ 							=	{
												    '''block_out_channels''': (32, 64, 128, 256),
												    '''in_channels''': 14,
												    '''out_channels''': 14,
												    '''time_embedding_type''': '''positional''',
												    '''use_timestep_embedding''': True,
												    '''flip_sin_to_cos''': False,
												    '''freq_shift''': 1.0,
												    '''out_block_type''': '''OutConv1DBlock''',
												    '''mid_block_type''': '''MidResTemporalBlock1D''',
												    '''down_block_types''': ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D'''),
												    '''up_block_types''': ('''UpResnetBlock1D''', '''UpResnetBlock1D''', '''UpResnetBlock1D'''),
												    '''act_fn''': '''mish''',
												}
												a__ 							=	self.dummy_input
												return init_dict, inputs_dict




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  str     ):

												'''simple docstring'''

												a__							,a__ 							=	UNetaDModel.from_pretrained(
												    '''bglick13/hopper-medium-v2-value-function-hor32'''					,		output_loading_info=__A					,		subfolder='''unet'''     )
												self.assertIsNotNone(__A     )
												self.assertEqual(len(loading_info['''missing_keys''']     )					,		0     )

												model.to(__A     )
												a__ 							=	model(**self.dummy_input     )

												assert image is not None, "Make sure output is not None"




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  str     ):

												'''simple docstring'''

												a__ 							=	UNetaDModel.from_pretrained('''bglick13/hopper-medium-v2-value-function-hor32'''					,		subfolder='''unet'''     )
												torch.manual_seed(0     )
												if torch.cuda.is_available():
																	torch.cuda.manual_seed_all(0     )

												a__ 							=	model.config.in_channels
												a__ 							=	16
												a__ 							=	torch.randn((1, seq_len, num_features)     ).permute(
												    0					,		2					,		1     )  # match original, we can update values and remove
												a__ 							=	torch.full((num_features,)					,		0     )

												with torch.no_grad():
																	a__ 							=	model(__A					,		__A     ).sample.permute(0					,		2					,		1     )

												a__ 							=	output[0, -3:, -3:].flatten()
												# fmt: off
												a__ 							=	torch.tensor([-2.1_3_7_1_7_2, 1.1_4_2_6_0_1_6, 0.3_6_8_8_6_8_7, -0.7_6_6_9_2_2, 0.7_3_0_3_1_4_6, 0.1_1_0_3_8_8_6_4, -0.4_7_6_0_6_3_3, 0.1_3_2_7_0_1_7_2, 0.0_2_5_9_1_3_4_8]     )
												# fmt: on
												self.assertTrue(torch.allclose(__A					,		__A					,		rtol=1e-3     )     )




							def 			lowercase		( self:  int     ):

												'''simple docstring'''

												pass





							@slow
							def 			lowercase		( self:  Any     ):

												'''simple docstring'''

												a__ 							=	'''harmonai/maestro-150k'''
												a__ 							=	UNetaDModel.from_pretrained(__A					,		subfolder='''unet'''     )
												model.to(__A     )

												a__ 							=	65536
												a__ 							=	torch.sin(torch.arange(__A     )[None, None, :].repeat(1					,		2					,		1     )     ).to(__A     )
												a__ 							=	torch.tensor([1]     ).to(__A     )

												with torch.no_grad():
																	a__ 							=	model(__A					,		__A     ).sample

												a__ 							=	output.abs().sum()
												a__ 							=	output.abs().max()

												assert (output_sum - 2_2_4.0_8_9_6).abs() < 0.5
												assert (output_max - 0.0_6_0_7).abs() < 4e-4







class 							_SCREAMING_SNAKE_CASE    (	__snake_case							,			__snake_case							,			unittest.TestCase				):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE     =UNetaDModel
							_SCREAMING_SNAKE_CASE     ='sample'




							@property
							def 			lowercase		( self:  List[str]     ):

												'''simple docstring'''

												a__ 							=	4
												a__ 							=	14
												a__ 							=	16

												a__ 							=	floats_tensor((batch_size, num_features, seq_len)     ).to(__A     )
												a__ 							=	torch.tensor([10] * batch_size     ).to(__A     )

												return {"sample": noise, "timestep": time_step}




							@property
							def 			lowercase		( self:  Dict     ):

												'''simple docstring'''

												return (4, 14, 16)




							@property
							def 			lowercase		( self:  int     ):

												'''simple docstring'''

												return (4, 14, 1)




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  int     ):

												'''simple docstring'''

												super().test_determinism()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  str     ):

												'''simple docstring'''

												super().test_outputs_equivalence()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  Optional[Any]     ):

												'''simple docstring'''

												super().test_from_save_pretrained()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  List[str]     ):

												'''simple docstring'''

												super().test_from_save_pretrained_variant()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  Optional[int]     ):

												'''simple docstring'''

												super().test_model_from_pretrained()




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  int     ):

												'''simple docstring'''

												a__							,a__ 							=	self.prepare_init_args_and_inputs_for_common()
												a__ 							=	self.model_class(**__A     )
												model.to(__A     )
												model.eval()

												with torch.no_grad():
																	a__ 							=	model(**__A     )

																	if isinstance(__A					,		__A     ):
																						a__ 							=	output.sample

												self.assertIsNotNone(__A     )
												a__ 							=	torch.Size((inputs_dict['''sample'''].shape[0], 1)     )
												self.assertEqual(output.shape					,		__A					,		'''Input and output shapes do not match'''     )




							def 			lowercase		( self:  Dict     ):

												'''simple docstring'''

												pass




							def 			lowercase		( self:  Dict     ):

												'''simple docstring'''

												pass




							def 			lowercase		( self:  Any     ):

												'''simple docstring'''

												a__ 							=	{
												    '''in_channels''': 14,
												    '''out_channels''': 14,
												    '''down_block_types''': ['''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D'''],
												    '''up_block_types''': [],
												    '''out_block_type''': '''ValueFunction''',
												    '''mid_block_type''': '''ValueFunctionMidBlock1D''',
												    '''block_out_channels''': [32, 64, 128, 256],
												    '''layers_per_block''': 1,
												    '''downsample_each_block''': True,
												    '''use_timestep_embedding''': True,
												    '''freq_shift''': 1.0,
												    '''flip_sin_to_cos''': False,
												    '''time_embedding_type''': '''positional''',
												    '''act_fn''': '''mish''',
												}
												a__ 							=	self.dummy_input
												return init_dict, inputs_dict




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  List[Any]     ):

												'''simple docstring'''

												a__							,a__ 							=	UNetaDModel.from_pretrained(
												    '''bglick13/hopper-medium-v2-value-function-hor32'''					,		output_loading_info=__A					,		subfolder='''value_function'''     )
												self.assertIsNotNone(__A     )
												self.assertEqual(len(vf_loading_info['''missing_keys''']     )					,		0     )

												value_function.to(__A     )
												a__ 							=	value_function(**self.dummy_input     )

												assert image is not None, "Make sure output is not None"




							@unittest.skipIf(torch_device == '''mps'''					,		'''mish op not supported in MPS'''     )
							def 			lowercase		( self:  Union[str, Any]     ):

												'''simple docstring'''

												a__							,a__ 							=	UNetaDModel.from_pretrained(
												    '''bglick13/hopper-medium-v2-value-function-hor32'''					,		output_loading_info=__A					,		subfolder='''value_function'''     )
												torch.manual_seed(0     )
												if torch.cuda.is_available():
																	torch.cuda.manual_seed_all(0     )

												a__ 							=	value_function.config.in_channels
												a__ 							=	14
												a__ 							=	torch.randn((1, seq_len, num_features)     ).permute(
												    0					,		2					,		1     )  # match original, we can update values and remove
												a__ 							=	torch.full((num_features,)					,		0     )

												with torch.no_grad():
																	a__ 							=	value_function(__A					,		__A     ).sample

												# fmt: off
												a__ 							=	torch.tensor([1_6_5.2_5] * seq_len     )
												# fmt: on
												self.assertTrue(torch.allclose(__A					,		__A					,		rtol=1e-3     )     )





							def 			lowercase		( self:  List[str]     ):

												'''simple docstring'''

												pass


