



'''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        lowerCAmelCase_(				unittest.TestCase     ):
  '''simple docstring'''




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




  @property
  def 							UpperCAmelCase_	(    self      )    ->		str:
      lowerCAmelCase__ :  Union[str, Any]							      =					1
      lowerCAmelCase__ :  Optional[Any]							      =					3
      lowerCAmelCase__ :  Optional[int]							      =					(32, 32)

      lowerCAmelCase__ :  Optional[int]							      =					floats_tensor((batch_size, num_channels) + sizes  ,rng=random.Random(0      )      ).to(__UpperCAmelCase      )
      return image




  @property
  def 							UpperCAmelCase_	(    self      )    ->		str:
      torch.manual_seed(0      )
      lowerCAmelCase__ :  Any							      =					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 							UpperCAmelCase_	(    self      )    ->		List[str]:
      torch.manual_seed(0      )
      lowerCAmelCase__ :  Optional[Any]							      =					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 							UpperCAmelCase_	(    self      )    ->		str:
      torch.manual_seed(0      )
      lowerCAmelCase__ :  List[Any]							      =					RobertaSeriesConfig(
          hidden_size=32  ,project_dim=32  ,intermediate_size=37  ,layer_norm_eps=1E-05  ,num_attention_heads=4  ,num_hidden_layers=5  ,pad_token_id=1  ,vocab_size=5006  ,)
      return RobertaSeriesModelWithTransformation(__UpperCAmelCase      )




  @property
  def 							UpperCAmelCase_	(    self      )    ->		int:
      def extract(*__UpperCAmelCase  ,**__UpperCAmelCase      ):






          class        lowerCAmelCase_:
            '''simple docstring'''




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






            def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		str:
                self.pixel_values.to(__UpperCAmelCase      )
                return self







          return Out()

      return extract




  def 							UpperCAmelCase_	(    self      )    ->		Union[str, Any]:
      lowerCAmelCase__ :  Optional[int]							      =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
      lowerCAmelCase__ :  List[Any]							      =					self.dummy_cond_unet
      lowerCAmelCase__ :  Tuple							      =					PNDMScheduler(skip_prk_steps=__UpperCAmelCase      )
      lowerCAmelCase__ :  Dict							      =					self.dummy_vae
      lowerCAmelCase__ :  Tuple							      =					self.dummy_text_encoder
      lowerCAmelCase__ :  Union[str, Any]							      =					XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""      )
      lowerCAmelCase__ :  str							      =					77

      lowerCAmelCase__ :  List[str]							      =					self.dummy_image.to(__UpperCAmelCase      )
      lowerCAmelCase__ :  int							      =					init_image / 2 + 0.5

      # make sure here that pndm scheduler skips prk
      lowerCAmelCase__ :  Dict							      =					AltDiffusionImgaImgPipeline(
          unet=__UpperCAmelCase  ,scheduler=__UpperCAmelCase  ,vae=__UpperCAmelCase  ,text_encoder=__UpperCAmelCase  ,tokenizer=__UpperCAmelCase  ,safety_checker=__UpperCAmelCase  ,feature_extractor=self.dummy_extractor  ,)
      lowerCAmelCase__ :  List[Any]							      =					VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor  ,do_normalize=__UpperCAmelCase      )
      lowerCAmelCase__ :  Tuple							      =					alt_pipe.to(__UpperCAmelCase      )
      alt_pipe.set_progress_bar_config(disable=__UpperCAmelCase      )

      lowerCAmelCase__ :  int							      =					"""A painting of a squirrel eating a burger"""
      lowerCAmelCase__ :  Optional[Any]							      =					torch.Generator(device=__UpperCAmelCase      ).manual_seed(0      )
      lowerCAmelCase__ :  Optional[Any]							      =					alt_pipe(
          [prompt]  ,generator=__UpperCAmelCase  ,guidance_scale=6.0  ,num_inference_steps=2  ,output_type="""np"""  ,image=__UpperCAmelCase  ,)

      lowerCAmelCase__ :  List[Any]							      =					output.images

      lowerCAmelCase__ :  Optional[Any]							      =					torch.Generator(device=__UpperCAmelCase      ).manual_seed(0      )
      lowerCAmelCase__ :  Dict							      =					alt_pipe(
          [prompt]  ,generator=__UpperCAmelCase  ,guidance_scale=6.0  ,num_inference_steps=2  ,output_type="""np"""  ,image=__UpperCAmelCase  ,return_dict=__UpperCAmelCase  ,)[0]

      lowerCAmelCase__ :  Optional[Any]							      =					image[0, -3:, -3:, -1]
      lowerCAmelCase__ :  str							      =					image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (1, 32, 32, 3)
      lowerCAmelCase__ :  Optional[Any]							      =					np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9]      )

      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 							UpperCAmelCase_	(    self      )    ->		str:
      lowerCAmelCase__ :  Any							      =					self.dummy_cond_unet
      lowerCAmelCase__ :  Any							      =					PNDMScheduler(skip_prk_steps=__UpperCAmelCase      )
      lowerCAmelCase__ :  int							      =					self.dummy_vae
      lowerCAmelCase__ :  Union[str, Any]							      =					self.dummy_text_encoder
      lowerCAmelCase__ :  Union[str, Any]							      =					XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""      )
      lowerCAmelCase__ :  Tuple							      =					77

      lowerCAmelCase__ :  Union[str, Any]							      =					self.dummy_image.to(__UpperCAmelCase      )

      # put models in fp16
      lowerCAmelCase__ :  Tuple							      =					unet.half()
      lowerCAmelCase__ :  str							      =					vae.half()
      lowerCAmelCase__ :  Union[str, Any]							      =					bert.half()

      # make sure here that pndm scheduler skips prk
      lowerCAmelCase__ :  Dict							      =					AltDiffusionImgaImgPipeline(
          unet=__UpperCAmelCase  ,scheduler=__UpperCAmelCase  ,vae=__UpperCAmelCase  ,text_encoder=__UpperCAmelCase  ,tokenizer=__UpperCAmelCase  ,safety_checker=__UpperCAmelCase  ,feature_extractor=self.dummy_extractor  ,)
      lowerCAmelCase__ :  Optional[int]							      =					VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor  ,do_normalize=__UpperCAmelCase      )
      lowerCAmelCase__ :  Optional[int]							      =					alt_pipe.to(__UpperCAmelCase      )
      alt_pipe.set_progress_bar_config(disable=__UpperCAmelCase      )

      lowerCAmelCase__ :  str							      =					"""A painting of a squirrel eating a burger"""
      lowerCAmelCase__ :  int							      =					torch.manual_seed(0      )
      lowerCAmelCase__ :  Optional[Any]							      =					alt_pipe(
          [prompt]  ,generator=__UpperCAmelCase  ,num_inference_steps=2  ,output_type="""np"""  ,image=__UpperCAmelCase  ,).images

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






  @unittest.skipIf(torch_device != """cuda"""  ,"""This test requires a GPU"""      )
  def 							UpperCAmelCase_	(    self      )    ->		str:
      lowerCAmelCase__ :  List[Any]							      =					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__ :  List[Any]							      =					init_image.resize((760, 504)      )

      lowerCAmelCase__ :  Tuple							      =					"""BAAI/AltDiffusion"""
      lowerCAmelCase__ :  str							      =					AltDiffusionImgaImgPipeline.from_pretrained(
          __UpperCAmelCase  ,safety_checker=__UpperCAmelCase  ,)
      pipe.to(__UpperCAmelCase      )
      pipe.set_progress_bar_config(disable=__UpperCAmelCase      )
      pipe.enable_attention_slicing()

      lowerCAmelCase__ :  Union[str, Any]							      =					"""A fantasy landscape, trending on artstation"""

      lowerCAmelCase__ :  Optional[Any]							      =					torch.manual_seed(0      )
      lowerCAmelCase__ :  Union[str, Any]							      =					pipe(
          prompt=__UpperCAmelCase  ,image=__UpperCAmelCase  ,strength=0.7_5  ,guidance_scale=7.5  ,generator=__UpperCAmelCase  ,output_type="""np"""  ,)
      lowerCAmelCase__ :  List[Any]							      =					output.images[0]

      lowerCAmelCase__ :  str							      =					image[255:258, 383:386, -1]

      assert image.shape == (504, 760, 3)
      lowerCAmelCase__ :  Any							      =					np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0]      )

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







@slow
@require_torch_gpu
class        lowerCAmelCase_(				unittest.TestCase     ):
  '''simple docstring'''




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






  def 							UpperCAmelCase_	(    self      )    ->		int:
      lowerCAmelCase__ :  Dict							      =					load_image(
          """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
          """/img2img/sketch-mountains-input.jpg"""      )
      lowerCAmelCase__ :  Optional[int]							      =					init_image.resize((768, 512)      )
      lowerCAmelCase__ :  Dict							      =					load_numpy(
          """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""      )

      lowerCAmelCase__ :  List[str]							      =					"""BAAI/AltDiffusion"""
      lowerCAmelCase__ :  Optional[Any]							      =					AltDiffusionImgaImgPipeline.from_pretrained(
          __UpperCAmelCase  ,safety_checker=__UpperCAmelCase  ,)
      pipe.to(__UpperCAmelCase      )
      pipe.set_progress_bar_config(disable=__UpperCAmelCase      )
      pipe.enable_attention_slicing()

      lowerCAmelCase__ :  int							      =					"""A fantasy landscape, trending on artstation"""

      lowerCAmelCase__ :  List[str]							      =					torch.manual_seed(0      )
      lowerCAmelCase__ :  List[str]							      =					pipe(
          prompt=__UpperCAmelCase  ,image=__UpperCAmelCase  ,strength=0.7_5  ,guidance_scale=7.5  ,generator=__UpperCAmelCase  ,output_type="""np"""  ,)
      lowerCAmelCase__ :  List[Any]							      =					output.images[0]

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







'''simple docstring'''





# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# this script dumps information about the environment

import os
import sys

import transformers


_lowerCAmelCase      						=	'''3'''

print('''Python version:''', sys.version)
print('''transformers version:''', transformers.__version__)

try:
 import torch

 print('''Torch version:''', torch.__version__)
 print('''Cuda available:''', torch.cuda.is_available())
 print('''Cuda version:''', torch.version.cuda)
 print('''CuDNN version:''', torch.backends.cudnn.version())
 print('''Number of GPUs available:''', torch.cuda.device_count())
 print('''NCCL version:''', torch.cuda.nccl.version())
except ImportError:
 print('''Torch version:''', None)

try:
 import deepspeed

 print('''DeepSpeed version:''', deepspeed.__version__)
except ImportError:
 print('''DeepSpeed version:''', None)

try:
 import tensorflow as tf

 print('''TensorFlow version:''', tf.__version__)
 print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU''')))
 print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU''')))
except ImportError:
 print('''TensorFlow version:''', None)


