




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

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


lowerCamelCase__					:  Union[str, Any]      							=				logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCamelCase__					:  Optional[Any]      							=				'\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n        ```\n'





@dataclass
class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 lowercase_							       =       42





class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 def __init__(				self    :						Optional[Any]							,							_lowerCAmelCase    :						PriorTransformer							,							_lowerCAmelCase    :						CLIPVisionModel							,							_lowerCAmelCase    :						CLIPImageProcessor							,							_lowerCAmelCase    :						HeunDiscreteScheduler							,							_lowerCAmelCase    :						ShapERenderer							,							):
       super().__init__()

       self.register_modules(
           prior=_lowerCAmelCase							,							image_encoder=_lowerCAmelCase							,							image_processor=_lowerCAmelCase							,							scheduler=_lowerCAmelCase							,							renderer=_lowerCAmelCase							,							)



 def  lowerCAmelCase_    (				self    :						Tuple							,							_lowerCAmelCase    :						List[Any]							,							_lowerCAmelCase    :						int							,							_lowerCAmelCase    :						Tuple							,							_lowerCAmelCase    :						List[Any]							,							_lowerCAmelCase    :						str							,							_lowerCAmelCase    :						List[Any]		):
       if latents is None:
             SCREAMING_SNAKE_CASE_      		=     randn_tensor(_lowerCAmelCase							,							generator=_lowerCAmelCase							,							device=_lowerCAmelCase							,							dtype=_lowerCAmelCase		)
       else:
             if latents.shape != shape:
                   raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"		)
             SCREAMING_SNAKE_CASE_      		=     latents.to(_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     latents * scheduler.init_noise_sigma
       return latents



 def  lowerCAmelCase_    (				self    :						Tuple							,							_lowerCAmelCase    :						List[Any]=0		):
       if is_accelerate_available():
             from accelerate import cpu_offload
       else:
             raise ImportError('Please install accelerate via `pip install accelerate`'		)

       SCREAMING_SNAKE_CASE_      		=     torch.device(F"cuda:{gpu_id}"		)

       SCREAMING_SNAKE_CASE_      		=     [self.image_encoder, self.prior]
       for cpu_offloaded_model in models:
             if cpu_offloaded_model is not None:
                   cpu_offload(_lowerCAmelCase							,							_lowerCAmelCase		)



 @property
 def  lowerCAmelCase_    (				self    :						int		):
       if self.device != torch.device('meta'		) or not hasattr(self.image_encoder							,							'_hf_hook'		):
             return self.device
       for module in self.image_encoder.modules():
             if (
                 hasattr(_lowerCAmelCase							,							'_hf_hook'		)
                 and hasattr(module._hf_hook							,							'execution_device'		)
                 and module._hf_hook.execution_device is not None
             ):
                   return torch.device(module._hf_hook.execution_device		)
       return self.device



 def  lowerCAmelCase_    (				self    :						Optional[Any]							,							_lowerCAmelCase    :						List[Any]							,							_lowerCAmelCase    :						str							,							_lowerCAmelCase    :						int							,							_lowerCAmelCase    :						List[str]							,							):
       if isinstance(_lowerCAmelCase							,							_lowerCAmelCase		) and isinstance(image[0]							,							torch.Tensor		):
             SCREAMING_SNAKE_CASE_      		=     torch.cat(_lowerCAmelCase							,							axis=0		) if image[0].ndim == 4 else torch.stack(_lowerCAmelCase							,							axis=0		)

       if not isinstance(_lowerCAmelCase							,							torch.Tensor		):
             SCREAMING_SNAKE_CASE_      		=     self.image_processor(_lowerCAmelCase							,							return_tensors='pt'		).pixel_values[0].unsqueeze(0		)

       SCREAMING_SNAKE_CASE_      		=     image.to(dtype=self.image_encoder.dtype							,							device=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     self.image_encoder(_lowerCAmelCase		)['last_hidden_state']
       SCREAMING_SNAKE_CASE_      		=     image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

       SCREAMING_SNAKE_CASE_      		=     image_embeds.repeat_interleave(_lowerCAmelCase							,							dim=0		)

       if do_classifier_free_guidance:
             SCREAMING_SNAKE_CASE_      		=     torch.zeros_like(_lowerCAmelCase		)

             # For classifier free guidance, we need to do two forward passes.
             # Here we concatenate the unconditional and text embeddings into a single batch
             # to avoid doing two forward passes
             SCREAMING_SNAKE_CASE_      		=     torch.cat([negative_image_embeds, image_embeds]		)

       return image_embeds




 @torch.no_grad()
 @replace_example_docstring(_lowerCAmelCase		)
 def __call__(				self    :						Tuple							,							_lowerCAmelCase    :						Union[PIL.Image.Image, List[PIL.Image.Image]]							,							_lowerCAmelCase    :						int = 1							,							_lowerCAmelCase    :						int = 25							,							_lowerCAmelCase    :						Optional[Union[torch.Generator, List[torch.Generator]]] = None							,							_lowerCAmelCase    :						Optional[torch.FloatTensor] = None							,							_lowerCAmelCase    :						float = 4.0							,							_lowerCAmelCase    :						int = 64							,							_lowerCAmelCase    :						Optional[str] = "pil"							,							_lowerCAmelCase    :						bool = True							,							):

       if isinstance(_lowerCAmelCase							,							PIL.Image.Image		):
             SCREAMING_SNAKE_CASE_      		=     1
       elif isinstance(_lowerCAmelCase							,							torch.Tensor		):
             SCREAMING_SNAKE_CASE_      		=     image.shape[0]
       elif isinstance(_lowerCAmelCase							,							_lowerCAmelCase		) and isinstance(image[0]							,							(torch.Tensor, PIL.Image.Image)		):
             SCREAMING_SNAKE_CASE_      		=     len(_lowerCAmelCase		)
       else:
             raise ValueError(
                 F"`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_lowerCAmelCase		)}"		)

       SCREAMING_SNAKE_CASE_      		=     self._execution_device

       SCREAMING_SNAKE_CASE_      		=     batch_size * num_images_per_prompt

       SCREAMING_SNAKE_CASE_      		=     guidance_scale > 1.0
       SCREAMING_SNAKE_CASE_      		=     self._encode_image(_lowerCAmelCase							,							_lowerCAmelCase							,							_lowerCAmelCase							,							_lowerCAmelCase		)

       # prior

       self.scheduler.set_timesteps(_lowerCAmelCase							,							device=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.scheduler.timesteps

       SCREAMING_SNAKE_CASE_      		=     self.prior.config.num_embeddings
       SCREAMING_SNAKE_CASE_      		=     self.prior.config.embedding_dim

       SCREAMING_SNAKE_CASE_      		=     self.prepare_latents(
           (batch_size, num_embeddings * embedding_dim)							,							image_embeds.dtype							,							_lowerCAmelCase							,							_lowerCAmelCase							,							_lowerCAmelCase							,							self.scheduler							,							)

       # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
       SCREAMING_SNAKE_CASE_      		=     latents.reshape(latents.shape[0]							,							_lowerCAmelCase							,							_lowerCAmelCase		)

       for i, t in enumerate(self.progress_bar(_lowerCAmelCase		)		):
             # expand the latents if we are doing classifier free guidance
             SCREAMING_SNAKE_CASE_      		=     torch.cat([latents] * 2		) if do_classifier_free_guidance else latents
             SCREAMING_SNAKE_CASE_      		=     self.scheduler.scale_model_input(_lowerCAmelCase							,							_lowerCAmelCase		)

             SCREAMING_SNAKE_CASE_      		=     self.prior(
                 _lowerCAmelCase							,							timestep=_lowerCAmelCase							,							proj_embedding=_lowerCAmelCase							,							).predicted_image_embedding

             # remove the variance
             SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     noise_pred.split(
                 scaled_model_input.shape[2]							,							dim=2		)  # batch_size, num_embeddings, embedding_dim

             if do_classifier_free_guidance is not None:
                   SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     noise_pred.chunk(2		)
                   SCREAMING_SNAKE_CASE_      		=     noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

             SCREAMING_SNAKE_CASE_      		=     self.scheduler.step(
                 _lowerCAmelCase							,							timestep=_lowerCAmelCase							,							sample=_lowerCAmelCase							,							).prev_sample

       if output_type == "latent":
             return ShapEPipelineOutput(images=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     []
       for i, latent in enumerate(_lowerCAmelCase		):
             print()
             SCREAMING_SNAKE_CASE_      		=     self.renderer.decode(
                 latent[None, :]							,							_lowerCAmelCase							,							size=_lowerCAmelCase							,							ray_batch_size=4_096							,							n_coarse_samples=64							,							n_fine_samples=128							,							)

             images.append(_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     torch.stack(_lowerCAmelCase		)

       if output_type not in ["np", "pil"]:
             raise ValueError(F"Only the output types `pil` and `np` are supported not output_type={output_type}"		)

       SCREAMING_SNAKE_CASE_      		=     images.cpu().numpy()

       if output_type == "pil":
             SCREAMING_SNAKE_CASE_      		=     [self.numpy_to_pil(_lowerCAmelCase		) for image in images]

       # Offload last model to CPU
       if hasattr(self							,							'final_offload_hook'		) and self.final_offload_hook is not None:
             self.final_offload_hook.offload()

       if not return_dict:
             return (images,)

       return ShapEPipelineOutput(images=_lowerCAmelCase		)
"""simple docstring"""


import unittest

from transformers import MraConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_torch_available():
    import torch

    from transformers import (
        MraForMaskedLM,
        MraForMultipleChoice,
        MraForQuestionAnswering,
        MraForSequenceClassification,
        MraForTokenClassification,
        MraModel,
    )
    from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST


class 							a					:


    def __init__(       self						:	Optional[int] ,					__lowerCAmelCase						:	Optional[Any] ,					__lowerCAmelCase						:	str=2 ,					__lowerCAmelCase						:	List[Any]=8 ,					__lowerCAmelCase						:	Dict=True ,					__lowerCAmelCase						:	List[Any]=True ,					__lowerCAmelCase						:	Optional[int]=True ,					__lowerCAmelCase						:	str=True ,					__lowerCAmelCase						:	Optional[Any]=99 ,					__lowerCAmelCase						:	Optional[Any]=16 ,					__lowerCAmelCase						:	Optional[int]=5 ,					__lowerCAmelCase						:	Optional[int]=2 ,					__lowerCAmelCase						:	Optional[int]=36 ,					__lowerCAmelCase						:	Any="gelu" ,					__lowerCAmelCase						:	Any=0.0 ,					__lowerCAmelCase						:	int=0.0 ,					__lowerCAmelCase						:	List[str]=512 ,					__lowerCAmelCase						:	List[str]=16 ,					__lowerCAmelCase						:	int=2 ,					__lowerCAmelCase						:	Any=0.02 ,					__lowerCAmelCase						:	List[str]=3 ,					__lowerCAmelCase						:	str=4 ,					__lowerCAmelCase						:	Dict=None ,					):
      _UpperCAmelCase    			=   parent
      _UpperCAmelCase    			=   batch_size
      _UpperCAmelCase    			=   seq_length
      _UpperCAmelCase    			=   is_training
      _UpperCAmelCase    			=   use_input_mask
      _UpperCAmelCase    			=   use_token_type_ids
      _UpperCAmelCase    			=   use_labels
      _UpperCAmelCase    			=   vocab_size
      _UpperCAmelCase    			=   hidden_size
      _UpperCAmelCase    			=   num_hidden_layers
      _UpperCAmelCase    			=   num_attention_heads
      _UpperCAmelCase    			=   intermediate_size
      _UpperCAmelCase    			=   hidden_act
      _UpperCAmelCase    			=   hidden_dropout_prob
      _UpperCAmelCase    			=   attention_probs_dropout_prob
      _UpperCAmelCase    			=   max_position_embeddings
      _UpperCAmelCase    			=   type_vocab_size
      _UpperCAmelCase    			=   type_sequence_label_size
      _UpperCAmelCase    			=   initializer_range
      _UpperCAmelCase    			=   num_labels
      _UpperCAmelCase    			=   num_choices
      _UpperCAmelCase    			=   scope


    def   lowerCAmelCase_	(       self						:	Optional[int]       ):
      _UpperCAmelCase    			=   ids_tensor([self.batch_size, self.seq_length] ,					self.vocab_size       )

      _UpperCAmelCase    			=   None
      if self.use_input_mask:
        _UpperCAmelCase    			=   random_attention_mask([self.batch_size, self.seq_length]       )

      _UpperCAmelCase    			=   None
      if self.use_token_type_ids:
        _UpperCAmelCase    			=   ids_tensor([self.batch_size, self.seq_length] ,					self.type_vocab_size       )

      _UpperCAmelCase    			=   None
      _UpperCAmelCase    			=   None
      _UpperCAmelCase    			=   None
      if self.use_labels:
        _UpperCAmelCase    			=   ids_tensor([self.batch_size] ,					self.type_sequence_label_size       )
        _UpperCAmelCase    			=   ids_tensor([self.batch_size, self.seq_length] ,					self.num_labels       )
        _UpperCAmelCase    			=   ids_tensor([self.batch_size] ,					self.num_choices       )

      _UpperCAmelCase    			=   self.get_config()

      return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels


    def   lowerCAmelCase_	(       self						:	Any       ):
      return MraConfig(
          vocab_size=self.vocab_size ,					hidden_size=self.hidden_size ,					num_hidden_layers=self.num_hidden_layers ,					num_attention_heads=self.num_attention_heads ,					intermediate_size=self.intermediate_size ,					hidden_act=self.hidden_act ,					hidden_dropout_prob=self.hidden_dropout_prob ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob ,					max_position_embeddings=self.max_position_embeddings ,					type_vocab_size=self.type_vocab_size ,					is_decoder=__lowerCAmelCase ,					initializer_range=self.initializer_range ,					)


    def   lowerCAmelCase_	(       self						:	int       ):
      _UpperCAmelCase    			=   self.get_config()
      _UpperCAmelCase    			=   300
      return config


    def   lowerCAmelCase_	(       self						:	Any       ):
      (
          (
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					
      )    			=   self.prepare_config_and_inputs()

      _UpperCAmelCase    			=   True
      _UpperCAmelCase    			=   floats_tensor([self.batch_size, self.seq_length, self.hidden_size]       )
      _UpperCAmelCase    			=   ids_tensor([self.batch_size, self.seq_length] ,					vocab_size=2       )

      return (
          config,
          input_ids,
          token_type_ids,
          input_mask,
          sequence_labels,
          token_labels,
          choice_labels,
          encoder_hidden_states,
          encoder_attention_mask,
      )


    def   lowerCAmelCase_	(       self						:	List[str] ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	Any ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	List[Any] ,					__lowerCAmelCase						:	Tuple       ):
      _UpperCAmelCase    			=   MraModel(config=__lowerCAmelCase       )
      model.to(__lowerCAmelCase       )
      model.eval()
      _UpperCAmelCase    			=   model(__lowerCAmelCase ,					attention_mask=__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase       )
      _UpperCAmelCase    			=   model(__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase       )
      _UpperCAmelCase    			=   model(__lowerCAmelCase       )
      self.parent.assertEqual(result.last_hidden_state.shape ,					(self.batch_size, self.seq_length, self.hidden_size)       )


    def   lowerCAmelCase_	(       self						:	Tuple ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	Any ,					__lowerCAmelCase						:	Optional[Any] ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	Optional[int] ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	Optional[int] ,					__lowerCAmelCase						:	Tuple ,					):
      _UpperCAmelCase    			=   True
      _UpperCAmelCase    			=   MraModel(__lowerCAmelCase       )
      model.to(__lowerCAmelCase       )
      model.eval()
      _UpperCAmelCase    			=   model(
          __lowerCAmelCase ,					attention_mask=__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase ,					encoder_hidden_states=__lowerCAmelCase ,					encoder_attention_mask=__lowerCAmelCase ,					)
      _UpperCAmelCase    			=   model(
          __lowerCAmelCase ,					attention_mask=__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase ,					encoder_hidden_states=__lowerCAmelCase ,					)
      _UpperCAmelCase    			=   model(__lowerCAmelCase ,					attention_mask=__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase       )
      self.parent.assertEqual(result.last_hidden_state.shape ,					(self.batch_size, self.seq_length, self.hidden_size)       )


    def   lowerCAmelCase_	(       self						:	Dict ,					__lowerCAmelCase						:	Optional[int] ,					__lowerCAmelCase						:	List[Any] ,					__lowerCAmelCase						:	Optional[int] ,					__lowerCAmelCase						:	str ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	str       ):
      _UpperCAmelCase    			=   MraForMaskedLM(config=__lowerCAmelCase       )
      model.to(__lowerCAmelCase       )
      model.eval()
      _UpperCAmelCase    			=   model(__lowerCAmelCase ,					attention_mask=__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase ,					labels=__lowerCAmelCase       )
      self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.seq_length, self.vocab_size)       )


    def   lowerCAmelCase_	(       self						:	int ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	Optional[Any] ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	Tuple ,					__lowerCAmelCase						:	List[str] ,					__lowerCAmelCase						:	Any ,					__lowerCAmelCase						:	int       ):
      _UpperCAmelCase    			=   MraForQuestionAnswering(config=__lowerCAmelCase       )
      model.to(__lowerCAmelCase       )
      model.eval()
      _UpperCAmelCase    			=   model(
          __lowerCAmelCase ,					attention_mask=__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase ,					start_positions=__lowerCAmelCase ,					end_positions=__lowerCAmelCase ,					)
      self.parent.assertEqual(result.start_logits.shape ,					(self.batch_size, self.seq_length)       )
      self.parent.assertEqual(result.end_logits.shape ,					(self.batch_size, self.seq_length)       )


    def   lowerCAmelCase_	(       self						:	List[Any] ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	List[str] ,					__lowerCAmelCase						:	Any ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	Union[str, Any] ,					__lowerCAmelCase						:	int       ):
      _UpperCAmelCase    			=   self.num_labels
      _UpperCAmelCase    			=   MraForSequenceClassification(__lowerCAmelCase       )
      model.to(__lowerCAmelCase       )
      model.eval()
      _UpperCAmelCase    			=   model(__lowerCAmelCase ,					attention_mask=__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase ,					labels=__lowerCAmelCase       )
      self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_labels)       )


    def   lowerCAmelCase_	(       self						:	List[str] ,					__lowerCAmelCase						:	Optional[int] ,					__lowerCAmelCase						:	Union[str, Any] ,					__lowerCAmelCase						:	List[Any] ,					__lowerCAmelCase						:	Optional[int] ,					__lowerCAmelCase						:	Tuple ,					__lowerCAmelCase						:	Optional[int] ,					__lowerCAmelCase						:	Optional[int]       ):
      _UpperCAmelCase    			=   self.num_labels
      _UpperCAmelCase    			=   MraForTokenClassification(config=__lowerCAmelCase       )
      model.to(__lowerCAmelCase       )
      model.eval()
      _UpperCAmelCase    			=   model(__lowerCAmelCase ,					attention_mask=__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase ,					labels=__lowerCAmelCase       )
      self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.seq_length, self.num_labels)       )


    def   lowerCAmelCase_	(       self						:	Optional[Any] ,					__lowerCAmelCase						:	Any ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	List[Any] ,					__lowerCAmelCase						:	Any ,					__lowerCAmelCase						:	str ,					__lowerCAmelCase						:	List[str] ,					__lowerCAmelCase						:	Optional[Any]       ):
      _UpperCAmelCase    			=   self.num_choices
      _UpperCAmelCase    			=   MraForMultipleChoice(config=__lowerCAmelCase       )
      model.to(__lowerCAmelCase       )
      model.eval()
      _UpperCAmelCase    			=   input_ids.unsqueeze(1       ).expand(-1 ,					self.num_choices ,					-1       ).contiguous()
      _UpperCAmelCase    			=   token_type_ids.unsqueeze(1       ).expand(-1 ,					self.num_choices ,					-1       ).contiguous()
      _UpperCAmelCase    			=   input_mask.unsqueeze(1       ).expand(-1 ,					self.num_choices ,					-1       ).contiguous()
      _UpperCAmelCase    			=   model(
          __lowerCAmelCase ,					attention_mask=__lowerCAmelCase ,					token_type_ids=__lowerCAmelCase ,					labels=__lowerCAmelCase ,					)
      self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_choices)       )


    def   lowerCAmelCase_	(       self						:	Tuple       ):
      _UpperCAmelCase    			=   self.prepare_config_and_inputs()
      (
          (
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					(
          _UpperCAmelCase
      )			,					
      )    			=   config_and_inputs
      _UpperCAmelCase    			=   {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
      return config, inputs_dict



@require_torch
class 							a					(		lowerCAmelCase_						,				unittest.TestCase ):
    _snake_case  :	str  				=				(
        (
            MraModel,
            MraForMaskedLM,
            MraForMultipleChoice,
            MraForQuestionAnswering,
            MraForSequenceClassification,
            MraForTokenClassification,
        )
        if is_torch_available()
        else ()
    )
    _snake_case  :	Dict  				=				False
    _snake_case  :	Any  				=				False
    _snake_case  :	List[str]  				=				False
    _snake_case  :	Tuple  				=				False

    _snake_case  :	int  				=				()


    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):
      _UpperCAmelCase    			=   MraModelTester(self       )
      _UpperCAmelCase    			=   ConfigTester(self ,					config_class=__lowerCAmelCase ,					hidden_size=37       )


    def   lowerCAmelCase_	(       self						:	Optional[Any]       ):
      self.config_tester.run_common_tests()


    def   lowerCAmelCase_	(       self						:	Tuple       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	Any       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
        _UpperCAmelCase    			=   type
        self.model_tester.create_and_check_model(*__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	str       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_multiple_choice(*__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	str       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	List[str]       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(*__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase       )


    @slow
    def   lowerCAmelCase_	(       self						:	Optional[Any]       ):
      for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _UpperCAmelCase    			=   MraModel.from_pretrained(__lowerCAmelCase       )
        self.assertIsNotNone(__lowerCAmelCase       )


    @unittest.skip(reason="""MRA does not output attentions"""       )
    def   lowerCAmelCase_	(       self						:	str       ):
      return



@require_torch
class 							a					(		unittest.TestCase ):


    @slow
    def   lowerCAmelCase_	(       self						:	Dict       ):
      _UpperCAmelCase    			=   MraModel.from_pretrained("""uw-madison/mra-base-512-4"""       )
      _UpperCAmelCase    			=   torch.arange(256       ).unsqueeze(0       )

      with torch.no_grad():
        _UpperCAmelCase    			=   model(__lowerCAmelCase       )[0]

      _UpperCAmelCase    			=   torch.Size((1, 256, 768)       )
      self.assertEqual(output.shape ,					__lowerCAmelCase       )

      _UpperCAmelCase    			=   torch.tensor(
          [[[-0.0_140, 0.0_830, -0.0_381], [0.1_546, 0.1_402, 0.0_220], [0.1_162, 0.0_851, 0.0_165]]]       )

      self.assertTrue(torch.allclose(output[:, :3, :3] ,					__lowerCAmelCase ,					atol=1e-4       )       )


    @slow
    def   lowerCAmelCase_	(       self						:	str       ):
      _UpperCAmelCase    			=   MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4"""       )
      _UpperCAmelCase    			=   torch.arange(256       ).unsqueeze(0       )

      with torch.no_grad():
        _UpperCAmelCase    			=   model(__lowerCAmelCase       )[0]

      _UpperCAmelCase    			=   5_0265

      _UpperCAmelCase    			=   torch.Size((1, 256, vocab_size)       )
      self.assertEqual(output.shape ,					__lowerCAmelCase       )

      _UpperCAmelCase    			=   torch.tensor(
          [[[9.2_595, -3.6_038, 11.8_819], [9.3_869, -3.2_693, 11.0_956], [11.8_524, -3.4_938, 13.1_210]]]       )

      self.assertTrue(torch.allclose(output[:, :3, :3] ,					__lowerCAmelCase ,					atol=1e-4       )       )


    @slow
    def   lowerCAmelCase_	(       self						:	Dict       ):
      _UpperCAmelCase    			=   MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3"""       )
      _UpperCAmelCase    			=   torch.arange(4096       ).unsqueeze(0       )

      with torch.no_grad():
        _UpperCAmelCase    			=   model(__lowerCAmelCase       )[0]

      _UpperCAmelCase    			=   5_0265

      _UpperCAmelCase    			=   torch.Size((1, 4096, vocab_size)       )
      self.assertEqual(output.shape ,					__lowerCAmelCase       )

      _UpperCAmelCase    			=   torch.tensor(
          [[[5.4_789, -2.3_564, 7.5_064], [7.9_067, -1.3_369, 9.9_668], [9.0_712, -1.8_106, 7.0_380]]]       )

      self.assertTrue(torch.allclose(output[:, :3, :3] ,					__lowerCAmelCase ,					atol=1e-4       )       )
