




import json
import os

import torch

from diffusers import UNetaDModel


os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True)
os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True)

os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True)



def 						lowerCAmelCase		(		_lowerCAmelCase							:   Optional[int]	):




 """simple docstring"""







 if hor == 128:
  UpperCAmelCase__							 =						("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
  UpperCAmelCase__							 =						(32, 128, 256)
  UpperCAmelCase__							 =						("UpResnetBlock1D", "UpResnetBlock1D")

 elif hor == 32:
  UpperCAmelCase__							 =						("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
  UpperCAmelCase__							 =						(32, 64, 128, 256)
  UpperCAmelCase__							 =						("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D")
 UpperCAmelCase__							 =						torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch'''	)
 UpperCAmelCase__							 =						model.state_dict()
 UpperCAmelCase__							 =						{
     "down_block_types": down_block_types,
     "block_out_channels": block_out_channels,
     "up_block_types": up_block_types,
     "layers_per_block": 1,
     "use_timestep_embedding": True,
     "out_block_type": "OutConv1DBlock",
     "norm_num_groups": 8,
     "downsample_each_block": False,
     "in_channels": 14,
     "out_channels": 14,
     "extra_in_channels": 0,
     "time_embedding_type": "positional",
     "flip_sin_to_cos": False,
     "freq_shift": 1,
     "sample_size": 6_5536,
     "mid_block_type": "MidResTemporalBlock1D",
     "act_fn": "mish",
 }
 UpperCAmelCase__							 =						UNetaDModel(**_lowerCAmelCase	)
 print(F'''length of state dict: {len(state_dict.keys()	)}'''	)
 print(F'''length of value function dict: {len(hf_value_function.state_dict().keys()	)}'''	)
 UpperCAmelCase__							 =						dict(zip(model.state_dict().keys()						,							hf_value_function.state_dict().keys()	)	)
 for k, v in mapping.items():
  UpperCAmelCase__							 =						state_dict.pop(_lowerCAmelCase	)
 hf_value_function.load_state_dict(_lowerCAmelCase	)

 torch.save(hf_value_function.state_dict()						,							F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin'''	)
 with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json'''						,							"w"	) as f:
  json.dump(_lowerCAmelCase						,							_lowerCAmelCase	)



def 						lowerCAmelCase		(		):




 """simple docstring"""







 UpperCAmelCase__							 =						{
     "in_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,
     "sample_size": 6_5536,
     "out_channels": 14,
     "extra_in_channels": 0,
     "time_embedding_type": "positional",
     "use_timestep_embedding": True,
     "flip_sin_to_cos": False,
     "freq_shift": 1,
     "norm_num_groups": 8,
     "act_fn": "mish",
 }

 UpperCAmelCase__							 =						torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch"	)
 UpperCAmelCase__							 =						model
 UpperCAmelCase__							 =						UNetaDModel(**_lowerCAmelCase	)
 print(F'''length of state dict: {len(state_dict.keys()	)}'''	)
 print(F'''length of value function dict: {len(hf_value_function.state_dict().keys()	)}'''	)

 UpperCAmelCase__							 =						dict(zip(state_dict.keys()						,							hf_value_function.state_dict().keys()	)	)
 for k, v in mapping.items():
  UpperCAmelCase__							 =						state_dict.pop(_lowerCAmelCase	)

 hf_value_function.load_state_dict(_lowerCAmelCase	)

 torch.save(hf_value_function.state_dict()						,							"hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin"	)
 with open("hub/hopper-medium-v2/value_function/config.json"						,							"w"	) as f:
  json.dump(_lowerCAmelCase						,							_lowerCAmelCase	)


if __name__ == "__main__":
    unet(3_2)
    # unet(128)
    value_function()











import random
import unittest

import torch

from diffusers import IFInpaintingSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class 			_UpperCamelCase      (				lowerCAmelCase	,       lowerCAmelCase	,       unittest.TestCase		):
      UpperCAmelCase_        =		IFInpaintingSuperResolutionPipeline
      UpperCAmelCase_        =		TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""width""", """height"""}
      UpperCAmelCase_        =		TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"""original_image"""}		)
      UpperCAmelCase_        =		PipelineTesterMixin.required_optional_params - {"""latents"""}
      def 	UpperCAmelCase_						(			self   :str      )     ->			Optional[Any]:
       return self._get_superresolution_dummy_components()
      def 	UpperCAmelCase_						(			self   :List[str] ,      lowerCamelCase   :Dict ,      lowerCamelCase   :Optional[Any]=0      )     ->			int:
       if str(lowerCamelCase      ).startswith("mps"      ):
        UpperCAmelCase__							 =						torch.manual_seed(lowerCamelCase      )
       else:
        UpperCAmelCase__							 =						torch.Generator(device=lowerCamelCase      ).manual_seed(lowerCamelCase      )

       UpperCAmelCase__							 =						floats_tensor((1, 3, 16, 16) ,      rng=random.Random(lowerCamelCase      )      ).to(lowerCamelCase      )
       UpperCAmelCase__							 =						floats_tensor((1, 3, 32, 32) ,      rng=random.Random(lowerCamelCase      )      ).to(lowerCamelCase      )
       UpperCAmelCase__							 =						floats_tensor((1, 3, 32, 32) ,      rng=random.Random(lowerCamelCase      )      ).to(lowerCamelCase      )

       UpperCAmelCase__							 =						{
           "prompt": "A painting of a squirrel eating a burger",
           "image": image,
           "original_image": original_image,
           "mask_image": mask_image,
           "generator": generator,
           "num_inference_steps": 2,
           "output_type": "numpy",
       }

       return inputs
      @unittest.skipIf(
          torch_device != "cuda" or not is_xformers_available() ,      reason="XFormers attention is only available with CUDA and `xformers` installed" ,      )
      def 	UpperCAmelCase_						(			self   :Union[str, Any]      )     ->			Dict:
       self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3      )
      def 	UpperCAmelCase_						(			self   :List[str]      )     ->			Dict:
       self._test_save_load_optional_components()
      @unittest.skipIf(torch_device != "cuda" ,      reason="float16 requires CUDA"      )
      def 	UpperCAmelCase_						(			self   :Tuple      )     ->			Dict:
       # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
       super().test_save_load_floataa(expected_max_diff=1e-1      )
      def 	UpperCAmelCase_						(			self   :Dict      )     ->			str:
       self._test_attention_slicing_forward_pass(expected_max_diff=1e-2      )
      def 	UpperCAmelCase_						(			self   :Dict      )     ->			str:
       self._test_save_load_local()







      def 	UpperCAmelCase_						(			self   :List[str]      )     ->			List[str]:
       self._test_inference_batch_single_identical(
           expected_max_diff=1e-2 ,      )





