


from typing import List, Optional, Union

import torch
from transformers import (
    XLMRobertaTokenizer,
)

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .text_encoder import MultilingualCLIP


SCREAMING_SNAKE_CASE :   List[str]							      =				logging.get_logger(__name__)  # pylint: disable=invalid-name

SCREAMING_SNAKE_CASE :   List[Any]							      =				"\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n        >>> import torch\n\n        >>> pipe_prior = KandinskyPriorPipeline.from_pretrained(\"kandinsky-community/Kandinsky-2-1-prior\")\n        >>> pipe_prior.to(\"cuda\")\n\n        >>> prompt = \"red cat, 4k photo\"\n        >>> out = pipe_prior(prompt)\n        >>> image_emb = out.image_embeds\n        >>> negative_image_emb = out.negative_image_embeds\n\n        >>> pipe = KandinskyPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-1\")\n        >>> pipe.to(\"cuda\")\n\n        >>> image = pipe(\n        ...     prompt,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=negative_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ... ).images\n\n        >>> image[0].save(\"cat.png\")\n        ```\n"



def        UpperCamelCase_(   lowerCamelCase_							,				lowerCamelCase_							,				lowerCamelCase_=8				)					->		Union[str, Any]:
    _lowercase :							Tuple   	=	h // scale_factor**2
    if h % scale_factor**2 != 0:
        new_h += 1
    _lowercase :							Optional[Any]   	=	w // scale_factor**2
    if w % scale_factor**2 != 0:
        new_w += 1
    return new_h * scale_factor, new_w * scale_factor






class _lowerCamelCase(		_a     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   ) ->     int:




           """simple docstring"""

           super().__init__()

           self.register_modules(
               text_encoder=lowerCamelCase,   tokenizer=lowerCamelCase,   unet=lowerCamelCase,   scheduler=lowerCamelCase,   movq=lowerCamelCase,   )
           _lowercase :							List[str]   	=	2 ** (len(self.movq.config.block_out_channels) - 1)
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     Optional[int]:




           """simple docstring"""

           if latents is None:
               _lowercase :							int   	=	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}''')
               _lowercase :							Dict   	=	latents.to(lowerCamelCase)

           _lowercase :							int   	=	latents * scheduler.init_noise_sigma
           return latents
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase=None,   ) ->     Optional[int]:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	len(lowerCamelCase) if isinstance(lowerCamelCase,   lowerCamelCase) else 1
           # get prompt text embeddings
           _lowercase :							List[str]   	=	self.tokenizer(
               lowerCamelCase,   padding='max_length',   truncation=lowerCamelCase,   max_length=77,   return_attention_mask=lowerCamelCase,   add_special_tokens=lowerCamelCase,   return_tensors='pt',   )

           _lowercase :							int   	=	text_inputs.input_ids
           _lowercase :							Tuple   	=	self.tokenizer(lowerCamelCase,   padding='longest',   return_tensors='pt').input_ids

           if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCamelCase,   lowerCamelCase):
               _lowercase :							Any   	=	self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
               logger.warning(
                   'The following part of your input was truncated because CLIP can only handle sequences up to'
                   F''' {self.tokenizer.model_max_length} tokens: {removed_text}''')

           _lowercase :							str   	=	text_input_ids.to(lowerCamelCase)
           _lowercase :							Union[str, Any]   	=	text_inputs.attention_mask.to(lowerCamelCase)

           _lowercase	,       _lowercase :							int   	=	self.text_encoder(
               input_ids=lowerCamelCase,   attention_mask=lowerCamelCase)

           _lowercase :							int   	=	prompt_embeds.repeat_interleave(lowerCamelCase,   dim=0)
           _lowercase :							Any   	=	text_encoder_hidden_states.repeat_interleave(lowerCamelCase,   dim=0)
           _lowercase :							Optional[Any]   	=	text_mask.repeat_interleave(lowerCamelCase,   dim=0)

           if do_classifier_free_guidance:
               _lowercase :							List[str]
               if negative_prompt is None:
                   _lowercase :							str   	=	[''] * batch_size
               elif type(lowerCamelCase) is not type(lowerCamelCase):
                   raise TypeError(
                       F'''`negative_prompt` should be the same type to `prompt`, but got {type(lowerCamelCase)} !='''
                       F''' {type(lowerCamelCase)}.''')
               elif isinstance(lowerCamelCase,   lowerCamelCase):
                   _lowercase :							Optional[Any]   	=	[negative_prompt]
               elif batch_size != len(lowerCamelCase):
                   raise ValueError(
                       F'''`negative_prompt`: {negative_prompt} has batch size {len(lowerCamelCase)}, but `prompt`:'''
                       F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
                       ' the batch size of `prompt`.')
               else:
                   _lowercase :							List[Any]   	=	negative_prompt

               _lowercase :							str   	=	self.tokenizer(
                   lowerCamelCase,   padding='max_length',   max_length=77,   truncation=lowerCamelCase,   return_attention_mask=lowerCamelCase,   add_special_tokens=lowerCamelCase,   return_tensors='pt',   )
               _lowercase :							Tuple   	=	uncond_input.input_ids.to(lowerCamelCase)
               _lowercase :							List[str]   	=	uncond_input.attention_mask.to(lowerCamelCase)

               _lowercase	,       _lowercase :							int   	=	self.text_encoder(
                   input_ids=lowerCamelCase,   attention_mask=lowerCamelCase)

               # duplicate unconditional embeddings for each generation per prompt, using mps friendly method

               _lowercase :							Any   	=	negative_prompt_embeds.shape[1]
               _lowercase :							List[Any]   	=	negative_prompt_embeds.repeat(1,   lowerCamelCase)
               _lowercase :							Any   	=	negative_prompt_embeds.view(batch_size * num_images_per_prompt,   lowerCamelCase)

               _lowercase :							Tuple   	=	uncond_text_encoder_hidden_states.shape[1]
               _lowercase :							Tuple   	=	uncond_text_encoder_hidden_states.repeat(1,   lowerCamelCase,   1)
               _lowercase :							Optional[Any]   	=	uncond_text_encoder_hidden_states.view(
                   batch_size * num_images_per_prompt,   lowerCamelCase,   -1)
               _lowercase :							Dict   	=	uncond_text_mask.repeat_interleave(lowerCamelCase,   dim=0)

               # done duplicates

               # 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
               _lowercase :							Dict   	=	torch.cat([negative_prompt_embeds, prompt_embeds])
               _lowercase :							Union[str, Any]   	=	torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states])

               _lowercase :							Optional[int]   	=	torch.cat([uncond_text_mask, text_mask])

           return prompt_embeds, text_encoder_hidden_states, text_mask
       def     UpperCamelCase  (      self,   lowerCamelCase=0) ->     List[Any]:




           """simple docstring"""

           if is_accelerate_available():
               from accelerate import cpu_offload
           else:
               raise ImportError('Please install accelerate via `pip install accelerate`')

           _lowercase :							List[Any]   	=	torch.device(F'''cuda:{gpu_id}''')

           _lowercase :							Tuple   	=	[
               self.unet,
               self.text_encoder,
               self.movq,
           ]
           for cpu_offloaded_model in models:
               if cpu_offloaded_model is not None:
                   cpu_offload(lowerCamelCase,   lowerCamelCase)
       def     UpperCamelCase  (      self,   lowerCamelCase=0) ->     str:




           """simple docstring"""

           if is_accelerate_available() and is_accelerate_version('>=',   '0.17.0.dev0'):
               from accelerate import cpu_offload_with_hook
           else:
               raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.')

           _lowercase :							Union[str, Any]   	=	torch.device(F'''cuda:{gpu_id}''')

           if self.device.type != "cpu":
               self.to('cpu',   silence_dtype_warnings=lowerCamelCase)
               torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

           _lowercase :							Union[str, Any]   	=	None
           for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
               _lowercase	,       _lowercase :							str   	=	cpu_offload_with_hook(lowerCamelCase,   lowerCamelCase,   prev_module_hook=lowerCamelCase)

           if self.safety_checker is not None:
               _lowercase	,       _lowercase :							Tuple   	=	cpu_offload_with_hook(self.safety_checker,   lowerCamelCase,   prev_module_hook=lowerCamelCase)

           # We'll offload the last model manually.
           _lowercase :							Any   	=	hook
       @property
       # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           if not hasattr(self.unet,   '_hf_hook'):
               return self.device
           for module in self.unet.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




       @torch.no_grad()
       @replace_example_docstring(lowerCamelCase)
       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase = None,   lowerCamelCase = 5_12,   lowerCamelCase = 5_12,   lowerCamelCase = 1_00,   lowerCamelCase = 4.0,   lowerCamelCase = 1,   lowerCamelCase = None,   lowerCamelCase = None,   lowerCamelCase = "pil",   lowerCamelCase = True,   ) ->     Optional[int]:




           """simple docstring"""

           if isinstance(lowerCamelCase,   lowerCamelCase):
               _lowercase :							Dict   	=	1
           elif isinstance(lowerCamelCase,   lowerCamelCase):
               _lowercase :							Tuple   	=	len(lowerCamelCase)
           else:
               raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase)}''')

           _lowercase :							Union[str, Any]   	=	self._execution_device

           _lowercase :							str   	=	batch_size * num_images_per_prompt
           _lowercase :							str   	=	guidance_scale > 1.0

           _lowercase	,       _lowercase	,       _lowercase :							Any   	=	self._encode_prompt(
               lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase)

           if isinstance(lowerCamelCase,   lowerCamelCase):
               _lowercase :							Tuple   	=	torch.cat(lowerCamelCase,   dim=0)
           if isinstance(lowerCamelCase,   lowerCamelCase):
               _lowercase :							Any   	=	torch.cat(lowerCamelCase,   dim=0)

           if do_classifier_free_guidance:
               _lowercase :							Optional[Any]   	=	image_embeds.repeat_interleave(lowerCamelCase,   dim=0)
               _lowercase :							Tuple   	=	negative_image_embeds.repeat_interleave(lowerCamelCase,   dim=0)

           _lowercase :							Any   	=	torch.cat([negative_image_embeds, image_embeds],   dim=0).to(
               dtype=prompt_embeds.dtype,   device=lowerCamelCase)

           self.scheduler.set_timesteps(lowerCamelCase,   device=lowerCamelCase)
           _lowercase :							Optional[Any]   	=	self.scheduler.timesteps

           _lowercase :							Any   	=	self.unet.config.in_channels

           _lowercase	,       _lowercase :							Optional[int]   	=	get_new_h_w(lowerCamelCase,   lowerCamelCase,   self.movq_scale_factor)

           # create initial latent
           _lowercase :							Dict   	=	self.prepare_latents(
               (batch_size, num_channels_latents, height, width),   text_encoder_hidden_states.dtype,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   self.scheduler,   )

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

               _lowercase :							Union[str, Any]   	=	{'text_embeds': prompt_embeds, 'image_embeds': image_embeds}
               _lowercase :							int   	=	self.unet(
                   sample=lowerCamelCase,   timestep=lowerCamelCase,   encoder_hidden_states=lowerCamelCase,   added_cond_kwargs=lowerCamelCase,   return_dict=lowerCamelCase,   )[0]

               if do_classifier_free_guidance:
                   _lowercase	,       _lowercase :							str   	=	noise_pred.split(latents.shape[1],   dim=1)
                   _lowercase	,       _lowercase :							Tuple   	=	noise_pred.chunk(2)
                   _lowercase	,       _lowercase :							Optional[Any]   	=	variance_pred.chunk(2)
                   _lowercase :							Any   	=	noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                   _lowercase :							Dict   	=	torch.cat([noise_pred, variance_pred_text],   dim=1)

               if not (
                   hasattr(self.scheduler.config,   'variance_type')
                   and self.scheduler.config.variance_type in ["learned", "learned_range"]
               ):
                   _lowercase	,       _lowercase :							List[Any]   	=	noise_pred.split(latents.shape[1],   dim=1)

               # compute the previous noisy sample x_t -> x_t-1
               _lowercase :							Any   	=	self.scheduler.step(
                   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   generator=lowerCamelCase,   ).prev_sample
           # post-processing
           _lowercase :							str   	=	self.movq.decode(lowerCamelCase,   force_not_quantize=lowerCamelCase)['sample']

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

           if output_type in ["np", "pil"]:
               _lowercase :							Union[str, Any]   	=	image * 0.5 + 0.5
               _lowercase :							Optional[int]   	=	image.clamp(0,   1)
               _lowercase :							Tuple   	=	image.cpu().permute(0,   2,   3,   1).float().numpy()

           if output_type == "pil":
               _lowercase :							Tuple   	=	self.numpy_to_pil(lowerCamelCase)

           if not return_dict:
               return (image,)

           return ImagePipelineOutput(images=lowerCamelCase)






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 _lowerCamelCase:
       def __init__(      self,   lowerCamelCase,   lowerCamelCase=2,   lowerCamelCase=8,   lowerCamelCase=True,   lowerCamelCase=True,   lowerCamelCase=True,   lowerCamelCase=True,   lowerCamelCase=99,   lowerCamelCase=16,   lowerCamelCase=5,   lowerCamelCase=2,   lowerCamelCase=36,   lowerCamelCase="gelu",   lowerCamelCase=0.0,   lowerCamelCase=0.0,   lowerCamelCase=5_12,   lowerCamelCase=16,   lowerCamelCase=2,   lowerCamelCase=0.0_2,   lowerCamelCase=3,   lowerCamelCase=4,   lowerCamelCase=None,   ) ->     Dict:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	parent
           _lowercase :							List[str]   	=	batch_size
           _lowercase :							Dict   	=	seq_length
           _lowercase :							List[str]   	=	is_training
           _lowercase :							Any   	=	use_input_mask
           _lowercase :							Any   	=	use_token_type_ids
           _lowercase :							Optional[int]   	=	use_labels
           _lowercase :							str   	=	vocab_size
           _lowercase :							str   	=	hidden_size
           _lowercase :							str   	=	num_hidden_layers
           _lowercase :							List[Any]   	=	num_attention_heads
           _lowercase :							Union[str, Any]   	=	intermediate_size
           _lowercase :							Tuple   	=	hidden_act
           _lowercase :							Optional[int]   	=	hidden_dropout_prob
           _lowercase :							Optional[Any]   	=	attention_probs_dropout_prob
           _lowercase :							int   	=	max_position_embeddings
           _lowercase :							str   	=	type_vocab_size
           _lowercase :							Tuple   	=	type_sequence_label_size
           _lowercase :							Optional[Any]   	=	initializer_range
           _lowercase :							Dict   	=	num_labels
           _lowercase :							Dict   	=	num_choices
           _lowercase :							int   	=	scope
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							str   	=	ids_tensor([self.batch_size, self.seq_length],   self.vocab_size)

           _lowercase :							List[Any]   	=	None
           if self.use_input_mask:
               _lowercase :							List[str]   	=	random_attention_mask([self.batch_size, self.seq_length])

           _lowercase :							List[Any]   	=	None
           if self.use_token_type_ids:
               _lowercase :							Dict   	=	ids_tensor([self.batch_size, self.seq_length],   self.type_vocab_size)

           _lowercase :							Optional[Any]   	=	None
           _lowercase :							Optional[int]   	=	None
           _lowercase :							Dict   	=	None
           if self.use_labels:
               _lowercase :							Tuple   	=	ids_tensor([self.batch_size],   self.type_sequence_label_size)
               _lowercase :							Tuple   	=	ids_tensor([self.batch_size, self.seq_length],   self.num_labels)
               _lowercase :							Tuple   	=	ids_tensor([self.batch_size],   self.num_choices)

           _lowercase :							Optional[int]   	=	self.get_config()

           return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           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     UpperCamelCase  (      self) ->     Union[str, Any]:




           """simple docstring"""

           _lowercase :							Any   	=	self.get_config()
           _lowercase :							List[str]   	=	3_00
           return config
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           (
               (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       
           ) :							List[str]   	=	self.prepare_config_and_inputs()

           _lowercase :							Tuple   	=	True
           _lowercase :							Any   	=	floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
           _lowercase :							Union[str, Any]   	=	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     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     Optional[int]:




           """simple docstring"""

           _lowercase :							Dict   	=	MraModel(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Dict   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase,   token_type_ids=lowerCamelCase)
           _lowercase :							Optional[Any]   	=	model(lowerCamelCase,   token_type_ids=lowerCamelCase)
           _lowercase :							Tuple   	=	model(lowerCamelCase)
           self.parent.assertEqual(result.last_hidden_state.shape,   (self.batch_size, self.seq_length, self.hidden_size))
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   ) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							int   	=	True
           _lowercase :							List[Any]   	=	MraModel(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Tuple   	=	model(
               lowerCamelCase,   attention_mask=lowerCamelCase,   token_type_ids=lowerCamelCase,   encoder_hidden_states=lowerCamelCase,   encoder_attention_mask=lowerCamelCase,   )
           _lowercase :							Union[str, Any]   	=	model(
               lowerCamelCase,   attention_mask=lowerCamelCase,   token_type_ids=lowerCamelCase,   encoder_hidden_states=lowerCamelCase,   )
           _lowercase :							Any   	=	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     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	MraForMaskedLM(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							int   	=	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     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     Any:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	MraForQuestionAnswering(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Union[str, Any]   	=	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     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							str   	=	self.num_labels
           _lowercase :							List[Any]   	=	MraForSequenceClassification(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Optional[int]   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase,   token_type_ids=lowerCamelCase,   labels=lowerCamelCase)
           self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_labels))
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	self.num_labels
           _lowercase :							str   	=	MraForTokenClassification(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Optional[int]   	=	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     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     int:




           """simple docstring"""

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




       def     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           _lowercase :							List[Any]   	=	self.prepare_config_and_inputs()
           (
               (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       
           ) :							Tuple   	=	config_and_inputs
           _lowercase :							Optional[Any]   	=	{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
           return config, inputs_dict






@require_torch
class _lowerCamelCase(		_a,				unittest.TestCase     ):
       lowercase_				:			Optional[int]									=    (
           (
               MraModel,
               MraForMaskedLM,
               MraForMultipleChoice,
               MraForQuestionAnswering,
               MraForSequenceClassification,
               MraForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       lowercase_				:			Optional[int]									=    False
       lowercase_				:			Optional[int]									=    False
       lowercase_				:			int									=    False
       lowercase_				:			Optional[Any]									=    False

       lowercase_				:			Any									=    ()
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							List[str]   	=	MraModelTester(self)
           _lowercase :							Any   	=	ConfigTester(self,   config_class=lowerCamelCase,   hidden_size=37)
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           self.config_tester.run_common_tests()
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           _lowercase :							Tuple   	=	self.model_tester.prepare_config_and_inputs()
           for type in ["absolute", "relative_key", "relative_key_query"]:
               _lowercase :							Optional[int]   	=	type
               self.model_tester.create_and_check_model(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							int   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           _lowercase :							Tuple   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_question_answering(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							List[str]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_token_classification(*lowerCamelCase)
       @slow
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase :							List[str]   	=	MraModel.from_pretrained(lowerCamelCase)
               self.assertIsNotNone(lowerCamelCase)




       @unittest.skip(reason='MRA does not output attentions')
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           return






@require_torch
class _lowerCamelCase(		unittest.TestCase     ):
       @slow
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							Dict   	=	MraModel.from_pretrained('uw-madison/mra-base-512-4')
           _lowercase :							Any   	=	torch.arange(2_56).unsqueeze(0)

           with torch.no_grad():
               _lowercase :							str   	=	model(lowerCamelCase)[0]

           _lowercase :							Union[str, Any]   	=	torch.Size((1, 2_56, 7_68))
           self.assertEqual(output.shape,   lowerCamelCase)

           _lowercase :							Dict   	=	torch.tensor(
               [[[-0.0_1_4_0, 0.0_8_3_0, -0.0_3_8_1], [0.1_5_4_6, 0.1_4_0_2, 0.0_2_2_0], [0.1_1_6_2, 0.0_8_5_1, 0.0_1_6_5]]])

           self.assertTrue(torch.allclose(output[:, :3, :3],   lowerCamelCase,   atol=1E-4))
       @slow
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							List[str]   	=	MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4')
           _lowercase :							Optional[int]   	=	torch.arange(2_56).unsqueeze(0)

           with torch.no_grad():
               _lowercase :							str   	=	model(lowerCamelCase)[0]

           _lowercase :							Union[str, Any]   	=	5_02_65

           _lowercase :							int   	=	torch.Size((1, 2_56, vocab_size))
           self.assertEqual(output.shape,   lowerCamelCase)

           _lowercase :							Optional[Any]   	=	torch.tensor(
               [[[9.2_5_9_5, -3.6_0_3_8, 1_1.8_8_1_9], [9.3_8_6_9, -3.2_6_9_3, 1_1.0_9_5_6], [1_1.8_5_2_4, -3.4_9_3_8, 1_3.1_2_1_0]]])

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




       @slow
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           _lowercase :							Any   	=	MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3')
           _lowercase :							Optional[int]   	=	torch.arange(40_96).unsqueeze(0)

           with torch.no_grad():
               _lowercase :							str   	=	model(lowerCamelCase)[0]

           _lowercase :							Optional[Any]   	=	5_02_65

           _lowercase :							Union[str, Any]   	=	torch.Size((1, 40_96, vocab_size))
           self.assertEqual(output.shape,   lowerCamelCase)

           _lowercase :							Any   	=	torch.tensor(
               [[[5.4_7_8_9, -2.3_5_6_4, 7.5_0_6_4], [7.9_0_6_7, -1.3_3_6_9, 9.9_6_6_8], [9.0_7_1_2, -1.8_1_0_6, 7.0_3_8_0]]])

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


