



import gc
import unittest

import numpy as np
import torch
from torch.backends.cuda import sdp_kernel

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class   _A   ( _lowercase  ,						unittest.TestCase	):


						'''simple docstring'''





						_snake_case			:     Any      							=      ConsistencyModelPipeline
						_snake_case			:     Union[str, Any]      							=      UNCONDITIONAL_IMAGE_GENERATION_PARAMS
						_snake_case			:     Optional[Any]      							=      UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

						# Override required_optional_params to remove num_images_per_prompt
						_snake_case			:     str      							=      frozenset(
						    [
						        """num_inference_steps""",
						        """generator""",
						        """latents""",
						        """output_type""",
						        """return_dict""",
						        """callback""",
						        """callback_steps""",
						    ]	)



						@property
						def     _snake_case	(	self	:							Tuple	):






							'''simple docstring'''



							__lowercase		       =			UNetaDModel.from_pretrained(
							    "diffusers/consistency-models-test"							,      subfolder="test_unet"							,      )
							return unet



						@property
						def     _snake_case	(	self	:							Union[str, Any]	):






							'''simple docstring'''



							__lowercase		       =			UNetaDModel.from_pretrained(
							    "diffusers/consistency-models-test"							,      subfolder="test_unet_class_cond"							,      )
							return unet



						def     _snake_case	(	self	:							Optional[Any]							,      lowerCamelCase	:							List[str]=False	):






							'''simple docstring'''



							if class_cond:
								__lowercase		       =			self.dummy_cond_unet
							else:
								__lowercase		       =			self.dummy_uncond_unet

							# Default to CM multistep sampler
							__lowercase		       =			CMStochasticIterativeScheduler(
							    num_train_timesteps=40							,      sigma_min=0.002							,      sigma_max=80.0							,      )

							__lowercase		       =			{
							    "unet": unet,
							    "scheduler": scheduler,
							}

							return components



						def     _snake_case	(	self	:							Tuple							,      lowerCamelCase	:							Dict							,      lowerCamelCase	:							Optional[int]=0	):






							'''simple docstring'''



							if str(lowerCamelCase	).startswith("mps"	):
								__lowercase		       =			torch.manual_seed(lowerCamelCase	)
							else:
								__lowercase		       =			torch.Generator(device=lowerCamelCase	).manual_seed(lowerCamelCase	)

							__lowercase		       =			{
							    "batch_size": 1,
							    "num_inference_steps": None,
							    "timesteps": [22, 0],
							    "generator": generator,
							    "output_type": "np",
							}

							return inputs



						def     _snake_case	(	self	:							Tuple	):






							'''simple docstring'''



							__lowercase		       =			"cpu"  # ensure determinism for the device-dependent torch.Generator
							__lowercase		       =			self.get_dummy_components()
							__lowercase		       =			ConsistencyModelPipeline(**lowerCamelCase	)
							__lowercase		       =			pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							__lowercase		       =			self.get_dummy_inputs(lowerCamelCase	)
							__lowercase		       =			pipe(**lowerCamelCase	).images
							assert image.shape == (1, 32, 32, 3)

							__lowercase		       =			image[0, -3:, -3:, -1]
							__lowercase		       =			np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004]	)

							assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-3



						def     _snake_case	(	self	:							Union[str, Any]	):






							'''simple docstring'''



							__lowercase		       =			"cpu"  # ensure determinism for the device-dependent torch.Generator
							__lowercase		       =			self.get_dummy_components(class_cond=lowerCamelCase	)
							__lowercase		       =			ConsistencyModelPipeline(**lowerCamelCase	)
							__lowercase		       =			pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							__lowercase		       =			self.get_dummy_inputs(lowerCamelCase	)
							__lowercase		       =			0
							__lowercase		       =			pipe(**lowerCamelCase	).images
							assert image.shape == (1, 32, 32, 3)

							__lowercase		       =			image[0, -3:, -3:, -1]
							__lowercase		       =			np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004]	)

							assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-3



						def     _snake_case	(	self	:							Tuple	):






							'''simple docstring'''



							__lowercase		       =			"cpu"  # ensure determinism for the device-dependent torch.Generator
							__lowercase		       =			self.get_dummy_components()
							__lowercase		       =			ConsistencyModelPipeline(**lowerCamelCase	)
							__lowercase		       =			pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							__lowercase		       =			self.get_dummy_inputs(lowerCamelCase	)
							__lowercase		       =			1
							__lowercase		       =			None
							__lowercase		       =			pipe(**lowerCamelCase	).images
							assert image.shape == (1, 32, 32, 3)

							__lowercase		       =			image[0, -3:, -3:, -1]
							__lowercase		       =			np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987]	)

							assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-3



						def     _snake_case	(	self	:							Tuple	):






							'''simple docstring'''



							__lowercase		       =			"cpu"  # ensure determinism for the device-dependent torch.Generator
							__lowercase		       =			self.get_dummy_components(class_cond=lowerCamelCase	)
							__lowercase		       =			ConsistencyModelPipeline(**lowerCamelCase	)
							__lowercase		       =			pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							__lowercase		       =			self.get_dummy_inputs(lowerCamelCase	)
							__lowercase		       =			1
							__lowercase		       =			None
							__lowercase		       =			0
							__lowercase		       =			pipe(**lowerCamelCase	).images
							assert image.shape == (1, 32, 32, 3)

							__lowercase		       =			image[0, -3:, -3:, -1]
							__lowercase		       =			np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987]	)

							assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-3

@slow
@require_torch_gpu
class   _A   ( unittest.TestCase	):


						'''simple docstring'''





						def     _snake_case	(	self	:							str	):






							'''simple docstring'''



							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



						def     _snake_case	(	self	:							str							,      lowerCamelCase	:							Tuple=0							,      lowerCamelCase	:							List[str]=False							,      lowerCamelCase	:							Tuple="cpu"							,      lowerCamelCase	:							Optional[Any]=torch.floataa							,      lowerCamelCase	:							Optional[int]=(1, 3, 64, 64)	):






							'''simple docstring'''



							__lowercase		       =			torch.manual_seed(lowerCamelCase	)

							__lowercase		       =			{
							    "num_inference_steps": None,
							    "timesteps": [22, 0],
							    "class_labels": 0,
							    "generator": generator,
							    "output_type": "np",
							}

							if get_fixed_latents:
								__lowercase		       =			self.get_fixed_latents(seed=lowerCamelCase							,      device=lowerCamelCase							,      dtype=lowerCamelCase							,      shape=lowerCamelCase	)
								__lowercase		       =			latents

							return inputs



						def     _snake_case	(	self	:							Tuple							,      lowerCamelCase	:							Tuple=0							,      lowerCamelCase	:							Dict="cpu"							,      lowerCamelCase	:							Optional[int]=torch.floataa							,      lowerCamelCase	:							Dict=(1, 3, 64, 64)	):






							'''simple docstring'''



							if type(lowerCamelCase	) == str:
								__lowercase		       =			torch.device(lowerCamelCase	)
							__lowercase		       =			torch.Generator(device=lowerCamelCase	).manual_seed(lowerCamelCase	)
							__lowercase		       =			randn_tensor(lowerCamelCase							,      generator=lowerCamelCase							,      device=lowerCamelCase							,      dtype=lowerCamelCase	)
							return latents



						def     _snake_case	(	self	:							int	):






							'''simple docstring'''



							__lowercase		       =			UNetaDModel.from_pretrained("diffusers/consistency_models"							,      subfolder="diffusers_cd_imagenet64_l2"	)
							__lowercase		       =			CMStochasticIterativeScheduler(
							    num_train_timesteps=40							,      sigma_min=0.002							,      sigma_max=80.0							,      )
							__lowercase		       =			ConsistencyModelPipeline(unet=lowerCamelCase							,      scheduler=lowerCamelCase	)
							pipe.to(torch_device=lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							__lowercase		       =			self.get_inputs()
							__lowercase		       =			pipe(**lowerCamelCase	).images
							assert image.shape == (1, 64, 64, 3)

							__lowercase		       =			image[0, -3:, -3:, -1]

							__lowercase		       =			np.array([0.0888, 0.0881, 0.0666, 0.0479, 0.0292, 0.0195, 0.0201, 0.0163, 0.0254]	)

							assert np.abs(image_slice.flatten() - expected_slice	).max() < 2e-2



						def     _snake_case	(	self	:							int	):






							'''simple docstring'''



							__lowercase		       =			UNetaDModel.from_pretrained("diffusers/consistency_models"							,      subfolder="diffusers_cd_imagenet64_l2"	)
							__lowercase		       =			CMStochasticIterativeScheduler(
							    num_train_timesteps=40							,      sigma_min=0.002							,      sigma_max=80.0							,      )
							__lowercase		       =			ConsistencyModelPipeline(unet=lowerCamelCase							,      scheduler=lowerCamelCase	)
							pipe.to(torch_device=lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							__lowercase		       =			self.get_inputs()
							__lowercase		       =			1
							__lowercase		       =			None
							__lowercase		       =			pipe(**lowerCamelCase	).images
							assert image.shape == (1, 64, 64, 3)

							__lowercase		       =			image[0, -3:, -3:, -1]

							__lowercase		       =			np.array([0.0340, 0.0152, 0.0063, 0.0267, 0.0221, 0.0107, 0.0416, 0.0186, 0.0217]	)

							assert np.abs(image_slice.flatten() - expected_slice	).max() < 2e-2



						@require_torch_a
						def     _snake_case	(	self	:							Optional[int]	):






							'''simple docstring'''



							__lowercase		       =			UNetaDModel.from_pretrained("diffusers/consistency_models"							,      subfolder="diffusers_cd_imagenet64_l2"	)
							__lowercase		       =			CMStochasticIterativeScheduler(
							    num_train_timesteps=40							,      sigma_min=0.002							,      sigma_max=80.0							,      )
							__lowercase		       =			ConsistencyModelPipeline(unet=lowerCamelCase							,      scheduler=lowerCamelCase	)
							pipe.to(torch_device=lowerCamelCase							,      torch_dtype=torch.floataa	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							__lowercase		       =			self.get_inputs(get_fixed_latents=lowerCamelCase							,      device=lowerCamelCase	)
							# Ensure usage of flash attention in torch 2.0
							with sdp_kernel(enable_flash=lowerCamelCase							,      enable_math=lowerCamelCase							,      enable_mem_efficient=lowerCamelCase	):
								__lowercase		       =			pipe(**lowerCamelCase	).images
							assert image.shape == (1, 64, 64, 3)

							__lowercase		       =			image[0, -3:, -3:, -1]

							__lowercase		       =			np.array([0.1875, 0.1428, 0.1289, 0.2151, 0.2092, 0.1477, 0.1877, 0.1641, 0.1353]	)

							assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-3



						@require_torch_a
						def     _snake_case	(	self	:							Optional[Any]	):






							'''simple docstring'''



							__lowercase		       =			UNetaDModel.from_pretrained("diffusers/consistency_models"							,      subfolder="diffusers_cd_imagenet64_l2"	)
							__lowercase		       =			CMStochasticIterativeScheduler(
							    num_train_timesteps=40							,      sigma_min=0.002							,      sigma_max=80.0							,      )
							__lowercase		       =			ConsistencyModelPipeline(unet=lowerCamelCase							,      scheduler=lowerCamelCase	)
							pipe.to(torch_device=lowerCamelCase							,      torch_dtype=torch.floataa	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							__lowercase		       =			self.get_inputs(get_fixed_latents=lowerCamelCase							,      device=lowerCamelCase	)
							__lowercase		       =			1
							__lowercase		       =			None
							# Ensure usage of flash attention in torch 2.0
							with sdp_kernel(enable_flash=lowerCamelCase							,      enable_math=lowerCamelCase							,      enable_mem_efficient=lowerCamelCase	):
								__lowercase		       =			pipe(**lowerCamelCase	).images
							assert image.shape == (1, 64, 64, 3)

							__lowercase		       =			image[0, -3:, -3:, -1]

							__lowercase		       =			np.array([0.1663, 0.1948, 0.2275, 0.1680, 0.1204, 0.1245, 0.1858, 0.1338, 0.2095]	)

							assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-3








def    snake_case_				(    _SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE   ):
	if len(_SCREAMING_SNAKE_CASE   ) != len(_SCREAMING_SNAKE_CASE   ):
		raise ValueError("The length of profit and weight must be same."   )
	if max_weight <= 0:
		raise ValueError("max_weight must greater than zero."   )
	if any(p < 0 for p in profit   ):
		raise ValueError("Profit can not be negative."   )
	if any(w < 0 for w in weight   ):
		raise ValueError("Weight can not be negative."   )

	# List created to store profit gained for the 1kg in case of each weight
	# respectively.  Calculate and append profit/weight for each element.
	__lowercase		       =			[p / w for p, w in zip(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE   )]

	# Creating a copy of the list and sorting profit/weight in ascending order
	__lowercase		       =			sorted(_SCREAMING_SNAKE_CASE   )

	# declaring useful variables
	__lowercase		       =			len(_SCREAMING_SNAKE_CASE   )
	__lowercase		       =			0
	__lowercase		       =			0
	__lowercase		       =			0

	# loop till the total weight do not reach max limit e.g. 15 kg and till i<length
	while limit <= max_weight and i < length:
		# flag value for encountered greatest element in sorted_profit_by_weight
		__lowercase		       =			sorted_profit_by_weight[length - i - 1]
		__lowercase		       =			profit_by_weight.index(_SCREAMING_SNAKE_CASE   )
		__lowercase		       =			-1

		# check if the weight encountered is less than the total weight
		# encountered before.
		if max_weight - limit >= weight[index]:
			limit += weight[index]
			# Adding profit gained for the given weight 1 ===
			# weight[index]/weight[index]
			gain += 1 * profit[index]
		else:
			# Since the weight encountered is greater than limit, therefore take the
			# required number of remaining kgs and calculate profit for it.
			# weight remaining / weight[index]
			gain += (max_weight - limit) / weight[index] * profit[index]
			break
		i += 1
	return gain


if __name__ == "__main__":
	print(
	    """Input profits, weights, and then max_weight (all positive ints) separated by """
	    """spaces."""
	)

	snake_case__					:     str    		=   [int(x) for x in input("""Input profits separated by spaces: """).split()]
	snake_case__					:     str    		=   [int(x) for x in input("""Input weights separated by spaces: """).split()]
	snake_case__					:     Optional[Any]    		=   int(input("""Max weight allowed: """))

	# Function Call
	calc_profit(profit, weight, max_weight)



