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       __lowerCAmelCase      (						A_   : Tuple						,	A_   : Optional[Any]						,	A_   : int						,	A_   : Optional[Any]=None						,	A_   : Union[str, Any]=None						,	A_   : Tuple=None						,	A_   : List[Any]=None						,	A_   : Optional[Any]=None						,	)    ->  Optional[int]:
  if attention_mask is None:
    __UpperCAmelCase						    =       input_ids.ne(config.pad_token_id					)
  if decoder_attention_mask is None:
    __UpperCAmelCase						    =       decoder_input_ids.ne(config.pad_token_id					)
  if head_mask is None:
    __UpperCAmelCase						    =       torch.ones(config.encoder_layers						,	config.encoder_attention_heads						,	device=A_					)
  if decoder_head_mask is None:
    __UpperCAmelCase						    =       torch.ones(config.decoder_layers						,	config.decoder_attention_heads						,	device=A_					)
  if cross_attn_head_mask is None:
    __UpperCAmelCase						    =       torch.ones(config.decoder_layers						,	config.decoder_attention_heads						,	device=A_					)
  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 			UpperCAmelCase__    :



  """simple docstring"""






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




    '''simple docstring'''




    __UpperCAmelCase						    =       parent
    __UpperCAmelCase						    =       batch_size
    __UpperCAmelCase						    =       seq_length
    __UpperCAmelCase						    =       is_training
    __UpperCAmelCase						    =       use_labels
    __UpperCAmelCase						    =       vocab_size
    __UpperCAmelCase						    =       hidden_size
    __UpperCAmelCase						    =       num_hidden_layers
    __UpperCAmelCase						    =       num_attention_heads
    __UpperCAmelCase						    =       intermediate_size
    __UpperCAmelCase						    =       hidden_act
    __UpperCAmelCase						    =       hidden_dropout_prob
    __UpperCAmelCase						    =       attention_probs_dropout_prob
    __UpperCAmelCase						    =       encoder_layerdrop
    __UpperCAmelCase						    =       decoder_layerdrop
    __UpperCAmelCase						    =       max_position_embeddings
    __UpperCAmelCase						    =       eos_token_id
    __UpperCAmelCase						    =       pad_token_id
    __UpperCAmelCase						    =       bos_token_id






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




    '''simple docstring'''




    __UpperCAmelCase						    =       ids_tensor([self.batch_size, self.seq_length]				,				self.vocab_size   )
    __UpperCAmelCase						    =       self.eos_token_id  # Eos Token
    __UpperCAmelCase						    =       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
    __UpperCAmelCase						    =       input_ids.clamp(self.pad_token_id + 1   )
    __UpperCAmelCase						    =       decoder_input_ids.clamp(self.pad_token_id + 1   )

    __UpperCAmelCase						    =       self.get_config()
    __UpperCAmelCase						    =       prepare_mam_aaa_inputs_dict(__lowerCAmelCase				,				__lowerCAmelCase				,				__lowerCAmelCase   )
    return config, inputs_dict






  def 	_UpperCAmelCase				(				self:			Dict   ) -> Optional[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 	_UpperCAmelCase				(				self:			int   ) -> Tuple:




    '''simple docstring'''




    __UpperCAmelCase    ,		__UpperCAmelCase						    =       self.prepare_config_and_inputs()
    return config, inputs_dict






  def 	_UpperCAmelCase				(				self:			int				,				__lowerCAmelCase:			str				,				__lowerCAmelCase:			Tuple   ) -> Dict:




    '''simple docstring'''




    __UpperCAmelCase						    =       MaMaaaModel(config=__lowerCAmelCase   ).get_decoder().to(__lowerCAmelCase   ).eval()
    __UpperCAmelCase						    =       inputs_dict["input_ids"]
    __UpperCAmelCase						    =       inputs_dict["attention_mask"]
    __UpperCAmelCase						    =       inputs_dict["head_mask"]

    # first forward pass
    __UpperCAmelCase						    =       model(__lowerCAmelCase				,				attention_mask=__lowerCAmelCase				,				head_mask=__lowerCAmelCase				,				use_cache=__lowerCAmelCase   )

    __UpperCAmelCase    ,		__UpperCAmelCase						    =       outputs.to_tuple()

    # create hypothetical multiple next token and extent to next_input_ids
    __UpperCAmelCase						    =       ids_tensor((self.batch_size, 3)				,				config.vocab_size   )
    __UpperCAmelCase						    =       ids_tensor((self.batch_size, 3)				,				2   )

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

    __UpperCAmelCase						    =       model(__lowerCAmelCase				,				attention_mask=__lowerCAmelCase   )["last_hidden_state"]
    __UpperCAmelCase						    =       model(__lowerCAmelCase				,				attention_mask=__lowerCAmelCase				,				past_key_values=__lowerCAmelCase   )[
        "last_hidden_state"
    ]

    # select random slice
    __UpperCAmelCase						    =       ids_tensor((1,)				,				output_from_past.shape[-1]   ).item()
    __UpperCAmelCase						    =       output_from_no_past[:, -3:, random_slice_idx].detach()
    __UpperCAmelCase						    =       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(__lowerCAmelCase				,				__lowerCAmelCase				,				atol=1E-2   )   )






  def 	_UpperCAmelCase				(				self:			Union[str, Any]				,				__lowerCAmelCase:			Dict				,				__lowerCAmelCase:			Optional[Any]   ) -> Dict:




    '''simple docstring'''




    __UpperCAmelCase						    =       MaMaaaModel(config=__lowerCAmelCase   ).to(__lowerCAmelCase   ).eval()
    __UpperCAmelCase						    =       model(**__lowerCAmelCase   )

    __UpperCAmelCase						    =       outputs.encoder_last_hidden_state
    __UpperCAmelCase						    =       outputs.last_hidden_state

    with tempfile.TemporaryDirectory() as tmpdirname:
      __UpperCAmelCase						    =       model.get_encoder()
      encoder.save_pretrained(__lowerCAmelCase   )
      __UpperCAmelCase						    =       MaMaaaEncoder.from_pretrained(__lowerCAmelCase   ).to(__lowerCAmelCase   )

    __UpperCAmelCase						    =       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:
      __UpperCAmelCase						    =       model.get_decoder()
      decoder.save_pretrained(__lowerCAmelCase   )
      __UpperCAmelCase						    =       MaMaaaDecoder.from_pretrained(__lowerCAmelCase   ).to(__lowerCAmelCase   )

    __UpperCAmelCase						    =       decoder(
        input_ids=inputs_dict["decoder_input_ids"]				,				attention_mask=inputs_dict["decoder_attention_mask"]				,				encoder_hidden_states=__lowerCAmelCase				,				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 			UpperCAmelCase__    (		snake_case		,	snake_case		,	snake_case		,	unittest.TestCase					):



  """simple docstring"""






  lowerCAmelCase__		:	Optional[Any]    		= (
      (
          MaMaaaModel,
          MaMaaaForConditionalGeneration,
      )
      if is_torch_available()
      else ()
  )
  lowerCAmelCase__		:	Optional[Any]    		= (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
  lowerCAmelCase__		:	Union[str, Any]    		= (
      {
          'conversational': MaMaaaForConditionalGeneration,
          'feature-extraction': MaMaaaModel,
          'summarization': MaMaaaForConditionalGeneration,
          'text2text-generation': MaMaaaForConditionalGeneration,
          'translation': MaMaaaForConditionalGeneration,
      }
      if is_torch_available()
      else {}
  )
  lowerCAmelCase__		:	int    		= True
  lowerCAmelCase__		:	Dict    		= True
  lowerCAmelCase__		:	int    		= False
  lowerCAmelCase__		:	Any    		= False






  def 	_UpperCAmelCase				(				self:			Tuple				,				__lowerCAmelCase:			Any				,				__lowerCAmelCase:			Union[str, Any]				,				__lowerCAmelCase:			Tuple				,				__lowerCAmelCase:			Optional[Any]				,				__lowerCAmelCase:			Optional[int]   ) -> Any:




    '''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 	_UpperCAmelCase				(				self:			Tuple   ) -> Optional[Any]:




    '''simple docstring'''




    __UpperCAmelCase						    =       MaMaaaModelTester(self   )
    __UpperCAmelCase						    =       ConfigTester(self				,				config_class=__lowerCAmelCase   )






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




    '''simple docstring'''




    self.config_tester.run_common_tests()






  def 	_UpperCAmelCase				(				self:			List[str]   ) -> Tuple:




    '''simple docstring'''




    __UpperCAmelCase    ,		__UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs()
    for model_class in self.all_model_classes:
      __UpperCAmelCase						    =       model_class(__lowerCAmelCase   )

      with tempfile.TemporaryDirectory() as tmpdirname:
        model.save_pretrained(__lowerCAmelCase   )
        __UpperCAmelCase    ,		__UpperCAmelCase						    =       model_class.from_pretrained(__lowerCAmelCase				,				output_loading_info=__lowerCAmelCase   )
      self.assertEqual(info["missing_keys"]				,				[]   )






  def 	_UpperCAmelCase				(				self:			Optional[int]   ) -> Optional[int]:




    '''simple docstring'''




    __UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_decoder_model_past_large_inputs(*__lowerCAmelCase   )






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




    '''simple docstring'''




    __UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs_for_common()
    self.model_tester.check_encoder_decoder_model_standalone(*__lowerCAmelCase   )






  def 	_UpperCAmelCase				(				self:			int   ) -> str:




    '''simple docstring'''




    __UpperCAmelCase    ,		__UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
      __UpperCAmelCase						    =       model_class(__lowerCAmelCase   )
      model.to(__lowerCAmelCase   )
      model.eval()

      __UpperCAmelCase						    =       copy.deepcopy(self._prepare_for_class(__lowerCAmelCase				,				__lowerCAmelCase   )   )

      if not self.is_encoder_decoder:
        __UpperCAmelCase						    =       inputs["input_ids"]
        del inputs["input_ids"]
      else:
        __UpperCAmelCase						    =       inputs["input_ids"]
        __UpperCAmelCase						    =       inputs.get("decoder_input_ids"				,				__lowerCAmelCase   )
        del inputs["input_ids"]
        inputs.pop("decoder_input_ids"				,				__lowerCAmelCase   )

      __UpperCAmelCase						    =       model.get_input_embeddings()
      if not self.is_encoder_decoder:
        __UpperCAmelCase						    =       wte(__lowerCAmelCase   )
      else:
        __UpperCAmelCase						    =       wte(__lowerCAmelCase   )
        __UpperCAmelCase						    =       wte(__lowerCAmelCase   )

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






  def 	_UpperCAmelCase				(				self:			Optional[int]   ) -> Optional[int]:




    '''simple docstring'''




    __UpperCAmelCase    ,		__UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs()
    __UpperCAmelCase						    =       input_dict["input_ids"]
    __UpperCAmelCase						    =       input_ids.ne(1   ).to(__lowerCAmelCase   )
    __UpperCAmelCase						    =       MaMaaaForConditionalGeneration(__lowerCAmelCase   ).eval().to(__lowerCAmelCase   )
    if torch_device == "cuda":
      model.half()
    model.generate(__lowerCAmelCase				,				attention_mask=__lowerCAmelCase   )
    model.generate(num_beams=4				,				do_sample=__lowerCAmelCase				,				early_stopping=__lowerCAmelCase				,				num_return_sequences=3   )






def       __lowerCAmelCase      (						A_   : Optional[Any]					)    ->  int:
  return torch.tensor(A_						,	dtype=torch.long						,	device=A_					)


a_							=      1e-4





@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 			UpperCAmelCase__    (		unittest.TestCase					):



  """simple docstring"""






  @cached_property
  def 	_UpperCAmelCase				(				self:			List[Any]   ) -> Dict:




    '''simple docstring'''




    return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"   )






  def 	_UpperCAmelCase				(				self:			Tuple   ) -> Tuple:




    '''simple docstring'''




    __UpperCAmelCase						    =       MaMaaaModel.from_pretrained("facebook/m2m100_418M"   ).to(__lowerCAmelCase   )
    __UpperCAmelCase						    =       _long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]   )
    __UpperCAmelCase						    =       _long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]   )
    __UpperCAmelCase						    =       prepare_mam_aaa_inputs_dict(model.config				,				__lowerCAmelCase				,				__lowerCAmelCase   )
    with torch.no_grad():
      __UpperCAmelCase						    =       model(**__lowerCAmelCase   )[0]
    __UpperCAmelCase						    =       torch.Size((1, 11, 1_024)   )
    self.assertEqual(output.shape				,				__lowerCAmelCase   )
    # change to expected output here
    __UpperCAmelCase						    =       torch.tensor(
        [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]				,				device=__lowerCAmelCase   )
    self.assertTrue(torch.allclose(output[:, :3, :3]				,				__lowerCAmelCase				,				atol=__lowerCAmelCase   )   )






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




    '''simple docstring'''




    __UpperCAmelCase						    =       MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"   ).to(__lowerCAmelCase   )

    # change to intended input
    __UpperCAmelCase						    =       _long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]   )
    __UpperCAmelCase						    =       _long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]   )
    __UpperCAmelCase						    =       prepare_mam_aaa_inputs_dict(model.config				,				__lowerCAmelCase				,				__lowerCAmelCase   )
    with torch.no_grad():
      __UpperCAmelCase						    =       model(**__lowerCAmelCase   )[0]
    __UpperCAmelCase						    =       torch.Size((1, 11, model.config.vocab_size)   )
    self.assertEqual(output.shape				,				__lowerCAmelCase   )
    # change to expected output here
    __UpperCAmelCase						    =       torch.tensor(
        [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]				,				device=__lowerCAmelCase   )
    self.assertTrue(torch.allclose(output[:, :3, :3]				,				__lowerCAmelCase				,				atol=__lowerCAmelCase   )   )






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




    '''simple docstring'''




    __UpperCAmelCase						    =       MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"   ).to(__lowerCAmelCase   )
    __UpperCAmelCase						    =       MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"				,				src_lang="fr"				,				tgt_lang="en"   )

    __UpperCAmelCase						    =       [
        "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
    __UpperCAmelCase						    =       tokenizer(__lowerCAmelCase				,				padding=__lowerCAmelCase				,				return_tensors="pt"   )

    __UpperCAmelCase						    =       model.generate(
        input_ids=dct["input_ids"].to(__lowerCAmelCase   )				,				attention_mask=dct["attention_mask"].to(__lowerCAmelCase   )				,				num_beams=5				,				forced_bos_token_id=tokenizer.get_lang_id("en"   )				,				)

    __UpperCAmelCase						    =       [
        "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.",
    ]

    __UpperCAmelCase						    =       tokenizer.batch_decode(
        hypotheses_batch.tolist()				,				clean_up_tokenization_spaces=__lowerCAmelCase				,				skip_special_tokens=__lowerCAmelCase   )
    assert generated == expected_en




import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class 			UpperCAmelCase__    (		snake_case		,	unittest.TestCase					):



  """simple docstring"""






  lowerCAmelCase__		:	int    		= DiTPipeline
  lowerCAmelCase__		:	Any    		= CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
  lowerCAmelCase__		:	Optional[Any]    		= PipelineTesterMixin.required_optional_params - {
      'latents',
      'num_images_per_prompt',
      'callback',
      'callback_steps',
  }
  lowerCAmelCase__		:	List[Any]    		= CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
  lowerCAmelCase__		:	Optional[int]    		= False






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




    '''simple docstring'''




    torch.manual_seed(0   )
    __UpperCAmelCase						    =       TransformeraDModel(
        sample_size=16				,				num_layers=2				,				patch_size=4				,				attention_head_dim=8				,				num_attention_heads=2				,				in_channels=4				,				out_channels=8				,				attention_bias=__lowerCAmelCase				,				activation_fn="gelu-approximate"				,				num_embeds_ada_norm=1_000				,				norm_type="ada_norm_zero"				,				norm_elementwise_affine=__lowerCAmelCase				,				)
    __UpperCAmelCase						    =       AutoencoderKL()
    __UpperCAmelCase						    =       DDIMScheduler()
    __UpperCAmelCase						    =       {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler}
    return components






  def 	_UpperCAmelCase				(				self:			str				,				__lowerCAmelCase:			str				,				__lowerCAmelCase:			Optional[int]=0   ) -> int:




    '''simple docstring'''




    if str(__lowerCAmelCase   ).startswith("mps"   ):
      __UpperCAmelCase						    =       torch.manual_seed(__lowerCAmelCase   )
    else:
      __UpperCAmelCase						    =       torch.Generator(device=__lowerCAmelCase   ).manual_seed(__lowerCAmelCase   )
    __UpperCAmelCase						    =       {
        "class_labels": [1],
        "generator": generator,
        "num_inference_steps": 2,
        "output_type": "numpy",
    }
    return inputs






  def 	_UpperCAmelCase				(				self:			Tuple   ) -> Dict:




    '''simple docstring'''




    __UpperCAmelCase						    =       "cpu"

    __UpperCAmelCase						    =       self.get_dummy_components()
    __UpperCAmelCase						    =       self.pipeline_class(**__lowerCAmelCase   )
    pipe.to(__lowerCAmelCase   )
    pipe.set_progress_bar_config(disable=__lowerCAmelCase   )

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

    self.assertEqual(image.shape				,				(1, 16, 16, 3)   )
    __UpperCAmelCase						    =       np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457]   )
    __UpperCAmelCase						    =       np.abs(image_slice.flatten() - expected_slice   ).max()
    self.assertLessEqual(__lowerCAmelCase				,				1E-3   )






  def 	_UpperCAmelCase				(				self:			int   ) -> str:




    '''simple docstring'''




    self._test_inference_batch_single_identical(relax_max_difference=__lowerCAmelCase				,				expected_max_diff=1E-3   )






  @unittest.skipIf(
      torch_device != "cuda" or not is_xformers_available()				,				reason="XFormers attention is only available with CUDA and `xformers` installed"				,				)
  def 	_UpperCAmelCase				(				self:			Optional[int]   ) -> str:




    '''simple docstring'''




    self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3   )






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



  """simple docstring"""






  def 	_UpperCAmelCase				(				self:			Any   ) -> Optional[Any]:




    '''simple docstring'''




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






  def 	_UpperCAmelCase				(				self:			Dict   ) -> List[Any]:




    '''simple docstring'''




    __UpperCAmelCase						    =       torch.manual_seed(0   )

    __UpperCAmelCase						    =       DiTPipeline.from_pretrained("facebook/DiT-XL-2-256"   )
    pipe.to("cuda"   )

    __UpperCAmelCase						    =       ["vase", "umbrella", "white shark", "white wolf"]
    __UpperCAmelCase						    =       pipe.get_label_ids(__lowerCAmelCase   )

    __UpperCAmelCase						    =       pipe(__lowerCAmelCase				,				generator=__lowerCAmelCase				,				num_inference_steps=40				,				output_type="np"   ).images

    for word, image in zip(__lowerCAmelCase				,				__lowerCAmelCase   ):
      __UpperCAmelCase						    =       load_numpy(
          F'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy'''   )
      assert np.abs((expected_image - image).max()   ) < 1E-2






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




    '''simple docstring'''




    __UpperCAmelCase						    =       DiTPipeline.from_pretrained("facebook/DiT-XL-2-512"   )
    __UpperCAmelCase						    =       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config   )
    pipe.to("cuda"   )

    __UpperCAmelCase						    =       ["vase", "umbrella"]
    __UpperCAmelCase						    =       pipe.get_label_ids(__lowerCAmelCase   )

    __UpperCAmelCase						    =       torch.manual_seed(0   )
    __UpperCAmelCase						    =       pipe(__lowerCAmelCase				,				generator=__lowerCAmelCase				,				num_inference_steps=25				,				output_type="np"   ).images

    for word, image in zip(__lowerCAmelCase				,				__lowerCAmelCase   ):
      __UpperCAmelCase						    =       load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          F'''/dit/{word}_512.npy'''   )

      assert np.abs((expected_image - image).max()   ) < 1E-1



