

import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
      import bitsandbytes as bnb

from copy import deepcopy


a_     :    Tuple     		=   logging.getLogger(__name__)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	torch.nn.Module		,				_UpperCamelCase		:	BnbQuantizationConfig		,				_UpperCamelCase		:	Union[str, os.PathLike] = None		,				_UpperCamelCase		:	Optional[Dict[str, Union[int, str, torch.device]]] = None		,				_UpperCamelCase		:	Optional[List[str]] = None		,				_UpperCamelCase		:	Optional[Dict[Union[int, str], Union[int, str]]] = None		,				_UpperCamelCase		:	Optional[Union[str, os.PathLike]] = None		,				_UpperCamelCase		:	bool = False		,				)		->				Tuple:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE		    =      bnb_quantization_config.load_in_abit
 SCREAMING_SNAKE_CASE		    =      bnb_quantization_config.load_in_abit

 if load_in_abit and not is_abit_bnb_available():
  raise ImportError(
      'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'
      ' make sure you have the latest version of `bitsandbytes` installed.'						)
 if load_in_abit and not is_abit_bnb_available():
  raise ValueError(
      'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'
      'make sure you have the latest version of `bitsandbytes` installed.'						)

 SCREAMING_SNAKE_CASE		    =      []
 # custom device map
 if isinstance(_UpperCamelCase		,				_UpperCamelCase						) and len(device_map.keys()						) > 1:
  SCREAMING_SNAKE_CASE		    =      [key for key, value in device_map.items() if value in ['disk', 'cpu']]

 # We keep some modules such as the lm_head in their original dtype for numerical stability reasons
 if bnb_quantization_config.skip_modules is None:
  SCREAMING_SNAKE_CASE		    =      get_keys_to_not_convert(_UpperCamelCase						)

 # add cpu modules to skip modules only for 4-bit modules
 if load_in_abit:
  bnb_quantization_config.skip_modules.extend(_UpperCamelCase						)
 SCREAMING_SNAKE_CASE		    =      bnb_quantization_config.skip_modules

 # We add the modules we want to keep in full precision
 if bnb_quantization_config.keep_in_fpaa_modules is None:
  SCREAMING_SNAKE_CASE		    =      []
 SCREAMING_SNAKE_CASE		    =      bnb_quantization_config.keep_in_fpaa_modules
 modules_to_not_convert.extend(_UpperCamelCase						)

 # compatibility with peft
 SCREAMING_SNAKE_CASE		    =      load_in_abit
 SCREAMING_SNAKE_CASE		    =      load_in_abit

 SCREAMING_SNAKE_CASE		    =      get_parameter_device(_UpperCamelCase						)
 if model_device.type != "meta":
  # quantization of an already loaded model
  logger.warning(
      'It is not recommended to quantize a loaded model. '
      'The model should be instantiated under the `init_empty_weights` context manager.'						)
  SCREAMING_SNAKE_CASE		    =      replace_with_bnb_layers(_UpperCamelCase		,				_UpperCamelCase		,				modules_to_not_convert=_UpperCamelCase						)
  # convert param to the right dtype
  SCREAMING_SNAKE_CASE		    =      bnb_quantization_config.torch_dtype
  for name, param in model.state_dict().items():
   if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules						):
    param.to(torch.floataa						)
    if param.dtype != torch.floataa:
     SCREAMING_SNAKE_CASE		    =      name.replace('.weight'		,				''						).replace('.bias'		,				''						)
     SCREAMING_SNAKE_CASE		    =      getattr(_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase						)
     if param is not None:
      param.to(torch.floataa						)
   elif torch.is_floating_point(_UpperCamelCase						):
    param.to(_UpperCamelCase						)
  if model_device.type == "cuda":
   # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
   model.cuda(torch.cuda.current_device()						)
   torch.cuda.empty_cache()
  elif torch.cuda.is_available():
   model.to(torch.cuda.current_device()						)
  else:
   raise RuntimeError('No GPU found. A GPU is needed for quantization.'						)
  logger.info(
      f"""The model device type is {model_device.type}. However, cuda is needed for quantization."""
      'We move the model to cuda.'						)
  return model

 elif weights_location is None:
  raise RuntimeError(
      f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """						)

 else:
  with init_empty_weights():
   SCREAMING_SNAKE_CASE		    =      replace_with_bnb_layers(
       _UpperCamelCase		,				_UpperCamelCase		,				modules_to_not_convert=_UpperCamelCase						)

  SCREAMING_SNAKE_CASE		    =      get_quantized_model_device_map(
      _UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase		,				max_memory=_UpperCamelCase		,				no_split_module_classes=_UpperCamelCase		,				)
  if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
   SCREAMING_SNAKE_CASE		    =      True

  SCREAMING_SNAKE_CASE		    =      any(x in list(device_map.values()						) for x in ['cpu', 'disk']						)

  load_checkpoint_in_model(
      _UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase		,				dtype=bnb_quantization_config.torch_dtype		,				offload_folder=_UpperCamelCase		,				offload_state_dict=_UpperCamelCase		,				keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules		,				offload_abit_bnb=load_in_abit and offload		,				)
  return dispatch_model(_UpperCamelCase		,				device_map=_UpperCamelCase		,				offload_dir=_UpperCamelCase						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Tuple		,				_UpperCamelCase		:	Dict		,				_UpperCamelCase		:	Optional[int]=None		,				_UpperCamelCase		:	Optional[Any]=None		,				_UpperCamelCase		:	Dict=None						)		->				Union[str, Any]:
 '''simple docstring'''


 if device_map is None:
  if torch.cuda.is_available():
   SCREAMING_SNAKE_CASE		    =      {'': torch.cuda.current_device()}
  else:
   raise RuntimeError('No GPU found. A GPU is needed for quantization.'						)
  logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.'						)

 if isinstance(_UpperCamelCase		,				_UpperCamelCase						):
  if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
   raise ValueError(
       'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '
       '\'sequential\'.'						)

  SCREAMING_SNAKE_CASE		    =      {}
  special_dtypes.update(
      {
          name: bnb_quantization_config.torch_dtype
          for name, _ in model.named_parameters()
          if any(m in name for m in bnb_quantization_config.skip_modules						)
      }						)
  special_dtypes.update(
      {
          name: torch.floataa
          for name, _ in model.named_parameters()
          if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules						)
      }						)

  SCREAMING_SNAKE_CASE		    =      {}
  SCREAMING_SNAKE_CASE		    =      special_dtypes
  SCREAMING_SNAKE_CASE		    =      no_split_module_classes
  SCREAMING_SNAKE_CASE		    =      bnb_quantization_config.target_dtype

  # get max_memory for each device.
  if device_map != "sequential":
   SCREAMING_SNAKE_CASE		    =      get_balanced_memory(
       _UpperCamelCase		,				low_zero=(device_map == 'balanced_low_0')		,				max_memory=_UpperCamelCase		,				**_UpperCamelCase		,				)

  SCREAMING_SNAKE_CASE		    =      max_memory
  SCREAMING_SNAKE_CASE		    =      infer_auto_device_map(_UpperCamelCase		,				**_UpperCamelCase						)

 if isinstance(_UpperCamelCase		,				_UpperCamelCase						):
  # check if don't have any quantized module on the cpu
  SCREAMING_SNAKE_CASE		    =      bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

  SCREAMING_SNAKE_CASE		    =      {
      key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
  }
  for device in ["cpu", "disk"]:
   if device in device_map_without_some_modules.values():
    if bnb_quantization_config.load_in_abit:
     raise ValueError(
         '\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        '						)
    else:
     logger.info(
         'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit'						)
  del device_map_without_some_modules
 return device_map


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Optional[Any]		,				_UpperCamelCase		:	Any		,				_UpperCamelCase		:	Union[str, Any]=None		,				_UpperCamelCase		:	Tuple=None						)		->				Optional[Any]:
 '''simple docstring'''


 if modules_to_not_convert is None:
  SCREAMING_SNAKE_CASE		    =      []

 SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      _replace_with_bnb_layers(
     _UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase						)
 if not has_been_replaced:
  logger.warning(
      'You are loading your model in 8bit or 4bit but no linear modules were found in your model.'
      ' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'
      ' Please double check your model architecture, or submit an issue on github if you think this is'
      ' a bug.'						)
 return model


def 							__lowerCAmelCase     (							_UpperCamelCase		:	List[Any]		,				_UpperCamelCase		:	int		,				_UpperCamelCase		:	Optional[int]=None		,				_UpperCamelCase		:	str=None		,				)		->				Dict:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE		    =      False
 for name, module in model.named_children():
  if current_key_name is None:
   SCREAMING_SNAKE_CASE		    =      []
  current_key_name.append(_UpperCamelCase						)
  if isinstance(_UpperCamelCase		,				nn.Linear						) and name not in modules_to_not_convert:
   # Check if the current key is not in the `modules_to_not_convert`
   SCREAMING_SNAKE_CASE		    =      '.'.join(_UpperCamelCase						)
   SCREAMING_SNAKE_CASE		    =      True
   for key in modules_to_not_convert:
    if (
        (key in current_key_name_str) and (key + "." in current_key_name_str)
    ) or key == current_key_name_str:
     SCREAMING_SNAKE_CASE		    =      False
     break
   if proceed:
    # Load bnb module with empty weight and replace ``nn.Linear` module
    if bnb_quantization_config.load_in_abit:
     SCREAMING_SNAKE_CASE		    =      bnb.nn.LinearabitLt(
         module.in_features		,				module.out_features		,				module.bias is not None		,				has_fpaa_weights=_UpperCamelCase		,				threshold=bnb_quantization_config.llm_inta_threshold		,				)
    elif bnb_quantization_config.load_in_abit:
     SCREAMING_SNAKE_CASE		    =      bnb.nn.Linearabit(
         module.in_features		,				module.out_features		,				module.bias is not None		,				bnb_quantization_config.bnb_abit_compute_dtype		,				compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant		,				quant_type=bnb_quantization_config.bnb_abit_quant_type		,				)
    else:
     raise ValueError('load_in_8bit and load_in_4bit can\'t be both False'						)
    SCREAMING_SNAKE_CASE		    =      module.weight.data
    if module.bias is not None:
     SCREAMING_SNAKE_CASE		    =      module.bias.data
    bnb_module.requires_grad_(_UpperCamelCase						)
    setattr(_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase						)
    SCREAMING_SNAKE_CASE		    =      True
  if len(list(module.children()						)						) > 0:
   SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      _replace_with_bnb_layers(
       _UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase						)
   SCREAMING_SNAKE_CASE		    =      has_been_replaced | _has_been_replaced
  # Remove the last key for recursion
  current_key_name.pop(-1						)
 return model, has_been_replaced


def 							__lowerCAmelCase     (							_UpperCamelCase		:	List[str]						)		->				str:
 '''simple docstring'''


 with init_empty_weights():
  SCREAMING_SNAKE_CASE		    =      deepcopy(_UpperCamelCase						)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

 SCREAMING_SNAKE_CASE		    =      find_tied_parameters(_UpperCamelCase						)
 # For compatibility with Accelerate < 0.18
 if isinstance(_UpperCamelCase		,				_UpperCamelCase						):
  SCREAMING_SNAKE_CASE		    =      sum(list(tied_params.values()						)		,				[]						) + list(tied_params.keys()						)
 else:
  SCREAMING_SNAKE_CASE		    =      sum(_UpperCamelCase		,				[]						)
 SCREAMING_SNAKE_CASE		    =      len(_UpperCamelCase						) > 0

 # Check if it is a base model
 SCREAMING_SNAKE_CASE		    =      False
 if hasattr(_UpperCamelCase		,				'base_model_prefix'						):
  SCREAMING_SNAKE_CASE		    =      not hasattr(_UpperCamelCase		,				model.base_model_prefix						)

 # Ignore this for base models (BertModel, GPT2Model, etc.)
 if (not has_tied_params) and is_base_model:
  return []

 # otherwise they have an attached head
 SCREAMING_SNAKE_CASE		    =      list(model.named_children()						)
 SCREAMING_SNAKE_CASE		    =      [list_modules[-1][0]]

 # add last module together with tied weights
 SCREAMING_SNAKE_CASE		    =      set(_UpperCamelCase						) - set(_UpperCamelCase						)
 SCREAMING_SNAKE_CASE		    =      list(set(_UpperCamelCase						)						) + list(_UpperCamelCase						)

 # remove ".weight" from the keys
 SCREAMING_SNAKE_CASE		    =      ['.weight', '.bias']
 SCREAMING_SNAKE_CASE		    =      []
 for name in list_untouched:
  for name_to_remove in names_to_remove:
   if name_to_remove in name:
    SCREAMING_SNAKE_CASE		    =      name.replace(_UpperCamelCase		,				''						)
  filtered_module_names.append(_UpperCamelCase						)

 return filtered_module_names


def 							__lowerCAmelCase     (							_UpperCamelCase		:	List[str]						)		->				Union[str, Any]:
 '''simple docstring'''


 for m in model.modules():
  if isinstance(_UpperCamelCase		,				bnb.nn.Linearabit						):
   return True
 return False


def 							__lowerCAmelCase     (							_UpperCamelCase		:	nn.Module						)		->				Optional[int]:
 '''simple docstring'''


 return next(parameter.parameters()						).device




def 							__lowerCAmelCase     (							_UpperCamelCase		:	Tuple		,				_UpperCamelCase		:	Dict		,				_UpperCamelCase		:	Optional[Any]		,				_UpperCamelCase		:	Union[str, Any]		,				_UpperCamelCase		:	Tuple		,				_UpperCamelCase		:	Dict		,				_UpperCamelCase		:	str						)		->				Any:
 '''simple docstring'''


 if fpaa_statistics is None:
  set_module_tensor_to_device(_UpperCamelCase		,				_UpperCamelCase		,				0		,				dtype=_UpperCamelCase		,				value=_UpperCamelCase						)
  SCREAMING_SNAKE_CASE		    =      param_name
  SCREAMING_SNAKE_CASE		    =      model
  if "." in tensor_name:
   SCREAMING_SNAKE_CASE		    =      tensor_name.split('.'						)
   for split in splits[:-1]:
    SCREAMING_SNAKE_CASE		    =      getattr(_UpperCamelCase		,				_UpperCamelCase						)
    if new_module is None:
     raise ValueError(f"""{module} has no attribute {split}."""						)
    SCREAMING_SNAKE_CASE		    =      new_module
   SCREAMING_SNAKE_CASE		    =      splits[-1]
  # offload weights
  SCREAMING_SNAKE_CASE		    =      False
  offload_weight(module._parameters[tensor_name]		,				_UpperCamelCase		,				_UpperCamelCase		,				index=_UpperCamelCase						)
  if hasattr(module._parameters[tensor_name]		,				'SCB'						):
   offload_weight(
       module._parameters[tensor_name].SCB		,				param_name.replace('weight'		,				'SCB'						)		,				_UpperCamelCase		,				index=_UpperCamelCase		,				)
 else:
  offload_weight(_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase		,				index=_UpperCamelCase						)
  offload_weight(_UpperCamelCase		,				param_name.replace('weight'		,				'SCB'						)		,				_UpperCamelCase		,				index=_UpperCamelCase						)

 set_module_tensor_to_device(_UpperCamelCase		,				_UpperCamelCase		,				'meta'		,				dtype=_UpperCamelCase		,				value=torch.empty(*param.size()						)						)




import gc
import random
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
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 UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






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

    @property
    def UpperCamelCase      (      self			:   Optional[int]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      1
     SCREAMING_SNAKE_CASE		    =      3
     SCREAMING_SNAKE_CASE		    =      (3_2, 3_2)

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

    @property
    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      UNetaDConditionModel(
         block_out_channels=(3_2, 3_2, 6_4)				,     layers_per_block=2				,     sample_size=3_2				,     in_channels=7				,     out_channels=4				,     down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D')				,     up_block_types=('CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'UpBlock2D')				,     cross_attention_dim=3_2				,     attention_head_dim=8				,     use_linear_projection=snake_case__				,     only_cross_attention=(True, True, False)				,     num_class_embeds=1_0_0				,     )
     return model

    @property
    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      AutoencoderKL(
         block_out_channels=[3_2, 3_2, 6_4]				,     in_channels=3				,     out_channels=3				,     down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D']				,     up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D']				,     latent_channels=4				,     )
     return model

    @property
    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      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				,     )
     return CLIPTextModel(snake_case__     )

    def UpperCamelCase      (      self			:   Dict     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      'cpu'  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE		    =      self.dummy_cond_unet_upscale
     SCREAMING_SNAKE_CASE		    =      DDPMScheduler()
     SCREAMING_SNAKE_CASE		    =      DDIMScheduler(prediction_type='v_prediction'     )
     SCREAMING_SNAKE_CASE		    =      self.dummy_vae
     SCREAMING_SNAKE_CASE		    =      self.dummy_text_encoder
     SCREAMING_SNAKE_CASE		    =      CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'     )

     SCREAMING_SNAKE_CASE		    =      self.dummy_image.cpu().permute(0				,     2				,     3				,     1     )[0]
     SCREAMING_SNAKE_CASE		    =      Image.fromarray(np.uinta(snake_case__     )     ).convert('RGB'     ).resize((6_4, 6_4)     )

     # make sure here that pndm scheduler skips prk
     SCREAMING_SNAKE_CASE		    =      StableDiffusionUpscalePipeline(
         unet=snake_case__				,     low_res_scheduler=snake_case__				,     scheduler=snake_case__				,     vae=snake_case__				,     text_encoder=snake_case__				,     tokenizer=snake_case__				,     max_noise_level=3_5_0				,     )
     SCREAMING_SNAKE_CASE		    =      sd_pipe.to(snake_case__     )
     sd_pipe.set_progress_bar_config(disable=snake_case__     )

     SCREAMING_SNAKE_CASE		    =      'A painting of a squirrel eating a burger'
     SCREAMING_SNAKE_CASE		    =      torch.Generator(device=snake_case__     ).manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      sd_pipe(
         [prompt]				,     image=snake_case__				,     generator=snake_case__				,     guidance_scale=6.0				,     noise_level=2_0				,     num_inference_steps=2				,     output_type='np'				,     )

     SCREAMING_SNAKE_CASE		    =      output.images

     SCREAMING_SNAKE_CASE		    =      torch.Generator(device=snake_case__     ).manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      sd_pipe(
         [prompt]				,     image=snake_case__				,     generator=snake_case__				,     guidance_scale=6.0				,     noise_level=2_0				,     num_inference_steps=2				,     output_type='np'				,     return_dict=snake_case__				,     )[0]

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

     SCREAMING_SNAKE_CASE		    =      low_res_image.size[0] * 4
     assert image.shape == (1, expected_height_width, expected_height_width, 3)
     SCREAMING_SNAKE_CASE		    =      np.array([0.3_113, 0.3_910, 0.4_272, 0.4_859, 0.5_061, 0.4_652, 0.5_362, 0.5_715, 0.5_661]     )

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

    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      'cpu'  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE		    =      self.dummy_cond_unet_upscale
     SCREAMING_SNAKE_CASE		    =      DDPMScheduler()
     SCREAMING_SNAKE_CASE		    =      DDIMScheduler(prediction_type='v_prediction'     )
     SCREAMING_SNAKE_CASE		    =      self.dummy_vae
     SCREAMING_SNAKE_CASE		    =      self.dummy_text_encoder
     SCREAMING_SNAKE_CASE		    =      CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'     )

     SCREAMING_SNAKE_CASE		    =      self.dummy_image.cpu().permute(0				,     2				,     3				,     1     )[0]
     SCREAMING_SNAKE_CASE		    =      Image.fromarray(np.uinta(snake_case__     )     ).convert('RGB'     ).resize((6_4, 6_4)     )

     # make sure here that pndm scheduler skips prk
     SCREAMING_SNAKE_CASE		    =      StableDiffusionUpscalePipeline(
         unet=snake_case__				,     low_res_scheduler=snake_case__				,     scheduler=snake_case__				,     vae=snake_case__				,     text_encoder=snake_case__				,     tokenizer=snake_case__				,     max_noise_level=3_5_0				,     )
     SCREAMING_SNAKE_CASE		    =      sd_pipe.to(snake_case__     )
     sd_pipe.set_progress_bar_config(disable=snake_case__     )

     SCREAMING_SNAKE_CASE		    =      'A painting of a squirrel eating a burger'
     SCREAMING_SNAKE_CASE		    =      sd_pipe(
         2 * [prompt]				,     image=2 * [low_res_image]				,     guidance_scale=6.0				,     noise_level=2_0				,     num_inference_steps=2				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      output.images
     assert image.shape[0] == 2

     SCREAMING_SNAKE_CASE		    =      torch.Generator(device=snake_case__     ).manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      sd_pipe(
         [prompt]				,     image=snake_case__				,     generator=snake_case__				,     num_images_per_prompt=2				,     guidance_scale=6.0				,     noise_level=2_0				,     num_inference_steps=2				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      output.images
     assert image.shape[0] == 2




    @unittest.skipIf(torch_device != 'cuda'				,     'This test requires a GPU'     )
    def UpperCamelCase      (      self			:   Union[str, Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.dummy_cond_unet_upscale
     SCREAMING_SNAKE_CASE		    =      DDPMScheduler()
     SCREAMING_SNAKE_CASE		    =      DDIMScheduler(prediction_type='v_prediction'     )
     SCREAMING_SNAKE_CASE		    =      self.dummy_vae
     SCREAMING_SNAKE_CASE		    =      self.dummy_text_encoder
     SCREAMING_SNAKE_CASE		    =      CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'     )

     SCREAMING_SNAKE_CASE		    =      self.dummy_image.cpu().permute(0				,     2				,     3				,     1     )[0]
     SCREAMING_SNAKE_CASE		    =      Image.fromarray(np.uinta(snake_case__     )     ).convert('RGB'     ).resize((6_4, 6_4)     )

     # put models in fp16, except vae as it overflows in fp16
     SCREAMING_SNAKE_CASE		    =      unet.half()
     SCREAMING_SNAKE_CASE		    =      text_encoder.half()

     # make sure here that pndm scheduler skips prk
     SCREAMING_SNAKE_CASE		    =      StableDiffusionUpscalePipeline(
         unet=snake_case__				,     low_res_scheduler=snake_case__				,     scheduler=snake_case__				,     vae=snake_case__				,     text_encoder=snake_case__				,     tokenizer=snake_case__				,     max_noise_level=3_5_0				,     )
     SCREAMING_SNAKE_CASE		    =      sd_pipe.to(snake_case__     )
     sd_pipe.set_progress_bar_config(disable=snake_case__     )

     SCREAMING_SNAKE_CASE		    =      'A painting of a squirrel eating a burger'
     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      sd_pipe(
         [prompt]				,     image=snake_case__				,     generator=snake_case__				,     num_inference_steps=2				,     output_type='np'				,     ).images

     SCREAMING_SNAKE_CASE		    =      low_res_image.size[0] * 4
     assert image.shape == (1, expected_height_width, expected_height_width, 3)




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

    def UpperCamelCase      (      self			:   List[str]     ):

     """simple docstring"""






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

    def UpperCamelCase      (      self			:   Optional[int]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/sd2-upscale/low_res_cat.png'     )
     SCREAMING_SNAKE_CASE		    =      load_numpy(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
         '/upsampled_cat.npy'     )

     SCREAMING_SNAKE_CASE		    =      'stabilityai/stable-diffusion-x4-upscaler'
     SCREAMING_SNAKE_CASE		    =      StableDiffusionUpscalePipeline.from_pretrained(snake_case__     )
     pipe.to(snake_case__     )
     pipe.set_progress_bar_config(disable=snake_case__     )
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE		    =      'a cat sitting on a park bench'

     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      pipe(
         prompt=snake_case__				,     image=snake_case__				,     generator=snake_case__				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      output.images[0]

     assert image.shape == (5_1_2, 5_1_2, 3)
     assert np.abs(expected_image - image     ).max() < 1E-3

    def UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/sd2-upscale/low_res_cat.png'     )
     SCREAMING_SNAKE_CASE		    =      load_numpy(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
         '/upsampled_cat_fp16.npy'     )

     SCREAMING_SNAKE_CASE		    =      'stabilityai/stable-diffusion-x4-upscaler'
     SCREAMING_SNAKE_CASE		    =      StableDiffusionUpscalePipeline.from_pretrained(
         snake_case__				,     torch_dtype=torch.floataa				,     )
     pipe.to(snake_case__     )
     pipe.set_progress_bar_config(disable=snake_case__     )
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE		    =      'a cat sitting on a park bench'

     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      pipe(
         prompt=snake_case__				,     image=snake_case__				,     generator=snake_case__				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      output.images[0]

     assert image.shape == (5_1_2, 5_1_2, 3)
     assert np.abs(expected_image - image     ).max() < 5E-1




    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     torch.cuda.empty_cache()
     torch.cuda.reset_max_memory_allocated()
     torch.cuda.reset_peak_memory_stats()

     SCREAMING_SNAKE_CASE		    =      load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/sd2-upscale/low_res_cat.png'     )

     SCREAMING_SNAKE_CASE		    =      'stabilityai/stable-diffusion-x4-upscaler'
     SCREAMING_SNAKE_CASE		    =      StableDiffusionUpscalePipeline.from_pretrained(
         snake_case__				,     torch_dtype=torch.floataa				,     )
     pipe.to(snake_case__     )
     pipe.set_progress_bar_config(disable=snake_case__     )
     pipe.enable_attention_slicing(1     )
     pipe.enable_sequential_cpu_offload()

     SCREAMING_SNAKE_CASE		    =      'a cat sitting on a park bench'

     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      pipe(
         prompt=snake_case__				,     image=snake_case__				,     generator=snake_case__				,     num_inference_steps=5				,     output_type='np'				,     )

     SCREAMING_SNAKE_CASE		    =      torch.cuda.max_memory_allocated()
     # make sure that less than 2.9 GB is allocated
     assert mem_bytes < 2.9 * 1_0**9

