





'''simple docstring'''






import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer
from ...utils import logging


A__    :       Optional[Any]              =logging.get_logger(__name__)

A__    :       Union[str, Any]              ='''▁'''

A__    :       List[Any]              ={
    '''vocab_file''': '''vocab.json''',
    '''spm_file''': '''sentencepiece.bpe.model''',
    '''tokenizer_config_file''': '''tokenizer_config.json''',
}

A__    :       str              ={
    '''vocab_file''': {
        '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json''',
        '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json''',
    },
    '''spm_file''': {
        '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model''',
        '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model''',
    },
    '''tokenizer_config_file''': {
        '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json''',
        '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json''',
    },
}

A__    :       List[str]              ={
    '''facebook/m2m100_418M''': 10_24,
}

# fmt: off
A__    :       Optional[Any]              ={
    '''m2m100''': ['''af''', '''am''', '''ar''', '''ast''', '''az''', '''ba''', '''be''', '''bg''', '''bn''', '''br''', '''bs''', '''ca''', '''ceb''', '''cs''', '''cy''', '''da''', '''de''', '''el''', '''en''', '''es''', '''et''', '''fa''', '''ff''', '''fi''', '''fr''', '''fy''', '''ga''', '''gd''', '''gl''', '''gu''', '''ha''', '''he''', '''hi''', '''hr''', '''ht''', '''hu''', '''hy''', '''id''', '''ig''', '''ilo''', '''is''', '''it''', '''ja''', '''jv''', '''ka''', '''kk''', '''km''', '''kn''', '''ko''', '''lb''', '''lg''', '''ln''', '''lo''', '''lt''', '''lv''', '''mg''', '''mk''', '''ml''', '''mn''', '''mr''', '''ms''', '''my''', '''ne''', '''nl''', '''no''', '''ns''', '''oc''', '''or''', '''pa''', '''pl''', '''ps''', '''pt''', '''ro''', '''ru''', '''sd''', '''si''', '''sk''', '''sl''', '''so''', '''sq''', '''sr''', '''ss''', '''su''', '''sv''', '''sw''', '''ta''', '''th''', '''tl''', '''tn''', '''tr''', '''uk''', '''ur''', '''uz''', '''vi''', '''wo''', '''xh''', '''yi''', '''yo''', '''zh''', '''zu'''],
    '''wmt21''': ['''en''', '''ha''', '''is''', '''ja''', '''cs''', '''ru''', '''zh''', '''de''']
}




class 			UpperCAmelCase					(      snake_case_       ):
						_lowercase:      Any											=       VOCAB_FILES_NAMES
						_lowercase:      List[Any]											=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						_lowercase:      Optional[int]											=       PRETRAINED_VOCAB_FILES_MAP
						_lowercase:      str											=       ['''input_ids''', '''attention_mask''']

						_lowercase:      List[int]											=       []
						_lowercase:      List[int]											=       []




						def __init__(      self      :			Any      ,      __snake_case      :			int      ,      __snake_case      :			List[str]      ,      __snake_case      :			Tuple=None      ,      __snake_case      :			str=None      ,      __snake_case      :			Union[str, Any]="<s>"      ,      __snake_case      :			Dict="</s>"      ,      __snake_case      :			Any="</s>"      ,      __snake_case      :			Optional[int]="<pad>"      ,      __snake_case      :			Optional[Any]="<unk>"      ,      __snake_case      :			Union[str, Any]="m2m100"      ,      __snake_case      :			Optional[Dict[str, Any]] = None      ,      __snake_case      :			List[Any]=8      ,      **__snake_case      :			Any      ,      )    ->				None:
												_lowerCAmelCase												=							{} if sp_model_kwargs is None else sp_model_kwargs

												_lowerCAmelCase												=							language_codes
												_lowerCAmelCase												=							FAIRSEQ_LANGUAGE_CODES[language_codes]
												_lowerCAmelCase												=							{lang_code: f"__{lang_code}__" for lang_code in fairseq_language_code}

												_lowerCAmelCase												=							kwargs.get("""additional_special_tokens"""      ,      []  )
												kwargs["additional_special_tokens"] += [
												    self.get_lang_token(__snake_case  )
												    for lang_code in fairseq_language_code
												    if self.get_lang_token(__snake_case  ) not in kwargs["additional_special_tokens"]
												]

												super().__init__(
												    src_lang=__snake_case      ,      tgt_lang=__snake_case      ,      bos_token=__snake_case      ,      eos_token=__snake_case      ,      sep_token=__snake_case      ,      unk_token=__snake_case      ,      pad_token=__snake_case      ,      language_codes=__snake_case      ,      sp_model_kwargs=self.sp_model_kwargs      ,      num_madeup_words=__snake_case      ,      **__snake_case      ,      )

												_lowerCAmelCase												=							vocab_file
												_lowerCAmelCase												=							load_json(__snake_case  )
												_lowerCAmelCase												=							{v: k for k, v in self.encoder.items()}
												_lowerCAmelCase												=							spm_file
												_lowerCAmelCase												=							load_spm(__snake_case      ,      self.sp_model_kwargs  )

												_lowerCAmelCase												=							len(self.encoder  )

												_lowerCAmelCase												=							{
												    self.get_lang_token(__snake_case  ): self.encoder_size + i for i, lang_code in enumerate(__snake_case  )
												}
												_lowerCAmelCase												=							{lang_code: self.encoder_size + i for i, lang_code in enumerate(__snake_case  )}
												_lowerCAmelCase												=							{v: k for k, v in self.lang_token_to_id.items()}

												_lowerCAmelCase												=							src_lang if src_lang is not None else """en"""
												_lowerCAmelCase												=							tgt_lang
												_lowerCAmelCase												=							self.get_lang_id(self._src_lang  )
												self.set_src_lang_special_tokens(self._src_lang  )

												_lowerCAmelCase												=							num_madeup_words




						@property
						def     lowercase__   (      self      :			List[str]  )    ->				int:
												return len(self.encoder  ) + len(self.lang_token_to_id  )




						@property
						def     lowercase__   (      self      :			Union[str, Any]  )    ->				str:
												return self._src_lang




						@src_lang.setter
						def     lowercase__   (      self      :			List[Any]      ,      __snake_case      :			str  )    ->				None:
												_lowerCAmelCase												=							new_src_lang
												self.set_src_lang_special_tokens(self._src_lang  )




						def     lowercase__   (      self      :			Optional[Any]      ,      __snake_case      :			str  )    ->				List[str]:
												return self.sp_model.encode(__snake_case      ,      out_type=__snake_case  )




						def     lowercase__   (      self      :			Optional[int]      ,      __snake_case      :			List[Any]  )    ->				str:
												if token in self.lang_token_to_id:
																		return self.lang_token_to_id[token]
												return self.encoder.get(__snake_case      ,      self.encoder[self.unk_token]  )




						def     lowercase__   (      self      :			List[str]      ,      __snake_case      :			int  )    ->				str:
												if index in self.id_to_lang_token:
																		return self.id_to_lang_token[index]
												return self.decoder.get(__snake_case      ,      self.unk_token  )




						def     lowercase__   (      self      :			List[str]      ,      __snake_case      :			Optional[int]  )    ->				Tuple:
												_lowerCAmelCase												=							[]
												_lowerCAmelCase												=							""""""
												for token in tokens:
																		# make sure that special tokens are not decoded using sentencepiece model
																		if token in self.all_special_tokens:
																								out_string += self.sp_model.decode(__snake_case  ) + token
																								_lowerCAmelCase												=							[]
																		else:
																								current_sub_tokens.append(__snake_case  )
												out_string += self.sp_model.decode(__snake_case  )
												return out_string.strip()




						def     lowercase__   (      self      :			Any      ,      __snake_case      :			List[int]      ,      __snake_case      :			Optional[List[int]] = None      ,      __snake_case      :			bool = False  )    ->				List[int]:

												if already_has_special_tokens:
																		return super().get_special_tokens_mask(
																		    token_ids_a=__snake_case      ,      token_ids_a=__snake_case      ,      already_has_special_tokens=__snake_case  )

												_lowerCAmelCase												=							[1] * len(self.prefix_tokens  )
												_lowerCAmelCase												=							[1] * len(self.suffix_tokens  )
												if token_ids_a is None:
																		return prefix_ones + ([0] * len(__snake_case  )) + suffix_ones
												return prefix_ones + ([0] * len(__snake_case  )) + ([0] * len(__snake_case  )) + suffix_ones




						def     lowercase__   (      self      :			Union[str, Any]      ,      __snake_case      :			List[int]      ,      __snake_case      :			Optional[List[int]] = None  )    ->				List[int]:
												if token_ids_a is None:
																		return self.prefix_tokens + token_ids_a + self.suffix_tokens
												# We don't expect to process pairs, but leave the pair logic for API consistency
												return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens




						def     lowercase__   (      self      :			List[Any]  )    ->				Dict:
												_lowerCAmelCase												=							{self.convert_ids_to_tokens(__snake_case  ): i for i in range(self.vocab_size  )}
												vocab.update(self.added_tokens_encoder  )
												return vocab




						def __getstate__(      self      :			List[Any]  )    ->				Dict:
												_lowerCAmelCase												=							self.__dict__.copy()
												_lowerCAmelCase												=							None
												return state




						def __setstate__(      self      :			Optional[int]      ,      __snake_case      :			Dict  )    ->				None:
												_lowerCAmelCase												=							d

												# for backward compatibility
												if not hasattr(self      ,      """sp_model_kwargs"""  ):
																		_lowerCAmelCase												=							{}

												_lowerCAmelCase												=							load_spm(self.spm_file      ,      self.sp_model_kwargs  )




						def     lowercase__   (      self      :			List[str]      ,      __snake_case      :			str      ,      __snake_case      :			Optional[str] = None  )    ->				Tuple[str]:
												_lowerCAmelCase												=							Path(__snake_case  )
												if not save_dir.is_dir():
																		raise OSError(f"{save_directory} should be a directory"  )
												_lowerCAmelCase												=							save_dir / (
												    (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""]
												)
												_lowerCAmelCase												=							save_dir / (
												    (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""]
												)

												save_json(self.encoder      ,      __snake_case  )

												if os.path.abspath(self.spm_file  ) != os.path.abspath(__snake_case  ) and os.path.isfile(self.spm_file  ):
																		copyfile(self.spm_file      ,      __snake_case  )
												elif not os.path.isfile(self.spm_file  ):
																		with open(__snake_case      ,      """wb"""  ) as fi:
																								_lowerCAmelCase												=							self.sp_model.serialized_model_proto()
																								fi.write(__snake_case  )

												return (str(__snake_case  ), str(__snake_case  ))




						def     lowercase__   (      self      :			Tuple      ,      __snake_case      :			List[str]      ,      __snake_case      :			str = "en"      ,      __snake_case      :			Optional[List[str]] = None      ,      __snake_case      :			str = "ro"      ,      **__snake_case      :			Tuple      ,      )    ->				BatchEncoding:
												_lowerCAmelCase												=							src_lang
												_lowerCAmelCase												=							tgt_lang
												self.set_src_lang_special_tokens(self.src_lang  )
												return super().prepare_seqaseq_batch(__snake_case      ,      __snake_case      ,      **__snake_case  )




						def     lowercase__   (      self      :			int      ,      __snake_case      :			List[Any]      ,      __snake_case      :			Optional[str]      ,      __snake_case      :			Optional[str]      ,      **__snake_case      :			Optional[Any]  )    ->				int:
												if src_lang is None or tgt_lang is None:
																		raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""  )
												_lowerCAmelCase												=							src_lang
												_lowerCAmelCase												=							self(__snake_case      ,      add_special_tokens=__snake_case      ,      **__snake_case  )
												_lowerCAmelCase												=							self.get_lang_id(__snake_case  )
												_lowerCAmelCase												=							tgt_lang_id
												return inputs




						def     lowercase__   (      self      :			List[Any]  )    ->				Optional[Any]:
												self.set_src_lang_special_tokens(self.src_lang  )




						def     lowercase__   (      self      :			Any  )    ->				int:
												self.set_tgt_lang_special_tokens(self.tgt_lang  )




						def     lowercase__   (      self      :			Optional[Any]      ,      __snake_case      :			str  )    ->				None:
												_lowerCAmelCase												=							self.get_lang_token(__snake_case  )
												_lowerCAmelCase												=							self.lang_token_to_id[lang_token]
												_lowerCAmelCase												=							[self.cur_lang_id]
												_lowerCAmelCase												=							[self.eos_token_id]




						def     lowercase__   (      self      :			Any      ,      __snake_case      :			str  )    ->				None:
												_lowerCAmelCase												=							self.get_lang_token(__snake_case  )
												_lowerCAmelCase												=							self.lang_token_to_id[lang_token]
												_lowerCAmelCase												=							[self.cur_lang_id]
												_lowerCAmelCase												=							[self.eos_token_id]




						def     lowercase__   (      self      :			List[Any]      ,      __snake_case      :			str  )    ->				str:
												return self.lang_code_to_token[lang]




						def     lowercase__   (      self      :			int      ,      __snake_case      :			str  )    ->				int:
												_lowerCAmelCase												=							self.get_lang_token(__snake_case  )
												return self.lang_token_to_id[lang_token]




def        UpperCamelCase__				(		lowerCAmelCase							,     lowerCAmelCase  ):





						"""simple docstring"""


						_lowerCAmelCase												=							sentencepiece.SentencePieceProcessor(**lowerCAmelCase  )
						spm.Load(str(lowerCAmelCase  )  )
						return spm
def        UpperCamelCase__				(		lowerCAmelCase  ):





						"""simple docstring"""


						with open(lowerCAmelCase							,     """r"""  ) as f:
												return json.load(lowerCAmelCase  )





def        UpperCamelCase__				(		lowerCAmelCase							,     lowerCAmelCase  ):





						"""simple docstring"""


						with open(lowerCAmelCase							,     """w"""  ) as f:
												json.dump(lowerCAmelCase							,     lowerCAmelCase							,     indent=2  )













'''simple docstring'''






import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
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


enable_full_determinism()




class 			UpperCAmelCase					(      unittest.TestCase       ):




      def     lowercase__   (      self      :			Optional[int]  )    ->				Dict:
            # clean up the VRAM after each test
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()




      @property
      def     lowercase__   (      self      :			List[Any]  )    ->				List[str]:
            _lowerCAmelCase												=							1
            _lowerCAmelCase												=							3
            _lowerCAmelCase												=							(32, 32)

            _lowerCAmelCase												=							floats_tensor((batch_size, num_channels) + sizes      ,      rng=random.Random(0  )  ).to(__snake_case  )
            return image




      @property
      def     lowercase__   (      self      :			int  )    ->				Union[str, Any]:
            torch.manual_seed(0  )
            _lowerCAmelCase												=							UNetaDConditionModel(
                block_out_channels=(32, 64)      ,      layers_per_block=2      ,      sample_size=32      ,      in_channels=4      ,      out_channels=4      ,      down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")      ,      up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")      ,      cross_attention_dim=32      ,      )
            return model




      @property
      def     lowercase__   (      self      :			Optional[int]  )    ->				List[str]:
            torch.manual_seed(0  )
            _lowerCAmelCase												=							AutoencoderKL(
                block_out_channels=[32, 64]      ,      in_channels=3      ,      out_channels=3      ,      down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]      ,      up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]      ,      latent_channels=4      ,      )
            return model




      @property
      def     lowercase__   (      self      :			Dict  )    ->				Optional[Any]:
            torch.manual_seed(0  )
            _lowerCAmelCase												=							RobertaSeriesConfig(
                hidden_size=32      ,      project_dim=32      ,      intermediate_size=37      ,      layer_norm_eps=1E-0_5      ,      num_attention_heads=4      ,      num_hidden_layers=5      ,      pad_token_id=1      ,      vocab_size=50_06      ,      )
            return RobertaSeriesModelWithTransformation(__snake_case  )




      @property
      def     lowercase__   (      self      :			Union[str, Any]  )    ->				str:
            def extract(*__snake_case      :			List[Any]      ,      **__snake_case      :			Any  ):




                  class 			UpperCAmelCase					:




                        def __init__(      self      :			Any  )    ->				Any:
                              _lowerCAmelCase												=							torch.ones([0]  )




                        def     lowercase__   (      self      :			Optional[Any]      ,      __snake_case      :			Tuple  )    ->				Dict:
                              self.pixel_values.to(__snake_case  )
                              return self




                  return Out()

            return extract




      def     lowercase__   (      self      :			List[str]  )    ->				Optional[int]:
            _lowerCAmelCase												=							"""cpu"""  # ensure determinism for the device-dependent torch.Generator
            _lowerCAmelCase												=							self.dummy_cond_unet
            _lowerCAmelCase												=							PNDMScheduler(skip_prk_steps=__snake_case  )
            _lowerCAmelCase												=							self.dummy_vae
            _lowerCAmelCase												=							self.dummy_text_encoder
            _lowerCAmelCase												=							XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""  )
            _lowerCAmelCase												=							77

            _lowerCAmelCase												=							self.dummy_image.to(__snake_case  )
            _lowerCAmelCase												=							init_image / 2 + 0.5

            # make sure here that pndm scheduler skips prk
            _lowerCAmelCase												=							AltDiffusionImgaImgPipeline(
                unet=__snake_case      ,      scheduler=__snake_case      ,      vae=__snake_case      ,      text_encoder=__snake_case      ,      tokenizer=__snake_case      ,      safety_checker=__snake_case      ,      feature_extractor=self.dummy_extractor      ,      )
            _lowerCAmelCase												=							VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor      ,      do_normalize=__snake_case  )
            _lowerCAmelCase												=							alt_pipe.to(__snake_case  )
            alt_pipe.set_progress_bar_config(disable=__snake_case  )

            _lowerCAmelCase												=							"""A painting of a squirrel eating a burger"""
            _lowerCAmelCase												=							torch.Generator(device=__snake_case  ).manual_seed(0  )
            _lowerCAmelCase												=							alt_pipe(
                [prompt]      ,      generator=__snake_case      ,      guidance_scale=6.0      ,      num_inference_steps=2      ,      output_type="""np"""      ,      image=__snake_case      ,      )

            _lowerCAmelCase												=							output.images

            _lowerCAmelCase												=							torch.Generator(device=__snake_case  ).manual_seed(0  )
            _lowerCAmelCase												=							alt_pipe(
                [prompt]      ,      generator=__snake_case      ,      guidance_scale=6.0      ,      num_inference_steps=2      ,      output_type="""np"""      ,      image=__snake_case      ,      return_dict=__snake_case      ,      )[0]

            _lowerCAmelCase												=							image[0, -3:, -3:, -1]
            _lowerCAmelCase												=							image_from_tuple[0, -3:, -3:, -1]

            assert image.shape == (1, 32, 32, 3)
            _lowerCAmelCase												=							np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99]  )

            assert np.abs(image_slice.flatten() - expected_slice  ).max() < 5E-3
            assert np.abs(image_from_tuple_slice.flatten() - expected_slice  ).max() < 5E-3




      @unittest.skipIf(torch_device != """cuda"""      ,      """This test requires a GPU"""  )
      def     lowercase__   (      self      :			Tuple  )    ->				str:
            _lowerCAmelCase												=							self.dummy_cond_unet
            _lowerCAmelCase												=							PNDMScheduler(skip_prk_steps=__snake_case  )
            _lowerCAmelCase												=							self.dummy_vae
            _lowerCAmelCase												=							self.dummy_text_encoder
            _lowerCAmelCase												=							XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""  )
            _lowerCAmelCase												=							77

            _lowerCAmelCase												=							self.dummy_image.to(__snake_case  )

            # put models in fp16
            _lowerCAmelCase												=							unet.half()
            _lowerCAmelCase												=							vae.half()
            _lowerCAmelCase												=							bert.half()

            # make sure here that pndm scheduler skips prk
            _lowerCAmelCase												=							AltDiffusionImgaImgPipeline(
                unet=__snake_case      ,      scheduler=__snake_case      ,      vae=__snake_case      ,      text_encoder=__snake_case      ,      tokenizer=__snake_case      ,      safety_checker=__snake_case      ,      feature_extractor=self.dummy_extractor      ,      )
            _lowerCAmelCase												=							VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor      ,      do_normalize=__snake_case  )
            _lowerCAmelCase												=							alt_pipe.to(__snake_case  )
            alt_pipe.set_progress_bar_config(disable=__snake_case  )

            _lowerCAmelCase												=							"""A painting of a squirrel eating a burger"""
            _lowerCAmelCase												=							torch.manual_seed(0  )
            _lowerCAmelCase												=							alt_pipe(
                [prompt]      ,      generator=__snake_case      ,      num_inference_steps=2      ,      output_type="""np"""      ,      image=__snake_case      ,      ).images

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




      @unittest.skipIf(torch_device != """cuda"""      ,      """This test requires a GPU"""  )
      def     lowercase__   (      self      :			Optional[Any]  )    ->				Optional[Any]:
            _lowerCAmelCase												=							load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                """/img2img/sketch-mountains-input.jpg"""  )
            # resize to resolution that is divisible by 8 but not 16 or 32
            _lowerCAmelCase												=							init_image.resize((7_60, 5_04)  )

            _lowerCAmelCase												=							"""BAAI/AltDiffusion"""
            _lowerCAmelCase												=							AltDiffusionImgaImgPipeline.from_pretrained(
                __snake_case      ,      safety_checker=__snake_case      ,      )
            pipe.to(__snake_case  )
            pipe.set_progress_bar_config(disable=__snake_case  )
            pipe.enable_attention_slicing()

            _lowerCAmelCase												=							"""A fantasy landscape, trending on artstation"""

            _lowerCAmelCase												=							torch.manual_seed(0  )
            _lowerCAmelCase												=							pipe(
                prompt=__snake_case      ,      image=__snake_case      ,      strength=0.75      ,      guidance_scale=7.5      ,      generator=__snake_case      ,      output_type="""np"""      ,      )
            _lowerCAmelCase												=							output.images[0]

            _lowerCAmelCase												=							image[2_55:2_58, 3_83:3_86, -1]

            assert image.shape == (5_04, 7_60, 3)
            _lowerCAmelCase												=							np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00]  )

            assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1E-2




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




      def     lowercase__   (      self      :			int  )    ->				Any:
            # clean up the VRAM after each test
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()




      def     lowercase__   (      self      :			Dict  )    ->				Tuple:
            _lowerCAmelCase												=							load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                """/img2img/sketch-mountains-input.jpg"""  )
            _lowerCAmelCase												=							init_image.resize((7_68, 5_12)  )
            _lowerCAmelCase												=							load_numpy(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""  )

            _lowerCAmelCase												=							"""BAAI/AltDiffusion"""
            _lowerCAmelCase												=							AltDiffusionImgaImgPipeline.from_pretrained(
                __snake_case      ,      safety_checker=__snake_case      ,      )
            pipe.to(__snake_case  )
            pipe.set_progress_bar_config(disable=__snake_case  )
            pipe.enable_attention_slicing()

            _lowerCAmelCase												=							"""A fantasy landscape, trending on artstation"""

            _lowerCAmelCase												=							torch.manual_seed(0  )
            _lowerCAmelCase												=							pipe(
                prompt=__snake_case      ,      image=__snake_case      ,      strength=0.75      ,      guidance_scale=7.5      ,      generator=__snake_case      ,      output_type="""np"""      ,      )
            _lowerCAmelCase												=							output.images[0]

            assert image.shape == (5_12, 7_68, 3)
            # img2img is flaky across GPUs even in fp32, so using MAE here
            assert np.abs(expected_image - image  ).max() < 1E-2






