


# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/

import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    ControlNetModel,
    DDIMScheduler,
    StableDiffusionControlNetImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
)


enable_full_determinism()
class 				SCREAMING_SNAKE_CASE__						(       lowercase__		,					lowercase__		,					lowercase__		,					unittest.TestCase    ):
      snake_case__       :  int       =		StableDiffusionControlNetImgaImgPipeline
      snake_case__       :  str       =		TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
      snake_case__       :  List[Any]       =		TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
      snake_case__       :  List[Any]       =		IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''}    )
      snake_case__       :  Any       =		IMAGE_TO_IMAGE_IMAGE_PARAMS
      def  SCREAMING_SNAKE_CASE							( self       : Optional[int]  )	->    Dict:
             torch.manual_seed(0  )
             a_      :	Optional[Any]							=						UNetaDConditionModel(
                 block_out_channels=(3_2, 6_4)  ,							layers_per_block=2  ,							sample_size=3_2  ,							in_channels=4  ,							out_channels=4  ,							down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,							up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')  ,							cross_attention_dim=3_2  ,							)
             torch.manual_seed(0  )
             a_      :	Dict							=						ControlNetModel(
                 block_out_channels=(3_2, 6_4)  ,							layers_per_block=2  ,							in_channels=4  ,							down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,							cross_attention_dim=3_2  ,							conditioning_embedding_out_channels=(1_6, 3_2)  ,							)
             torch.manual_seed(0  )
             a_      :	List[Any]							=						DDIMScheduler(
                 beta_start=0.00085  ,							beta_end=0.012  ,							beta_schedule='scaled_linear'  ,							clip_sample=SCREAMING_SNAKE_CASE__  ,							set_alpha_to_one=SCREAMING_SNAKE_CASE__  ,							)
             torch.manual_seed(0  )
             a_      :	Dict							=						AutoencoderKL(
                 block_out_channels=[3_2, 6_4]  ,							in_channels=3  ,							out_channels=3  ,							down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']  ,							up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']  ,							latent_channels=4  ,							)
             torch.manual_seed(0  )
             a_      :	Dict							=						CLIPTextConfig(
                 bos_token_id=0  ,							eos_token_id=2  ,							hidden_size=3_2  ,							intermediate_size=3_7  ,							layer_norm_eps=1E-05  ,							num_attention_heads=4  ,							num_hidden_layers=5  ,							pad_token_id=1  ,							vocab_size=1_0_0_0  ,							)
             a_      :	int							=						CLIPTextModel(SCREAMING_SNAKE_CASE__  )
             a_      :	int							=						CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

             a_      :	Optional[Any]							=						{
                 'unet': unet,
                 'controlnet': controlnet,
                 'scheduler': scheduler,
                 'vae': vae,
                 'text_encoder': text_encoder,
                 'tokenizer': tokenizer,
                 'safety_checker': None,
                 'feature_extractor': None,
             }
             return components
      def  SCREAMING_SNAKE_CASE							( self       : str  ,							SCREAMING_SNAKE_CASE__       : List[str]  ,							SCREAMING_SNAKE_CASE__       : Any=0  )	->    Any:
             if str(SCREAMING_SNAKE_CASE__  ).startswith('mps'  ):
                    a_      :	List[Any]							=						torch.manual_seed(SCREAMING_SNAKE_CASE__  )
             else:
                    a_      :	int							=						torch.Generator(device=SCREAMING_SNAKE_CASE__  ).manual_seed(SCREAMING_SNAKE_CASE__  )

             a_      :	Optional[int]							=						2
             a_      :	List[Any]							=						randn_tensor(
                 (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor)  ,							generator=SCREAMING_SNAKE_CASE__  ,							device=torch.device(SCREAMING_SNAKE_CASE__  )  ,							)
             a_      :	Union[str, Any]							=						floats_tensor(control_image.shape  ,							rng=random.Random(SCREAMING_SNAKE_CASE__  )  ).to(SCREAMING_SNAKE_CASE__  )
             a_      :	int							=						image.cpu().permute(0  ,							2  ,							3  ,							1  )[0]
             a_      :	Union[str, Any]							=						Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__  )  ).convert('RGB'  ).resize((6_4, 6_4)  )
             a_      :	Any							=						{
                 'prompt': 'A painting of a squirrel eating a burger',
                 'generator': generator,
                 'num_inference_steps': 2,
                 'guidance_scale': 6.0,
                 'output_type': 'numpy',
                 'image': image,
                 'control_image': control_image,
             }

             return inputs
      def  SCREAMING_SNAKE_CASE							( self       : List[str]  )	->    str:
             return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3  )
      @unittest.skipIf(
          torch_device != 'cuda' or not is_xformers_available()  ,							reason='XFormers attention is only available with CUDA and `xformers` installed'  ,							)
      def  SCREAMING_SNAKE_CASE							( self       : Optional[int]  )	->    Tuple:
             self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3  )

      def  SCREAMING_SNAKE_CASE							( self       : Any  )	->    Optional[Any]:
             self._test_inference_batch_single_identical(expected_max_diff=2E-3  )
class 				SCREAMING_SNAKE_CASE__						(       lowercase__		,					lowercase__		,					unittest.TestCase    ):
      snake_case__       :  int       =		StableDiffusionControlNetImgaImgPipeline
      snake_case__       :  Tuple       =		TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
      snake_case__       :  Optional[int]       =		TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
      snake_case__       :  str       =		frozenset([]    )  # TO_DO: add image_params once refactored VaeImageProcessor.preprocess
      def  SCREAMING_SNAKE_CASE							( self       : int  )	->    List[str]:
             torch.manual_seed(0  )
             a_      :	Tuple							=						UNetaDConditionModel(
                 block_out_channels=(3_2, 6_4)  ,							layers_per_block=2  ,							sample_size=3_2  ,							in_channels=4  ,							out_channels=4  ,							down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,							up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')  ,							cross_attention_dim=3_2  ,							)
             torch.manual_seed(0  )

             def init_weights(SCREAMING_SNAKE_CASE__       : Optional[Any]  ):
                    if isinstance(SCREAMING_SNAKE_CASE__  ,							torch.nn.Convad  ):
                           torch.nn.init.normal(m.weight  )
                           m.bias.data.fill_(1.0  )

             a_      :	int							=						ControlNetModel(
                 block_out_channels=(3_2, 6_4)  ,							layers_per_block=2  ,							in_channels=4  ,							down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,							cross_attention_dim=3_2  ,							conditioning_embedding_out_channels=(1_6, 3_2)  ,							)
             controlneta.controlnet_down_blocks.apply(SCREAMING_SNAKE_CASE__  )

             torch.manual_seed(0  )
             a_      :	Dict							=						ControlNetModel(
                 block_out_channels=(3_2, 6_4)  ,							layers_per_block=2  ,							in_channels=4  ,							down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,							cross_attention_dim=3_2  ,							conditioning_embedding_out_channels=(1_6, 3_2)  ,							)
             controlneta.controlnet_down_blocks.apply(SCREAMING_SNAKE_CASE__  )

             torch.manual_seed(0  )
             a_      :	Optional[int]							=						DDIMScheduler(
                 beta_start=0.00085  ,							beta_end=0.012  ,							beta_schedule='scaled_linear'  ,							clip_sample=SCREAMING_SNAKE_CASE__  ,							set_alpha_to_one=SCREAMING_SNAKE_CASE__  ,							)
             torch.manual_seed(0  )
             a_      :	List[Any]							=						AutoencoderKL(
                 block_out_channels=[3_2, 6_4]  ,							in_channels=3  ,							out_channels=3  ,							down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']  ,							up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']  ,							latent_channels=4  ,							)
             torch.manual_seed(0  )
             a_      :	Dict							=						CLIPTextConfig(
                 bos_token_id=0  ,							eos_token_id=2  ,							hidden_size=3_2  ,							intermediate_size=3_7  ,							layer_norm_eps=1E-05  ,							num_attention_heads=4  ,							num_hidden_layers=5  ,							pad_token_id=1  ,							vocab_size=1_0_0_0  ,							)
             a_      :	List[Any]							=						CLIPTextModel(SCREAMING_SNAKE_CASE__  )
             a_      :	int							=						CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

             a_      :	Union[str, Any]							=						MultiControlNetModel([controlneta, controlneta]  )

             a_      :	Any							=						{
                 'unet': unet,
                 'controlnet': controlnet,
                 'scheduler': scheduler,
                 'vae': vae,
                 'text_encoder': text_encoder,
                 'tokenizer': tokenizer,
                 'safety_checker': None,
                 'feature_extractor': None,
             }
             return components
      def  SCREAMING_SNAKE_CASE							( self       : List[Any]  ,							SCREAMING_SNAKE_CASE__       : List[Any]  ,							SCREAMING_SNAKE_CASE__       : Optional[int]=0  )	->    Optional[Any]:
             if str(SCREAMING_SNAKE_CASE__  ).startswith('mps'  ):
                    a_      :	List[str]							=						torch.manual_seed(SCREAMING_SNAKE_CASE__  )
             else:
                    a_      :	Optional[Any]							=						torch.Generator(device=SCREAMING_SNAKE_CASE__  ).manual_seed(SCREAMING_SNAKE_CASE__  )

             a_      :	Any							=						2

             a_      :	Any							=						[
                 randn_tensor(
                     (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor)  ,							generator=SCREAMING_SNAKE_CASE__  ,							device=torch.device(SCREAMING_SNAKE_CASE__  )  ,							),
                 randn_tensor(
                     (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor)  ,							generator=SCREAMING_SNAKE_CASE__  ,							device=torch.device(SCREAMING_SNAKE_CASE__  )  ,							),
             ]

             a_      :	Dict							=						floats_tensor(control_image[0].shape  ,							rng=random.Random(SCREAMING_SNAKE_CASE__  )  ).to(SCREAMING_SNAKE_CASE__  )
             a_      :	str							=						image.cpu().permute(0  ,							2  ,							3  ,							1  )[0]
             a_      :	int							=						Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__  )  ).convert('RGB'  ).resize((6_4, 6_4)  )
             a_      :	Optional[int]							=						{
                 'prompt': 'A painting of a squirrel eating a burger',
                 'generator': generator,
                 'num_inference_steps': 2,
                 'guidance_scale': 6.0,
                 'output_type': 'numpy',
                 'image': image,
                 'control_image': control_image,
             }

             return inputs
      def  SCREAMING_SNAKE_CASE							( self       : Optional[int]  )	->    int:
             a_      :	Tuple							=						self.get_dummy_components()
             a_      :	List[Any]							=						self.pipeline_class(**SCREAMING_SNAKE_CASE__  )
             pipe.to(SCREAMING_SNAKE_CASE__  )

             a_      :	Optional[Any]							=						10.0
             a_      :	str							=						4

             a_      :	Any							=						self.get_dummy_inputs(SCREAMING_SNAKE_CASE__  )
             a_      :	Optional[Any]							=						steps
             a_      :	Union[str, Any]							=						scale
             a_      :	List[Any]							=						pipe(**SCREAMING_SNAKE_CASE__  )[0]

             a_      :	Dict							=						self.get_dummy_inputs(SCREAMING_SNAKE_CASE__  )
             a_      :	Any							=						steps
             a_      :	List[Any]							=						scale
             a_      :	Tuple							=						pipe(**SCREAMING_SNAKE_CASE__  ,							control_guidance_start=0.1  ,							control_guidance_end=0.2  )[0]

             a_      :	Optional[Any]							=						self.get_dummy_inputs(SCREAMING_SNAKE_CASE__  )
             a_      :	List[Any]							=						steps
             a_      :	str							=						scale
             a_      :	str							=						pipe(**SCREAMING_SNAKE_CASE__  ,							control_guidance_start=[0.1, 0.3]  ,							control_guidance_end=[0.2, 0.7]  )[0]

             a_      :	List[Any]							=						self.get_dummy_inputs(SCREAMING_SNAKE_CASE__  )
             a_      :	List[Any]							=						steps
             a_      :	int							=						scale
             a_      :	int							=						pipe(**SCREAMING_SNAKE_CASE__  ,							control_guidance_start=0.4  ,							control_guidance_end=[0.5, 0.8]  )[0]

             # make sure that all outputs are different
             assert np.sum(np.abs(output_a - output_a  )  ) > 1E-3
             assert np.sum(np.abs(output_a - output_a  )  ) > 1E-3
             assert np.sum(np.abs(output_a - output_a  )  ) > 1E-3
      def  SCREAMING_SNAKE_CASE							( self       : Optional[Any]  )	->    str:
             return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3  )
      @unittest.skipIf(
          torch_device != 'cuda' or not is_xformers_available()  ,							reason='XFormers attention is only available with CUDA and `xformers` installed'  ,							)
      def  SCREAMING_SNAKE_CASE							( self       : Union[str, Any]  )	->    List[Any]:
             self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3  )
      def  SCREAMING_SNAKE_CASE							( self       : Optional[Any]  )	->    Optional[Any]:
             self._test_inference_batch_single_identical(expected_max_diff=2E-3  )

      def  SCREAMING_SNAKE_CASE							( self       : List[Any]  )	->    str:
             a_      :	Optional[int]							=						self.get_dummy_components()
             a_      :	Tuple							=						self.pipeline_class(**SCREAMING_SNAKE_CASE__  )
             pipe.to(SCREAMING_SNAKE_CASE__  )
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__  )
             with tempfile.TemporaryDirectory() as tmpdir:
                    try:
                           # save_pretrained is not implemented for Multi-ControlNet
                           pipe.save_pretrained(SCREAMING_SNAKE_CASE__  )
                    except NotImplementedError:
                           pass
@slow
@require_torch_gpu
class 				SCREAMING_SNAKE_CASE__						(       unittest.TestCase    ):
      def  SCREAMING_SNAKE_CASE							( self       : Union[str, Any]  )	->    List[Any]:
             super().tearDown()
             gc.collect()
             torch.cuda.empty_cache()

      def  SCREAMING_SNAKE_CASE							( self       : Dict  )	->    Any:
             a_      :	int							=						ControlNetModel.from_pretrained('lllyasviel/sd-controlnet-canny'  )

             a_      :	Optional[Any]							=						StableDiffusionControlNetImgaImgPipeline.from_pretrained(
                 'runwayml/stable-diffusion-v1-5'  ,							safety_checker=SCREAMING_SNAKE_CASE__  ,							controlnet=SCREAMING_SNAKE_CASE__  )
             pipe.enable_model_cpu_offload()
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__  )

             a_      :	List[Any]							=						torch.Generator(device='cpu'  ).manual_seed(0  )
             a_      :	int							=						'evil space-punk bird'
             a_      :	Union[str, Any]							=						load_image(
                 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png'  ).resize((5_1_2, 5_1_2)  )
             a_      :	int							=						load_image(
                 'https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png'  ).resize((5_1_2, 5_1_2)  )

             a_      :	int							=						pipe(
                 SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  ,							control_image=SCREAMING_SNAKE_CASE__  ,							generator=SCREAMING_SNAKE_CASE__  ,							output_type='np'  ,							num_inference_steps=5_0  ,							strength=0.6  ,							)

             a_      :	int							=						output.images[0]

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

             a_      :	Optional[Any]							=						load_numpy(
                 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy'  )

             assert np.abs(expected_image - image  ).max() < 9E-2






import unittest

import numpy as np







def  SCREAMING_SNAKE_CASE_		(    __A				:    np.ndarray						,					__A				:    np.ndarray						,					__A				:    np.ndarray						,					__A				:    np.ndarray | None = None						,					)			->	np.ndarray:

       """simple docstring"""

       a_      :	List[str]							=						np.shape(__A       )
       a_      :	Any							=						np.shape(__A       )
       a_      :	List[Any]							=						np.shape(__A       )

       if shape_a[0] != shape_b[0]:
              a_      :	List[Any]							=						(
                  'Expected the same number of rows for A and B. '
                  F"""Instead found A of size {shape_a} and B of size {shape_b}"""
              )
              raise ValueError(__A       )

       if shape_b[1] != shape_c[1]:
              a_      :	int							=						(
                  'Expected the same number of columns for B and C. '
                  F"""Instead found B of size {shape_b} and C of size {shape_c}"""
              )
              raise ValueError(__A       )

       a_      :	Any							=						pseudo_inv
       if a_inv is None:
              try:
                     a_      :	List[str]							=						np.linalg.inv(__A       )
              except np.linalg.LinAlgError:
                     raise ValueError(
                         'Input matrix A is not invertible. Cannot compute Schur complement.'       )

       return mat_c - mat_b.T @ a_inv @ mat_b
class 				SCREAMING_SNAKE_CASE__						(       unittest.TestCase    ):
      def  SCREAMING_SNAKE_CASE							( self       : Tuple  )	->    None:
             a_      :	str							=						np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]  )
             a_      :	Any							=						np.array([[0, 3], [3, 0], [2, 3]]  )
             a_      :	List[str]							=						np.array([[2, 1], [6, 3]]  )

             a_      :	int							=						schur_complement(SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  )

             a_      :	Optional[Any]							=						np.block([[a, b], [b.T, c]]  )

             a_      :	str							=						np.linalg.det(SCREAMING_SNAKE_CASE__  )
             a_      :	List[Any]							=						np.linalg.det(SCREAMING_SNAKE_CASE__  )
             a_      :	str							=						np.linalg.det(SCREAMING_SNAKE_CASE__  )

             self.assertAlmostEqual(SCREAMING_SNAKE_CASE__  ,							det_a * det_s  )
      def  SCREAMING_SNAKE_CASE							( self       : Optional[Any]  )	->    None:
             a_      :	Optional[int]							=						np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]  )
             a_      :	Dict							=						np.array([[0, 3], [3, 0], [2, 3]]  )
             a_      :	str							=						np.array([[2, 1], [6, 3]]  )

             with self.assertRaises(SCREAMING_SNAKE_CASE__  ):
                    schur_complement(SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  )

      def  SCREAMING_SNAKE_CASE							( self       : List[Any]  )	->    None:
             a_      :	Tuple							=						np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]  )
             a_      :	Dict							=						np.array([[0, 3], [3, 0], [2, 3]]  )
             a_      :	List[str]							=						np.array([[2, 1, 3], [6, 3, 5]]  )

             with self.assertRaises(SCREAMING_SNAKE_CASE__  ):
                    schur_complement(SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  )


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   unittest.main()


