





import tempfile
import unittest

import numpy as np
import torch

from diffusers import DiffusionPipeline
from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor







class        __snake_case			(				unittest.TestCase     ):





       '''simple docstring'''







       def 				UpperCAmelCase__					(    self					:       str				,							A					:       bool = False						):
         __snake_case:		Tuple					    =		10

         if only_cross_attention:
           __snake_case:		Optional[Any]					    =		12
         else:
           # when only cross attention is not set, the cross attention dim must be the same as the query dim
           __snake_case:		Tuple					    =		query_dim

         return {
             "query_dim": query_dim,
             "cross_attention_dim": cross_attention_dim,
             "heads": 2,
             "dim_head": 4,
             "added_kv_proj_dim": 6,
             "norm_num_groups": 1,
             "only_cross_attention": only_cross_attention,
             "processor": AttnAddedKVProcessor(),
         }




       def 				UpperCAmelCase__					(    self					:       Dict				,							A					:       Tuple				,							A					:       Any						):
         __snake_case:		Any					    =		2

         __snake_case:		Optional[Any]					    =		torch.rand(A				,							A				,							3				,							2						)
         __snake_case:		Any					    =		torch.rand(A				,							4				,							A						)
         __snake_case:		Optional[int]					    =		None

         return {
             "hidden_states": hidden_states,
             "encoder_hidden_states": encoder_hidden_states,
             "attention_mask": attention_mask,
         }






       def 				UpperCAmelCase__					(    self					:       Optional[Any]						):
         # self and cross attention

         torch.manual_seed(0						)

         __snake_case:		Dict					    =		self.get_constructor_arguments(only_cross_attention=A						)
         __snake_case:		List[Any]					    =		Attention(**A						)

         self.assertTrue(attn.to_k is not None						)
         self.assertTrue(attn.to_v is not None						)

         __snake_case:		int					    =		self.get_forward_arguments(
             query_dim=constructor_args["""query_dim"""]				,							added_kv_proj_dim=constructor_args["""added_kv_proj_dim"""]						)

         __snake_case:		Tuple					    =		attn(**A						)

         # only self attention

         torch.manual_seed(0						)

         __snake_case:		str					    =		self.get_constructor_arguments(only_cross_attention=A						)
         __snake_case:		Any					    =		Attention(**A						)

         self.assertTrue(attn.to_k is None						)
         self.assertTrue(attn.to_v is None						)

         __snake_case:		Union[str, Any]					    =		self.get_forward_arguments(
             query_dim=constructor_args["""query_dim"""]				,							added_kv_proj_dim=constructor_args["""added_kv_proj_dim"""]						)

         __snake_case:		Union[str, Any]					    =		attn(**A						)

         self.assertTrue((only_cross_attn_out != self_and_cross_attn_out).all()						)







class        __snake_case			(				unittest.TestCase     ):





       '''simple docstring'''







       def 				UpperCAmelCase__					(    self					:       Optional[Any]						):
         __snake_case:		int					    =		DiffusionPipeline.from_pretrained("""hf-internal-testing/tiny-stable-diffusion-pipe"""				,							safety_checker=A						)

         __snake_case:		Union[str, Any]					    =		pipe(
             """foo"""				,							num_inference_steps=2				,							generator=torch.Generator("""cpu"""						).manual_seed(0						)				,							output_type="""np"""				,							).images

         # the initial conversion succeeds
         __snake_case:		Optional[int]					    =		DiffusionPipeline.from_pretrained(
             """hf-internal-testing/tiny-stable-diffusion-pipe"""				,							device_map="""sequential"""				,							safety_checker=A						)

         __snake_case:		Any					    =		pipe(
             """foo"""				,							num_inference_steps=2				,							generator=torch.Generator("""cpu"""						).manual_seed(0						)				,							output_type="""np"""				,							).images

         with tempfile.TemporaryDirectory() as tmpdir:
           # save the converted model
           pipe.save_pretrained(A						)

           # can also load the converted weights
           __snake_case:		str					    =		DiffusionPipeline.from_pretrained(A				,							device_map="""sequential"""				,							safety_checker=A						)

         __snake_case:		Optional[Any]					    =		pipe(
             """foo"""				,							num_inference_steps=2				,							generator=torch.Generator("""cpu"""						).manual_seed(0						)				,							output_type="""np"""				,							).images

         self.assertTrue(np.allclose(A				,							A				,							atol=1E-5						)						)
         self.assertTrue(np.allclose(A				,							A				,							atol=1E-5						)						)













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        __snake_case			:





       '''simple docstring'''







       def __init__(    self					:       Union[str, Any]				,							A					:       Optional[Any]				,							A					:       str=13				,							A					:       List[Any]=7				,							A					:       str=True				,							A					:       Optional[int]=True				,							A					:       Any=True				,							A					:       List[str]=True				,							A					:       str=99				,							A					:       str=32				,							A					:       Any=5				,							A					:       Any=4				,							A					:       str=37				,							A					:       List[Any]="gelu"				,							A					:       Union[str, Any]=0.1				,							A					:       str=0.1				,							A					:       List[Any]=512				,							A					:       Optional[int]=16				,							A					:       List[str]=2				,							A					:       Optional[int]=0.02				,							A					:       Optional[int]=3				,							A					:       int=4				,							A					:       List[Any]=None				,							):
         __snake_case:		Any					    =		parent
         __snake_case:		Optional[int]					    =		batch_size
         __snake_case:		Optional[int]					    =		seq_length
         __snake_case:		Any					    =		is_training
         __snake_case:		int					    =		use_input_mask
         __snake_case:		Tuple					    =		use_token_type_ids
         __snake_case:		Optional[Any]					    =		use_labels
         __snake_case:		Optional[Any]					    =		vocab_size
         __snake_case:		str					    =		hidden_size
         __snake_case:		int					    =		num_hidden_layers
         __snake_case:		Optional[int]					    =		num_attention_heads
         __snake_case:		Tuple					    =		intermediate_size
         __snake_case:		Optional[int]					    =		hidden_act
         __snake_case:		Union[str, Any]					    =		hidden_dropout_prob
         __snake_case:		Any					    =		attention_probs_dropout_prob
         __snake_case:		List[str]					    =		max_position_embeddings
         __snake_case:		Any					    =		type_vocab_size
         __snake_case:		Dict					    =		type_sequence_label_size
         __snake_case:		int					    =		initializer_range
         __snake_case:		Union[str, Any]					    =		num_labels
         __snake_case:		int					    =		num_choices
         __snake_case:		List[Any]					    =		scope




       def 				UpperCAmelCase__					(    self					:       List[Any]						):
         __snake_case:		Any					    =		ids_tensor([self.batch_size, self.seq_length]				,							self.vocab_size						)

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

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

         __snake_case:		int					    =		None
         __snake_case:		Union[str, Any]					    =		None
         __snake_case:		str					    =		None
         if self.use_labels:
           __snake_case:		str					    =		ids_tensor([self.batch_size]				,							self.type_sequence_label_size						)
           __snake_case:		int					    =		ids_tensor([self.batch_size, self.seq_length]				,							self.num_labels						)
           __snake_case:		Tuple					    =		ids_tensor([self.batch_size]				,							self.num_choices						)

         __snake_case:		List[str]					    =		self.get_config()

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




       def 				UpperCAmelCase__					(    self					:       Union[str, 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=A				,							initializer_range=self.initializer_range				,							)




       def 				UpperCAmelCase__					(    self					:       Any						):
         __snake_case:		str					    =		self.get_config()
         __snake_case:		Optional[Any]					    =		300
         return config




       def 				UpperCAmelCase__					(    self					:       Optional[Any]						):
         (
             (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  
         ):		List[str]					    =		self.prepare_config_and_inputs()

         __snake_case:		Optional[Any]					    =		True
         __snake_case:		Optional[Any]					    =		floats_tensor([self.batch_size, self.seq_length, self.hidden_size]						)
         __snake_case:		Tuple					    =		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				,							A					:       Dict				,							A					:       str				,							A					:       Tuple				,							A					:       Dict				,							A					:       List[str]				,							A					:       List[str]				,							A					:       Optional[int]						):
         __snake_case:		Optional[int]					    =		YosoModel(config=A						)
         model.to(A						)
         model.eval()
         __snake_case:		List[Any]					    =		model(A				,							attention_mask=A				,							token_type_ids=A						)
         __snake_case:		str					    =		model(A				,							token_type_ids=A						)
         __snake_case:		int					    =		model(A						)
         self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, self.seq_length, self.hidden_size)						)




       def 				UpperCAmelCase__					(    self					:       Optional[int]				,							A					:       Dict				,							A					:       int				,							A					:       str				,							A					:       List[str]				,							A					:       int				,							A					:       Optional[int]				,							A					:       str				,							A					:       Optional[int]				,							A					:       str				,							):
         __snake_case:		Optional[Any]					    =		True
         __snake_case:		List[str]					    =		YosoModel(A						)
         model.to(A						)
         model.eval()
         __snake_case:		Optional[int]					    =		model(
             A				,							attention_mask=A				,							token_type_ids=A				,							encoder_hidden_states=A				,							encoder_attention_mask=A				,							)
         __snake_case:		Optional[int]					    =		model(
             A				,							attention_mask=A				,							token_type_ids=A				,							encoder_hidden_states=A				,							)
         __snake_case:		Optional[int]					    =		model(A				,							attention_mask=A				,							token_type_ids=A						)
         self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, self.seq_length, self.hidden_size)						)




       def 				UpperCAmelCase__					(    self					:       Optional[Any]				,							A					:       str				,							A					:       Optional[int]				,							A					:       List[Any]				,							A					:       Optional[Any]				,							A					:       Dict				,							A					:       int				,							A					:       Optional[int]						):
         __snake_case:		List[str]					    =		YosoForMaskedLM(config=A						)
         model.to(A						)
         model.eval()
         __snake_case:		int					    =		model(A				,							attention_mask=A				,							token_type_ids=A				,							labels=A						)
         self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.seq_length, self.vocab_size)						)




       def 				UpperCAmelCase__					(    self					:       int				,							A					:       Any				,							A					:       Union[str, Any]				,							A					:       Optional[int]				,							A					:       Any				,							A					:       int				,							A					:       Any				,							A					:       Optional[int]						):
         __snake_case:		int					    =		YosoForQuestionAnswering(config=A						)
         model.to(A						)
         model.eval()
         __snake_case:		Any					    =		model(
             A				,							attention_mask=A				,							token_type_ids=A				,							start_positions=A				,							end_positions=A				,							)
         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					:       str				,							A					:       Union[str, Any]				,							A					:       Tuple				,							A					:       Union[str, Any]				,							A					:       int				,							A					:       Optional[int]				,							A					:       int				,							A					:       List[Any]						):
         __snake_case:		Union[str, Any]					    =		self.num_labels
         __snake_case:		Union[str, Any]					    =		YosoForSequenceClassification(A						)
         model.to(A						)
         model.eval()
         __snake_case:		Optional[int]					    =		model(A				,							attention_mask=A				,							token_type_ids=A				,							labels=A						)
         self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_labels)						)




       def 				UpperCAmelCase__					(    self					:       Dict				,							A					:       Optional[int]				,							A					:       Dict				,							A					:       Any				,							A					:       Dict				,							A					:       str				,							A					:       int				,							A					:       Optional[int]						):
         __snake_case:		List[Any]					    =		self.num_labels
         __snake_case:		Union[str, Any]					    =		YosoForTokenClassification(config=A						)
         model.to(A						)
         model.eval()
         __snake_case:		List[Any]					    =		model(A				,							attention_mask=A				,							token_type_ids=A				,							labels=A						)
         self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.seq_length, self.num_labels)						)




       def 				UpperCAmelCase__					(    self					:       List[str]				,							A					:       Union[str, Any]				,							A					:       Tuple				,							A					:       int				,							A					:       Dict				,							A					:       Optional[int]				,							A					:       str				,							A					:       Optional[Any]						):
         __snake_case:		List[Any]					    =		self.num_choices
         __snake_case:		List[Any]					    =		YosoForMultipleChoice(config=A						)
         model.to(A						)
         model.eval()
         __snake_case:		str					    =		input_ids.unsqueeze(1						).expand(-1				,							self.num_choices				,							-1						).contiguous()
         __snake_case:		Any					    =		token_type_ids.unsqueeze(1						).expand(-1				,							self.num_choices				,							-1						).contiguous()
         __snake_case:		Optional[int]					    =		input_mask.unsqueeze(1						).expand(-1				,							self.num_choices				,							-1						).contiguous()
         __snake_case:		Any					    =		model(
             A				,							attention_mask=A				,							token_type_ids=A				,							labels=A				,							)
         self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_choices)						)






       def 				UpperCAmelCase__					(    self					:       List[Any]						):
         __snake_case:		List[str]					    =		self.prepare_config_and_inputs()
         (
             (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  (
             __snake_case
         )    ,  
         ):		int					    =		config_and_inputs
         __snake_case:		str					    =		{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
         return config, inputs_dict







@require_torch
class        __snake_case			(				__lowerCamelCase  ,     __lowerCamelCase  ,     unittest.TestCase     ):





       '''simple docstring'''







       lowerCAmelCase__ 						=	(
           (
               YosoModel,
               YosoForMaskedLM,
               YosoForMultipleChoice,
               YosoForQuestionAnswering,
               YosoForSequenceClassification,
               YosoForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       lowerCAmelCase__ 						=	False
       lowerCAmelCase__ 						=	False
       lowerCAmelCase__ 						=	False

       lowerCAmelCase__ 						=	()
       lowerCAmelCase__ 						=	(
           {
               """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					:       str						):
         __snake_case:		List[str]					    =		YosoModelTester(self						)
         __snake_case:		Optional[int]					    =		ConfigTester(self				,							config_class=A				,							hidden_size=37						)




       def 				UpperCAmelCase__					(    self					:       List[str]						):
         self.config_tester.run_common_tests()




       def 				UpperCAmelCase__					(    self					:       Optional[int]						):
         __snake_case:		Union[str, Any]					    =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*A						)




       def 				UpperCAmelCase__					(    self					:       Union[str, Any]						):
         __snake_case:		Optional[Any]					    =		self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
           __snake_case:		Optional[Any]					    =		type
           self.model_tester.create_and_check_model(*A						)




       def 				UpperCAmelCase__					(    self					:       str						):
         __snake_case:		List[Any]					    =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*A						)




       def 				UpperCAmelCase__					(    self					:       List[Any]						):
         __snake_case:		List[str]					    =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_multiple_choice(*A						)




       def 				UpperCAmelCase__					(    self					:       int						):
         __snake_case:		Any					    =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(*A						)




       def 				UpperCAmelCase__					(    self					:       Optional[Any]						):
         __snake_case:		List[Any]					    =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_sequence_classification(*A						)




       def 				UpperCAmelCase__					(    self					:       List[str]						):
         __snake_case:		Optional[int]					    =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*A						)




       @slow
       def 				UpperCAmelCase__					(    self					:       Any						):
         for model_name in YOSO_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __snake_case:		str					    =		YosoModel.from_pretrained(A						)
           self.assertIsNotNone(A						)






       def 				UpperCAmelCase__					(    self					:       Tuple						):
         return







@require_torch
class        __snake_case			(				unittest.TestCase     ):





       '''simple docstring'''







       @slow
       def 				UpperCAmelCase__					(    self					:       Tuple						):
         __snake_case:		Any					    =		YosoModel.from_pretrained("""uw-madison/yoso-4096"""						)
         __snake_case:		Union[str, Any]					    =		torch.tensor([[0, 1, 2, 3, 4, 5]]						)

         with torch.no_grad():
           __snake_case:		Optional[Any]					    =		model(A						)[0]

         __snake_case:		List[str]					    =		torch.Size((1, 6, 768)						)
         self.assertEqual(output.shape				,							A						)

         __snake_case:		List[Any]					    =		torch.tensor(
             [[[-0.0611, 0.1242, 0.0840], [0.0280, -0.0048, 0.1125], [0.0106, 0.0226, 0.0751]]]						)

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




       @slow
       def 				UpperCAmelCase__					(    self					:       Optional[Any]						):
         __snake_case:		Optional[Any]					    =		YosoForMaskedLM.from_pretrained("""uw-madison/yoso-4096"""						)
         __snake_case:		Tuple					    =		torch.tensor([[0, 1, 2, 3, 4, 5]]						)

         with torch.no_grad():
           __snake_case:		Optional[int]					    =		model(A						)[0]

         __snake_case:		Tuple					    =		50_265

         __snake_case:		List[str]					    =		torch.Size((1, 6, vocab_size)						)
         self.assertEqual(output.shape				,							A						)

         __snake_case:		Any					    =		torch.tensor(
             [[[-2.1313, -3.7285, -2.2407], [-2.7047, -3.3314, -2.6408], [0.0629, -2.5166, -0.3356]]]						)

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






       @slow
       def 				UpperCAmelCase__					(    self					:       Any						):
         __snake_case:		int					    =		YosoForMaskedLM.from_pretrained("""uw-madison/yoso-4096"""						)
         __snake_case:		Optional[Any]					    =		torch.arange(4_096						).unsqueeze(0						)

         with torch.no_grad():
           __snake_case:		Tuple					    =		model(A						)[0]

         __snake_case:		List[str]					    =		50_265

         __snake_case:		Union[str, Any]					    =		torch.Size((1, 4_096, vocab_size)						)
         self.assertEqual(output.shape				,							A						)

         __snake_case:		List[str]					    =		torch.tensor(
             [[[-2.3914, -4.3742, -5.0956], [-4.0988, -4.2384, -7.0406], [-3.1427, -3.7192, -6.6800]]]						)

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






