


'''simple docstring'''







import random
import unittest

import torch

from diffusers import IFSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin







@skip_mps
class A__	(						UpperCAmelCase__			,					UpperCAmelCase__			,					unittest.TestCase				):
      __UpperCamelCase	:  Any     	=							IFSuperResolutionPipeline
      __UpperCamelCase	:  List[str]     	=							TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"width", "height"}
      __UpperCamelCase	:  Tuple     	=							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
      __UpperCamelCase	:  str     	=							PipelineTesterMixin.required_optional_params - {"latents"}






      def __UpperCAmelCase	(			self      :str     )	-> List[Any]:




             '''simple docstring'''
             return self._get_superresolution_dummy_components()






      def __UpperCAmelCase	(			self      :List[Any]					,						SCREAMING_SNAKE_CASE      :str					,						SCREAMING_SNAKE_CASE      :List[Any]=0     )	-> Dict:




             '''simple docstring'''
             if str(SCREAMING_SNAKE_CASE     ).startswith("""mps"""     ):
                    _a   :			Union[str, Any]					 =torch.manual_seed(SCREAMING_SNAKE_CASE     )
             else:
                    _a   :			List[str]					 =torch.Generator(device=SCREAMING_SNAKE_CASE     ).manual_seed(SCREAMING_SNAKE_CASE     )

             _a   :			Tuple					 =floats_tensor((1, 3, 3_2, 3_2)					,						rng=random.Random(SCREAMING_SNAKE_CASE     )     ).to(SCREAMING_SNAKE_CASE     )

             _a   :			int					 ={
                 """prompt""": """A painting of a squirrel eating a burger""",
                 """image""": image,
                 """generator""": generator,
                 """num_inference_steps""": 2,
                 """output_type""": """numpy""",
             }

             return inputs






      @unittest.skipIf(
          torch_device != """cuda""" or not is_xformers_available()					,						reason="""XFormers attention is only available with CUDA and `xformers` installed"""					,						)
      def __UpperCAmelCase	(			self      :str     )	-> str:




             '''simple docstring'''
             self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3     )






      def __UpperCAmelCase	(			self      :Union[str, Any]     )	-> Optional[int]:




             '''simple docstring'''
             self._test_save_load_optional_components()






      @unittest.skipIf(torch_device != """cuda"""					,						reason="""float16 requires CUDA"""     )
      def __UpperCAmelCase	(			self      :Union[str, Any]     )	-> Any:




             '''simple docstring'''
             super().test_save_load_floataa(expected_max_diff=1e-1     )






      def __UpperCAmelCase	(			self      :Optional[Any]     )	-> Tuple:




             '''simple docstring'''
             self._test_attention_slicing_forward_pass(expected_max_diff=1e-2     )






      def __UpperCAmelCase	(			self      :Dict     )	-> Optional[Any]:




             '''simple docstring'''
             self._test_save_load_local()






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




             '''simple docstring'''
             self._test_inference_batch_single_identical(
                 expected_max_diff=1e-2					,						)






'''simple docstring'''







from typing import Dict, Optional, Tuple

import torch


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor  )  ->      torch.Tensor:
       _a   :			Tuple					 =boundaries[1] - boundaries[0]
       _a   :			Dict					 =boundaries + step / 2
       _a   :			List[Any]					 =torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1  )]   ,dim=0  )
       return bin_centers


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     torch.Tensor   ,)  ->      Tuple[torch.Tensor, torch.Tensor]:
       _a   :			Any					 =_calculate_bin_centers(_UpperCAmelCase  )
       return (
           torch.sum(aligned_distance_error_probs * bin_centers   ,dim=-1  ),
           bin_centers[-1],
       )


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     int = 31   ,_UpperCAmelCase     :     int = 64   ,**_UpperCAmelCase     :     Dict   ,)  ->      Dict[str, torch.Tensor]:
       _a   :			Dict					 =torch.linspace(0   ,_UpperCAmelCase   ,steps=(no_bins - 1)   ,device=logits.device  )

       _a   :			int					 =torch.nn.functional.softmax(_UpperCAmelCase   ,dim=-1  )
       _a ,   _a   :			List[Any]					 =_calculate_expected_aligned_error(
           alignment_confidence_breaks=_UpperCAmelCase   ,aligned_distance_error_probs=_UpperCAmelCase   ,)

       return {
           "aligned_confidence_probs": aligned_confidence_probs,
           "predicted_aligned_error": predicted_aligned_error,
           "max_predicted_aligned_error": max_predicted_aligned_error,
       }


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     Optional[torch.Tensor] = None   ,_UpperCAmelCase     :     int = 31   ,_UpperCAmelCase     :     int = 64   ,_UpperCAmelCase     :     float = 1e-8   ,**_UpperCAmelCase     :     Optional[Any]   ,)  ->      torch.Tensor:
       if residue_weights is None:
              _a   :			Dict					 =logits.new_ones(logits.shape[-2]  )

       _a   :			str					 =torch.linspace(0   ,_UpperCAmelCase   ,steps=(no_bins - 1)   ,device=logits.device  )

       _a   :			Optional[int]					 =_calculate_bin_centers(_UpperCAmelCase  )
       torch.sum(_UpperCAmelCase  )
       _a   :			List[str]					 =logits.shape[-2]
       _a   :			List[Any]					 =max(_UpperCAmelCase   ,19  )

       _a   :			Union[str, Any]					 =1.2_4 * (clipped_n - 15) ** (1.0 / 3) - 1.8

       _a   :			Tuple					 =torch.nn.functional.softmax(_UpperCAmelCase   ,dim=-1  )

       _a   :			Dict					 =1.0 / (1 + (bin_centers**2) / (da**2))
       _a   :			int					 =torch.sum(probs * tm_per_bin   ,dim=-1  )

       _a   :			List[Any]					 =residue_weights / (eps + residue_weights.sum())
       _a   :			List[str]					 =torch.sum(predicted_tm_term * normed_residue_mask   ,dim=-1  )

       _a   :			int					 =per_alignment * residue_weights

       _a   :			List[Any]					 =(weighted == torch.max(_UpperCAmelCase  )).nonzero()[0]
       return per_alignment[tuple(_UpperCAmelCase  )]


