


'''simple docstring'''






import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaControlnetImgaImgPipeline,
    KandinskyVaaPriorEmbaEmbPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()
class 						__UpperCamelCase	(						lowercase__						,  unittest.TestCase							):
							lowercase			:		Optional[int]   		=  KandinskyVaaControlnetImgaImgPipeline
							lowercase			:		str   		=  ['image_embeds', 'negative_image_embeds', 'image', 'hint']
							lowercase			:		Any   		=  ['image_embeds', 'negative_image_embeds', 'image', 'hint']
							lowercase			:		Optional[Any]   		=  [
							    'generator',
							    'height',
							    'width',
							    'strength',
							    'guidance_scale',
							    'num_inference_steps',
							    'return_dict',
							    'guidance_scale',
							    'num_images_per_prompt',
							    'output_type',
							    'return_dict',
							]
							lowercase			:		Optional[int]   		=  False





							@property
							def 		a__   (  self		:Optional[Any]			):
									return 3_2





							@property
							def 		a__   (  self		:Optional[int]			):
									return 3_2





							@property
							def 		a__   (  self		:int			):
									return self.time_input_dim





							@property
							def 		a__   (  self		:Dict			):
									return self.time_input_dim * 4





							@property
							def 		a__   (  self		:Dict			):
									return 1_0_0





							@property
							def 		a__   (  self		:str			):
									torch.manual_seed(0			)

									snake_case_		:							Any			       =						{
									    """in_channels""": 8,
									    # Out channels is double in channels because predicts mean and variance
									    """out_channels""": 8,
									    """addition_embed_type""": """image_hint""",
									    """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
									    """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
									    """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
									    """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
									    """layers_per_block""": 1,
									    """encoder_hid_dim""": self.text_embedder_hidden_size,
									    """encoder_hid_dim_type""": """image_proj""",
									    """cross_attention_dim""": self.cross_attention_dim,
									    """attention_head_dim""": 4,
									    """resnet_time_scale_shift""": """scale_shift""",
									    """class_embed_type""": None,
									}

									snake_case_		:							Any			       =						UNetaDConditionModel(**_UpperCamelCase			)
									return model





							@property
							def 		a__   (  self		:Dict			):
									return {
									    "block_out_channels": [3_2, 3_2, 6_4, 6_4],
									    "down_block_types": [
									        "DownEncoderBlock2D",
									        "DownEncoderBlock2D",
									        "DownEncoderBlock2D",
									        "AttnDownEncoderBlock2D",
									    ],
									    "in_channels": 3,
									    "latent_channels": 4,
									    "layers_per_block": 1,
									    "norm_num_groups": 8,
									    "norm_type": "spatial",
									    "num_vq_embeddings": 1_2,
									    "out_channels": 3,
									    "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
									    "vq_embed_dim": 4,
									}





							@property
							def 		a__   (  self		:int			):
									torch.manual_seed(0			)
									snake_case_		:							List[str]			       =						VQModel(**self.dummy_movq_kwargs			)
									return model





							def 		a__   (  self		:List[Any]			):
									snake_case_		:							List[str]			       =						self.dummy_unet
									snake_case_		:							int			       =						self.dummy_movq

									snake_case_		:							List[str]			       =						{
									    """num_train_timesteps""": 1_0_0_0,
									    """beta_schedule""": """linear""",
									    """beta_start""": 0.0_00_85,
									    """beta_end""": 0.0_12,
									    """clip_sample""": False,
									    """set_alpha_to_one""": False,
									    """steps_offset""": 0,
									    """prediction_type""": """epsilon""",
									    """thresholding""": False,
									}

									snake_case_		:							int			       =						DDIMScheduler(**_UpperCamelCase			)

									snake_case_		:							Optional[int]			       =						{
									    """unet""": unet,
									    """scheduler""": scheduler,
									    """movq""": movq,
									}

									return components





							def 		a__   (  self		:Any  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:Any=0			):
									snake_case_		:							Union[str, Any]			       =						floats_tensor((1, self.text_embedder_hidden_size)  ,rng=random.Random(_UpperCamelCase			)			).to(_UpperCamelCase			)
									snake_case_		:							Tuple			       =						floats_tensor((1, self.text_embedder_hidden_size)  ,rng=random.Random(seed + 1			)			).to(
									    _UpperCamelCase			)
									# create init_image
									snake_case_		:							Any			       =						floats_tensor((1, 3, 6_4, 6_4)  ,rng=random.Random(_UpperCamelCase			)			).to(_UpperCamelCase			)
									snake_case_		:							Dict			       =						image.cpu().permute(0  ,2  ,3  ,1			)[0]
									snake_case_		:							int			       =						Image.fromarray(np.uinta(_UpperCamelCase			)			).convert("""RGB"""			).resize((2_5_6, 2_5_6)			)
									# create hint
									snake_case_		:							str			       =						floats_tensor((1, 3, 6_4, 6_4)  ,rng=random.Random(_UpperCamelCase			)			).to(_UpperCamelCase			)

									if str(_UpperCamelCase			).startswith("""mps"""			):
											snake_case_		:							int			       =						torch.manual_seed(_UpperCamelCase			)
									else:
											snake_case_		:							int			       =						torch.Generator(device=_UpperCamelCase			).manual_seed(_UpperCamelCase			)
									snake_case_		:							List[Any]			       =						{
									    """image""": init_image,
									    """image_embeds""": image_embeds,
									    """negative_image_embeds""": negative_image_embeds,
									    """hint""": hint,
									    """generator""": generator,
									    """height""": 6_4,
									    """width""": 6_4,
									    """num_inference_steps""": 1_0,
									    """guidance_scale""": 7.0,
									    """strength""": 0.2,
									    """output_type""": """np""",
									}
									return inputs





							def 		a__   (  self		:Optional[int]			):
									snake_case_		:							Optional[int]			       =						"""cpu"""

									snake_case_		:							List[str]			       =						self.get_dummy_components()

									snake_case_		:							Optional[int]			       =						self.pipeline_class(**_UpperCamelCase			)
									snake_case_		:							Optional[Any]			       =						pipe.to(_UpperCamelCase			)

									pipe.set_progress_bar_config(disable=_UpperCamelCase			)

									snake_case_		:							Any			       =						pipe(**self.get_dummy_inputs(_UpperCamelCase			)			)
									snake_case_		:							int			       =						output.images

									snake_case_		:							List[Any]			       =						pipe(
									    **self.get_dummy_inputs(_UpperCamelCase			)  ,return_dict=_UpperCamelCase  ,)[0]

									snake_case_		:							str			       =						image[0, -3:, -3:, -1]
									snake_case_		:							List[Any]			       =						image_from_tuple[0, -3:, -3:, -1]

									assert image.shape == (1, 6_4, 6_4, 3)

									snake_case_		:							str			       =						np.array(
									    [0.54_98_50_34, 0.55_50_93_65, 0.52_56_15_04, 0.5_57_04_94, 0.5_59_38_18, 0.5_26_39_79, 0.50_28_56_43, 0.5_06_98_46, 0.51_19_67_36]			)
									assert (
									    np.abs(image_slice.flatten() - expected_slice			).max() < 1E-2
									), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
									assert (
									    np.abs(image_from_tuple_slice.flatten() - expected_slice			).max() < 1E-2
									), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''





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





							def 		a__   (  self		:int			):
									# clean up the VRAM after each test
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()





							def 		a__   (  self		:Optional[int]			):
									snake_case_		:							Any			       =						load_numpy(
									    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
									    """/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy"""			)

									snake_case_		:							List[Any]			       =						load_image(
									    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png"""			)
									snake_case_		:							List[str]			       =						init_image.resize((5_1_2, 5_1_2)			)

									snake_case_		:							Optional[int]			       =						load_image(
									    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
									    """/kandinskyv22/hint_image_cat.png"""			)
									snake_case_		:							List[str]			       =						torch.from_numpy(np.array(_UpperCamelCase			)			).float() / 2_55.0
									snake_case_		:							Union[str, Any]			       =						hint.permute(2  ,0  ,1			).unsqueeze(0			)

									snake_case_		:							Optional[int]			       =						"""A robot, 4k photo"""

									snake_case_		:							List[Any]			       =						KandinskyVaaPriorEmbaEmbPipeline.from_pretrained(
									    """kandinsky-community/kandinsky-2-2-prior"""  ,torch_dtype=torch.floataa			)
									pipe_prior.to(_UpperCamelCase			)

									snake_case_		:							str			       =						KandinskyVaaControlnetImgaImgPipeline.from_pretrained(
									    """kandinsky-community/kandinsky-2-2-controlnet-depth"""  ,torch_dtype=torch.floataa			)
									snake_case_		:							List[Any]			       =						pipeline.to(_UpperCamelCase			)

									pipeline.set_progress_bar_config(disable=_UpperCamelCase			)

									snake_case_		:							Optional[int]			       =						torch.Generator(device="""cpu"""			).manual_seed(0			)

									snake_case_       ,      snake_case_		:							Any			       =						pipe_prior(
									    _UpperCamelCase  ,image=_UpperCamelCase  ,strength=0.85  ,generator=_UpperCamelCase  ,negative_prompt=""""""  ,).to_tuple()

									snake_case_		:							int			       =						pipeline(
									    image=_UpperCamelCase  ,image_embeds=_UpperCamelCase  ,negative_image_embeds=_UpperCamelCase  ,hint=_UpperCamelCase  ,generator=_UpperCamelCase  ,num_inference_steps=1_0_0  ,height=5_1_2  ,width=5_1_2  ,strength=0.5  ,output_type="""np"""  ,)

									snake_case_		:							List[str]			       =						output.images[0]

									assert image.shape == (5_1_2, 5_1_2, 3)

									assert_mean_pixel_difference(_UpperCamelCase  ,_UpperCamelCase			)



'''simple docstring'''






from __future__ import annotations

import math





def      UpperCAmelCase      (		lowerCamelCase_  :list				,      lowerCamelCase_  :list ):







		'''simple docstring'''
		if len(lowerCamelCase_ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase_ ) != 2 or len(b[0] ) != 2:
				raise Exception("""Matrices are not 2x2""" )
		snake_case_		:							Tuple			       =						[
		    [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]],
		    [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]],
		]
		return new_matrix





def      UpperCAmelCase      (		lowerCamelCase_  :list				,      lowerCamelCase_  :list ):







		'''simple docstring'''
		return [
		    [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )]
		    for row in range(len(lowerCamelCase_ ) )
		]





def      UpperCAmelCase      (		lowerCamelCase_  :list				,      lowerCamelCase_  :list ):







		'''simple docstring'''
		return [
		    [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )]
		    for row in range(len(lowerCamelCase_ ) )
		]





def      UpperCAmelCase      (		lowerCamelCase_  :list ):







		'''simple docstring'''
		if len(lowerCamelCase_ ) % 2 != 0 or len(a[0] ) % 2 != 0:
				raise Exception("""Odd matrices are not supported!""" )

		snake_case_		:							Optional[int]			       =						len(lowerCamelCase_ )
		snake_case_		:							List[str]			       =						matrix_length // 2

		snake_case_		:							Union[str, Any]			       =						[[a[i][j] for j in range(lowerCamelCase_				,      lowerCamelCase_ )] for i in range(lowerCamelCase_ )]
		snake_case_		:							Dict			       =						[
		    [a[i][j] for j in range(lowerCamelCase_				,      lowerCamelCase_ )] for i in range(lowerCamelCase_				,      lowerCamelCase_ )
		]

		snake_case_		:							str			       =						[[a[i][j] for j in range(lowerCamelCase_ )] for i in range(lowerCamelCase_ )]
		snake_case_		:							Dict			       =						[[a[i][j] for j in range(lowerCamelCase_ )] for i in range(lowerCamelCase_				,      lowerCamelCase_ )]

		return top_left, top_right, bot_left, bot_right





def      UpperCAmelCase      (		lowerCamelCase_  :list ):







		'''simple docstring'''
		return len(lowerCamelCase_ ), len(matrix[0] )





def      UpperCAmelCase      (		lowerCamelCase_  :list ):







		'''simple docstring'''
		print("""\n""".join(str(lowerCamelCase_ ) for line in matrix ) )





def      UpperCAmelCase      (		lowerCamelCase_  :list				,      lowerCamelCase_  :list ):







		'''simple docstring'''
		if matrix_dimensions(lowerCamelCase_ ) == (2, 2):
				return default_matrix_multiplication(lowerCamelCase_				,      lowerCamelCase_ )

		snake_case_       ,      snake_case_       ,      snake_case_       ,      snake_case_		:							Any			       =						split_matrix(lowerCamelCase_ )
		snake_case_       ,      snake_case_       ,      snake_case_       ,      snake_case_		:							List[Any]			       =						split_matrix(lowerCamelCase_ )

		snake_case_		:							Any			       =						actual_strassen(lowerCamelCase_				,      matrix_subtraction(lowerCamelCase_				,      lowerCamelCase_ ) )
		snake_case_		:							str			       =						actual_strassen(matrix_addition(lowerCamelCase_				,      lowerCamelCase_ )				,      lowerCamelCase_ )
		snake_case_		:							str			       =						actual_strassen(matrix_addition(lowerCamelCase_				,      lowerCamelCase_ )				,      lowerCamelCase_ )
		snake_case_		:							List[str]			       =						actual_strassen(lowerCamelCase_				,      matrix_subtraction(lowerCamelCase_				,      lowerCamelCase_ ) )
		snake_case_		:							Optional[int]			       =						actual_strassen(matrix_addition(lowerCamelCase_				,      lowerCamelCase_ )				,      matrix_addition(lowerCamelCase_				,      lowerCamelCase_ ) )
		snake_case_		:							Dict			       =						actual_strassen(matrix_subtraction(lowerCamelCase_				,      lowerCamelCase_ )				,      matrix_addition(lowerCamelCase_				,      lowerCamelCase_ ) )
		snake_case_		:							int			       =						actual_strassen(matrix_subtraction(lowerCamelCase_				,      lowerCamelCase_ )				,      matrix_addition(lowerCamelCase_				,      lowerCamelCase_ ) )

		snake_case_		:							List[Any]			       =						matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase_				,      lowerCamelCase_ )				,      lowerCamelCase_ )				,      lowerCamelCase_ )
		snake_case_		:							List[Any]			       =						matrix_addition(lowerCamelCase_				,      lowerCamelCase_ )
		snake_case_		:							str			       =						matrix_addition(lowerCamelCase_				,      lowerCamelCase_ )
		snake_case_		:							Any			       =						matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase_				,      lowerCamelCase_ )				,      lowerCamelCase_ )				,      lowerCamelCase_ )

		# construct the new matrix from our 4 quadrants
		snake_case_		:							Dict			       =						[]
		for i in range(len(lowerCamelCase_ ) ):
				new_matrix.append(top_left[i] + top_right[i] )
		for i in range(len(lowerCamelCase_ ) ):
				new_matrix.append(bot_left[i] + bot_right[i] )
		return new_matrix





def      UpperCAmelCase      (		lowerCamelCase_  :list				,      lowerCamelCase_  :list ):







		'''simple docstring'''
		if matrix_dimensions(lowerCamelCase_ )[1] != matrix_dimensions(lowerCamelCase_ )[0]:
				snake_case_		:							Optional[int]			       =						(
				    """Unable to multiply these matrices, please check the dimensions.\n"""
				    F'''Matrix A: {matrixa}\n'''
				    F'''Matrix B: {matrixa}'''
				)
				raise Exception(lowerCamelCase_ )
		snake_case_		:							Tuple			       =						matrix_dimensions(lowerCamelCase_ )
		snake_case_		:							Union[str, Any]			       =						matrix_dimensions(lowerCamelCase_ )

		if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]:
				return [matrixa, matrixa]

		snake_case_		:							int			       =						max(*lowerCamelCase_				,      *lowerCamelCase_ )
		snake_case_		:							Union[str, Any]			       =						int(math.pow(2				,      math.ceil(math.loga(lowerCamelCase_ ) ) ) )
		snake_case_		:							Dict			       =						matrixa
		snake_case_		:							Optional[int]			       =						matrixa

		# Adding zeros to the matrices so that the arrays dimensions are the same and also
		# power of 2
		for i in range(0				,      lowerCamelCase_ ):
				if i < dimensiona[0]:
						for _ in range(dimensiona[1]				,      lowerCamelCase_ ):
								new_matrixa[i].append(0 )
				else:
						new_matrixa.append([0] * maxim )
				if i < dimensiona[0]:
						for _ in range(dimensiona[1]				,      lowerCamelCase_ ):
								new_matrixa[i].append(0 )
				else:
						new_matrixa.append([0] * maxim )

		snake_case_		:							Dict			       =						actual_strassen(lowerCamelCase_				,      lowerCamelCase_ )

		# Removing the additional zeros
		for i in range(0				,      lowerCamelCase_ ):
				if i < dimensiona[0]:
						for _ in range(dimensiona[1]				,      lowerCamelCase_ ):
								final_matrix[i].pop()
				else:
						final_matrix.pop()
		return final_matrix


if __name__ == "__main__":
							__A	:	Optional[int]     =     [
							    [2, 3, 4, 5],
							    [6, 4, 3, 1],
							    [2, 3, 6, 7],
							    [3, 1, 2, 4],
							    [2, 3, 4, 5],
							    [6, 4, 3, 1],
							    [2, 3, 6, 7],
							    [3, 1, 2, 4],
							    [2, 3, 4, 5],
							    [6, 2, 3, 1],
							]
							__A	:	List[str]     =     [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]]
							print(strassen(matrixa, matrixa))