code: 
  
  
  '''simple docstring'''
  
  
  
  import argparse
  import json
  from pathlib import Path
  
  import requests
  import torch
  from datasets import load_dataset
  from huggingface_hub import hf_hub_download
  from PIL import Image
  
  from transformers import (
      BeitConfig,
      BeitForImageClassification,
      BeitForMaskedImageModeling,
      BeitForSemanticSegmentation,
      BeitImageProcessor,
  )
  from transformers.image_utils import PILImageResampling
  from transformers.utils import logging
  
  
  logging.set_verbosity_info()
  __lowercase			:		str =			logging.get_logger(__name__)
  
  
  
  
  
  
  def 						lowerCamelCase							(_SCREAMING_SNAKE_CASE   :     Dict		,   _SCREAMING_SNAKE_CASE   :     Optional[Any]=False		,   _SCREAMING_SNAKE_CASE   :     List[Any]=False     ):
  					__a    : int      					=						'backbone.' if is_semantic else ''
  
  					__a    : Dict      					=						[]
  					for i in range(config.num_hidden_layers     ):
  										# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
  										rename_keys.append((F"""{prefix}blocks.{i}.norm1.weight""", F"""beit.encoder.layer.{i}.layernorm_before.weight""")     )
  										rename_keys.append((F"""{prefix}blocks.{i}.norm1.bias""", F"""beit.encoder.layer.{i}.layernorm_before.bias""")     )
  										rename_keys.append(
  										    (F"""{prefix}blocks.{i}.attn.proj.weight""", F"""beit.encoder.layer.{i}.attention.output.dense.weight""")     )
  										rename_keys.append(
  										    (F"""{prefix}blocks.{i}.attn.proj.bias""", F"""beit.encoder.layer.{i}.attention.output.dense.bias""")     )
  										rename_keys.append((F"""{prefix}blocks.{i}.norm2.weight""", F"""beit.encoder.layer.{i}.layernorm_after.weight""")     )
  										rename_keys.append((F"""{prefix}blocks.{i}.norm2.bias""", F"""beit.encoder.layer.{i}.layernorm_after.bias""")     )
  										rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc1.weight""", F"""beit.encoder.layer.{i}.intermediate.dense.weight""")     )
  										rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc1.bias""", F"""beit.encoder.layer.{i}.intermediate.dense.bias""")     )
  										rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc2.weight""", F"""beit.encoder.layer.{i}.output.dense.weight""")     )
  										rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc2.bias""", F"""beit.encoder.layer.{i}.output.dense.bias""")     )
  
  					# projection layer + position embeddings
  					rename_keys.extend(
  					    [
  					        (F"""{prefix}cls_token""", 'beit.embeddings.cls_token'),
  					        (F"""{prefix}patch_embed.proj.weight""", 'beit.embeddings.patch_embeddings.projection.weight'),
  					        (F"""{prefix}patch_embed.proj.bias""", 'beit.embeddings.patch_embeddings.projection.bias'),
  					    ]     )
  
  					if has_lm_head:
  										# mask token + shared relative position bias + layernorm
  										rename_keys.extend(
  										    [
  										        ('mask_token', 'beit.embeddings.mask_token'),
  										        (
  										            'rel_pos_bias.relative_position_bias_table',
  										            'beit.encoder.relative_position_bias.relative_position_bias_table',
  										        ),
  										        (
  										            'rel_pos_bias.relative_position_index',
  										            'beit.encoder.relative_position_bias.relative_position_index',
  										        ),
  										        ('norm.weight', 'layernorm.weight'),
  										        ('norm.bias', 'layernorm.bias'),
  										    ]     )
  					elif is_semantic:
  										# semantic segmentation classification heads
  										rename_keys.extend(
  										    [
  										        ('decode_head.conv_seg.weight', 'decode_head.classifier.weight'),
  										        ('decode_head.conv_seg.bias', 'decode_head.classifier.bias'),
  										        ('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'),
  										        ('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'),
  										    ]     )
  					else:
  										# layernorm + classification head
  										rename_keys.extend(
  										    [
  										        ('fc_norm.weight', 'beit.pooler.layernorm.weight'),
  										        ('fc_norm.bias', 'beit.pooler.layernorm.bias'),
  										        ('head.weight', 'classifier.weight'),
  										        ('head.bias', 'classifier.bias'),
  										    ]     )
  
  					return rename_keys
  
  
  
  
  
  
  def 						lowerCamelCase							(_SCREAMING_SNAKE_CASE   :     Optional[Any]		,   _SCREAMING_SNAKE_CASE   :     Optional[int]		,   _SCREAMING_SNAKE_CASE   :     Union[str, Any]=False		,   _SCREAMING_SNAKE_CASE   :     List[str]=False     ):
  					for i in range(config.num_hidden_layers     ):
  										__a    : Optional[int]      					=						'backbone.' if is_semantic else ''
  										# queries, keys and values
  										__a    : Optional[int]      					=						state_dict.pop(F"""{prefix}blocks.{i}.attn.qkv.weight"""     )
  										__a    : int      					=						state_dict.pop(F"""{prefix}blocks.{i}.attn.q_bias"""     )
  										__a    : Optional[Any]      					=						state_dict.pop(F"""{prefix}blocks.{i}.attn.v_bias"""     )
  
  										__a    : Tuple      					=						in_proj_weight[
  										    : config.hidden_size, :
  										]
  										__a    : Any      					=						q_bias
  										__a    : List[Any]      					=						in_proj_weight[
  										    config.hidden_size : config.hidden_size * 2, :
  										]
  										__a    : str      					=						in_proj_weight[
  										    -config.hidden_size :, :
  										]
  										__a    : Dict      					=						v_bias
  
  										# gamma_1 and gamma_2
  										# we call them lambda because otherwise they are renamed when using .from_pretrained
  										__a    : Dict      					=						state_dict.pop(F"""{prefix}blocks.{i}.gamma_1"""     )
  										__a    : int      					=						state_dict.pop(F"""{prefix}blocks.{i}.gamma_2"""     )
  
  										__a    : List[str]      					=						gamma_a
  										__a    : str      					=						gamma_a
  
  										# relative_position bias table + index
  										if not has_lm_head:
  															# each layer has its own relative position bias
  															__a    : List[str]      					=						state_dict.pop(F"""{prefix}blocks.{i}.attn.relative_position_bias_table"""     )
  															__a    : Any      					=						state_dict.pop(F"""{prefix}blocks.{i}.attn.relative_position_index"""     )
  
  															__a    : Dict      					=						table
  															__a    : Any      					=						index
  
  
  
  
  
  
  def 						lowerCamelCase							(_SCREAMING_SNAKE_CASE   :     int		,   _SCREAMING_SNAKE_CASE   :     Dict		,   _SCREAMING_SNAKE_CASE   :     Dict     ):
  					__a    : int      					=						dct.pop(_SCREAMING_SNAKE_CASE     )
  					__a    : List[Any]      					=						val
  
  
  
  
  
  
  def 						lowerCamelCase							():
  					__a    : Optional[int]      					=						'http://images.cocodataset.org/val2017/000000039769.jpg'
  					__a    : Optional[int]      					=						Image.open(requests.get(_SCREAMING_SNAKE_CASE		,   stream=_SCREAMING_SNAKE_CASE     ).raw     )
  					return im
  
  
  
  
  
  
  @torch.no_grad()
  def 						lowerCamelCase							(_SCREAMING_SNAKE_CASE   :     Any		,   _SCREAMING_SNAKE_CASE   :     Optional[Any]     ):
  					__a    : Tuple      					=						BeitConfig()
  					__a    : Optional[int]      					=						False
  					__a    : List[str]      					=						False
  					__a    : List[str]      					=						'huggingface/label-files'
  					# set config parameters based on URL
  					if checkpoint_url[-9:-4] == "pt22k":
  										# masked image modeling
  										__a    : List[str]      					=						True
  										__a    : Tuple      					=						True
  										__a    : int      					=						True
  					elif checkpoint_url[-9:-4] == "ft22k":
  										# intermediate fine-tuning on ImageNet-22k
  										__a    : Dict      					=						True
  										__a    : Union[str, Any]      					=						21_841
  										__a    : Tuple      					=						'imagenet-22k-id2label.json'
  										__a    : str      					=						json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE		,   _SCREAMING_SNAKE_CASE		,   repo_type='dataset'     )		,   'r'     )     )
  										__a    : int      					=						{int(_SCREAMING_SNAKE_CASE     ): v for k, v in idalabel.items()}
  										# this dataset contains 21843 labels but the model only has 21841
  										# we delete the classes as mentioned in https://github.com/google-research/big_transfer/issues/18
  										del idalabel[9_205]
  										del idalabel[15_027]
  										__a    : str      					=						idalabel
  										__a    : Optional[Any]      					=						{v: k for k, v in idalabel.items()}
  					elif checkpoint_url[-8:-4] == "to1k":
  										# fine-tuning on ImageNet-1k
  										__a    : int      					=						True
  										__a    : List[Any]      					=						1_000
  										__a    : Any      					=						'imagenet-1k-id2label.json'
  										__a    : Union[str, Any]      					=						json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE		,   _SCREAMING_SNAKE_CASE		,   repo_type='dataset'     )		,   'r'     )     )
  										__a    : List[Any]      					=						{int(_SCREAMING_SNAKE_CASE     ): v for k, v in idalabel.items()}
  										__a    : List[Any]      					=						idalabel
  										__a    : Union[str, Any]      					=						{v: k for k, v in idalabel.items()}
  										if "384" in checkpoint_url:
  															__a    : List[str]      					=						384
  										if "512" in checkpoint_url:
  															__a    : Optional[int]      					=						512
  					elif "ade20k" in checkpoint_url:
  										# fine-tuning
  										__a    : Optional[int]      					=						True
  										__a    : Any      					=						150
  										__a    : Union[str, Any]      					=						'ade20k-id2label.json'
  										__a    : Any      					=						json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE		,   _SCREAMING_SNAKE_CASE		,   repo_type='dataset'     )		,   'r'     )     )
  										__a    : Union[str, Any]      					=						{int(_SCREAMING_SNAKE_CASE     ): v for k, v in idalabel.items()}
  										__a    : List[Any]      					=						idalabel
  										__a    : Union[str, Any]      					=						{v: k for k, v in idalabel.items()}
  										__a    : List[str]      					=						640
  										__a    : Tuple      					=						True
  					else:
  										raise ValueError('Checkpoint not supported, URL should either end with \'pt22k\', \'ft22k\', \'to1k\' or \'ade20k\''     )
  
  					# size of the architecture
  					if "base" in checkpoint_url:
  										pass
  					elif "large" in checkpoint_url:
  										__a    : Any      					=						1_024
  										__a    : List[Any]      					=						4_096
  										__a    : Union[str, Any]      					=						24
  										__a    : Tuple      					=						16
  										if "ade20k" in checkpoint_url:
  															__a    : int      					=						640
  															__a    : Union[str, Any]      					=						[7, 11, 15, 23]
  					else:
  										raise ValueError('Should either find \'base\' or \'large\' in checkpoint URL'     )
  
  					# load state_dict of original model, remove and rename some keys
  					__a    : Dict      					=						torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE		,   map_location='cpu'		,   check_hash=_SCREAMING_SNAKE_CASE     )
  					__a    : Optional[int]      					=						state_dict['model'] if 'ade20k' not in checkpoint_url else state_dict['state_dict']
  
  					__a    : Dict      					=						create_rename_keys(_SCREAMING_SNAKE_CASE		,   has_lm_head=_SCREAMING_SNAKE_CASE		,   is_semantic=_SCREAMING_SNAKE_CASE     )
  					for src, dest in rename_keys:
  										rename_key(_SCREAMING_SNAKE_CASE		,   _SCREAMING_SNAKE_CASE		,   _SCREAMING_SNAKE_CASE     )
  					read_in_q_k_v(_SCREAMING_SNAKE_CASE		,   _SCREAMING_SNAKE_CASE		,   has_lm_head=_SCREAMING_SNAKE_CASE		,   is_semantic=_SCREAMING_SNAKE_CASE     )
  					if is_semantic:
  										# add prefix to decoder keys
  										for key, val in state_dict.copy().items():
  															__a    : List[str]      					=						state_dict.pop(_SCREAMING_SNAKE_CASE     )
  															if key.startswith('backbone.fpn'     ):
  																				__a    : Optional[Any]      					=						key.replace('backbone.fpn'		,   'fpn'     )
  															__a    : List[Any]      					=						val
  
      # load HuggingFace model
  					if checkpoint_url[-9:-4] == "pt22k":
  										__a    : Dict      					=						BeitForMaskedImageModeling(_SCREAMING_SNAKE_CASE     )
  					elif "ade20k" in checkpoint_url:
  										__a    : Tuple      					=						BeitForSemanticSegmentation(_SCREAMING_SNAKE_CASE     )
  					else:
  										__a    : List[Any]      					=						BeitForImageClassification(_SCREAMING_SNAKE_CASE     )
  					model.eval()
  					model.load_state_dict(_SCREAMING_SNAKE_CASE     )
  
  					# Check outputs on an image
  					if is_semantic:
  										__a    : Optional[int]      					=						BeitImageProcessor(size=config.image_size		,   do_center_crop=_SCREAMING_SNAKE_CASE     )
  										__a    : Optional[int]      					=						load_dataset('hf-internal-testing/fixtures_ade20k'		,   split='test'     )
  										__a    : List[str]      					=						Image.open(ds[0]['file']     )
  					else:
  										__a    : Union[str, Any]      					=						BeitImageProcessor(
  										    size=config.image_size		,   resample=PILImageResampling.BILINEAR		,   do_center_crop=_SCREAMING_SNAKE_CASE     )
  										__a    : Tuple      					=						prepare_img()
  
  					__a    : List[Any]      					=						image_processor(images=_SCREAMING_SNAKE_CASE		,   return_tensors='pt'     )
  					__a    : List[str]      					=						encoding['pixel_values']
  
  					__a    : Optional[Any]      					=						model(_SCREAMING_SNAKE_CASE     )
  					__a    : Any      					=						outputs.logits
  
  					# verify logits
  					__a    : int      					=						torch.Size([1, 1_000]     )
  					if checkpoint_url[:-4].endswith('beit_base_patch16_224_pt22k'     ):
  										__a    : int      					=						torch.Size([1, 196, 8_192]     )
  					elif checkpoint_url[:-4].endswith('beit_large_patch16_224_pt22k'     ):
  										__a    : Tuple      					=						torch.Size([1, 196, 8_192]     )
  					elif checkpoint_url[:-4].endswith('beit_base_patch16_224_pt22k_ft22k'     ):
  										__a    : Union[str, Any]      					=						torch.Size([1, 21_841]     )
  										__a    : int      					=						torch.tensor([2.2_2_8_8, 2.4_6_7_1, 0.7_3_9_5]     )
  										__a    : Any      					=						2_397
  					elif checkpoint_url[:-4].endswith('beit_large_patch16_224_pt22k_ft22k'     ):
  										__a    : Optional[Any]      					=						torch.Size([1, 21_841]     )
  										__a    : List[str]      					=						torch.tensor([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1]     )
  										__a    : Optional[Any]      					=						2_396
  					elif checkpoint_url[:-4].endswith('beit_base_patch16_224_pt22k_ft1k'     ):
  										__a    : Dict      					=						torch.tensor([0.1_2_4_1, 0.0_7_9_8, -0.6_5_6_9]     )
  										__a    : Optional[int]      					=						285
  					elif checkpoint_url[:-4].endswith('beit_base_patch16_224_pt22k_ft22kto1k'     ):
  										__a    : Union[str, Any]      					=						torch.tensor([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8]     )
  										__a    : List[str]      					=						281
  					elif checkpoint_url[:-4].endswith('beit_base_patch16_384_pt22k_ft22kto1k'     ):
  										__a    : int      					=						torch.tensor([-1.5_3_0_3, -0.9_4_8_4, -0.3_1_4_7]     )
  										__a    : Any      					=						761
  					elif checkpoint_url[:-4].endswith('beit_large_patch16_224_pt22k_ft1k'     ):
  										__a    : str      					=						torch.tensor([0.4_6_1_0, -0.0_9_2_8, 0.2_0_8_6]     )
  										__a    : Optional[int]      					=						761
  					elif checkpoint_url[:-4].endswith('beit_large_patch16_224_pt22k_ft22kto1k'     ):
  										__a    : Optional[int]      					=						torch.tensor([-0.4_8_0_4, 0.6_2_5_7, -0.1_8_3_7]     )
  										__a    : int      					=						761
  					elif checkpoint_url[:-4].endswith('beit_large_patch16_384_pt22k_ft22kto1k'     ):
  										__a    : str      					=						torch.tensor([[-0.5_1_2_2, 0.5_1_1_7, -0.2_1_1_3]]     )
  										__a    : Tuple      					=						761
  					elif checkpoint_url[:-4].endswith('beit_large_patch16_512_pt22k_ft22kto1k'     ):
  										__a    : Any      					=						torch.tensor([-0.3_0_6_2, 0.7_2_6_1, 0.4_8_5_2]     )
  										__a    : Optional[Any]      					=						761
  					elif checkpoint_url[:-4].endswith('beit_base_patch16_640_pt22k_ft22ktoade20k'     ):
  										__a    : int      					=						(1, 150, 160, 160)
  										__a    : int      					=						torch.tensor(
  										    [
  										        [[-4.9_2_2_5, -2.3_9_5_4, -3.0_5_2_2], [-2.8_8_2_2, -1.0_0_4_6, -1.7_5_6_1], [-2.9_5_4_9, -1.3_2_2_8, -2.1_3_4_7]],
  										        [[-5.8_1_6_8, -3.4_1_2_9, -4.0_7_7_8], [-3.8_6_5_1, -2.2_2_1_4, -3.0_2_7_7], [-3.8_3_5_6, -2.4_6_4_3, -3.3_5_3_5]],
  										        [[-0.0_0_7_8, 3.9_9_5_2, 4.0_7_5_4], [2.9_8_5_6, 4.6_9_4_4, 5.0_0_3_5], [3.2_4_1_3, 4.7_8_1_3, 4.9_9_6_9]],
  										    ]     )
  					elif checkpoint_url[:-4].endswith('beit_large_patch16_640_pt22k_ft22ktoade20k'     ):
  										__a    : Tuple      					=						(1, 150, 160, 160)
  										__a    : Optional[Any]      					=						torch.tensor(
  										    [
  										        [[-4.3_3_0_5, -2.3_0_4_9, -3.0_1_6_1], [-2.9_5_9_1, -1.5_3_0_5, -2.2_2_5_1], [-3.4_1_9_8, -1.8_0_0_4, -2.9_0_6_2]],
  										        [[-5.8_9_2_2, -3.7_4_3_5, -4.3_9_7_8], [-4.2_0_6_3, -2.7_8_7_2, -3.4_7_5_5], [-4.2_7_9_1, -3.1_8_7_4, -4.1_6_8_1]],
  										        [[0.9_8_9_5, 4.3_4_6_7, 4.7_6_6_3], [4.2_4_7_6, 5.6_8_3_0, 6.1_5_1_8], [4.5_5_5_0, 6.2_4_9_5, 6.5_1_5_4]],
  										    ]     )
  					else:
  										raise ValueError('Can\'t verify logits as model is not supported'     )
  
  					assert logits.shape == expected_shape, "Shape of logits not as expected"
  					if not has_lm_head:
  										if is_semantic:
  															assert torch.allclose(
  															    logits[0, :3, :3, :3]		,   _SCREAMING_SNAKE_CASE		,   atol=1e-3     ), "First elements of logits not as expected"
  										else:
  															print('Predicted class idx:'		,   logits.argmax(-1     ).item()     )
  															assert torch.allclose(
  															    logits[0, :3]		,   _SCREAMING_SNAKE_CASE		,   atol=1e-3     ), "First elements of logits not as expected"
  															assert logits.argmax(-1     ).item() == expected_class_idx, "Predicted class index not as expected"
  
  					Path(_SCREAMING_SNAKE_CASE     ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE     )
  					print(F"""Saving model to {pytorch_dump_folder_path}"""     )
  					model.save_pretrained(_SCREAMING_SNAKE_CASE     )
  					print(F"""Saving image processor to {pytorch_dump_folder_path}"""     )
  					image_processor.save_pretrained(_SCREAMING_SNAKE_CASE     )
  
  
  if __name__ == "__main__":
  	__lowercase			:		Optional[Any] =			argparse.ArgumentParser()
  
  	parser.add_argument(
  	    '--checkpoint_url',
  	    default='https://conversationhub.blob.core.windows.net/beit-share-public/beit/beit_base_patch16_224_pt22k_ft22kto1k.pth',
  	    type=str,
  	    help='URL to the original PyTorch checkpoint (.pth file).',
  	)
  	parser.add_argument(
  	    '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.'
  	)
  	__lowercase			:		Dict =			parser.parse_args()
  	convert_beit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
  
  
  
  
style_context: 
  
  
  '''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 							__UpperCamelCase       (	lowerCAmelCase_	,   lowerCAmelCase_	,   unittest.TestCase      ):
  	A_			    =					UNetaDModel
  	A_			    =					"sample"
  
  
  
  
  	@property
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a    : List[str]      					=						4
  						__a    : str      					=						14
  						__a    : int      					=						16
  
  						__a    : List[str]      					=						floats_tensor((batch_size, num_features, seq_len)							).to(__a							)
  						__a    : Optional[Any]      					=						torch.tensor([10] * batch_size							).to(__a							)
  
  						return {"sample": noise, "timestep": time_step}
  
  
  
  
  	@property
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						return (4, 14, 16)
  
  
  
  
  	@property
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						return (4, 14, 16)
  
  
  
  
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						pass
  
  
  
  
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						pass
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_determinism()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_outputs_equivalence()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_from_save_pretrained()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_from_save_pretrained_variant()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_model_from_pretrained()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_output()
  
  
  
  
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a    : Union[str, Any]      					=						{
  						    '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    : str      					=						self.dummy_input
  						return init_dict, inputs_dict
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a					,       __a    : List[str]      					=						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    : Optional[int]      					=						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    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a    : List[Any]      					=						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    : str      					=						model.config.in_channels
  						__a    : int      					=						16
  						__a    : List[str]      					=						torch.randn((1, seq_len, num_features)							).permute(
  						    0		,       2		,       1							)  # match original, we can update values and remove
  						__a    : List[Any]      					=						torch.full((num_features,)		,       0							)
  
  						with torch.no_grad():
  											__a    : Tuple      					=						model(__a		,       __a							).sample.permute(0		,       2		,       1							)
  
  						__a    : int      					=						output[0, -3:, -3:].flatten()
  						# fmt: off
  						__a    : List[str]      					=						torch.tensor([-2.137172, 1.1426016, 0.3688687, -0.766922, 0.7303146, 0.11038864, -0.4760633, 0.13270172, 0.02591348]							)
  						# fmt: on
  						self.assertTrue(torch.allclose(__a		,       __a		,       rtol=1E-3							)							)
  
  
  
  
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						pass
  
  
  
  
  
  	@slow
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a    : Tuple      					=						'harmonai/maestro-150k'
  						__a    : Any      					=						UNetaDModel.from_pretrained(__a		,       subfolder='unet'							)
  						model.to(__a							)
  
  						__a    : Optional[Any]      					=						6_5536
  						__a    : str      					=						torch.sin(torch.arange(__a							)[None, None, :].repeat(1		,       2		,       1							)							).to(__a							)
  						__a    : int      					=						torch.tensor([1]							).to(__a							)
  
  						with torch.no_grad():
  											__a    : Optional[int]      					=						model(__a		,       __a							).sample
  
  						__a    : Union[str, Any]      					=						output.abs().sum()
  						__a    : Dict      					=						output.abs().max()
  
  						assert (output_sum - 224.0896).abs() < 0.5
  						assert (output_max - 0.0607).abs() < 4E-4
  
  
  
  
  
  class 							__UpperCamelCase       (	lowerCAmelCase_	,   lowerCAmelCase_	,   unittest.TestCase      ):
  	A_			    =					UNetaDModel
  	A_			    =					"sample"
  
  
  
  
  	@property
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a    : str      					=						4
  						__a    : str      					=						14
  						__a    : Optional[int]      					=						16
  
  						__a    : str      					=						floats_tensor((batch_size, num_features, seq_len)							).to(__a							)
  						__a    : Optional[Any]      					=						torch.tensor([10] * batch_size							).to(__a							)
  
  						return {"sample": noise, "timestep": time_step}
  
  
  
  
  	@property
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						return (4, 14, 16)
  
  
  
  
  	@property
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						return (4, 14, 1)
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_determinism()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_outputs_equivalence()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_from_save_pretrained()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_from_save_pretrained_variant()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						super().test_model_from_pretrained()
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a					,       __a    : List[Any]      					=						self.prepare_init_args_and_inputs_for_common()
  						__a    : int      					=						self.model_class(**__a							)
  						model.to(__a							)
  						model.eval()
  
  						with torch.no_grad():
  											__a    : Optional[Any]      					=						model(**__a							)
  
  											if isinstance(__a		,       __a							):
  																__a    : Any      					=						output.sample
  
  						self.assertIsNotNone(__a							)
  						__a    : Tuple      					=						torch.Size((inputs_dict['sample'].shape[0], 1)							)
  						self.assertEqual(output.shape		,       __a		,       'Input and output shapes do not match'							)
  
  
  
  
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						pass
  
  
  
  
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						pass
  
  
  
  
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a    : int      					=						{
  						    '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    : Union[str, Any]      					=						self.dummy_input
  						return init_dict, inputs_dict
  
  
  
  
  	@unittest.skipIf(torch_device == 'mps'		,       'mish op not supported in MPS'							)
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a					,       __a    : List[str]      					=						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    : Optional[Any]      					=						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    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						__a					,       __a    : Dict      					=						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    : str      					=						value_function.config.in_channels
  						__a    : Dict      					=						14
  						__a    : List[str]      					=						torch.randn((1, seq_len, num_features)							).permute(
  						    0		,       2		,       1							)  # match original, we can update values and remove
  						__a    : List[Any]      					=						torch.full((num_features,)		,       0							)
  
  						with torch.no_grad():
  											__a    : Any      					=						value_function(__a		,       __a							).sample
  
  						# fmt: off
  						__a    : str      					=						torch.tensor([165.25] * seq_len							)
  						# fmt: on
  						self.assertTrue(torch.allclose(__a		,       __a		,       rtol=1E-3							)							)
  
  
  
  
  
  	def    __UpperCAmelCase							(     self							):
  
  						'''simple docstring'''
  
  
  
  
  
  						pass
  
  
  
  