



"""simple docstring"""




def 		UpperCamelCase     (       snake_case__	:   int	,					snake_case__	:   list     )     ->					Tuple:
   _enforce_args(snake_case__	,					snake_case__     )
   if n == 0:
      return 0
   UpperCamelCase   :  Dict						     =     float('-inf'     )
   for i in range(1	,					n + 1     ):
      UpperCamelCase   :  List[str]						     =     max(
          snake_case__	,					prices[i - 1] + naive_cut_rod_recursive(n - i	,					snake_case__     )     )

   return max_revue
def 		UpperCamelCase     (       snake_case__	:   int	,					snake_case__	:   list     )     ->					str:
   _enforce_args(snake_case__	,					snake_case__     )
   UpperCamelCase   :  Union[str, Any]						     =     [float('-inf'     ) for _ in range(n + 1     )]
   return _top_down_cut_rod_recursive(snake_case__	,					snake_case__	,					snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   int	,					snake_case__	:   list	,					snake_case__	:   list     )     ->					str:
   if max_rev[n] >= 0:
      return max_rev[n]
   elif n == 0:
      return 0
   else:
      UpperCamelCase   :  Union[str, Any]						     =     float('-inf'     )
      for i in range(1	,					n + 1     ):
         UpperCamelCase   :  int						     =     max(
             snake_case__	,					prices[i - 1] + _top_down_cut_rod_recursive(n - i	,					snake_case__	,					snake_case__     )	,					)

      UpperCamelCase   :  Optional[int]						     =     max_revenue

   return max_rev[n]
def 		UpperCamelCase     (       snake_case__	:   int	,					snake_case__	:   list     )     ->					Tuple:
   _enforce_args(snake_case__	,					snake_case__     )

   # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
   # length 0.
   UpperCamelCase   :  Dict						     =     [float('-inf'     ) for _ in range(n + 1     )]
   UpperCamelCase   :  Optional[int]						     =     0

   for i in range(1	,					n + 1     ):
      UpperCamelCase   :  Any						     =     max_rev[i]
      for j in range(1	,					i + 1     ):
         UpperCamelCase   :  int						     =     max(snake_case__	,					prices[j - 1] + max_rev[i - j]     )

      UpperCamelCase   :  Optional[Any]						     =     max_revenue_i

   return max_rev[n]
def 		UpperCamelCase     (       snake_case__	:   int	,					snake_case__	:   list     )     ->					Dict:
   if n < 0:
      UpperCamelCase   :  Dict						     =     F"""n must be greater than or equal to 0. Got n = {n}"""
      raise ValueError(snake_case__     )

   if n > len(snake_case__     ):
      UpperCamelCase   :  Optional[int]						     =     (
          'Each integral piece of rod must have a corresponding price. '
          F"""Got n = {n} but length of prices = {len(snake_case__     )}"""
      )
      raise ValueError(snake_case__     )
def 		UpperCamelCase     (       )     ->					Tuple:
   UpperCamelCase   :  List[Any]						     =     [6, 10, 12, 15, 20, 23]
   UpperCamelCase   :  Dict						     =     len(snake_case__     )

   # the best revenue comes from cutting the rod into 6 pieces, each
   # of length 1 resulting in a revenue of 6 * 6 = 36.
   UpperCamelCase   :  Tuple						     =     36

   UpperCamelCase   :  List[str]						     =     top_down_cut_rod(snake_case__	,					snake_case__     )
   UpperCamelCase   :  Any						     =     bottom_up_cut_rod(snake_case__	,					snake_case__     )
   UpperCamelCase   :  int						     =     naive_cut_rod_recursive(snake_case__	,					snake_case__     )

   assert expected_max_revenue == max_rev_top_down
   assert max_rev_top_down == max_rev_bottom_up
   assert max_rev_bottom_up == max_rev_naive


if __name__ == "__main__":
    main()








import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference



class     lowerCAmelCase_		(  a__	,   unittest.TestCase							):
       UpperCAmelCase__    : Union[str, Any]       					=  ShapEPipeline
       UpperCAmelCase__    : List[Any]       					=  ["prompt"]
       UpperCAmelCase__    : List[str]       					=  ["prompt"]
       UpperCAmelCase__    : int       					=  [
           "num_images_per_prompt",
           "num_inference_steps",
           "generator",
           "latents",
           "guidance_scale",
           "frame_size",
           "output_type",
           "return_dict",
       ]
       UpperCAmelCase__    : Union[str, Any]       					=  False
       @property
       def  snake_case_	(      self	)					->		Union[str, Any]:
          return 32
       @property
       def  snake_case_	(      self	)					->		List[str]:
          return 32
       @property
       def  snake_case_	(      self	)					->		int:
          return self.time_input_dim * 4
       @property
       def  snake_case_	(      self	)					->		Optional[int]:
          return 8
       @property
       def  snake_case_	(      self	)					->		str:
          UpperCamelCase   :  Union[str, Any]						     =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'	)
          return tokenizer
       @property
       def  snake_case_	(      self	)					->		Optional[Any]:
          torch.manual_seed(0	)
          UpperCamelCase   :  Dict						     =     CLIPTextConfig(
              bos_token_id=0,      eos_token_id=2,      hidden_size=self.text_embedder_hidden_size,      projection_dim=self.text_embedder_hidden_size,      intermediate_size=37,      layer_norm_eps=1e-05,      num_attention_heads=4,      num_hidden_layers=5,      pad_token_id=1,      vocab_size=1000,      )
          return CLIPTextModelWithProjection(SCREAMING_SNAKE_CASE_	)
       @property
       def  snake_case_	(      self	)					->		Dict:
          torch.manual_seed(0	)

          UpperCamelCase   :  int						     =     {
              'num_attention_heads': 2,
              'attention_head_dim': 16,
              'embedding_dim': self.time_input_dim,
              'num_embeddings': 32,
              'embedding_proj_dim': self.text_embedder_hidden_size,
              'time_embed_dim': self.time_embed_dim,
              'num_layers': 1,
              'clip_embed_dim': self.time_input_dim * 2,
              'additional_embeddings': 0,
              'time_embed_act_fn': 'gelu',
              'norm_in_type': 'layer',
              'encoder_hid_proj_type': None,
              'added_emb_type': None,
          }

          UpperCamelCase   :  Any						     =     PriorTransformer(**SCREAMING_SNAKE_CASE_	)
          return model
       @property
       def  snake_case_	(      self	)					->		Tuple:
          torch.manual_seed(0	)

          UpperCamelCase   :  Any						     =     {
              'param_shapes': (
                  (self.renderer_dim, 93),
                  (self.renderer_dim, 8),
                  (self.renderer_dim, 8),
                  (self.renderer_dim, 8),
              ),
              'd_latent': self.time_input_dim,
              'd_hidden': self.renderer_dim,
              'n_output': 12,
              'background': (
                  0.1,
                  0.1,
                  0.1,
              ),
          }
          UpperCamelCase   :  Dict						     =     ShapERenderer(**SCREAMING_SNAKE_CASE_	)
          return model
       def  snake_case_	(      self	)					->		Tuple:
          UpperCamelCase   :  List[Any]						     =     self.dummy_prior
          UpperCamelCase   :  int						     =     self.dummy_text_encoder
          UpperCamelCase   :  Dict						     =     self.dummy_tokenizer
          UpperCamelCase   :  List[str]						     =     self.dummy_renderer

          UpperCamelCase   :  str						     =     HeunDiscreteScheduler(
              beta_schedule='exp',      num_train_timesteps=1024,      prediction_type='sample',      use_karras_sigmas=SCREAMING_SNAKE_CASE_,      clip_sample=SCREAMING_SNAKE_CASE_,      clip_sample_range=1.0,      )
          UpperCamelCase   :  List[str]						     =     {
              'prior': prior,
              'text_encoder': text_encoder,
              'tokenizer': tokenizer,
              'renderer': renderer,
              'scheduler': scheduler,
          }

          return components
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_=0	)					->		Any:
          if str(SCREAMING_SNAKE_CASE_	).startswith('mps'	):
             UpperCamelCase   :  Optional[int]						     =     torch.manual_seed(SCREAMING_SNAKE_CASE_	)
          else:
             UpperCamelCase   :  Any						     =     torch.Generator(device=SCREAMING_SNAKE_CASE_	).manual_seed(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  str						     =     {
              'prompt': 'horse',
              'generator': generator,
              'num_inference_steps': 1,
              'frame_size': 32,
              'output_type': 'np',
          }
          return inputs
       def  snake_case_	(      self	)					->		int:
          UpperCamelCase   :  str						     =     'cpu'

          UpperCamelCase   :  Optional[int]						     =     self.get_dummy_components()

          UpperCamelCase   :  int						     =     self.pipeline_class(**SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Optional[Any]						     =     pipe.to(SCREAMING_SNAKE_CASE_	)

          pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_	)

          UpperCamelCase   :  str						     =     pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_	)	)
          UpperCamelCase   :  Optional[int]						     =     output.images[0]
          UpperCamelCase   :  Union[str, Any]						     =     image[0, -3:, -3:, -1]

          assert image.shape == (20, 32, 32, 3)

          UpperCamelCase   :  List[str]						     =     np.array(
              [
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
              ]	)

          assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-2
       def  snake_case_	(      self	)					->		int:
          # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
          self._test_inference_batch_consistent(batch_sizes=[1, 2]	)
       def  snake_case_	(      self	)					->		str:
          UpperCamelCase   :  str						     =     torch_device == 'cpu'
          UpperCamelCase   :  Optional[int]						     =     True

          self._test_inference_batch_single_identical(
              batch_size=2,      test_max_difference=SCREAMING_SNAKE_CASE_,      relax_max_difference=SCREAMING_SNAKE_CASE_,      )






       def  snake_case_	(      self	)					->		List[Any]:
          UpperCamelCase   :  List[Any]						     =     self.get_dummy_components()
          UpperCamelCase   :  str						     =     self.pipeline_class(**SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Optional[int]						     =     pipe.to(SCREAMING_SNAKE_CASE_	)
          pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_	)

          UpperCamelCase   :  Optional[Any]						     =     1
          UpperCamelCase   :  Union[str, Any]						     =     2

          UpperCamelCase   :  Union[str, Any]						     =     self.get_dummy_inputs(SCREAMING_SNAKE_CASE_	)

          for key in inputs.keys():
             if key in self.batch_params:
                UpperCamelCase   :  List[Any]						     =     batch_size * [inputs[key]]

          UpperCamelCase   :  int						     =     pipe(**SCREAMING_SNAKE_CASE_,      num_images_per_prompt=SCREAMING_SNAKE_CASE_	)[0]

          assert images.shape[0] == batch_size * num_images_per_prompt






@slow
@require_torch_gpu
class     lowerCAmelCase_		(  unittest.TestCase							):
       def  snake_case_	(      self	)					->		str:
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()






       def  snake_case_	(      self	)					->		Tuple:
          UpperCamelCase   :  Optional[int]						     =     load_numpy(
              'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
              '/shap_e/test_shap_e_np_out.npy'	)
          UpperCamelCase   :  Optional[int]						     =     ShapEPipeline.from_pretrained('openai/shap-e'	)
          UpperCamelCase   :  Optional[int]						     =     pipe.to(SCREAMING_SNAKE_CASE_	)
          pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_	)

          UpperCamelCase   :  str						     =     torch.Generator(device=SCREAMING_SNAKE_CASE_	).manual_seed(0	)

          UpperCamelCase   :  Dict						     =     pipe(
              'a shark',      generator=SCREAMING_SNAKE_CASE_,      guidance_scale=15.0,      num_inference_steps=64,      frame_size=64,      output_type='np',      ).images[0]

          assert images.shape == (20, 64, 64, 3)

          assert_mean_pixel_difference(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)



