

from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block
@dataclass
class 					A_   (      _a						):


    '''simple docstring'''






    a__     							=       42






class 					A_   (      _a ,     _a						):


    '''simple docstring'''






    @register_to_config
    def __init__(self     ,      lowercase__ = None     ,      lowercase__ = 3     ,      lowercase__ = 3     ,      lowercase__ = False     ,      lowercase__ = "positional"     ,      lowercase__ = 0     ,      lowercase__ = True     ,      lowercase__ = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")     ,      lowercase__ = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")     ,      lowercase__ = (224, 448, 672, 896)     ,      lowercase__ = 2     ,      lowercase__ = 1     ,      lowercase__ = 1     ,      lowercase__ = "conv"     ,      lowercase__ = "conv"     ,      lowercase__ = "silu"     ,      lowercase__ = 8     ,      lowercase__ = 32     ,      lowercase__ = 1E-5     ,      lowercase__ = "default"     ,      lowercase__ = True     ,      lowercase__ = None     ,      lowercase__ = None     ,      )     ->      Tuple:
        super().__init__()

        __UpperCAmelCase									=			sample_size
        __UpperCAmelCase									=			block_out_channels[0] * 4

        # Check inputs
        if len(lowercase__  ) != len(lowercase__  ):
            raise ValueError(
                F'''Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}.'''  )

        if len(lowercase__  ) != len(lowercase__  ):
            raise ValueError(
                F'''Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.'''  )

        # input
        __UpperCAmelCase									=			nn.Convad(lowercase__     ,      block_out_channels[0]     ,      kernel_size=3     ,      padding=(1, 1)  )

        # time
        if time_embedding_type == "fourier":
            __UpperCAmelCase									=			GaussianFourierProjection(embedding_size=block_out_channels[0]     ,      scale=16  )
            __UpperCAmelCase									=			2 * block_out_channels[0]
        elif time_embedding_type == "positional":
            __UpperCAmelCase									=			Timesteps(block_out_channels[0]     ,      lowercase__     ,      lowercase__  )
            __UpperCAmelCase									=			block_out_channels[0]

        __UpperCAmelCase									=			TimestepEmbedding(lowercase__     ,      lowercase__  )

        # class embedding
        if class_embed_type is None and num_class_embeds is not None:
            __UpperCAmelCase									=			nn.Embedding(lowercase__     ,      lowercase__  )
        elif class_embed_type == "timestep":
            __UpperCAmelCase									=			TimestepEmbedding(lowercase__     ,      lowercase__  )
        elif class_embed_type == "identity":
            __UpperCAmelCase									=			nn.Identity(lowercase__     ,      lowercase__  )
        else:
            __UpperCAmelCase									=			None

        __UpperCAmelCase									=			nn.ModuleList([]  )
        __UpperCAmelCase									=			None
        __UpperCAmelCase									=			nn.ModuleList([]  )

        # down
        __UpperCAmelCase									=			block_out_channels[0]
        for i, down_block_type in enumerate(lowercase__  ):
            __UpperCAmelCase									=			output_channel
            __UpperCAmelCase									=			block_out_channels[i]
            __UpperCAmelCase									=			i == len(lowercase__  ) - 1

            __UpperCAmelCase									=			get_down_block(
                lowercase__     ,      num_layers=lowercase__     ,      in_channels=lowercase__     ,      out_channels=lowercase__     ,      temb_channels=lowercase__     ,      add_downsample=not is_final_block     ,      resnet_eps=lowercase__     ,      resnet_act_fn=lowercase__     ,      resnet_groups=lowercase__     ,      attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel     ,      downsample_padding=lowercase__     ,      resnet_time_scale_shift=lowercase__     ,      downsample_type=lowercase__     ,      )
            self.down_blocks.append(lowercase__  )

        # mid
        __UpperCAmelCase									=			UNetMidBlockaD(
            in_channels=block_out_channels[-1]     ,      temb_channels=lowercase__     ,      resnet_eps=lowercase__     ,      resnet_act_fn=lowercase__     ,      output_scale_factor=lowercase__     ,      resnet_time_scale_shift=lowercase__     ,      attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]     ,      resnet_groups=lowercase__     ,      add_attention=lowercase__     ,      )

        # up
        __UpperCAmelCase									=			list(reversed(lowercase__  )  )
        __UpperCAmelCase									=			reversed_block_out_channels[0]
        for i, up_block_type in enumerate(lowercase__  ):
            __UpperCAmelCase									=			output_channel
            __UpperCAmelCase									=			reversed_block_out_channels[i]
            __UpperCAmelCase									=			reversed_block_out_channels[min(i + 1     ,      len(lowercase__  ) - 1  )]

            __UpperCAmelCase									=			i == len(lowercase__  ) - 1

            __UpperCAmelCase									=			get_up_block(
                lowercase__     ,      num_layers=layers_per_block + 1     ,      in_channels=lowercase__     ,      out_channels=lowercase__     ,      prev_output_channel=lowercase__     ,      temb_channels=lowercase__     ,      add_upsample=not is_final_block     ,      resnet_eps=lowercase__     ,      resnet_act_fn=lowercase__     ,      resnet_groups=lowercase__     ,      attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel     ,      resnet_time_scale_shift=lowercase__     ,      upsample_type=lowercase__     ,      )
            self.up_blocks.append(lowercase__  )
            __UpperCAmelCase									=			output_channel

        # out
        __UpperCAmelCase									=			norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4     ,      32  )
        __UpperCAmelCase									=			nn.GroupNorm(num_channels=block_out_channels[0]     ,      num_groups=lowercase__     ,      eps=lowercase__  )
        __UpperCAmelCase									=			nn.SiLU()
        __UpperCAmelCase									=			nn.Convad(block_out_channels[0]     ,      lowercase__     ,      kernel_size=3     ,      padding=1  )






    def      lowerCAmelCase_						(self     ,      lowercase__     ,      lowercase__     ,      lowercase__ = None     ,      lowercase__ = True     ,      )     ->      Union[UNetaDOutput, Tuple]:
        # 0. center input if necessary
        if self.config.center_input_sample:
            __UpperCAmelCase									=			2 * sample - 1.0

        # 1. time
        __UpperCAmelCase									=			timestep
        if not torch.is_tensor(lowercase__  ):
            __UpperCAmelCase									=			torch.tensor([timesteps]     ,      dtype=torch.long     ,      device=sample.device  )
        elif torch.is_tensor(lowercase__  ) and len(timesteps.shape  ) == 0:
            __UpperCAmelCase									=			timesteps[None].to(sample.device  )

        # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
        __UpperCAmelCase									=			timesteps * torch.ones(sample.shape[0]     ,      dtype=timesteps.dtype     ,      device=timesteps.device  )

        __UpperCAmelCase									=			self.time_proj(lowercase__  )

        # timesteps does not contain any weights and will always return f32 tensors
        # but time_embedding might actually be running in fp16. so we need to cast here.
        # there might be better ways to encapsulate this.
        __UpperCAmelCase									=			t_emb.to(dtype=self.dtype  )
        __UpperCAmelCase									=			self.time_embedding(lowercase__  )

        if self.class_embedding is not None:
            if class_labels is None:
                raise ValueError('''class_labels should be provided when doing class conditioning'''  )

            if self.config.class_embed_type == "timestep":
                __UpperCAmelCase									=			self.time_proj(lowercase__  )

            __UpperCAmelCase									=			self.class_embedding(lowercase__  ).to(dtype=self.dtype  )
            __UpperCAmelCase									=			emb + class_emb

        # 2. pre-process
        __UpperCAmelCase									=			sample
        __UpperCAmelCase									=			self.conv_in(lowercase__  )

        # 3. down
        __UpperCAmelCase									=			(sample,)
        for downsample_block in self.down_blocks:
            if hasattr(lowercase__     ,      '''skip_conv'''  ):
                __UpperCAmelCase					,     __UpperCAmelCase					,     __UpperCAmelCase									=			downsample_block(
                    hidden_states=lowercase__     ,      temb=lowercase__     ,      skip_sample=lowercase__  )
            else:
                __UpperCAmelCase					,     __UpperCAmelCase									=			downsample_block(hidden_states=lowercase__     ,      temb=lowercase__  )

            down_block_res_samples += res_samples

        # 4. mid
        __UpperCAmelCase									=			self.mid_block(lowercase__     ,      lowercase__  )

        # 5. up
        __UpperCAmelCase									=			None
        for upsample_block in self.up_blocks:
            __UpperCAmelCase									=			down_block_res_samples[-len(upsample_block.resnets  ) :]
            __UpperCAmelCase									=			down_block_res_samples[: -len(upsample_block.resnets  )]

            if hasattr(lowercase__     ,      '''skip_conv'''  ):
                __UpperCAmelCase					,     __UpperCAmelCase									=			upsample_block(lowercase__     ,      lowercase__     ,      lowercase__     ,      lowercase__  )
            else:
                __UpperCAmelCase									=			upsample_block(lowercase__     ,      lowercase__     ,      lowercase__  )

        # 6. post-process
        __UpperCAmelCase									=			self.conv_norm_out(lowercase__  )
        __UpperCAmelCase									=			self.conv_act(lowercase__  )
        __UpperCAmelCase									=			self.conv_out(lowercase__  )

        if skip_sample is not None:
            sample += skip_sample

        if self.config.time_embedding_type == "fourier":
            __UpperCAmelCase									=			timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]  )))  )
            __UpperCAmelCase									=			sample / timesteps

        if not return_dict:
            return (sample,)

        return UNetaDOutput(sample=lowercase__  )







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import SwinaSRImageProcessor
       from transformers.image_transforms import get_image_size
class 					A_   (      unittest.TestCase						):


    '''simple docstring'''






    def __init__(self     ,      lowercase__     ,      lowercase__=7     ,      lowercase__=3     ,      lowercase__=18     ,      lowercase__=30     ,      lowercase__=400     ,      lowercase__=True     ,      lowercase__=1 / 255     ,      lowercase__=True     ,      lowercase__=8     ,      )     ->      List[str]:
        __UpperCAmelCase									=			parent
        __UpperCAmelCase									=			batch_size
        __UpperCAmelCase									=			num_channels
        __UpperCAmelCase									=			image_size
        __UpperCAmelCase									=			min_resolution
        __UpperCAmelCase									=			max_resolution
        __UpperCAmelCase									=			do_rescale
        __UpperCAmelCase									=			rescale_factor
        __UpperCAmelCase									=			do_pad
        __UpperCAmelCase									=			pad_size


    def      lowerCAmelCase_						(self  )     ->      int:
        return {
            "do_rescale": self.do_rescale,
            "rescale_factor": self.rescale_factor,
            "do_pad": self.do_pad,
            "pad_size": self.pad_size,
        }






    def      lowerCAmelCase_						(self     ,      lowercase__=False     ,      lowercase__=False     ,      lowercase__=False  )     ->      Tuple:
        assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

        if equal_resolution:
            __UpperCAmelCase									=			[]
            for i in range(self.batch_size  ):
                image_inputs.append(
                    np.random.randint(
                        255     ,      size=(self.num_channels, self.max_resolution, self.max_resolution)     ,      dtype=np.uinta  )  )
        else:
            __UpperCAmelCase									=			[]
            for i in range(self.batch_size  ):
                __UpperCAmelCase					,     __UpperCAmelCase									=			np.random.choice(np.arange(self.min_resolution     ,      self.max_resolution  )     ,      2  )
                image_inputs.append(np.random.randint(255     ,      size=(self.num_channels, width, height)     ,      dtype=np.uinta  )  )

        if not numpify and not torchify:
            # PIL expects the channel dimension as last dimension
            __UpperCAmelCase									=			[Image.fromarray(np.moveaxis(lowercase__     ,      0     ,      -1  )  ) for x in image_inputs]

        if torchify:
            __UpperCAmelCase									=			[torch.from_numpy(lowercase__  ) for x in image_inputs]

        return image_inputs






@require_torch
@require_vision
class 					A_   (      _a ,     unittest.TestCase						):


    '''simple docstring'''






    a__     							=       SwinaSRImageProcessor if is_vision_available() else None


    def      lowerCAmelCase_						(self  )     ->      str:
        __UpperCAmelCase									=			SwinaSRImageProcessingTester(self  )


    @property
    def      lowerCAmelCase_						(self  )     ->      str:
        return self.image_processor_tester.prepare_image_processor_dict()


    def      lowerCAmelCase_						(self  )     ->      List[Any]:
        __UpperCAmelCase									=			self.image_processing_class(**self.image_processor_dict  )
        self.assertTrue(hasattr(lowercase__     ,      '''do_rescale'''  )  )
        self.assertTrue(hasattr(lowercase__     ,      '''rescale_factor'''  )  )
        self.assertTrue(hasattr(lowercase__     ,      '''do_pad'''  )  )
        self.assertTrue(hasattr(lowercase__     ,      '''pad_size'''  )  )


    def      lowerCAmelCase_						(self  )     ->      Optional[Any]:
        pass


    def      lowerCAmelCase_						(self     ,      lowercase__  )     ->      int:
        __UpperCAmelCase					,     __UpperCAmelCase									=			get_image_size(lowercase__  )
        __UpperCAmelCase									=			self.image_processor_tester.pad_size

        __UpperCAmelCase									=			(old_height // size + 1) * size - old_height
        __UpperCAmelCase									=			(old_width // size + 1) * size - old_width
        return old_height + pad_height, old_width + pad_width


    def      lowerCAmelCase_						(self  )     ->      Optional[int]:
        # Initialize image_processor
        __UpperCAmelCase									=			self.image_processing_class(**self.image_processor_dict  )
        # create random PIL images
        __UpperCAmelCase									=			self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__  )
        for image in image_inputs:
            self.assertIsInstance(lowercase__     ,      Image.Image  )

        # Test not batched input
        __UpperCAmelCase									=			image_processor(image_inputs[0]     ,      return_tensors='''pt'''  ).pixel_values
        __UpperCAmelCase					,     __UpperCAmelCase									=			self.calculate_expected_size(np.array(image_inputs[0]  )  )
        self.assertEqual(
            encoded_images.shape     ,      (
                1,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )     ,      )


    def      lowerCAmelCase_						(self  )     ->      str:
        # Initialize image_processor
        __UpperCAmelCase									=			self.image_processing_class(**self.image_processor_dict  )
        # create random numpy tensors
        __UpperCAmelCase									=			self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__     ,      numpify=lowercase__  )
        for image in image_inputs:
            self.assertIsInstance(lowercase__     ,      np.ndarray  )

        # Test not batched input
        __UpperCAmelCase									=			image_processor(image_inputs[0]     ,      return_tensors='''pt'''  ).pixel_values
        __UpperCAmelCase					,     __UpperCAmelCase									=			self.calculate_expected_size(image_inputs[0]  )
        self.assertEqual(
            encoded_images.shape     ,      (
                1,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )     ,      )






    def      lowerCAmelCase_						(self  )     ->      int:
        # Initialize image_processor
        __UpperCAmelCase									=			self.image_processing_class(**self.image_processor_dict  )
        # create random PyTorch tensors
        __UpperCAmelCase									=			self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__     ,      torchify=lowercase__  )
        for image in image_inputs:
            self.assertIsInstance(lowercase__     ,      torch.Tensor  )

        # Test not batched input
        __UpperCAmelCase									=			image_processor(image_inputs[0]     ,      return_tensors='''pt'''  ).pixel_values
        __UpperCAmelCase					,     __UpperCAmelCase									=			self.calculate_expected_size(image_inputs[0]  )
        self.assertEqual(
            encoded_images.shape     ,      (
                1,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )     ,      )




