



'''simple docstring'''





import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
    from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder





def   a_   (		_UpperCAmelCase    :      int ,_UpperCAmelCase    :      List[Any] ,_UpperCAmelCase    :      int ,_UpperCAmelCase    :      Tuple=None ,_UpperCAmelCase    :      Optional[int]=None ,_UpperCAmelCase    :      List[Any]=None ,_UpperCAmelCase    :      List[Any]=None ,_UpperCAmelCase    :      Tuple=None ,)    ->  str:
      if attention_mask is None:
            __snake_case :   Tuple													=    input_ids.ne(config.pad_token_id				)
      if decoder_attention_mask is None:
            __snake_case :   Optional[Any]													=    decoder_input_ids.ne(config.pad_token_id				)
      if head_mask is None:
            __snake_case :   Any													=    torch.ones(config.encoder_layers ,config.encoder_attention_heads ,device=_UpperCAmelCase				)
      if decoder_head_mask is None:
            __snake_case :   List[str]													=    torch.ones(config.decoder_layers ,config.decoder_attention_heads ,device=_UpperCAmelCase				)
      if cross_attn_head_mask is None:
            __snake_case :   str													=    torch.ones(config.decoder_layers ,config.decoder_attention_heads ,device=_UpperCAmelCase				)
      return {
          "input_ids": input_ids,
          "decoder_input_ids": decoder_input_ids,
          "attention_mask": attention_mask,
          "decoder_attention_mask": attention_mask,
          "head_mask": head_mask,
          "decoder_head_mask": decoder_head_mask,
          "cross_attn_head_mask": cross_attn_head_mask,
      }



class  snake_case__						:
 def __init__(   self						:							int      ,     __a						:							Dict      ,     __a						:							str=13      ,     __a						:							Dict=7      ,     __a						:							Tuple=True      ,     __a						:							str=False      ,     __a						:							int=99      ,     __a						:							Optional[Any]=16      ,     __a						:							List[str]=2      ,     __a						:							Optional[Any]=4      ,     __a						:							Dict=4      ,     __a						:							List[str]="relu"      ,     __a						:							Tuple=0.1      ,     __a						:							str=0.1      ,     __a						:							List[Any]=0.0      ,     __a						:							Optional[int]=0.0      ,     __a						:							Any=20      ,     __a						:							Tuple=2      ,     __a						:							List[Any]=1      ,     __a						:							Tuple=0      ,     )      ->   Union[str, Any]:







       '''simple docstring'''
       __snake_case :   Optional[Any]													=    parent
       __snake_case :   List[str]													=    batch_size
       __snake_case :   Union[str, Any]													=    seq_length
       __snake_case :   List[str]													=    is_training
       __snake_case :   Dict													=    use_labels
       __snake_case :   List[str]													=    vocab_size
       __snake_case :   Dict													=    hidden_size
       __snake_case :   int													=    num_hidden_layers
       __snake_case :   Dict													=    num_attention_heads
       __snake_case :   Dict													=    intermediate_size
       __snake_case :   int													=    hidden_act
       __snake_case :   Optional[Any]													=    hidden_dropout_prob
       __snake_case :   List[str]													=    attention_probs_dropout_prob
       __snake_case :   Tuple													=    encoder_layerdrop
       __snake_case :   List[Any]													=    decoder_layerdrop
       __snake_case :   Dict													=    max_position_embeddings
       __snake_case :   List[str]													=    eos_token_id
       __snake_case :   Optional[int]													=    pad_token_id
       __snake_case :   Dict													=    bos_token_id
 def A_   (   self						:							Optional[Any]  )      ->   str:







       '''simple docstring'''
       __snake_case :   Any													=    ids_tensor([self.batch_size, self.seq_length]      ,     self.vocab_size  )
       __snake_case :   Tuple													=    self.eos_token_id  # Eos Token
       __snake_case :   List[Any]													=    ids_tensor([self.batch_size, self.seq_length]      ,     self.vocab_size  )

       # we need to clamp the input ids here to avoid having pad token in between
       # this is because for M2M100 the position_ids are prepared such that
       # all pad tokens have pos id = 2 and rest are between 2..seq_length
       # and the seq_length here is seq_length - num_pad_tokens
       # but when using past, there is no way of knowing if the past input ids had
       # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
       # position_ids being off by num_pad_tokens in past input
       __snake_case :   Optional[Any]													=    input_ids.clamp(self.pad_token_id + 1  )
       __snake_case :   Any													=    decoder_input_ids.clamp(self.pad_token_id + 1  )

       __snake_case :   List[Any]													=    self.get_config()
       __snake_case :   str													=    prepare_mam_aaa_inputs_dict(__a      ,     __a      ,     __a  )
       return config, inputs_dict
 def A_   (   self						:							List[Any]  )      ->   Union[str, Any]:







       '''simple docstring'''
       return MaMaaaConfig(
           vocab_size=self.vocab_size      ,     d_model=self.hidden_size      ,     encoder_layers=self.num_hidden_layers      ,     decoder_layers=self.num_hidden_layers      ,     encoder_attention_heads=self.num_attention_heads      ,     decoder_attention_heads=self.num_attention_heads      ,     encoder_ffn_dim=self.intermediate_size      ,     decoder_ffn_dim=self.intermediate_size      ,     dropout=self.hidden_dropout_prob      ,     attention_dropout=self.attention_probs_dropout_prob      ,     encoder_layerdrop=self.encoder_layerdrop      ,     decoder_layerdrop=self.decoder_layerdrop      ,     max_position_embeddings=self.max_position_embeddings      ,     eos_token_id=self.eos_token_id      ,     bos_token_id=self.bos_token_id      ,     pad_token_id=self.pad_token_id      ,     )
 def A_   (   self						:							List[str]  )      ->   Tuple:







       '''simple docstring'''
       __snake_case							,     __snake_case :   Union[str, Any]													=    self.prepare_config_and_inputs()
       return config, inputs_dict
 def A_   (   self						:							List[Any]      ,     __a						:							Union[str, Any]      ,     __a						:							List[Any]  )      ->   Any:







       '''simple docstring'''
       __snake_case :   int													=    MaMaaaModel(config=__a  ).get_decoder().to(__a  ).eval()
       __snake_case :   List[str]													=    inputs_dict['input_ids']
       __snake_case :   str													=    inputs_dict['attention_mask']
       __snake_case :   List[str]													=    inputs_dict['head_mask']

       # first forward pass
       __snake_case :   Union[str, Any]													=    model(__a      ,     attention_mask=__a      ,     head_mask=__a      ,     use_cache=__a  )

       __snake_case							,     __snake_case :   str													=    outputs.to_tuple()

       # create hypothetical multiple next token and extent to next_input_ids
       __snake_case :   Tuple													=    ids_tensor((self.batch_size, 3)      ,     config.vocab_size  )
       __snake_case :   Optional[int]													=    ids_tensor((self.batch_size, 3)      ,     2  )

       # append to next input_ids and
       __snake_case :   Any													=    torch.cat([input_ids, next_tokens]      ,     dim=-1  )
       __snake_case :   List[Any]													=    torch.cat([attention_mask, next_attn_mask]      ,     dim=-1  )

       __snake_case :   List[str]													=    model(__a      ,     attention_mask=__a  )['last_hidden_state']
       __snake_case :   Any													=    model(__a      ,     attention_mask=__a      ,     past_key_values=__a  )[
           'last_hidden_state'
       ]

       # select random slice
       __snake_case :   Optional[Any]													=    ids_tensor((1,)      ,     output_from_past.shape[-1]  ).item()
       __snake_case :   Optional[Any]													=    output_from_no_past[:, -3:, random_slice_idx].detach()
       __snake_case :   Tuple													=    output_from_past[:, :, random_slice_idx].detach()

       self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]  )

       # test that outputs are equal for slice
       self.parent.assertTrue(torch.allclose(__a      ,     __a      ,     atol=1e-2  )  )





 def A_   (   self						:							int      ,     __a						:							Optional[int]      ,     __a						:							int  )      ->   Dict:







       '''simple docstring'''
       __snake_case :   Optional[int]													=    MaMaaaModel(config=__a  ).to(__a  ).eval()
       __snake_case :   Dict													=    model(**__a  )

       __snake_case :   List[Any]													=    outputs.encoder_last_hidden_state
       __snake_case :   Any													=    outputs.last_hidden_state

       with tempfile.TemporaryDirectory() as tmpdirname:
             __snake_case :   Optional[Any]													=    model.get_encoder()
             encoder.save_pretrained(__a  )
             __snake_case :   List[str]													=    MaMaaaEncoder.from_pretrained(__a  ).to(__a  )

       __snake_case :   Dict													=    encoder(inputs_dict['input_ids']      ,     attention_mask=inputs_dict['attention_mask']  )[
           0
       ]

       self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3  )

       with tempfile.TemporaryDirectory() as tmpdirname:
             __snake_case :   str													=    model.get_decoder()
             decoder.save_pretrained(__a  )
             __snake_case :   Any													=    MaMaaaDecoder.from_pretrained(__a  ).to(__a  )

       __snake_case :   Optional[Any]													=    decoder(
           input_ids=inputs_dict['decoder_input_ids']      ,     attention_mask=inputs_dict['decoder_attention_mask']      ,     encoder_hidden_states=__a      ,     encoder_attention_mask=inputs_dict['attention_mask']      ,     )[0]

       self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3  )



@require_torch
class  snake_case__						(    SCREAMING_SNAKE_CASE_  ,     SCREAMING_SNAKE_CASE_  ,     SCREAMING_SNAKE_CASE_  ,     unittest.TestCase				):
 A__				= (
     (
         MaMaaaModel,
         MaMaaaForConditionalGeneration,
     )
     if is_torch_available()
     else ()
 )
 A__				= (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
 A__				= (
     {
         '''conversational''': MaMaaaForConditionalGeneration,
         '''feature-extraction''': MaMaaaModel,
         '''summarization''': MaMaaaForConditionalGeneration,
         '''text2text-generation''': MaMaaaForConditionalGeneration,
         '''translation''': MaMaaaForConditionalGeneration,
     }
     if is_torch_available()
     else {}
 )
 A__				= True
 A__				= True
 A__				= False
 A__				= False
 def A_   (   self						:							Optional[int]      ,     __a						:							Any      ,     __a						:							Union[str, Any]      ,     __a						:							Optional[Any]      ,     __a						:							Dict      ,     __a						:							int  )      ->   Tuple:







       '''simple docstring'''
       if pipeline_test_casse_name == "TranslationPipelineTests":
             # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
             # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
             return True

       return False
 def A_   (   self						:							int  )      ->   Optional[int]:







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    MaMaaaModelTester(self  )
       __snake_case :   str													=    ConfigTester(self      ,     config_class=__a  )
 def A_   (   self						:							Any  )      ->   Dict:







       '''simple docstring'''
       self.config_tester.run_common_tests()
 def A_   (   self						:							Tuple  )      ->   List[Any]:







       '''simple docstring'''
       __snake_case							,     __snake_case :   Tuple													=    self.model_tester.prepare_config_and_inputs()
       for model_class in self.all_model_classes:
             __snake_case :   Union[str, Any]													=    model_class(__a  )

             with tempfile.TemporaryDirectory() as tmpdirname:
                   model.save_pretrained(__a  )
                   __snake_case							,     __snake_case :   int													=    model_class.from_pretrained(__a      ,     output_loading_info=__a  )
             self.assertEqual(info['missing_keys']      ,     []  )
 def A_   (   self						:							List[Any]  )      ->   str:







       '''simple docstring'''
       __snake_case :   str													=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_decoder_model_past_large_inputs(*__a  )
 def A_   (   self						:							Any  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   Tuple													=    self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.check_encoder_decoder_model_standalone(*__a  )
 def A_   (   self						:							Union[str, Any]  )      ->   Optional[int]:







       '''simple docstring'''
       __snake_case							,     __snake_case :   int													=    self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
             __snake_case :   List[str]													=    model_class(__a  )
             model.to(__a  )
             model.eval()

             __snake_case :   List[str]													=    copy.deepcopy(self._prepare_for_class(__a      ,     __a  )  )

             if not self.is_encoder_decoder:
                   __snake_case :   str													=    inputs['input_ids']
                   del inputs["input_ids"]
             else:
                   __snake_case :   Tuple													=    inputs['input_ids']
                   __snake_case :   Optional[Any]													=    inputs.get('decoder_input_ids'      ,     __a  )
                   del inputs["input_ids"]
                   inputs.pop('decoder_input_ids'      ,     __a  )

             __snake_case :   Tuple													=    model.get_input_embeddings()
             if not self.is_encoder_decoder:
                   __snake_case :   List[str]													=    wte(__a  )
             else:
                   __snake_case :   str													=    wte(__a  )
                   __snake_case :   List[str]													=    wte(__a  )

             with torch.no_grad():
                   model(**__a  )[0]





 def A_   (   self						:							Optional[Any]  )      ->   Dict:







       '''simple docstring'''
       __snake_case							,     __snake_case :   Any													=    self.model_tester.prepare_config_and_inputs()
       __snake_case :   Dict													=    input_dict['input_ids']
       __snake_case :   Union[str, Any]													=    input_ids.ne(1  ).to(__a  )
       __snake_case :   Optional[Any]													=    MaMaaaForConditionalGeneration(__a  ).eval().to(__a  )
       if torch_device == "cuda":
             model.half()
       model.generate(__a      ,     attention_mask=__a  )
       model.generate(num_beams=4      ,     do_sample=__a      ,     early_stopping=__a      ,     num_return_sequences=3  )





def   a_   (		_UpperCAmelCase    :      Tuple				)    ->  str:
      return torch.tensor(_UpperCAmelCase ,dtype=torch.long ,device=_UpperCAmelCase				)


A__    :   Dict           =					1E-4





@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class  snake_case__						(    unittest.TestCase				):
 @cached_property
 def A_   (   self						:							Any  )      ->   Any:







       '''simple docstring'''
       return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'  )
 def A_   (   self						:							List[Any]  )      ->   Optional[int]:







       '''simple docstring'''
       __snake_case :   Any													=    MaMaaaModel.from_pretrained('facebook/m2m100_418M'  ).to(__a  )
       __snake_case :   Union[str, Any]													=    _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]  )
       __snake_case :   Optional[int]													=    _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]  )
       __snake_case :   List[str]													=    prepare_mam_aaa_inputs_dict(model.config      ,     __a      ,     __a  )
       with torch.no_grad():
             __snake_case :   Optional[Any]													=    model(**__a  )[0]
       __snake_case :   str													=    torch.Size((1, 11, 1024)  )
       self.assertEqual(output.shape      ,     __a  )
       # change to expected output here
       __snake_case :   Optional[Any]													=    torch.tensor(
           [[-0.7_7_8_0, -0.1_6_7_6, 0.1_0_3_8], [-6.7_5_5_6, -1.3_9_9_2, 0.0_5_6_7], [-7.5_3_8_3, -0.5_9_2_0, -0.2_7_7_9]]      ,     device=__a  )
       self.assertTrue(torch.allclose(output[:, :3, :3]      ,     __a      ,     atol=__a  )  )
 def A_   (   self						:							Any  )      ->   Optional[Any]:







       '''simple docstring'''
       __snake_case :   str													=    MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'  ).to(__a  )

       # change to intended input
       __snake_case :   Dict													=    _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]  )
       __snake_case :   List[str]													=    _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]  )
       __snake_case :   Optional[int]													=    prepare_mam_aaa_inputs_dict(model.config      ,     __a      ,     __a  )
       with torch.no_grad():
             __snake_case :   List[Any]													=    model(**__a  )[0]
       __snake_case :   List[str]													=    torch.Size((1, 11, model.config.vocab_size)  )
       self.assertEqual(output.shape      ,     __a  )
       # change to expected output here
       __snake_case :   Tuple													=    torch.tensor(
           [[-1.0_4_4_8, -1.0_4_1_1, 3.7_9_9_2], [-3.2_1_9_1, -3.2_3_8_6, -1.3_4_5_1], [-3.6_2_1_0, -3.5_9_9_3, 0.4_9_2_5]]      ,     device=__a  )
       self.assertTrue(torch.allclose(output[:, :3, :3]      ,     __a      ,     atol=__a  )  )





 def A_   (   self						:							Any  )      ->   List[str]:







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'  ).to(__a  )
       __snake_case :   Optional[int]													=    MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'      ,     src_lang='fr'      ,     tgt_lang='en'  )

       __snake_case :   List[str]													=    [
           'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
           'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
           'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'
           ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'
           ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.',
       ]

       # The below article tests that we don't add any hypotheses outside of the top n_beams
       __snake_case :   Optional[int]													=    tokenizer(__a      ,     padding=__a      ,     return_tensors='pt'  )

       __snake_case :   Union[str, Any]													=    model.generate(
           input_ids=dct['input_ids'].to(__a  )      ,     attention_mask=dct['attention_mask'].to(__a  )      ,     num_beams=5      ,     forced_bos_token_id=tokenizer.get_lang_id('en'  )      ,     )

       __snake_case :   Dict													=    [
           'The NSA case highlights the total absence of intelligence debate',
           'I think there are two levels of response from the French government.',
           'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'
           ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'
           ' communications in France.',
       ]

       __snake_case :   Tuple													=    tokenizer.batch_decode(
           hypotheses_batch.tolist()      ,     clean_up_tokenization_spaces=__a      ,     skip_special_tokens=__a  )
       assert generated == expected_en








'''simple docstring'''





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()



class  snake_case__						(    SCREAMING_SNAKE_CASE_  ,     unittest.TestCase				):
 A__				= KandinskyInpaintPipeline
 A__				= ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''']
 A__				= [
     '''prompt''',
     '''negative_prompt''',
     '''image_embeds''',
     '''negative_image_embeds''',
     '''image''',
     '''mask_image''',
 ]
 A__				= [
     '''generator''',
     '''height''',
     '''width''',
     '''latents''',
     '''guidance_scale''',
     '''negative_prompt''',
     '''num_inference_steps''',
     '''return_dict''',
     '''guidance_scale''',
     '''num_images_per_prompt''',
     '''output_type''',
     '''return_dict''',
 ]
 A__				= False
 @property
 def A_   (   self						:							Dict  )      ->   Union[str, Any]:







       '''simple docstring'''
       return 32
 @property
 def A_   (   self						:							Optional[int]  )      ->   Tuple:







       '''simple docstring'''
       return 32
 @property
 def A_   (   self						:							Dict  )      ->   str:







       '''simple docstring'''
       return self.time_input_dim
 @property
 def A_   (   self						:							Dict  )      ->   Any:







       '''simple docstring'''
       return self.time_input_dim * 4
 @property
 def A_   (   self						:							List[Any]  )      ->   List[str]:







       '''simple docstring'''
       return 100
 @property
 def A_   (   self						:							int  )      ->   Union[str, Any]:







       '''simple docstring'''
       __snake_case :   List[str]													=    XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base'  )
       return tokenizer
 @property
 def A_   (   self						:							Tuple  )      ->   str:







       '''simple docstring'''
       torch.manual_seed(0  )
       __snake_case :   str													=    MCLIPConfig(
           numDims=self.cross_attention_dim      ,     transformerDimensions=self.text_embedder_hidden_size      ,     hidden_size=self.text_embedder_hidden_size      ,     intermediate_size=37      ,     num_attention_heads=4      ,     num_hidden_layers=5      ,     vocab_size=1005      ,     )

       __snake_case :   List[Any]													=    MultilingualCLIP(__a  )
       __snake_case :   List[str]													=    text_encoder.eval()

       return text_encoder
 @property
 def A_   (   self						:							Dict  )      ->   List[str]:







       '''simple docstring'''
       torch.manual_seed(0  )

       __snake_case :   Tuple													=    {
           'in_channels': 9,
           # Out channels is double in channels because predicts mean and variance
           'out_channels': 8,
           'addition_embed_type': 'text_image',
           'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'),
           'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'),
           'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn',
           'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2),
           'layers_per_block': 1,
           'encoder_hid_dim': self.text_embedder_hidden_size,
           'encoder_hid_dim_type': 'text_image_proj',
           'cross_attention_dim': self.cross_attention_dim,
           'attention_head_dim': 4,
           'resnet_time_scale_shift': 'scale_shift',
           'class_embed_type': None,
       }

       __snake_case :   Any													=    UNetaDConditionModel(**__a  )
       return model
 @property
 def A_   (   self						:							List[str]  )      ->   List[Any]:







       '''simple docstring'''
       return {
           "block_out_channels": [32, 64],
           "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
           "in_channels": 3,
           "latent_channels": 4,
           "layers_per_block": 1,
           "norm_num_groups": 8,
           "norm_type": "spatial",
           "num_vq_embeddings": 12,
           "out_channels": 3,
           "up_block_types": [
               "AttnUpDecoderBlock2D",
               "UpDecoderBlock2D",
           ],
           "vq_embed_dim": 4,
       }
 @property
 def A_   (   self						:							int  )      ->   List[str]:







       '''simple docstring'''
       torch.manual_seed(0  )
       __snake_case :   Optional[int]													=    VQModel(**self.dummy_movq_kwargs  )
       return model
 def A_   (   self						:							Dict  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   Tuple													=    self.dummy_text_encoder
       __snake_case :   str													=    self.dummy_tokenizer
       __snake_case :   Any													=    self.dummy_unet
       __snake_case :   Optional[Any]													=    self.dummy_movq

       __snake_case :   Optional[Any]													=    DDIMScheduler(
           num_train_timesteps=1000      ,     beta_schedule='linear'      ,     beta_start=0.0_0_0_8_5      ,     beta_end=0.0_1_2      ,     clip_sample=__a      ,     set_alpha_to_one=__a      ,     steps_offset=1      ,     prediction_type='epsilon'      ,     thresholding=__a      ,     )

       __snake_case :   List[str]													=    {
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'unet': unet,
           'scheduler': scheduler,
           'movq': movq,
       }

       return components
 def A_   (   self						:							List[str]      ,     __a						:							Dict      ,     __a						:							int=0  )      ->   Optional[Any]:







       '''simple docstring'''
       __snake_case :   int													=    floats_tensor((1, self.cross_attention_dim)      ,     rng=random.Random(__a  )  ).to(__a  )
       __snake_case :   str													=    floats_tensor((1, self.cross_attention_dim)      ,     rng=random.Random(seed + 1  )  ).to(__a  )
       # create init_image
       __snake_case :   Any													=    floats_tensor((1, 3, 64, 64)      ,     rng=random.Random(__a  )  ).to(__a  )
       __snake_case :   Optional[int]													=    image.cpu().permute(0      ,     2      ,     3      ,     1  )[0]
       __snake_case :   List[str]													=    Image.fromarray(np.uinta(__a  )  ).convert('RGB'  ).resize((256, 256)  )
       # create mask
       __snake_case :   Optional[int]													=    np.ones((64, 64)      ,     dtype=np.floataa  )
       __snake_case :   List[Any]													=    0

       if str(__a  ).startswith('mps'  ):
             __snake_case :   Any													=    torch.manual_seed(__a  )
       else:
             __snake_case :   Optional[int]													=    torch.Generator(device=__a  ).manual_seed(__a  )
       __snake_case :   int													=    {
           'prompt': 'horse',
           'image': init_image,
           'mask_image': mask,
           'image_embeds': image_embeds,
           'negative_image_embeds': negative_image_embeds,
           'generator': generator,
           'height': 64,
           'width': 64,
           'num_inference_steps': 2,
           'guidance_scale': 4.0,
           'output_type': 'np',
       }
       return inputs
 def A_   (   self						:							Any  )      ->   int:







       '''simple docstring'''
       __snake_case :   List[str]													=    'cpu'

       __snake_case :   Tuple													=    self.get_dummy_components()

       __snake_case :   Optional[int]													=    self.pipeline_class(**__a  )
       __snake_case :   Union[str, Any]													=    pipe.to(__a  )

       pipe.set_progress_bar_config(disable=__a  )

       __snake_case :   Optional[Any]													=    pipe(**self.get_dummy_inputs(__a  )  )
       __snake_case :   Dict													=    output.images

       __snake_case :   Union[str, Any]													=    pipe(
           **self.get_dummy_inputs(__a  )      ,     return_dict=__a      ,     )[0]

       __snake_case :   int													=    image[0, -3:, -3:, -1]
       __snake_case :   Optional[int]													=    image_from_tuple[0, -3:, -3:, -1]

       print(f'''image.shape {image.shape}'''  )

       assert image.shape == (1, 64, 64, 3)

       __snake_case :   List[Any]													=    np.array(
           [0.8_3_2_6_9_1_9, 0.7_3_7_9_0_4_6_7, 0.2_0_9_1_8_5_8_1, 0.9_3_0_9_6_1_2, 0.5_5_1_1_7_9_1, 0.4_3_7_1_3_3_2_8, 0.5_5_1_3_3_2_1, 0.4_9_9_2_2_9_3_4, 0.5_9_4_9_7_7_8_6]  )

       assert (
           np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2
       ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
       assert (
           np.abs(image_from_tuple_slice.flatten() - expected_slice  ).max() < 1e-2
       ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''





 def A_   (   self						:							List[Any]  )      ->   List[str]:







       '''simple docstring'''
       super().test_inference_batch_single_identical(expected_max_diff=3e-3  )



@slow
@require_torch_gpu
class  snake_case__						(    unittest.TestCase				):
 def A_   (   self						:							Dict  )      ->   List[str]:







       '''simple docstring'''
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()





 def A_   (   self						:							Optional[int]  )      ->   List[Any]:







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    load_numpy(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
           '/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy'  )

       __snake_case :   Tuple													=    load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png'  )
       __snake_case :   Tuple													=    np.ones((768, 768)      ,     dtype=np.floataa  )
       __snake_case :   Tuple													=    0

       __snake_case :   Tuple													=    'a hat'

       __snake_case :   Optional[Any]													=    KandinskyPriorPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-1-prior'      ,     torch_dtype=torch.floataa  )
       pipe_prior.to(__a  )

       __snake_case :   int													=    KandinskyInpaintPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-1-inpaint'      ,     torch_dtype=torch.floataa  )
       __snake_case :   Optional[Any]													=    pipeline.to(__a  )
       pipeline.set_progress_bar_config(disable=__a  )

       __snake_case :   Any													=    torch.Generator(device='cpu'  ).manual_seed(0  )
       __snake_case							,     __snake_case :   Union[str, Any]													=    pipe_prior(
           __a      ,     generator=__a      ,     num_inference_steps=5      ,     negative_prompt=''      ,     ).to_tuple()

       __snake_case :   List[str]													=    pipeline(
           __a      ,     image=__a      ,     mask_image=__a      ,     image_embeds=__a      ,     negative_image_embeds=__a      ,     generator=__a      ,     num_inference_steps=100      ,     height=768      ,     width=768      ,     output_type='np'      ,     )

       __snake_case :   int													=    output.images[0]

       assert image.shape == (768, 768, 3)

       assert_mean_pixel_difference(__a      ,     __a  )



