




from logging import getLogger
from typing import Any, Callable, List, Optional, Union

import numpy as np
import PIL
import torch

from ...schedulers import DDPMScheduler
from ..onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
from ..pipeline_utils import ImagePipelineOutput
from . import StableDiffusionUpscalePipeline


_lowerCAmelCase  :				List[Any]						=				getLogger(__name__)


_lowerCAmelCase  :				List[Any]						=				4
_lowerCAmelCase  :				Dict						=				7

_lowerCAmelCase  :				Tuple						=				{
    "float16": torch.floataa,
    "float32": torch.floataa,
}



def   lowerCAmelCase						(						_lowerCAmelCase							:				Optional[Any]		):




 """simple docstring"""







 if isinstance(_lowerCAmelCase  ,							torch.Tensor		):
  return image
 elif isinstance(_lowerCAmelCase  ,							PIL.Image.Image		):
  UpperCAmelCase__								=  [image]

 if isinstance(image[0]  ,							PIL.Image.Image		):
  UpperCAmelCase__	,	UpperCAmelCase__								=  image[0].size
  UpperCAmelCase__	,	UpperCAmelCase__								=  (x - x % 64 for x in (w, h))  # resize to integer multiple of 32

  UpperCAmelCase__								=  [np.array(i.resize((w, h)		)		)[None, :] for i in image]
  UpperCAmelCase__								=  np.concatenate(_lowerCAmelCase  ,							axis=0		)
  UpperCAmelCase__								=  np.array(_lowerCAmelCase		).astype(np.floataa		) / 255.0
  UpperCAmelCase__								=  image.transpose(0  ,							3  ,							1  ,							2		)
  UpperCAmelCase__								=  2.0 * image - 1.0
  UpperCAmelCase__								=  torch.from_numpy(_lowerCAmelCase		)
 elif isinstance(image[0]  ,							torch.Tensor		):
  UpperCAmelCase__								=  torch.cat(_lowerCAmelCase  ,							dim=0		)

 return image


class      _UpperCamelCase (			lowerCAmelCase						):
      def __init__(     self				:Union[str, Any]	, lowerCamelCase				:OnnxRuntimeModel	, lowerCamelCase				:OnnxRuntimeModel	, lowerCamelCase				:Any	, lowerCamelCase				:OnnxRuntimeModel	, lowerCamelCase				:DDPMScheduler	, lowerCamelCase				:Any	, lowerCamelCase				:int = 350	, )       ->     Dict:
       super().__init__(
           vae=lowerCamelCase	, text_encoder=lowerCamelCase	, tokenizer=lowerCamelCase	, unet=lowerCamelCase	, low_res_scheduler=lowerCamelCase	, scheduler=lowerCamelCase	, safety_checker=lowerCamelCase	, feature_extractor=lowerCamelCase	, watermarker=lowerCamelCase	, max_noise_level=lowerCamelCase	, )
      def __call__(     self				:Any	, lowerCamelCase				:Union[str, List[str]]	, lowerCamelCase				:Union[torch.FloatTensor, PIL.Image.Image, List[PIL.Image.Image]]	, lowerCamelCase				:int = 75	, lowerCamelCase				:float = 9.0	, lowerCamelCase				:int = 20	, lowerCamelCase				:Optional[Union[str, List[str]]] = None	, lowerCamelCase				:Optional[int] = 1	, lowerCamelCase				:float = 0.0	, lowerCamelCase				:Optional[Union[torch.Generator, List[torch.Generator]]] = None	, lowerCamelCase				:Optional[torch.FloatTensor] = None	, lowerCamelCase				:Optional[np.ndarray] = None	, lowerCamelCase				:Optional[np.ndarray] = None	, lowerCamelCase				:Optional[str] = "pil"	, lowerCamelCase				:bool = True	, lowerCamelCase				:Optional[Callable[[int, int, torch.FloatTensor], None]] = None	, lowerCamelCase				:Optional[int] = 1	, )       ->     List[str]:
       self.check_inputs(lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase )

       # 2. Define call parameters
       if prompt is not None and isinstance(lowerCamelCase	, lowerCamelCase ):
        UpperCAmelCase__								=  1
       elif prompt is not None and isinstance(lowerCamelCase	, lowerCamelCase ):
        UpperCAmelCase__								=  len(lowerCamelCase )
       else:
        UpperCAmelCase__								=  prompt_embeds.shape[0]

       UpperCAmelCase__								=  self._execution_device
       # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
       # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
       # corresponds to doing no classifier free guidance.
       UpperCAmelCase__								=  guidance_scale > 1.0

       # 3. Encode input prompt
       UpperCAmelCase__								=  self._encode_prompt(
           lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, prompt_embeds=lowerCamelCase	, negative_prompt_embeds=lowerCamelCase	, )

       UpperCAmelCase__								=  ORT_TO_PT_TYPE[str(text_embeddings.dtype )]

       # 4. Preprocess image
       UpperCAmelCase__								=  preprocess(lowerCamelCase )
       UpperCAmelCase__								=  image.cpu()

       # 5. set timesteps
       self.scheduler.set_timesteps(lowerCamelCase	, device=lowerCamelCase )
       UpperCAmelCase__								=  self.scheduler.timesteps

       # 5. Add noise to image
       UpperCAmelCase__								=  torch.tensor([noise_level]	, dtype=torch.long	, device=lowerCamelCase )
       UpperCAmelCase__								=  torch.randn(image.shape	, generator=lowerCamelCase	, device=lowerCamelCase	, dtype=lowerCamelCase )
       UpperCAmelCase__								=  self.low_res_scheduler.add_noise(lowerCamelCase	, lowerCamelCase	, lowerCamelCase )

       UpperCAmelCase__								=  2 if do_classifier_free_guidance else 1
       UpperCAmelCase__								=  np.concatenate([image] * batch_multiplier * num_images_per_prompt )
       UpperCAmelCase__								=  np.concatenate([noise_level] * image.shape[0] )

       # 6. Prepare latent variables
       UpperCAmelCase__	,	UpperCAmelCase__								=  image.shape[2:]
       UpperCAmelCase__								=  self.prepare_latents(
           batch_size * num_images_per_prompt	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, )

       # 7. Check that sizes of image and latents match
       UpperCAmelCase__								=  image.shape[1]
       if NUM_LATENT_CHANNELS + num_channels_image != NUM_UNET_INPUT_CHANNELS:
        raise ValueError(
            "Incorrect configuration settings! The config of `pipeline.unet` expects"
            f''' {NUM_UNET_INPUT_CHANNELS} but received `num_channels_latents`: {NUM_LATENT_CHANNELS} +'''
            f''' `num_channels_image`: {num_channels_image} '''
            f''' = {NUM_LATENT_CHANNELS+num_channels_image}. Please verify the config of'''
            " `pipeline.unet` or your `image` input." )

       # 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
       UpperCAmelCase__								=  self.prepare_extra_step_kwargs(lowerCamelCase	, lowerCamelCase )

       UpperCAmelCase__								=  next(
           (input.type for input in self.unet.model.get_inputs() if input.name == "timestep")	, "tensor(float)" )
       UpperCAmelCase__								=  ORT_TO_NP_TYPE[timestep_dtype]

       # 9. Denoising loop
       UpperCAmelCase__								=  len(lowerCamelCase ) - num_inference_steps * self.scheduler.order
       with self.progress_bar(total=lowerCamelCase ) as progress_bar:
        for i, t in enumerate(lowerCamelCase ):
         # expand the latents if we are doing classifier free guidance
         UpperCAmelCase__								=  np.concatenate([latents] * 2 ) if do_classifier_free_guidance else latents

         # concat latents, mask, masked_image_latents in the channel dimension
         UpperCAmelCase__								=  self.scheduler.scale_model_input(lowerCamelCase	, lowerCamelCase )
         UpperCAmelCase__								=  np.concatenate([latent_model_input, image]	, axis=1 )

         # timestep to tensor
         UpperCAmelCase__								=  np.array([t]	, dtype=lowerCamelCase )

         # predict the noise residual
         UpperCAmelCase__								=  self.unet(
             sample=lowerCamelCase	, timestep=lowerCamelCase	, encoder_hidden_states=lowerCamelCase	, class_labels=noise_level.astype(np.intaa )	, )[0]

         # perform guidance
         if do_classifier_free_guidance:
          UpperCAmelCase__	,	UpperCAmelCase__								=  np.split(lowerCamelCase	, 2 )
         UpperCAmelCase__								=  noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

         # compute the previous noisy sample x_t -> x_t-1
         UpperCAmelCase__								=  self.scheduler.step(
             torch.from_numpy(lowerCamelCase )	, lowerCamelCase	, lowerCamelCase	, **lowerCamelCase ).prev_sample

         # call the callback, if provided
         if i == len(lowerCamelCase ) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
          progress_bar.update()
          if callback is not None and i % callback_steps == 0:
           callback(lowerCamelCase	, lowerCamelCase	, lowerCamelCase )

        # 10. Post-processing
       UpperCAmelCase__								=  self.decode_latents(latents.float() )

       # 11. Convert to PIL
       if output_type == "pil":
        UpperCAmelCase__								=  self.numpy_to_pil(lowerCamelCase )

       if not return_dict:
        return (image,)

       return ImagePipelineOutput(images=lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Tuple	, lowerCamelCase				:List[str] )       ->     List[str]:
       UpperCAmelCase__								=  1 / 0.0_83_33 * latents
       UpperCAmelCase__								=  self.vae(latent_sample=lowerCamelCase )[0]
       UpperCAmelCase__								=  np.clip(image / 2 + 0.5	, 0	, 1 )
       UpperCAmelCase__								=  image.transpose((0, 2, 3, 1) )
       return image







      def 		UpperCAmelCase_  (     self				:List[Any]	, lowerCamelCase				:Union[str, List[str]]	, lowerCamelCase				:Any	, lowerCamelCase				:Optional[int]	, lowerCamelCase				:bool	, lowerCamelCase				:Optional[str]	, lowerCamelCase				:Optional[torch.FloatTensor] = None	, lowerCamelCase				:Optional[torch.FloatTensor] = None	, )       ->     Tuple:
       if prompt is not None and isinstance(lowerCamelCase	, lowerCamelCase ):
        UpperCAmelCase__								=  1
       elif prompt is not None and isinstance(lowerCamelCase	, lowerCamelCase ):
        UpperCAmelCase__								=  len(lowerCamelCase )
       else:
        UpperCAmelCase__								=  prompt_embeds.shape[0]

       if prompt_embeds is None:
        UpperCAmelCase__								=  self.tokenizer(
            lowerCamelCase	, padding="max_length"	, max_length=self.tokenizer.model_max_length	, truncation=lowerCamelCase	, return_tensors="pt"	, )
        UpperCAmelCase__								=  text_inputs.input_ids
        UpperCAmelCase__								=  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 ):
         UpperCAmelCase__								=  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}''' )

        # no positional arguments to text_encoder
        UpperCAmelCase__								=  self.text_encoder(
            input_ids=text_input_ids.int().to(lowerCamelCase )	, )
        UpperCAmelCase__								=  prompt_embeds[0]

       UpperCAmelCase__	,	UpperCAmelCase__	,	UpperCAmelCase__								=  prompt_embeds.shape
       # duplicate text embeddings for each generation per prompt, using mps friendly method
       UpperCAmelCase__								=  prompt_embeds.repeat(1	, lowerCamelCase )
       UpperCAmelCase__								=  prompt_embeds.reshape(bs_embed * num_images_per_prompt	, lowerCamelCase	, -1 )

       # get unconditional embeddings for classifier free guidance
       if do_classifier_free_guidance and negative_prompt_embeds is None:
        UpperCAmelCase__								=  42
        if negative_prompt is None:
         UpperCAmelCase__								=  [""] * 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 ):
         UpperCAmelCase__								=  [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:
         UpperCAmelCase__								=  negative_prompt

        UpperCAmelCase__								=  text_input_ids.shape[-1]
        UpperCAmelCase__								=  self.tokenizer(
            lowerCamelCase	, padding="max_length"	, max_length=lowerCamelCase	, truncation=lowerCamelCase	, return_tensors="pt"	, )

        # if hasattr(uncond_input, "attention_mask"):
        #     attention_mask = uncond_input.attention_mask.to(device)
        # else:
        #     attention_mask = None

        UpperCAmelCase__								=  self.text_encoder(
            input_ids=uncond_input.input_ids.int().to(lowerCamelCase )	, )
        UpperCAmelCase__								=  uncond_embeddings[0]

       if do_classifier_free_guidance:
        UpperCAmelCase__								=  uncond_embeddings.shape[1]
        # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
        UpperCAmelCase__								=  uncond_embeddings.repeat(1	, lowerCamelCase )
        UpperCAmelCase__								=  uncond_embeddings.reshape(batch_size * num_images_per_prompt	, lowerCamelCase	, -1 )

        # 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
        UpperCAmelCase__								=  np.concatenate([uncond_embeddings, prompt_embeds] )

       return prompt_embeds











import unittest

from transformers import YosoConfig, 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
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import (
      YosoForMaskedLM,
      YosoForMultipleChoice,
      YosoForQuestionAnswering,
      YosoForSequenceClassification,
      YosoForTokenClassification,
      YosoModel,
  )
  from transformers.models.yoso.modeling_yoso import YOSO_PRETRAINED_MODEL_ARCHIVE_LIST
class      _UpperCamelCase :
      def __init__(     self				:int	, lowerCamelCase				:int	, lowerCamelCase				:Optional[Any]=13	, lowerCamelCase				:Optional[Any]=7	, lowerCamelCase				:Union[str, Any]=True	, lowerCamelCase				:Tuple=True	, lowerCamelCase				:Optional[Any]=True	, lowerCamelCase				:str=True	, lowerCamelCase				:Any=99	, lowerCamelCase				:Optional[int]=32	, lowerCamelCase				:Any=5	, lowerCamelCase				:List[Any]=4	, lowerCamelCase				:Optional[Any]=37	, lowerCamelCase				:Tuple="gelu"	, lowerCamelCase				:Optional[int]=0.1	, lowerCamelCase				:Any=0.1	, lowerCamelCase				:List[Any]=512	, lowerCamelCase				:Tuple=16	, lowerCamelCase				:Optional[int]=2	, lowerCamelCase				:str=0.02	, lowerCamelCase				:Dict=3	, lowerCamelCase				:Union[str, Any]=4	, lowerCamelCase				:Union[str, Any]=None	, )       ->     List[Any]:
       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 		UpperCAmelCase_  (     self				:Union[str, Any] )       ->     Any:
       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 		UpperCAmelCase_  (     self				:List[Any] )       ->     Optional[Any]:
       return YosoConfig(
           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				:int )       ->     Any:
       UpperCAmelCase__								=  self.get_config()
       UpperCAmelCase__								=  300
       return config
      def 		UpperCAmelCase_  (     self				:List[str] )       ->     Tuple:
       (
           (
           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 		UpperCAmelCase_  (     self				:Any	, lowerCamelCase				:List[str]	, lowerCamelCase				:List[str]	, lowerCamelCase				:str	, lowerCamelCase				:Union[str, Any]	, lowerCamelCase				:Optional[int]	, lowerCamelCase				:Any	, lowerCamelCase				:Tuple )       ->     List[Any]:
       UpperCAmelCase__								=  YosoModel(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 		UpperCAmelCase_  (     self				:Any	, lowerCamelCase				:str	, lowerCamelCase				:Dict	, lowerCamelCase				:Any	, lowerCamelCase				:Any	, lowerCamelCase				:int	, lowerCamelCase				:Dict	, lowerCamelCase				:Any	, lowerCamelCase				:Union[str, Any]	, lowerCamelCase				:List[Any]	, )       ->     Optional[int]:
       UpperCAmelCase__								=  True
       UpperCAmelCase__								=  YosoModel(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 		UpperCAmelCase_  (     self				:Tuple	, lowerCamelCase				:List[Any]	, lowerCamelCase				:Tuple	, lowerCamelCase				:List[str]	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:Tuple	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:int )       ->     Optional[int]:
       UpperCAmelCase__								=  YosoForMaskedLM(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 		UpperCAmelCase_  (     self				:Dict	, lowerCamelCase				:str	, lowerCamelCase				:Dict	, lowerCamelCase				:List[Any]	, lowerCamelCase				:Optional[int]	, lowerCamelCase				:Union[str, Any]	, lowerCamelCase				:int	, lowerCamelCase				:Optional[Any] )       ->     Any:
       UpperCAmelCase__								=  YosoForQuestionAnswering(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 		UpperCAmelCase_  (     self				:Optional[Any]	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:Any	, lowerCamelCase				:List[str]	, lowerCamelCase				:Dict	, lowerCamelCase				:str	, lowerCamelCase				:Tuple	, lowerCamelCase				:int )       ->     Dict:
       UpperCAmelCase__								=  self.num_labels
       UpperCAmelCase__								=  YosoForSequenceClassification(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 		UpperCAmelCase_  (     self				:Tuple	, lowerCamelCase				:str	, lowerCamelCase				:int	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:List[str]	, lowerCamelCase				:Dict	, lowerCamelCase				:Optional[int]	, lowerCamelCase				:str )       ->     Dict:
       UpperCAmelCase__								=  self.num_labels
       UpperCAmelCase__								=  YosoForTokenClassification(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 		UpperCAmelCase_  (     self				:Optional[int]	, lowerCamelCase				:Tuple	, lowerCamelCase				:Tuple	, lowerCamelCase				:int	, lowerCamelCase				:Tuple	, lowerCamelCase				:List[str]	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:List[str] )       ->     List[Any]:
       UpperCAmelCase__								=  self.num_choices
       UpperCAmelCase__								=  YosoForMultipleChoice(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 		UpperCAmelCase_  (     self				:int )       ->     List[Any]:
       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      _UpperCamelCase (			lowerCAmelCase		,    lowerCAmelCase		,    unittest.TestCase						):
      UpperCAmelCase_            =						(
          (
              YosoModel,
              YosoForMaskedLM,
              YosoForMultipleChoice,
              YosoForQuestionAnswering,
              YosoForSequenceClassification,
              YosoForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      UpperCAmelCase_            =						False
      UpperCAmelCase_            =						False
      UpperCAmelCase_            =						False

      UpperCAmelCase_            =						()
      UpperCAmelCase_            =						(
          {
              """feature-extraction""": YosoModel,
              """fill-mask""": YosoForMaskedLM,
              """question-answering""": YosoForQuestionAnswering,
              """text-classification""": YosoForSequenceClassification,
              """token-classification""": YosoForTokenClassification,
              """zero-shot""": YosoForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      def 		UpperCAmelCase_  (     self				:Any )       ->     Optional[Any]:
       UpperCAmelCase__								=  YosoModelTester(self )
       UpperCAmelCase__								=  ConfigTester(self	, config_class=lowerCamelCase	, hidden_size=37 )
      def 		UpperCAmelCase_  (     self				:List[Any] )       ->     List[str]:
       self.config_tester.run_common_tests()
      def 		UpperCAmelCase_  (     self				:Optional[int] )       ->     List[Any]:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Tuple )       ->     Optional[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 		UpperCAmelCase_  (     self				:Tuple )       ->     Optional[int]:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Union[str, Any] )       ->     Dict:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:str )       ->     Optional[Any]:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Any )       ->     List[str]:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Any )       ->     str:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*lowerCamelCase )
      @slow
      def 		UpperCAmelCase_  (     self				:List[Any] )       ->     Optional[int]:
       for model_name in YOSO_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCAmelCase__								=  YosoModel.from_pretrained(lowerCamelCase )
        self.assertIsNotNone(lowerCamelCase )







      def 		UpperCAmelCase_  (     self				:int )       ->     List[str]:
       return



@require_torch
class      _UpperCamelCase (			unittest.TestCase						):
      @slow
      def 		UpperCAmelCase_  (     self				:Optional[Any] )       ->     Optional[int]:
       UpperCAmelCase__								=  YosoModel.from_pretrained("uw-madison/yoso-4096" )
       UpperCAmelCase__								=  torch.tensor([[0, 1, 2, 3, 4, 5]] )

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

       UpperCAmelCase__								=  torch.Size((1, 6, 768) )
       self.assertEqual(output.shape	, lowerCamelCase )

       UpperCAmelCase__								=  torch.tensor(
           [[[-0.06_11, 0.12_42, 0.08_40], [0.02_80, -0.00_48, 0.11_25], [0.01_06, 0.02_26, 0.07_51]]] )

       self.assertTrue(torch.allclose(output[:, :3, :3]	, lowerCamelCase	, atol=1e-4 ) )
      @slow
      def 		UpperCAmelCase_  (     self				:Optional[Any] )       ->     List[Any]:
       UpperCAmelCase__								=  YosoForMaskedLM.from_pretrained("uw-madison/yoso-4096" )
       UpperCAmelCase__								=  torch.tensor([[0, 1, 2, 3, 4, 5]] )

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

       UpperCAmelCase__								=  5_0265

       UpperCAmelCase__								=  torch.Size((1, 6, vocab_size) )
       self.assertEqual(output.shape	, lowerCamelCase )

       UpperCAmelCase__								=  torch.tensor(
           [[[-2.13_13, -3.72_85, -2.24_07], [-2.70_47, -3.33_14, -2.64_08], [0.06_29, -2.51_66, -0.33_56]]] )

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







      @slow
      def 		UpperCAmelCase_  (     self				:Any )       ->     str:
       UpperCAmelCase__								=  YosoForMaskedLM.from_pretrained("uw-madison/yoso-4096" )
       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(
           [[[-2.39_14, -4.37_42, -5.09_56], [-4.09_88, -4.23_84, -7.04_06], [-3.14_27, -3.71_92, -6.68_00]]] )

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





