




import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
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 						lowercase							(   UpperCamelCase__,UpperCamelCase__,unittest.TestCase		):
     _a							 =						IFImgaImgSuperResolutionPipeline
     _a							 =						TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"width", "height"}
     _a							 =						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"original_image"}		)
     _a							 =						PipelineTesterMixin.required_optional_params - {"latents"}

     def 					a__	(  self				)						->							List[Any]:
           return self._get_superresolution_dummy_components()

     def 					a__	(  self		,     _a		,     _a=0				)						->							Any:
           if str(_a				).startswith("""mps"""				):
                 _A							:     Tuple			=						torch.manual_seed(_a				)
           else:
                 _A							:     Tuple			=						torch.Generator(device=_a				).manual_seed(_a				)

           _A							:     List[Any]			=						floats_tensor((1, 3, 32, 32)		,     rng=random.Random(_a				)				).to(_a				)
           _A							:     Dict			=						floats_tensor((1, 3, 16, 16)		,     rng=random.Random(_a				)				).to(_a				)

           _A							:     Optional[int]			=						{
               """prompt""": """A painting of a squirrel eating a burger""",
               """image""": image,
               """original_image""": original_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 					a__	(  self				)						->							Optional[int]:
           self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3				)

     def 					a__	(  self				)						->							List[Any]:
           self._test_save_load_optional_components()

     @unittest.skipIf(torch_device != """cuda"""		,     reason="""float16 requires CUDA"""				)
     def 					a__	(  self				)						->							Any:
           # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
           super().test_save_load_floataa(expected_max_diff=1e-1				)

     def 					a__	(  self				)						->							Union[str, Any]:
           self._test_attention_slicing_forward_pass(expected_max_diff=1e-2				)

     def 					a__	(  self				)						->							List[Any]:
           self._test_save_load_local()



     def 					a__	(  self				)						->							str:
           self._test_inference_batch_single_identical(
               expected_max_diff=1e-2		,     )







from __future__ import absolute_import, division, print_function, unicode_literals

from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers import RobertaConfig
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.roberta.modeling_roberta import (
    ROBERTA_INPUTS_DOCSTRING,
    ROBERTA_START_DOCSTRING,
    RobertaEmbeddings,
)

from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy







@add_start_docstrings(
    "The RoBERTa Model transformer with early exiting (DeeRoBERTa). ",UpperCamelCase__,)
class 						lowercase							(   UpperCamelCase__		):
     _a							 =						RobertaConfig
     _a							 =						"roberta"

     def __init__(  self		,     _a				)						->							Optional[int]:
           super().__init__(_a				)

           _A							:     Union[str, Any]			=						RobertaEmbeddings(_a				)
           self.init_weights()







@add_start_docstrings(
    "RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n    also takes care of multi-layer training. ",UpperCamelCase__,)
class 						lowercase							(   UpperCamelCase__		):
     _a							 =						RobertaConfig
     _a							 =						"roberta"

     def __init__(  self		,     _a				)						->							str:
           super().__init__(_a				)
           _A							:     Any			=						config.num_labels
           _A							:     Dict			=						config.num_hidden_layers

           _A							:     List[str]			=						DeeRobertaModel(_a				)
           _A							:     int			=						nn.Dropout(config.hidden_dropout_prob				)
           _A							:     int			=						nn.Linear(config.hidden_size		,     self.config.num_labels				)



     @add_start_docstrings_to_model_forward(_a				)
     def 					a__	(  self		,     _a=None		,     _a=None		,     _a=None		,     _a=None		,     _a=None		,     _a=None		,     _a=None		,     _a=-1		,     _a=False		,     )						->							Any:
           _A							:     Optional[int]			=						self.num_layers
           try:
                 _A							:     List[str]			=						self.roberta(
                     _a		,     attention_mask=_a		,     token_type_ids=_a		,     position_ids=_a		,     head_mask=_a		,     inputs_embeds=_a		,     )

                 _A							:     List[str]			=						outputs[1]

                 _A							:     List[str]			=						self.dropout(_a				)
                 _A							:     Optional[Any]			=						self.classifier(_a				)
                 _A							:     List[Any]			=						(logits,) + outputs[2:]  # add hidden states and attention if they are here
           except HighwayException as e:
                 _A							:     List[Any]			=						e.message
                 _A							:     Optional[int]			=						e.exit_layer
                 _A							:     Optional[int]			=						outputs[0]

           if not self.training:
                 _A							:     int			=						entropy(_a				)
                 _A							:     int			=						[]
                 _A							:     int			=						[]
           if labels is not None:
                 if self.num_labels == 1:
                       #  We are doing regression
                       _A							:     Union[str, Any]			=						MSELoss()
                       _A							:     Tuple			=						loss_fct(logits.view(-1				)		,     labels.view(-1				)				)
                 else:
                       _A							:     List[Any]			=						CrossEntropyLoss()
                       _A							:     Dict			=						loss_fct(logits.view(-1		,     self.num_labels				)		,     labels.view(-1				)				)

                 # work with highway exits
                 _A							:     Optional[Any]			=						[]
                 for highway_exit in outputs[-1]:
                       _A							:     Tuple			=						highway_exit[0]
                       if not self.training:
                             highway_logits_all.append(_a				)
                             highway_entropy.append(highway_exit[2]				)
                       if self.num_labels == 1:
                             #  We are doing regression
                             _A							:     List[str]			=						MSELoss()
                             _A							:     Optional[int]			=						loss_fct(highway_logits.view(-1				)		,     labels.view(-1				)				)
                       else:
                             _A							:     List[Any]			=						CrossEntropyLoss()
                             _A							:     Tuple			=						loss_fct(highway_logits.view(-1		,     self.num_labels				)		,     labels.view(-1				)				)
                       highway_losses.append(_a				)

                 if train_highway:
                       _A							:     Dict			=						(sum(highway_losses[:-1]				),) + outputs
                       # exclude the final highway, of course
                 else:
                       _A							:     int			=						(loss,) + outputs
           if not self.training:
                 _A							:     Optional[Any]			=						outputs + ((original_entropy, highway_entropy), exit_layer)
                 if output_layer >= 0:
                       _A							:     Union[str, Any]			=						(
                           (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
                       )  # use the highway of the last layer

           return outputs  # (loss), logits, (hidden_states), (attentions), entropy

