





import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import (
    MobileViTConfig,
    MobileViTForImageClassification,
    MobileViTForSemanticSegmentation,
    MobileViTImageProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
UpperCAmelCase_     							= logging.get_logger(__name__)




def 		lowerCAmelCase_    (  __UpperCAmelCase:			Optional[Any]      )      ->	Any:
    UpperCamelCase__							:				Any          =      MobileViTConfig()

    # size of the architecture
    if "mobilevit_s" in mobilevit_name:
        UpperCamelCase__							:				Optional[int]          =      [144, 192, 240]
        UpperCamelCase__							:				Tuple          =      [16, 32, 64, 96, 128, 160, 640]
    elif "mobilevit_xs" in mobilevit_name:
        UpperCamelCase__							:				str          =      [96, 120, 144]
        UpperCamelCase__							:				Dict          =      [16, 32, 48, 64, 80, 96, 384]
    elif "mobilevit_xxs" in mobilevit_name:
        UpperCamelCase__							:				Optional[int]          =      [64, 80, 96]
        UpperCamelCase__							:				Any          =      [16, 16, 24, 48, 64, 80, 320]
        UpperCamelCase__							:				Tuple          =      0.05
        UpperCamelCase__							:				Any          =      2.0

    if mobilevit_name.startswith('''deeplabv3_'''      ):
        UpperCamelCase__							:				Any          =      512
        UpperCamelCase__							:				Optional[int]          =      16
        UpperCamelCase__							:				Dict          =      21
        UpperCamelCase__							:				Optional[int]          =      '''pascal-voc-id2label.json'''
    else:
        UpperCamelCase__							:				List[str]          =      1000
        UpperCamelCase__							:				List[Any]          =      '''imagenet-1k-id2label.json'''

    UpperCamelCase__							:				Any          =      '''huggingface/label-files'''
    UpperCamelCase__							:				int          =      json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__		,   SCREAMING_SNAKE_CASE__		,   repo_type='''dataset'''      )		,   '''r'''      )      )
    UpperCamelCase__							:				Optional[int]          =      {int(SCREAMING_SNAKE_CASE__      ): v for k, v in idalabel.items()}
    UpperCamelCase__							:				int          =      idalabel
    UpperCamelCase__							:				int          =      {v: k for k, v in idalabel.items()}

    return config




def 		lowerCAmelCase_    (  __UpperCAmelCase:			Union[str, Any]		,   __UpperCAmelCase:			int=False      )      ->	Optional[Any]:






    for i in range(1		,   6      ):
        if f"layer_{i}." in name:
            UpperCamelCase__							:				List[Any]          =      name.replace(f"layer_{i}."		,   f"encoder.layer.{i - 1}."      )

    if "conv_1." in name:
        UpperCamelCase__							:				Optional[Any]          =      name.replace('''conv_1.'''		,   '''conv_stem.'''      )
    if ".block." in name:
        UpperCamelCase__							:				List[str]          =      name.replace('''.block.'''		,   '''.'''      )

    if "exp_1x1" in name:
        UpperCamelCase__							:				Tuple          =      name.replace('''exp_1x1'''		,   '''expand_1x1'''      )
    if "red_1x1" in name:
        UpperCamelCase__							:				Optional[int]          =      name.replace('''red_1x1'''		,   '''reduce_1x1'''      )
    if ".local_rep.conv_3x3." in name:
        UpperCamelCase__							:				Any          =      name.replace('''.local_rep.conv_3x3.'''		,   '''.conv_kxk.'''      )
    if ".local_rep.conv_1x1." in name:
        UpperCamelCase__							:				Optional[int]          =      name.replace('''.local_rep.conv_1x1.'''		,   '''.conv_1x1.'''      )
    if ".norm." in name:
        UpperCamelCase__							:				Union[str, Any]          =      name.replace('''.norm.'''		,   '''.normalization.'''      )
    if ".conv." in name:
        UpperCamelCase__							:				Tuple          =      name.replace('''.conv.'''		,   '''.convolution.'''      )
    if ".conv_proj." in name:
        UpperCamelCase__							:				str          =      name.replace('''.conv_proj.'''		,   '''.conv_projection.'''      )

    for i in range(0		,   2      ):
        for j in range(0		,   4      ):
            if f".{i}.{j}." in name:
                UpperCamelCase__							:				Optional[int]          =      name.replace(f".{i}.{j}."		,   f".{i}.layer.{j}."      )

    for i in range(2		,   6      ):
        for j in range(0		,   4      ):
            if f".{i}.{j}." in name:
                UpperCamelCase__							:				Dict          =      name.replace(f".{i}.{j}."		,   f".{i}."      )
                if "expand_1x1" in name:
                    UpperCamelCase__							:				str          =      name.replace('''expand_1x1'''		,   '''downsampling_layer.expand_1x1'''      )
                if "conv_3x3" in name:
                    UpperCamelCase__							:				Optional[int]          =      name.replace('''conv_3x3'''		,   '''downsampling_layer.conv_3x3'''      )
                if "reduce_1x1" in name:
                    UpperCamelCase__							:				Any          =      name.replace('''reduce_1x1'''		,   '''downsampling_layer.reduce_1x1'''      )

    for i in range(2		,   5      ):
        if f".global_rep.{i}.weight" in name:
            UpperCamelCase__							:				Tuple          =      name.replace(f".global_rep.{i}.weight"		,   '''.layernorm.weight'''      )
        if f".global_rep.{i}.bias" in name:
            UpperCamelCase__							:				Union[str, Any]          =      name.replace(f".global_rep.{i}.bias"		,   '''.layernorm.bias'''      )

    if ".global_rep." in name:
        UpperCamelCase__							:				str          =      name.replace('''.global_rep.'''		,   '''.transformer.'''      )
    if ".pre_norm_mha.0." in name:
        UpperCamelCase__							:				List[Any]          =      name.replace('''.pre_norm_mha.0.'''		,   '''.layernorm_before.'''      )
    if ".pre_norm_mha.1.out_proj." in name:
        UpperCamelCase__							:				Dict          =      name.replace('''.pre_norm_mha.1.out_proj.'''		,   '''.attention.output.dense.'''      )
    if ".pre_norm_ffn.0." in name:
        UpperCamelCase__							:				Any          =      name.replace('''.pre_norm_ffn.0.'''		,   '''.layernorm_after.'''      )
    if ".pre_norm_ffn.1." in name:
        UpperCamelCase__							:				List[str]          =      name.replace('''.pre_norm_ffn.1.'''		,   '''.intermediate.dense.'''      )
    if ".pre_norm_ffn.4." in name:
        UpperCamelCase__							:				int          =      name.replace('''.pre_norm_ffn.4.'''		,   '''.output.dense.'''      )
    if ".transformer." in name:
        UpperCamelCase__							:				Optional[Any]          =      name.replace('''.transformer.'''		,   '''.transformer.layer.'''      )

    if ".aspp_layer." in name:
        UpperCamelCase__							:				Any          =      name.replace('''.aspp_layer.'''		,   '''.'''      )
    if ".aspp_pool." in name:
        UpperCamelCase__							:				Dict          =      name.replace('''.aspp_pool.'''		,   '''.'''      )
    if "seg_head." in name:
        UpperCamelCase__							:				Any          =      name.replace('''seg_head.'''		,   '''segmentation_head.'''      )
    if "segmentation_head.classifier.classifier." in name:
        UpperCamelCase__							:				List[Any]          =      name.replace('''segmentation_head.classifier.classifier.'''		,   '''segmentation_head.classifier.'''      )

    if "classifier.fc." in name:
        UpperCamelCase__							:				Tuple          =      name.replace('''classifier.fc.'''		,   '''classifier.'''      )
    elif (not base_model) and ("segmentation_head." not in name):
        UpperCamelCase__							:				Union[str, Any]          =      '''mobilevit.''' + name

    return name




def 		lowerCAmelCase_    (  __UpperCAmelCase:			int		,   __UpperCAmelCase:			List[Any]		,   __UpperCAmelCase:			Union[str, Any]=False      )      ->	List[str]:






    if base_model:
        UpperCamelCase__							:				List[Any]          =      ''''''
    else:
        UpperCamelCase__							:				str          =      '''mobilevit.'''

    for key in orig_state_dict.copy().keys():
        UpperCamelCase__							:				Optional[int]          =      orig_state_dict.pop(SCREAMING_SNAKE_CASE__      )

        if key[:8] == "encoder.":
            UpperCamelCase__							:				Union[str, Any]          =      key[8:]

        if "qkv" in key:
            UpperCamelCase__							:				Dict          =      key.split('''.'''      )
            UpperCamelCase__							:				str          =      int(key_split[0][6:]      ) - 1
            UpperCamelCase__							:				Dict          =      int(key_split[3]      )
            UpperCamelCase__							:				Union[str, Any]          =      model.get_submodule(f"{model_prefix}encoder.layer.{layer_num}"      )
            UpperCamelCase__							:				List[str]          =      layer.transformer.layer[transformer_num].attention.attention.all_head_size
            UpperCamelCase__							:				Optional[Any]          =      (
                f"{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention."
            )
            if "weight" in key:
                UpperCamelCase__							:				Any          =      val[:dim, :]
                UpperCamelCase__							:				Optional[int]          =      val[dim : dim * 2, :]
                UpperCamelCase__							:				List[str]          =      val[-dim:, :]
            else:
                UpperCamelCase__							:				Any          =      val[:dim]
                UpperCamelCase__							:				Union[str, Any]          =      val[dim : dim * 2]
                UpperCamelCase__							:				List[Any]          =      val[-dim:]
        else:
            UpperCamelCase__							:				int          =      val

    return orig_state_dict




def 		lowerCAmelCase_    (  )      ->	Union[str, Any]:
    UpperCamelCase__							:				Dict          =      '''http://images.cocodataset.org/val2017/000000039769.jpg'''
    UpperCamelCase__							:				Tuple          =      Image.open(requests.get(SCREAMING_SNAKE_CASE__		,   stream=SCREAMING_SNAKE_CASE__      ).raw      )
    return im




@torch.no_grad()
def 		lowerCAmelCase_    (  __UpperCAmelCase:			Dict		,   __UpperCAmelCase:			Union[str, Any]		,   __UpperCAmelCase:			Optional[int]		,   __UpperCAmelCase:			Tuple=False      )      ->	List[str]:
    UpperCamelCase__							:				Optional[int]          =      get_mobilevit_config(SCREAMING_SNAKE_CASE__      )

    # load original state_dict
    UpperCamelCase__							:				List[Any]          =      torch.load(SCREAMING_SNAKE_CASE__		,   map_location='''cpu'''      )

    # load 🤗 model
    if mobilevit_name.startswith('''deeplabv3_'''      ):
        UpperCamelCase__							:				int          =      MobileViTForSemanticSegmentation(SCREAMING_SNAKE_CASE__      ).eval()
    else:
        UpperCamelCase__							:				Optional[Any]          =      MobileViTForImageClassification(SCREAMING_SNAKE_CASE__      ).eval()

    UpperCamelCase__							:				Optional[Any]          =      convert_state_dict(SCREAMING_SNAKE_CASE__		,   SCREAMING_SNAKE_CASE__      )
    model.load_state_dict(SCREAMING_SNAKE_CASE__      )

    # Check outputs on an image, prepared by MobileViTImageProcessor
    UpperCamelCase__							:				Dict          =      MobileViTImageProcessor(crop_size=config.image_size		,   size=config.image_size + 32      )
    UpperCamelCase__							:				Tuple          =      image_processor(images=prepare_img()		,   return_tensors='''pt'''      )
    UpperCamelCase__							:				Any          =      model(**SCREAMING_SNAKE_CASE__      )
    UpperCamelCase__							:				int          =      outputs.logits

    if mobilevit_name.startswith('''deeplabv3_'''      ):
        assert logits.shape == (1, 21, 32, 32)

        if mobilevit_name == "deeplabv3_mobilevit_s":
            UpperCamelCase__							:				str          =      torch.tensor(
                [
                    [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]],
                    [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]],
                    [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]],
                ]      )
        elif mobilevit_name == "deeplabv3_mobilevit_xs":
            UpperCamelCase__							:				List[str]          =      torch.tensor(
                [
                    [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]],
                    [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]],
                    [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]],
                ]      )
        elif mobilevit_name == "deeplabv3_mobilevit_xxs":
            UpperCamelCase__							:				Tuple          =      torch.tensor(
                [
                    [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]],
                    [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]],
                    [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]],
                ]      )
        else:
            raise ValueError(f"Unknown mobilevit_name: {mobilevit_name}"      )

        assert torch.allclose(logits[0, :3, :3, :3]		,   SCREAMING_SNAKE_CASE__		,   atol=1e-4      )
    else:
        assert logits.shape == (1, 1000)

        if mobilevit_name == "mobilevit_s":
            UpperCamelCase__							:				Optional[int]          =      torch.tensor([-0.9866, 0.2392, -1.1241]      )
        elif mobilevit_name == "mobilevit_xs":
            UpperCamelCase__							:				Optional[Any]          =      torch.tensor([-2.4761, -0.9399, -1.9587]      )
        elif mobilevit_name == "mobilevit_xxs":
            UpperCamelCase__							:				int          =      torch.tensor([-1.9364, -1.2327, -0.4653]      )
        else:
            raise ValueError(f"Unknown mobilevit_name: {mobilevit_name}"      )

        assert torch.allclose(logits[0, :3]		,   SCREAMING_SNAKE_CASE__		,   atol=1e-4      )

    Path(SCREAMING_SNAKE_CASE__      ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__      )
    print(f"Saving model {mobilevit_name} to {pytorch_dump_folder_path}"      )
    model.save_pretrained(SCREAMING_SNAKE_CASE__      )
    print(f"Saving image processor to {pytorch_dump_folder_path}"      )
    image_processor.save_pretrained(SCREAMING_SNAKE_CASE__      )

    if push_to_hub:
        UpperCamelCase__							:				Dict          =      {
            '''mobilevit_s''': '''mobilevit-small''',
            '''mobilevit_xs''': '''mobilevit-x-small''',
            '''mobilevit_xxs''': '''mobilevit-xx-small''',
            '''deeplabv3_mobilevit_s''': '''deeplabv3-mobilevit-small''',
            '''deeplabv3_mobilevit_xs''': '''deeplabv3-mobilevit-x-small''',
            '''deeplabv3_mobilevit_xxs''': '''deeplabv3-mobilevit-xx-small''',
        }

        print('''Pushing to the hub...'''      )
        UpperCamelCase__							:				int          =      model_mapping[mobilevit_name]
        image_processor.push_to_hub(SCREAMING_SNAKE_CASE__		,   organization='''apple'''      )
        model.push_to_hub(SCREAMING_SNAKE_CASE__		,   organization='''apple'''      )


if __name__ == "__main__":
  UpperCAmelCase_     							= argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '--mobilevit_name',
      default='mobilevit_s',
      type=str,
      help=(
          'Name of the MobileViT model you\'d like to convert. Should be one of \'mobilevit_s\', \'mobilevit_xs\','
          ' \'mobilevit_xxs\', \'deeplabv3_mobilevit_s\', \'deeplabv3_mobilevit_xs\', \'deeplabv3_mobilevit_xxs\'.'
      ),
  )
  parser.add_argument(
      '--checkpoint_path', required=True, type=str, help='Path to the original state dict (.pt file).'
  )
  parser.add_argument(
      '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.'
  )
  parser.add_argument(
      '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
  )

  UpperCAmelCase_     							= parser.parse_args()
  convert_movilevit_checkpoint(
      args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
  )




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


lowercase_       		=  False


@skip_mps
class  A						(							_UpperCAmelCase    ,							_UpperCAmelCase    ,							_UpperCAmelCase    ,							unittest.TestCase ):







    """simple docstring"""





    lowerCamelCase			=							StableDiffusionAttendAndExcitePipeline
    lowerCamelCase			=							False
    lowerCamelCase			=							TEXT_TO_IMAGE_PARAMS
    lowerCamelCase			=							TEXT_TO_IMAGE_BATCH_PARAMS.union({'token_indices'} )
    lowerCamelCase			=							TEXT_TO_IMAGE_IMAGE_PARAMS
    lowerCamelCase			=							TEXT_TO_IMAGE_IMAGE_PARAMS


    @classmethod
    def 						snake_case__     (      cls :       Any		)->    Optional[Any]:





        '''simple docstring'''







        super().setUpClass()
        torch.use_deterministic_algorithms(lowercase_		)


    @classmethod
    def 						snake_case__     (      cls :       Optional[Any]		)->    Dict:





        '''simple docstring'''







        super().tearDownClass()
        torch.use_deterministic_algorithms(lowercase_		)


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





        '''simple docstring'''







        torch.manual_seed(0		)
        A__          =   UNetaDConditionModel(
            block_out_channels=(3_2, 6_4),layers_per_block=1,sample_size=3_2,in_channels=4,out_channels=4,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D'),up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D'),cross_attention_dim=3_2,attention_head_dim=(2, 4),use_linear_projection=lowercase_,)
        A__          =   DDIMScheduler(
            beta_start=0.00_085,beta_end=0.012,beta_schedule='scaled_linear',clip_sample=lowercase_,set_alpha_to_one=lowercase_,)
        torch.manual_seed(0		)
        A__          =   AutoencoderKL(
            block_out_channels=[3_2, 6_4],in_channels=3,out_channels=3,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'],up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'],latent_channels=4,sample_size=1_2_8,)
        torch.manual_seed(0		)
        A__          =   CLIPTextConfig(
            bos_token_id=0,eos_token_id=2,hidden_size=3_2,intermediate_size=3_7,layer_norm_eps=1E-05,num_attention_heads=4,num_hidden_layers=5,pad_token_id=1,vocab_size=1_0_0_0,hidden_act='gelu',projection_dim=5_1_2,)
        A__          =   CLIPTextModel(lowercase_		)
        A__          =   CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'		)

        A__          =   {
            'unet': unet,
            'scheduler': scheduler,
            'vae': vae,
            'text_encoder': text_encoder,
            'tokenizer': tokenizer,
            'safety_checker': None,
            'feature_extractor': None,
        }

        return components


    def 						snake_case__     (      self :       Tuple,lowercase_ :       str,lowercase_ :       List[Any]=0		)->    int:





        '''simple docstring'''







        if str(lowercase_		).startswith('mps'		):
            A__          =   torch.manual_seed(lowercase_		)
        else:
            A__          =   torch.Generator(device=lowercase_		).manual_seed(lowercase_		)
        A__          =   A__          =   {
            'prompt': 'a cat and a frog',
            'token_indices': [2, 5],
            'generator': generator,
            'num_inference_steps': 1,
            'guidance_scale': 6.0,
            'output_type': 'numpy',
            'max_iter_to_alter': 2,
            'thresholds': {0: 0.7},
        }
        return inputs


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





        '''simple docstring'''







        A__          =   'cpu'

        A__          =   self.get_dummy_components()
        A__          =   self.pipeline_class(**lowercase_		)
        pipe.to(lowercase_		)
        pipe.set_progress_bar_config(disable=lowercase_		)

        A__          =   self.get_dummy_inputs(lowercase_		)
        A__          =   pipe(**lowercase_		).images
        A__          =   image[0, -3:, -3:, -1]

        self.assertEqual(image.shape,(1, 6_4, 6_4, 3)		)
        A__          =   np.array(
            [0.63_905_364, 0.62_897_307, 0.48_599_017, 0.5_133_624, 0.5_550_048, 0.45_769_516, 0.50_326_973, 0.5_023_139, 0.45_384_496]		)
        A__          =   np.abs(image_slice.flatten() - expected_slice		).max()
        self.assertLessEqual(lowercase_,1E-3		)


    def 						snake_case__     (      self :       str		)->    Optional[Any]:





        '''simple docstring'''







        super().test_cpu_offload_forward_pass(expected_max_diff=5E-4		)


    def 						snake_case__     (      self :       str		)->    int:





        '''simple docstring'''







        self._test_inference_batch_consistent(batch_sizes=[1, 2]		)


    def 						snake_case__     (      self :       str		)->    Optional[int]:





        '''simple docstring'''







        self._test_inference_batch_single_identical(batch_size=2,expected_max_diff=7E-4		)


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





        '''simple docstring'''







        super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3		)


    def 						snake_case__     (      self :       Union[str, Any]		)->    str:





        '''simple docstring'''







        super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4		)


    def 						snake_case__     (      self :       Dict		)->    Any:





        '''simple docstring'''







        super().test_save_load_local(expected_max_difference=5E-4		)


    def 						snake_case__     (      self :       Dict		)->    List[str]:





        '''simple docstring'''







        super().test_save_load_optional_components(expected_max_difference=4E-4		)




@require_torch_gpu
@slow
class  A						(							unittest.TestCase ):







    """simple docstring"""





    @classmethod
    def 						snake_case__     (      cls :       Any		)->    Optional[int]:





        '''simple docstring'''







        super().setUpClass()
        torch.use_deterministic_algorithms(lowercase_		)


    @classmethod
    def 						snake_case__     (      cls :       int		)->    List[Any]:





        '''simple docstring'''







        super().tearDownClass()
        torch.use_deterministic_algorithms(lowercase_		)


    def 						snake_case__     (      self :       List[Any]		)->    Any:





        '''simple docstring'''







        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()


    def 						snake_case__     (      self :       Union[str, Any]		)->    List[Any]:





        '''simple docstring'''







        A__          =   torch.manual_seed(5_1		)

        A__          =   StableDiffusionAttendAndExcitePipeline.from_pretrained(
            'CompVis/stable-diffusion-v1-4',safety_checker=lowercase_,torch_dtype=torch.floataa		)
        pipe.to('cuda'		)

        A__          =   'a painting of an elephant with glasses'
        A__          =   [5, 7]

        A__          =   pipe(
            prompt=lowercase_,token_indices=lowercase_,guidance_scale=7.5,generator=lowercase_,num_inference_steps=5,max_iter_to_alter=5,output_type='numpy',).images[0]

        A__          =   load_numpy(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy'		)
        assert np.abs((expected_image - image).max()		) < 5E-1

