





import gc
import unittest

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

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, 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


enable_full_determinism()
class      UpperCamelCase_						(					_lowerCamelCase							,					_lowerCamelCase							,					_lowerCamelCase							,					unittest.TestCase   ):
     lowerCAmelCase_							=		AltDiffusionPipeline
     lowerCAmelCase_							=		TEXT_TO_IMAGE_PARAMS
     lowerCAmelCase_							=		TEXT_TO_IMAGE_BATCH_PARAMS
     lowerCAmelCase_							=		TEXT_TO_IMAGE_IMAGE_PARAMS
     lowerCAmelCase_							=		TEXT_TO_IMAGE_IMAGE_PARAMS




     def 		lowerCAmelCase     (						self					)						->							Optional[Any]:
          torch.manual_seed(0					)
          _snake_case													=			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			,  )
          _snake_case													=			DDIMScheduler(
              beta_start=0.0_00_85			,  beta_end=0.0_12			,  beta_schedule='scaled_linear'			,  clip_sample=lowerCAmelCase_			,  set_alpha_to_one=lowerCAmelCase_			,  )
          torch.manual_seed(0					)
          _snake_case													=			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			,  )

          # TODO: address the non-deterministic text encoder (fails for save-load tests)
          # torch.manual_seed(0)
          # text_encoder_config = RobertaSeriesConfig(
          #     hidden_size=32,
          #     project_dim=32,
          #     intermediate_size=37,
          #     layer_norm_eps=1e-05,
          #     num_attention_heads=4,
          #     num_hidden_layers=5,
          #     vocab_size=5002,
          # )
          # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

          torch.manual_seed(0					)
          _snake_case													=			CLIPTextConfig(
              bos_token_id=0			,  eos_token_id=2			,  hidden_size=32			,  projection_dim=32			,  intermediate_size=37			,  layer_norm_eps=1E-05			,  num_attention_heads=4			,  num_hidden_layers=5			,  pad_token_id=1			,  vocab_size=5002			,  )
          _snake_case													=			CLIPTextModel(lowerCAmelCase_					)

          _snake_case													=			XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'					)
          _snake_case													=			77

          _snake_case													=			{
              'unet': unet,
              'scheduler': scheduler,
              'vae': vae,
              'text_encoder': text_encoder,
              'tokenizer': tokenizer,
              'safety_checker': None,
              'feature_extractor': None,
          }
          return components




     def 		lowerCAmelCase     (						self			,  lowerCAmelCase_			,  lowerCAmelCase_=0					)						->							List[str]:
          if str(lowerCAmelCase_					).startswith('mps'					):
               _snake_case													=			torch.manual_seed(lowerCAmelCase_					)
          else:
               _snake_case													=			torch.Generator(device=lowerCAmelCase_					).manual_seed(lowerCAmelCase_					)
          _snake_case													=			{
              'prompt': 'A painting of a squirrel eating a burger',
              'generator': generator,
              'num_inference_steps': 2,
              'guidance_scale': 6.0,
              'output_type': 'numpy',
          }
          return inputs




     def 		lowerCAmelCase     (						self					)						->							List[str]:
          super().test_attention_slicing_forward_pass(expected_max_diff=3E-3					)




     def 		lowerCAmelCase     (						self					)						->							Optional[Any]:
          super().test_inference_batch_single_identical(expected_max_diff=3E-3					)




     def 		lowerCAmelCase     (						self					)						->							List[str]:
          _snake_case													=			'cpu'  # ensure determinism for the device-dependent torch.Generator

          _snake_case													=			self.get_dummy_components()
          torch.manual_seed(0					)
          _snake_case													=			RobertaSeriesConfig(
              hidden_size=32			,  project_dim=32			,  intermediate_size=37			,  layer_norm_eps=1E-05			,  num_attention_heads=4			,  num_hidden_layers=5			,  vocab_size=5002			,  )
          # TODO: remove after fixing the non-deterministic text encoder
          _snake_case													=			RobertaSeriesModelWithTransformation(lowerCAmelCase_					)
          _snake_case													=			text_encoder

          _snake_case													=			AltDiffusionPipeline(**lowerCAmelCase_					)
          _snake_case													=			alt_pipe.to(lowerCAmelCase_					)
          alt_pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

          _snake_case													=			self.get_dummy_inputs(lowerCAmelCase_					)
          _snake_case													=			'A photo of an astronaut'
          _snake_case													=			alt_pipe(**lowerCAmelCase_					)
          _snake_case													=			output.images
          _snake_case													=			image[0, -3:, -3:, -1]

          assert image.shape == (1, 64, 64, 3)
          _snake_case													=			np.array(
              [0.5_74_81_62, 0.60_44_71_45, 0.48_82_12_17, 0.50_10_06_36, 0.5_43_11_85, 0.45_76_36_83, 0.49_65_76_96, 0.48_13_27_33, 0.47_57_30_93]					)

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






     def 		lowerCAmelCase     (						self					)						->							str:
          _snake_case													=			'cpu'  # ensure determinism for the device-dependent torch.Generator

          _snake_case													=			self.get_dummy_components()
          _snake_case													=			PNDMScheduler(skip_prk_steps=lowerCAmelCase_					)
          torch.manual_seed(0					)
          _snake_case													=			RobertaSeriesConfig(
              hidden_size=32			,  project_dim=32			,  intermediate_size=37			,  layer_norm_eps=1E-05			,  num_attention_heads=4			,  num_hidden_layers=5			,  vocab_size=5002			,  )
          # TODO: remove after fixing the non-deterministic text encoder
          _snake_case													=			RobertaSeriesModelWithTransformation(lowerCAmelCase_					)
          _snake_case													=			text_encoder
          _snake_case													=			AltDiffusionPipeline(**lowerCAmelCase_					)
          _snake_case													=			alt_pipe.to(lowerCAmelCase_					)
          alt_pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

          _snake_case													=			self.get_dummy_inputs(lowerCAmelCase_					)
          _snake_case													=			alt_pipe(**lowerCAmelCase_					)
          _snake_case													=			output.images
          _snake_case													=			image[0, -3:, -3:, -1]

          assert image.shape == (1, 64, 64, 3)
          _snake_case													=			np.array(
              [0.51_60_50_93, 0.5_70_72_41, 0.47_36_55_07, 0.50_57_88_86, 0.5_63_38_77, 0.4_64_25_03, 0.5_18_20_81, 0.48_76_34_84, 0.49_08_42_37]					)

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





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




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




     def 		lowerCAmelCase     (						self					)						->							Tuple:
          # make sure here that pndm scheduler skips prk
          _snake_case													=			AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion'			,  safety_checker=lowerCAmelCase_					)
          _snake_case													=			alt_pipe.to(lowerCAmelCase_					)
          alt_pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

          _snake_case													=			'A painting of a squirrel eating a burger'
          _snake_case													=			torch.manual_seed(0					)
          _snake_case													=			alt_pipe([prompt]			,  generator=lowerCAmelCase_			,  guidance_scale=6.0			,  num_inference_steps=20			,  output_type='np'					)

          _snake_case													=			output.images

          _snake_case													=			image[0, -3:, -3:, -1]

          assert image.shape == (1, 512, 512, 3)
          _snake_case													=			np.array([0.10_10, 0.08_00, 0.07_94, 0.08_85, 0.08_43, 0.07_62, 0.07_69, 0.07_29, 0.05_86]					)

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






     def 		lowerCAmelCase     (						self					)						->							List[Any]:
          _snake_case													=			DDIMScheduler.from_pretrained('BAAI/AltDiffusion'			,  subfolder='scheduler'					)

          _snake_case													=			AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion'			,  scheduler=lowerCAmelCase_			,  safety_checker=lowerCAmelCase_					)
          _snake_case													=			alt_pipe.to(lowerCAmelCase_					)
          alt_pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

          _snake_case													=			'A painting of a squirrel eating a burger'
          _snake_case													=			torch.manual_seed(0					)

          _snake_case													=			alt_pipe([prompt]			,  generator=lowerCAmelCase_			,  num_inference_steps=2			,  output_type='numpy'					)
          _snake_case													=			output.images

          _snake_case													=			image[0, -3:, -3:, -1]

          assert image.shape == (1, 512, 512, 3)
          _snake_case													=			np.array([0.40_19, 0.40_52, 0.38_10, 0.41_19, 0.39_16, 0.39_82, 0.46_51, 0.41_95, 0.53_23]					)

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










from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging


UpperCAmelCase_ 							=       logging.get_logger(__name__)

UpperCAmelCase_ 							=       {
    """EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
    # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class      UpperCamelCase_						(					_lowerCamelCase   ):
					lowerCAmelCase_							=		'''gpt_neo'''
					lowerCAmelCase_							=		['''past_key_values''']
					lowerCAmelCase_							=		{'''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''}




					def __init__(						self			,  lowerCAmelCase_=5_0257			,  lowerCAmelCase_=2048			,  lowerCAmelCase_=2048			,  lowerCAmelCase_=24			,  lowerCAmelCase_=[[["global", "local"], 12]]			,  lowerCAmelCase_=16			,  lowerCAmelCase_=None			,  lowerCAmelCase_=256			,  lowerCAmelCase_="gelu_new"			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=0.1			,  lowerCAmelCase_=1E-5			,  lowerCAmelCase_=0.02			,  lowerCAmelCase_=True			,  lowerCAmelCase_=5_0256			,  lowerCAmelCase_=5_0256			,  **lowerCAmelCase_			,  )						->							Tuple:
										_snake_case													=			vocab_size
										_snake_case													=			max_position_embeddings
										_snake_case													=			hidden_size
										_snake_case													=			num_layers
										_snake_case													=			num_heads
										_snake_case													=			intermediate_size
										_snake_case													=			window_size
										_snake_case													=			activation_function
										_snake_case													=			resid_dropout
										_snake_case													=			embed_dropout
										_snake_case													=			attention_dropout
										_snake_case													=			classifier_dropout
										_snake_case													=			layer_norm_epsilon
										_snake_case													=			initializer_range
										_snake_case													=			use_cache

										_snake_case													=			bos_token_id
										_snake_case													=			eos_token_id

										_snake_case													=			attention_types
										_snake_case													=			self.expand_attention_types_params(lowerCAmelCase_					)

										if len(self.attention_layers					) != self.num_layers:
															raise ValueError(
															    'Configuration for convolutional module is incorrect. '
															    'It is required that `len(config.attention_layers)` == `config.num_layers` '
															    F'''but is `len(config.attention_layers) = {len(self.attention_layers					)}`, '''
															    F'''`config.num_layers = {self.num_layers}`. '''
															    '`config.attention_layers` is prepared using `config.attention_types`. '
															    'Please verify the value of `config.attention_types` argument.'					)

										super().__init__(bos_token_id=lowerCAmelCase_			,  eos_token_id=lowerCAmelCase_			,  **lowerCAmelCase_					)






					@staticmethod
					def 		lowerCAmelCase     (						lowerCAmelCase_					)						->							Any:
										_snake_case													=			[]
										for item in attention_types:
															for _ in range(item[1]					):
																				attentions.extend(item[0]					)
										return attentions





def   lowerCamelCase__       (       UpperCamelCase__     :    Tuple    ,      UpperCamelCase__     :    int    ,      UpperCamelCase__     :    Tuple    ,      UpperCamelCase__     :    Optional[int]  )     ->	Any:



					'''simple docstring'''




					import torch

					_snake_case													=			input.size()
					_snake_case													=			len(UpperCamelCase__  )
					_snake_case													=			shape[dimension]

					_snake_case													=			torch.arange(0    ,      UpperCamelCase__    ,      UpperCamelCase__  )
					_snake_case													=			torch.div(sizedim - size    ,      UpperCamelCase__    ,      rounding_mode='floor'  ) + 1
					_snake_case													=			torch.arange(UpperCamelCase__  ) + low_indices[:min_length][:, None]

					_snake_case													=			[slice(UpperCamelCase__  )] * rank
					_snake_case													=			indices
					_snake_case													=			input[s]

					_snake_case													=			list(range(0    ,      rank + 1  )  )
					perm.append(perm.pop(dimension + 1  )  )

					return sliced.permute(UpperCamelCase__  )





def   lowerCamelCase__       (       UpperCamelCase__     :    Tuple    ,      UpperCamelCase__     :    Dict  )     ->	str:



					'''simple docstring'''




					import torch

					_snake_case													=			torch.arange(1    ,      UpperCamelCase__  )
					_snake_case													=			torch.remainder(UpperCamelCase__    ,      UpperCamelCase__  )
					_snake_case													=			remainders == 0
					_snake_case													=			candidates[divisor_indices]
					_snake_case													=			torch.max(UpperCamelCase__  )
					return largest_divisor, torch.div(UpperCamelCase__    ,      UpperCamelCase__    ,      rounding_mode='floor'  )




class      UpperCamelCase_						(					_lowerCamelCase   ):




					@property
					def 		lowerCAmelCase     (						self					)						->							Mapping[str, Mapping[int, str]]:
										_snake_case													=			OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}					)
										if self.use_past:
															self.fill_with_past_key_values_(lowerCAmelCase_			,  direction='inputs'					)
															_snake_case													=			{0: 'batch', 1: 'past_sequence + sequence'}
										else:
															_snake_case													=			{0: 'batch', 1: 'sequence'}

										return common_inputs




					@property
					def 		lowerCAmelCase     (						self					)						->							int:
										return self._config.num_heads




					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_			,  lowerCAmelCase_ = -1			,  lowerCAmelCase_ = -1			,  lowerCAmelCase_ = False			,  lowerCAmelCase_ = None			,  )						->							Mapping[str, Any]:
										_snake_case													=			super(lowerCAmelCase_			,  self					).generate_dummy_inputs(
										    lowerCAmelCase_			,  batch_size=lowerCAmelCase_			,  seq_length=lowerCAmelCase_			,  is_pair=lowerCAmelCase_			,  framework=lowerCAmelCase_					)

										# We need to order the input in the way they appears in the forward()
										_snake_case													=			OrderedDict({'input_ids': common_inputs['input_ids']}					)

										# Need to add the past_keys
										if self.use_past:
															if not is_torch_available():
																				raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'					)
															else:
																				import torch

																				_snake_case							,       _snake_case													=			common_inputs['input_ids'].shape
																				# Not using the same length for past_key_values
																				_snake_case													=			seqlen + 2
																				_snake_case													=			(
																				    batch,
																				    self.num_attention_heads,
																				    past_key_values_length,
																				    self._config.hidden_size // self.num_attention_heads,
																				)
																				_snake_case													=			[
																				    (torch.zeros(lowerCAmelCase_					), torch.zeros(lowerCAmelCase_					)) for _ in range(self.num_layers					)
																				]

										_snake_case													=			common_inputs['attention_mask']
										if self.use_past:
															_snake_case													=			ordered_inputs['attention_mask'].dtype
															_snake_case													=			torch.cat(
															    [ordered_inputs['attention_mask'], torch.ones(lowerCAmelCase_			,  lowerCAmelCase_			,  dtype=lowerCAmelCase_					)]			,  dim=1					)

										return ordered_inputs






					@property
					def 		lowerCAmelCase     (						self					)						->							int:
										return 13



