





'''simple docstring'''





from __future__ import annotations

from math import pi, pow
def   _A (	SCREAMING_SNAKE_CASE  :     int | float		):





  """simple docstring"""



  if side_length < 0:
    raise ValueError("vol_cube() only accepts non-negative values"		)
  return pow(SCREAMING_SNAKE_CASE , 3		)
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if height < 0 or radius < 0:
    raise ValueError("vol_spherical_cap() only accepts non-negative values"		)
  # Volume is 1/3 pi * height squared * (3 * radius - height)
  return 1 / 3 * pi * pow(SCREAMING_SNAKE_CASE , 2		) * (3 * radius - height)
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if radius_a < 0 or radius_a < 0 or centers_distance < 0:
    raise ValueError("vol_spheres_intersect() only accepts non-negative values"		)
  if centers_distance == 0:
    return vol_sphere(min(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)		)

  a__			:      Dict            =(
      (radius_a - radius_a + centers_distance)
      * (radius_a + radius_a - centers_distance)
      / (2 * centers_distance)
  )
  a__			:      Dict            =(
      (radius_a - radius_a + centers_distance)
      * (radius_a + radius_a - centers_distance)
      / (2 * centers_distance)
  )

  return vol_spherical_cap(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		) + vol_spherical_cap(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if radius_a <= 0 or radius_a <= 0 or centers_distance < 0:
    raise ValueError(
        "vol_spheres_union() only accepts non-negative values, non-zero radius"		)

  if centers_distance == 0:
    return vol_sphere(max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)		)

  return (
      vol_sphere(SCREAMING_SNAKE_CASE		)
      + vol_sphere(SCREAMING_SNAKE_CASE		)
      - vol_spheres_intersect(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)
  )
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if width < 0 or height < 0 or length < 0:
    raise ValueError("vol_cuboid() only accepts non-negative values"		)
  return float(width * height * length		)
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if height < 0 or area_of_base < 0:
    raise ValueError("vol_cone() only accepts non-negative values"		)
  return area_of_base * height / 3.0
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if height < 0 or radius < 0:
    raise ValueError("vol_right_circ_cone() only accepts non-negative values"		)
  return pi * pow(SCREAMING_SNAKE_CASE , 2		) * height / 3.0
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if height < 0 or area_of_base < 0:
    raise ValueError("vol_prism() only accepts non-negative values"		)
  return float(area_of_base * height		)
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if height < 0 or area_of_base < 0:
    raise ValueError("vol_pyramid() only accepts non-negative values"		)
  return area_of_base * height / 3.0
def   _A (	SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if radius < 0:
    raise ValueError("vol_sphere() only accepts non-negative values"		)
  # Volume is 4/3 * pi * radius cubed
  return 4 / 3 * pi * pow(SCREAMING_SNAKE_CASE , 3		)
def   _A (	SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if radius < 0:
    raise ValueError("vol_hemisphere() only accepts non-negative values"		)
  # Volume is radius cubed * pi * 2/3
  return pow(SCREAMING_SNAKE_CASE , 3		) * pi * 2 / 3
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if height < 0 or radius < 0:
    raise ValueError("vol_circular_cylinder() only accepts non-negative values"		)
  # Volume is radius squared * height * pi
  return pow(SCREAMING_SNAKE_CASE , 2		) * height * pi
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if inner_radius < 0 or outer_radius < 0 or height < 0:
    raise ValueError(
        "vol_hollow_circular_cylinder() only accepts non-negative values"		)
  if outer_radius <= inner_radius:
    raise ValueError("outer_radius must be greater than inner_radius"		)
  return pi * (pow(SCREAMING_SNAKE_CASE , 2		) - pow(SCREAMING_SNAKE_CASE , 2		)) * height
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if radius_a < 0 or radius_a < 0 or height < 0:
    raise ValueError("vol_conical_frustum() only accepts non-negative values"		)
  return (
      1
      / 3
      * pi
      * height
      * (pow(SCREAMING_SNAKE_CASE , 2		) + pow(SCREAMING_SNAKE_CASE , 2		) + radius_a * radius_a)
  )
def   _A (	SCREAMING_SNAKE_CASE  :     float , SCREAMING_SNAKE_CASE  :     float		):





  """simple docstring"""



  if torus_radius < 0 or tube_radius < 0:
    raise ValueError("vol_torus() only accepts non-negative values"		)
  return 2 * pow(SCREAMING_SNAKE_CASE , 2		) * torus_radius * pow(SCREAMING_SNAKE_CASE , 2		)
def   _A (	):





  """simple docstring"""



  print("Volumes:"		)
  print(f'''Cube: {vol_cube(2		) = }'''		)  # = 8
  print(f'''Cuboid: {vol_cuboid(2 , 2 , 2		) = }'''		)  # = 8
  print(f'''Cone: {vol_cone(2 , 2		) = }'''		)  # ~= 1.33
  print(f'''Right Circular Cone: {vol_right_circ_cone(2 , 2		) = }'''		)  # ~= 8.38
  print(f'''Prism: {vol_prism(2 , 2		) = }'''		)  # = 4
  print(f'''Pyramid: {vol_pyramid(2 , 2		) = }'''		)  # ~= 1.33
  print(f'''Sphere: {vol_sphere(2		) = }'''		)  # ~= 33.5
  print(f'''Hemisphere: {vol_hemisphere(2		) = }'''		)  # ~= 16.75
  print(f'''Circular Cylinder: {vol_circular_cylinder(2 , 2		) = }'''		)  # ~= 25.1
  print(f'''Torus: {vol_torus(2 , 2		) = }'''		)  # ~= 157.9
  print(f'''Conical Frustum: {vol_conical_frustum(2 , 2 , 4		) = }'''		)  # ~= 58.6
  print(f'''Spherical cap: {vol_spherical_cap(1 , 2		) = }'''		)  # ~= 5.24
  print(f'''Spheres intersetion: {vol_spheres_intersect(2 , 2 , 1		) = }'''		)  # ~= 21.21
  print(f'''Spheres union: {vol_spheres_union(2 , 2 , 1		) = }'''		)  # ~= 45.81
  print(
      f'''Hollow Circular Cylinder: {vol_hollow_circular_cylinder(1 , 2 , 3		) = }'''		)  # ~= 28.3


if __name__ == "__main__":
     main()













import tempfile
import unittest

import torch

from diffusers import UNetaDConditionModel
from diffusers.training_utils import EMAModel
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps, torch_device


enable_full_determinism()







class        __lowerCAmelCase (					unittest.TestCase):
      _lowercase       :      str        =    """hf-internal-testing/tiny-stable-diffusion-pipe"""
      _lowercase       :      Optional[int]        =    1
      _lowercase       :      List[str]        =    77
      _lowercase       :      int        =    32
      _lowercase       :      Dict        =    4
      _lowercase       :      str        =    64
      _lowercase       :      Optional[Any]        =    torch.manual_seed(0)







      def      _lowercase						(					self	,   lowerCAmelCase__=0.99_99							)     ->		Tuple:



        '''simple docstring'''




        a__			:      int            =UNetaDConditionModel.from_pretrained(self.model_id	,   subfolder="unet"							)
        a__			:      Any            =unet.to(lowerCAmelCase__							)
        a__			:      int            =EMAModel(unet.parameters()	,   decay=lowerCAmelCase__	,   model_cls=lowerCAmelCase__	,   model_config=unet.config							)
        return unet, ema_unet







      def      _lowercase						(					self							)     ->		Dict:



        '''simple docstring'''




        a__			:      str            =torch.randn(
            self.batch_size	,   self.num_in_channels	,   self.latent_height	,   self.latent_width	,   generator=self.generator							).to(lowerCAmelCase__							)
        a__			:      Any            =torch.randint(0	,   1_0_0_0	,   size=(self.batch_size,)	,   generator=self.generator							).to(lowerCAmelCase__							)
        a__			:      Tuple            =torch.randn(
            self.batch_size	,   self.prompt_length	,   self.text_encoder_hidden_dim	,   generator=self.generator							).to(lowerCAmelCase__							)
        return noisy_latents, timesteps, encoder_hidden_states







      def      _lowercase						(					self	,   lowerCAmelCase__							)     ->		Any:



        '''simple docstring'''




        a__			:      Any            ={}
        for k, param in unet.state_dict().items():
          a__			:      Tuple            =torch.randn_like(lowerCAmelCase__							) + (param * torch.randn_like(lowerCAmelCase__							))
          updated_state_dict.update({k: updated_param}							)
        unet.load_state_dict(lowerCAmelCase__							)
        return unet







      def      _lowercase						(					self							)     ->		Tuple:



        '''simple docstring'''




        a__      ,							a__			:      List[Any]            =self.get_models()
        # Take the first (hypothetical) EMA step.
        ema_unet.step(unet.parameters()							)
        assert ema_unet.optimization_step == 1

        # Take two more.
        for _ in range(2							):
          ema_unet.step(unet.parameters()							)
        assert ema_unet.optimization_step == 3







      def      _lowercase						(					self							)     ->		List[str]:



        '''simple docstring'''




        a__      ,							a__			:      Any            =self.get_models()
        # Since the `unet` is not being updated (i.e., backprop'd)
        # there won't be any difference between the `params` of `unet`
        # and `ema_unet` even if we call `ema_unet.step(unet.parameters())`.
        ema_unet.step(unet.parameters()							)
        a__			:      str            =list(unet.parameters()							)
        for s_param, param in zip(ema_unet.shadow_params	,   lowerCAmelCase__							):
          assert torch.allclose(lowerCAmelCase__	,   lowerCAmelCase__							)

        # The above holds true even if we call `ema.step()` multiple times since
        # `unet` params are still not being updated.
        for _ in range(4							):
          ema_unet.step(unet.parameters()							)
        for s_param, param in zip(ema_unet.shadow_params	,   lowerCAmelCase__							):
          assert torch.allclose(lowerCAmelCase__	,   lowerCAmelCase__							)







      def      _lowercase						(					self							)     ->		List[Any]:



        '''simple docstring'''




        a__      ,							a__			:      Optional[Any]            =self.get_models()
        # Here we simulate the parameter updates for `unet`. Since there might
        # be some parameters which are initialized to zero we take extra care to
        # initialize their values to something non-zero before the multiplication.
        a__			:      List[str]            =self.simulate_backprop(lowerCAmelCase__							)

        # Take the EMA step.
        ema_unet.step(unet_pseudo_updated_step_one.parameters()							)

        # Now the EMA'd parameters won't be equal to the original model parameters.
        a__			:      Optional[int]            =list(unet_pseudo_updated_step_one.parameters()							)
        for s_param, param in zip(ema_unet.shadow_params	,   lowerCAmelCase__							):
          assert ~torch.allclose(lowerCAmelCase__	,   lowerCAmelCase__							)

        # Ensure this is the case when we take multiple EMA steps.
        for _ in range(4							):
          ema_unet.step(unet.parameters()							)
        for s_param, param in zip(ema_unet.shadow_params	,   lowerCAmelCase__							):
          assert ~torch.allclose(lowerCAmelCase__	,   lowerCAmelCase__							)







      def      _lowercase						(					self							)     ->		Union[str, Any]:



        '''simple docstring'''




        a__      ,							a__			:      Dict            =self.get_models()

        # First backprop + EMA
        a__			:      Tuple            =self.simulate_backprop(lowerCAmelCase__							)
        ema_unet.step(unet_step_one.parameters()							)
        a__			:      Dict            =ema_unet.shadow_params

        # Second backprop + EMA
        a__			:      str            =self.simulate_backprop(lowerCAmelCase__							)
        ema_unet.step(unet_step_two.parameters()							)
        a__			:      List[str]            =ema_unet.shadow_params

        for step_one, step_two in zip(lowerCAmelCase__	,   lowerCAmelCase__							):
          assert ~torch.allclose(lowerCAmelCase__	,   lowerCAmelCase__							)







      def      _lowercase						(					self							)     ->		List[str]:



        '''simple docstring'''




        a__      ,							a__			:      int            =self.get_models(decay=0.0							)
        a__			:      Optional[int]            =self.simulate_backprop(lowerCAmelCase__							)
        ema_unet.step(unet_step_one.parameters()							)
        a__			:      List[Any]            =ema_unet.shadow_params

        a__			:      Tuple            =self.simulate_backprop(lowerCAmelCase__							)
        ema_unet.step(unet_step_two.parameters()							)
        a__			:      List[Any]            =ema_unet.shadow_params

        for step_one, step_two in zip(lowerCAmelCase__	,   lowerCAmelCase__							):
          assert torch.allclose(lowerCAmelCase__	,   lowerCAmelCase__							)







      @skip_mps
      def      _lowercase						(					self							)     ->		Optional[Any]:



        '''simple docstring'''




        a__      ,							a__			:      Union[str, Any]            =self.get_models()
        a__      ,							a__      ,							a__			:      Tuple            =self.get_dummy_inputs()

        with tempfile.TemporaryDirectory() as tmpdir:
          ema_unet.save_pretrained(lowerCAmelCase__							)
          a__			:      List[str]            =UNetaDConditionModel.from_pretrained(lowerCAmelCase__	,   model_cls=lowerCAmelCase__							)
          a__			:      Tuple            =loaded_unet.to(unet.device							)

        # Since no EMA step has been performed the outputs should match.
        a__			:      Optional[Any]            =unet(lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							).sample
        a__			:      Optional[int]            =loaded_unet(lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							).sample

        assert torch.allclose(lowerCAmelCase__	,   lowerCAmelCase__	,   atol=1E-4							)






