code: 
  
  
  
  
  """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_						(		A_,     A_,     unittest.TestCase							):
      lowercase__		      =   UNetaDModel
      lowercase__		      =   '''sample'''
  
  
  
  
      @property
      def 							__magic_name__							(					self		: Optional[int]   )   ->							Optional[Any]:
  
  
  
  
       '''simple docstring'''
  
       A__ =       4
       A__ =       14
       A__ =       16
  
       A__ =       floats_tensor((batch_size, num_features, seq_len)   ).to(snake_case_   )
       A__ =       torch.tensor([10] * batch_size   ).to(snake_case_   )
  
       return {"sample": noise, "timestep": time_step}
  
  
  
  
      @property
      def 							__magic_name__							(					self		: Tuple   )   ->							Optional[int]:
  
  
  
  
       '''simple docstring'''
  
       return (4, 14, 16)
  
  
  
  
      @property
      def 							__magic_name__							(					self		: Optional[Any]   )   ->							List[str]:
  
  
  
  
       '''simple docstring'''
  
       return (4, 14, 16)
  
  
  
  
      def 							__magic_name__							(					self		: Any   )   ->							str:
  
  
  
  
       '''simple docstring'''
  
       pass
  
  
  
  
      def 							__magic_name__							(					self		: List[Any]   )   ->							Any:
  
  
  
  
       '''simple docstring'''
  
       pass
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Any   )   ->							Optional[Any]:
  
  
  
  
       '''simple docstring'''
  
       super().test_determinism()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: List[str]   )   ->							str:
  
  
  
  
       '''simple docstring'''
  
       super().test_outputs_equivalence()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Optional[int]   )   ->							List[str]:
  
  
  
  
       '''simple docstring'''
  
       super().test_from_save_pretrained()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Dict   )   ->							List[str]:
  
  
  
  
       '''simple docstring'''
  
       super().test_from_save_pretrained_variant()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Optional[Any]   )   ->							Optional[Any]:
  
  
  
  
       '''simple docstring'''
  
       super().test_model_from_pretrained()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Tuple   )   ->							Optional[int]:
  
  
  
  
       '''simple docstring'''
  
       super().test_output()
  
  
  
  
      def 							__magic_name__							(					self		: Optional[Any]   )   ->							Optional[int]:
  
  
  
  
       '''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 							__magic_name__							(					self		: List[Any]   )   ->							List[str]:
  
  
  
  
       '''simple docstring'''
  
       A__,   A__ =       UNetaDModel.from_pretrained(
           "bglick13/hopper-medium-v2-value-function-hor32"			,				output_loading_info=snake_case_			,				subfolder="unet"   )
       self.assertIsNotNone(snake_case_   )
       self.assertEqual(len(loading_info["missing_keys"]   )			,				0   )
  
       model.to(snake_case_   )
       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 							__magic_name__							(					self		: int   )   ->							Optional[int]:
  
  
  
  
       '''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(snake_case_			,				snake_case_   ).sample.permute(0			,				2			,				1   )
  
       A__ =       output[0, -3:, -3:].flatten()
       # fmt: off
       A__ =       torch.tensor([-2.13_7172, 1.142_6016, 0.368_8687, -0.76_6922, 0.730_3146, 0.1103_8864, -0.476_0633, 0.1327_0172, 0.0259_1348]   )
       # fmt: on
       self.assertTrue(torch.allclose(snake_case_			,				snake_case_			,				rtol=1e-3   )   )
  
  
  
  
      def 							__magic_name__							(					self		: Tuple   )   ->							List[str]:
  
  
  
  
       '''simple docstring'''
  
       pass
  
  
  
  
      @slow
      def 							__magic_name__							(					self		: List[str]   )   ->							str:
  
  
  
  
       '''simple docstring'''
  
       A__ =       "harmonai/maestro-150k"
       A__ =       UNetaDModel.from_pretrained(snake_case_			,				subfolder="unet"   )
       model.to(snake_case_   )
  
       A__ =       65_536
       A__ =       torch.sin(torch.arange(snake_case_   )[None, None, :].repeat(1			,				2			,				1   )   ).to(snake_case_   )
       A__ =       torch.tensor([1]   ).to(snake_case_   )
  
       with torch.no_grad():
        A__ =       model(snake_case_			,				snake_case_   ).sample
  
       A__ =       output.abs().sum()
       A__ =       output.abs().max()
  
       assert (output_sum - 224.0896).abs() < 0.5
       assert (output_max - 0.0607).abs() < 4e-4
  
  
  
  
  
  
  class 			UpperCAmelCase_						(		A_,     A_,     unittest.TestCase							):
      lowercase__		      =   UNetaDModel
      lowercase__		      =   '''sample'''
  
  
  
  
      @property
      def 							__magic_name__							(					self		: List[Any]   )   ->							Union[str, Any]:
  
  
  
  
       '''simple docstring'''
  
       A__ =       4
       A__ =       14
       A__ =       16
  
       A__ =       floats_tensor((batch_size, num_features, seq_len)   ).to(snake_case_   )
       A__ =       torch.tensor([10] * batch_size   ).to(snake_case_   )
  
       return {"sample": noise, "timestep": time_step}
  
  
  
  
      @property
      def 							__magic_name__							(					self		: Any   )   ->							Union[str, Any]:
  
  
  
  
       '''simple docstring'''
  
       return (4, 14, 16)
  
  
  
  
      @property
      def 							__magic_name__							(					self		: Optional[Any]   )   ->							int:
  
  
  
  
       '''simple docstring'''
  
       return (4, 14, 1)
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Union[str, Any]   )   ->							List[Any]:
  
  
  
  
       '''simple docstring'''
  
       super().test_determinism()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Tuple   )   ->							Tuple:
  
  
  
  
       '''simple docstring'''
  
       super().test_outputs_equivalence()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: str   )   ->							Union[str, Any]:
  
  
  
  
       '''simple docstring'''
  
       super().test_from_save_pretrained()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Optional[int]   )   ->							int:
  
  
  
  
       '''simple docstring'''
  
       super().test_from_save_pretrained_variant()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Optional[Any]   )   ->							List[Any]:
  
  
  
  
       '''simple docstring'''
  
       super().test_model_from_pretrained()
  
  
  
  
      @unittest.skipIf(torch_device == "mps"			,				"mish op not supported in MPS"   )
      def 							__magic_name__							(					self		: Optional[Any]   )   ->							Dict:
  
  
  
  
       '''simple docstring'''
  
       A__,   A__ =       self.prepare_init_args_and_inputs_for_common()
       A__ =       self.model_class(**snake_case_   )
       model.to(snake_case_   )
       model.eval()
  
       with torch.no_grad():
        A__ =       model(**snake_case_   )
  
        if isinstance(snake_case_			,				snake_case_   ):
         A__ =       output.sample
  
       self.assertIsNotNone(snake_case_   )
       A__ =       torch.Size((inputs_dict["sample"].shape[0], 1)   )
       self.assertEqual(output.shape			,				snake_case_			,				"Input and output shapes do not match"   )
  
  
  
  
      def 							__magic_name__							(					self		: Any   )   ->							Union[str, Any]:
  
  
  
  
       '''simple docstring'''
  
       pass
  
  
  
  
      def 							__magic_name__							(					self		: int   )   ->							Any:
  
  
  
  
       '''simple docstring'''
  
       pass
  
  
  
  
      def 							__magic_name__							(					self		: List[str]   )   ->							Optional[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 							__magic_name__							(					self		: int   )   ->							Tuple:
  
  
  
  
       '''simple docstring'''
  
       A__,   A__ =       UNetaDModel.from_pretrained(
           "bglick13/hopper-medium-v2-value-function-hor32"			,				output_loading_info=snake_case_			,				subfolder="value_function"   )
       self.assertIsNotNone(snake_case_   )
       self.assertEqual(len(vf_loading_info["missing_keys"]   )			,				0   )
  
       value_function.to(snake_case_   )
       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 							__magic_name__							(					self		: str   )   ->							Dict:
  
  
  
  
       '''simple docstring'''
  
       A__,   A__ =       UNetaDModel.from_pretrained(
           "bglick13/hopper-medium-v2-value-function-hor32"			,				output_loading_info=snake_case_			,				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(snake_case_			,				snake_case_   ).sample
  
       # fmt: off
       A__ =       torch.tensor([165.25] * seq_len   )
       # fmt: on
       self.assertTrue(torch.allclose(snake_case_			,				snake_case_			,				rtol=1e-3   )   )
  
  
  
  
      def 							__magic_name__							(					self		: Tuple   )   ->							Union[str, Any]:
  
  
  
  
       '''simple docstring'''
  
       pass
  
  
  
  
  
  
style_context: 
  
  
  
  
  """simple docstring"""
  
  
  
  import logging
  from pathlib import Path
  
  import numpy as np
  import pytorch_lightning as pl
  import torch
  from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
  from pytorch_lightning.utilities import rank_zero_only
  
  from utils import save_json
  
  
  
  
  
  
  
  def 						_SCREAMING_SNAKE_CASE     (							lowercase_		)		->	List[Any]:
   A__ =       filter(lambda lowercase_		: p.requires_grad    ,				model.parameters()		)
   A__ =       sum([np.prod(p.size()		) for p in model_parameters]		)
   return params
  
  
  SCREAMING_SNAKE_CASE       = logging.getLogger(__name__)
  
  
  
  
  class 			UpperCAmelCase_						(		pl.Callback							):
  
  
  
  
      def 							__magic_name__							(					self		: List[str]			,				snake_case_		: Optional[Any]			,				snake_case_		: Tuple   )   ->							Optional[int]:
  
  
  
  
       '''simple docstring'''
  
       A__ =       {F"""lr_group_{i}""": param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups   )}
       pl_module.logger.log_metrics(snake_case_   )
  
  
  
  
      @rank_zero_only
      def 							__magic_name__							(					self		: Dict			,				snake_case_		: pl.Trainer			,				snake_case_		: pl.LightningModule			,				snake_case_		: str			,				snake_case_		: List[str]=True   )   ->							None:
  
  
  
  
       '''simple docstring'''
  
       logger.info(F"""***** {type_path} results at step {trainer.global_step:05d} *****"""   )
       A__ =       trainer.callback_metrics
       trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]}   )
       # Log results
       A__ =       Path(pl_module.hparams.output_dir   )
       if type_path == "test":
        A__ =       od / "test_results.txt"
        A__ =       od / "test_generations.txt"
       else:
        # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
        # If people want this it will be easy enough to add back.
        A__ =       od / F"""{type_path}_results/{trainer.global_step:05d}.txt"""
        A__ =       od / F"""{type_path}_generations/{trainer.global_step:05d}.txt"""
        results_file.parent.mkdir(exist_ok=snake_case_   )
        generations_file.parent.mkdir(exist_ok=snake_case_   )
       with open(snake_case_			,				"a+"   ) as writer:
        for key in sorted(snake_case_   ):
         if key in ["log", "progress_bar", "preds"]:
          continue
         A__ =       metrics[key]
         if isinstance(snake_case_			,				torch.Tensor   ):
          A__ =       val.item()
         A__ =       F"""{key}: {val:.6f}\n"""
         writer.write(snake_case_   )
  
       if not save_generations:
        return
  
       if "preds" in metrics:
        A__ =       "\n".join(metrics["preds"]   )
        generations_file.open("w+"   ).write(snake_case_   )
  
  
  
  
      @rank_zero_only
      def 							__magic_name__							(					self		: str			,				snake_case_		: Tuple			,				snake_case_		: Dict   )   ->							Any:
  
  
  
  
       '''simple docstring'''
  
       try:
        A__ =       pl_module.model.model.num_parameters()
       except AttributeError:
        A__ =       pl_module.model.num_parameters()
  
       A__ =       count_trainable_parameters(snake_case_   )
       # mp stands for million parameters
       trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6}   )
  
  
  
  
      @rank_zero_only
      def 							__magic_name__							(					self		: List[Any]			,				snake_case_		: pl.Trainer			,				snake_case_		: pl.LightningModule   )   ->							Union[str, Any]:
  
  
  
  
       '''simple docstring'''
  
       save_json(pl_module.metrics			,				pl_module.metrics_save_path   )
       return self._write_logs(snake_case_			,				snake_case_			,				"test"   )
  
  
  
  
      @rank_zero_only
      def 							__magic_name__							(					self		: Optional[int]			,				snake_case_		: pl.Trainer			,				snake_case_		: int   )   ->							Optional[Any]:
  
  
  
  
       '''simple docstring'''
  
       save_json(pl_module.metrics			,				pl_module.metrics_save_path   )
       # Uncommenting this will save val generations
       # return self._write_logs(trainer, pl_module, "valid")
  
  
  
  
  
  
  
  def 						_SCREAMING_SNAKE_CASE     (							lowercase_    ,				lowercase_    ,				lowercase_=1    ,				lowercase_=False		)		->	Dict:
   if metric == "rouge2":
    A__ =       "{val_avg_rouge2:.4f}-{step_count}"
   elif metric == "bleu":
    A__ =       "{val_avg_bleu:.4f}-{step_count}"
   elif metric == "loss":
    A__ =       "{val_avg_loss:.4f}-{step_count}"
   else:
    raise NotImplementedError(
        f"""seq2seq callbacks only support rouge2, bleu and loss, got {metric}, You can make your own by adding to"""
        " this function."		)
  
   A__ =       ModelCheckpoint(
       dirpath=lowercase_    ,				filename=lowercase_    ,				monitor=f"""val_{metric}"""    ,				mode="min" if "loss" in metric else "max"    ,				save_top_k=lowercase_    ,				)
   return checkpoint_callback
  
  
  
  
  
  
  
  def 						_SCREAMING_SNAKE_CASE     (							lowercase_    ,				lowercase_		)		->	Union[str, Any]:
   return EarlyStopping(
       monitor=f"""val_{metric}"""    ,				mode="min" if "loss" in metric else "max"    ,				patience=lowercase_    ,				verbose=lowercase_    ,				)
  
  
  
  
  
  