






import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
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 PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class 							A_    (						lowercase__ ,   lowercase__ ,   unittest.TestCase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			List[Any] =					StableDiffusionSAGPipeline
 _SCREAMING_SNAKE_CASE							:			str =					TEXT_TO_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE							:			List[Any] =					TEXT_TO_IMAGE_BATCH_PARAMS
 _SCREAMING_SNAKE_CASE							:			List[Any] =					TEXT_TO_IMAGE_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE							:			List[Any] =					TEXT_TO_IMAGE_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE							:			int =					False


 def  snake_case__				(	self) ->		str:

     """simple docstring"""



     torch.manual_seed(0)
     _UpperCAmelCase				:      Tuple			  =				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							,  )
     _UpperCAmelCase				:      Union[str, Any]			  =				DDIMScheduler(
         beta_start=0.00085							,  beta_end=0.012							,  beta_schedule='''scaled_linear'''							,  clip_sample=UpperCAmelCase__							,  set_alpha_to_one=UpperCAmelCase__							,  )
     torch.manual_seed(0)
     _UpperCAmelCase				:      Dict			  =				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							,  )
     torch.manual_seed(0)
     _UpperCAmelCase				:      int			  =				CLIPTextConfig(
         bos_token_id=0							,  eos_token_id=2							,  hidden_size=32							,  intermediate_size=37							,  layer_norm_eps=1e-05							,  num_attention_heads=4							,  num_hidden_layers=5							,  pad_token_id=1							,  vocab_size=1000							,  )
     _UpperCAmelCase				:      str			  =				CLIPTextModel(UpperCAmelCase__)
     _UpperCAmelCase				:      Tuple			  =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

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


 def  snake_case__				(	self							,  _A							,  _A=0) ->		List[str]:

     """simple docstring"""



     if str(UpperCAmelCase__).startswith('''mps'''):
         _UpperCAmelCase				:      List[Any]			  =				torch.manual_seed(UpperCAmelCase__)
     else:
         _UpperCAmelCase				:      Optional[Any]			  =				torch.Generator(device=UpperCAmelCase__).manual_seed(UpperCAmelCase__)
     _UpperCAmelCase				:      Any			  =				{
         '''prompt''': '''.''',
         '''generator''': generator,
         '''num_inference_steps''': 2,
         '''guidance_scale''': 1.0,
         '''sag_scale''': 1.0,
         '''output_type''': '''numpy''',
     }
     return inputs


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     super().test_inference_batch_single_identical(expected_max_diff=3e-3)



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






 '''simple docstring'''




 def  snake_case__				(	self) ->		List[Any]:

     """simple docstring"""



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


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

     """simple docstring"""



     _UpperCAmelCase				:      int			  =				StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''')
     _UpperCAmelCase				:      Tuple			  =				sag_pipe.to(UpperCAmelCase__)
     sag_pipe.set_progress_bar_config(disable=UpperCAmelCase__)

     _UpperCAmelCase				:      str			  =				'''.'''
     _UpperCAmelCase				:      int			  =				torch.manual_seed(0)
     _UpperCAmelCase				:      Optional[int]			  =				sag_pipe(
         [prompt]							,  generator=UpperCAmelCase__							,  guidance_scale=7.5							,  sag_scale=1.0							,  num_inference_steps=20							,  output_type='''np''')

     _UpperCAmelCase				:      str			  =				output.images

     _UpperCAmelCase				:      Union[str, Any]			  =				image[0, -3:, -3:, -1]

     assert image.shape == (1, 512, 512, 3)
     _UpperCAmelCase				:      Optional[int]			  =				np.array([0.1568, 0.1738, 0.1695, 0.1693, 0.1507, 0.1705, 0.1547, 0.1751, 0.1949])

     assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''')
     _UpperCAmelCase				:      Tuple			  =				sag_pipe.to(UpperCAmelCase__)
     sag_pipe.set_progress_bar_config(disable=UpperCAmelCase__)

     _UpperCAmelCase				:      Optional[int]			  =				'''.'''
     _UpperCAmelCase				:      List[Any]			  =				torch.manual_seed(0)
     _UpperCAmelCase				:      Optional[int]			  =				sag_pipe(
         [prompt]							,  generator=UpperCAmelCase__							,  guidance_scale=7.5							,  sag_scale=1.0							,  num_inference_steps=20							,  output_type='''np''')

     _UpperCAmelCase				:      List[Any]			  =				output.images

     _UpperCAmelCase				:      Union[str, Any]			  =				image[0, -3:, -3:, -1]

     assert image.shape == (1, 512, 512, 3)
     _UpperCAmelCase				:      Any			  =				np.array([0.3459, 0.2876, 0.2537, 0.3002, 0.2671, 0.2160, 0.3026, 0.2262, 0.2371])

     assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2


 def  snake_case__				(	self) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''')
     _UpperCAmelCase				:      List[str]			  =				sag_pipe.to(UpperCAmelCase__)
     sag_pipe.set_progress_bar_config(disable=UpperCAmelCase__)

     _UpperCAmelCase				:      List[str]			  =				'''.'''
     _UpperCAmelCase				:      List[str]			  =				torch.manual_seed(0)
     _UpperCAmelCase				:      List[Any]			  =				sag_pipe(
         [prompt]							,  width=768							,  height=512							,  generator=UpperCAmelCase__							,  guidance_scale=7.5							,  sag_scale=1.0							,  num_inference_steps=20							,  output_type='''np'''							,  )

     _UpperCAmelCase				:      Any			  =				output.images

     assert image.shape == (1, 512, 768, 3)













import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_blenderbot import BlenderbotTokenizer


if TYPE_CHECKING:
  from transformers.pipelines.conversational import Conversation

SCREAMING_SNAKE_CASE 							=						logging.get_logger(__name__)


SCREAMING_SNAKE_CASE 							=						{
    'vocab_file': 'vocab.json',
    'merges_file': 'merges.txt',
    'tokenizer_config_file': 'tokenizer_config.json',
}

SCREAMING_SNAKE_CASE 							=						{
    'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'},
    'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'},
    'tokenizer_config_file': {
        'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json'
    },
}

SCREAMING_SNAKE_CASE 							=						{'facebook/blenderbot-3B': 128}
class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Tuple =					VOCAB_FILES_NAMES
 _SCREAMING_SNAKE_CASE							:			Optional[Any] =					PRETRAINED_VOCAB_FILES_MAP
 _SCREAMING_SNAKE_CASE							:			Optional[int] =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _SCREAMING_SNAKE_CASE							:			List[Any] =					["input_ids", "attention_mask"]
 _SCREAMING_SNAKE_CASE							:			Dict =					BlenderbotTokenizer


 def __init__(	self							,  _A=None							,  _A=None							,  _A=None							,  _A="replace"							,  _A="<s>"							,  _A="</s>"							,  _A="</s>"							,  _A="<s>"							,  _A="<unk>"							,  _A="<pad>"							,  _A="<mask>"							,  _A=False							,  _A=True							,  **_A							,  ) ->		str:

     """simple docstring"""



     super().__init__(
         _A							,  _A							,  tokenizer_file=_A							,  errors=_A							,  bos_token=_A							,  eos_token=_A							,  sep_token=_A							,  cls_token=_A							,  unk_token=_A							,  pad_token=_A							,  mask_token=_A							,  add_prefix_space=_A							,  trim_offsets=_A							,  **_A							,  )

     _UpperCAmelCase				:      Any			  =				json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
     if pre_tok_state.get('''add_prefix_space'''							,  _A) != add_prefix_space:
         _UpperCAmelCase				:      Optional[int]			  =				getattr(_A							,  pre_tok_state.pop('''type'''))
         _UpperCAmelCase				:      Optional[int]			  =				add_prefix_space
         _UpperCAmelCase				:      Dict			  =				pre_tok_class(**_A)

     _UpperCAmelCase				:      Dict			  =				add_prefix_space

     _UpperCAmelCase				:      Tuple			  =				'''post_processor'''
     _UpperCAmelCase				:      str			  =				getattr(self.backend_tokenizer							,  _A							,  _A)
     if tokenizer_component_instance:
         _UpperCAmelCase				:      str			  =				json.loads(tokenizer_component_instance.__getstate__())

         # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
         if "sep" in state:
             _UpperCAmelCase				:      str			  =				tuple(state['''sep'''])
         if "cls" in state:
             _UpperCAmelCase				:      List[str]			  =				tuple(state['''cls'''])

         _UpperCAmelCase				:      List[str]			  =				False

         if state.get('''add_prefix_space'''							,  _A) != add_prefix_space:
             _UpperCAmelCase				:      int			  =				add_prefix_space
             _UpperCAmelCase				:      Optional[int]			  =				True

         if state.get('''trim_offsets'''							,  _A) != trim_offsets:
             _UpperCAmelCase				:      List[Any]			  =				trim_offsets
             _UpperCAmelCase				:      Any			  =				True

         if changes_to_apply:
             _UpperCAmelCase				:      Optional[Any]			  =				getattr(_A							,  state.pop('''type'''))
             _UpperCAmelCase				:      Union[str, Any]			  =				component_class(**_A)
             setattr(self.backend_tokenizer							,  _A							,  _A)


 @property
 # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot
 def  snake_case__				(	self) ->		str:

     """simple docstring"""



     if self._mask_token is None:
         if self.verbose:
             logger.error('''Using mask_token, but it is not set yet.''')
         return None
     return str(self._mask_token)


 @mask_token.setter
 def  snake_case__				(	self							,  _A) ->		str:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				AddedToken(_A							,  lstrip=_A							,  rstrip=_A) if isinstance(_A							,  _A) else value
     _UpperCAmelCase				:      Union[str, Any]			  =				value


 def  snake_case__				(	self							,  *_A							,  **_A) ->		BatchEncoding:

     """simple docstring"""



     _UpperCAmelCase				:      List[Any]			  =				kwargs.get('''is_split_into_words'''							,  _A)
     assert self.add_prefix_space or not is_split_into_words, (
         f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
         "to use it with pretokenized inputs."
     )

     return super()._batch_encode_plus(*_A							,  **_A)


 def  snake_case__				(	self							,  *_A							,  **_A) ->		BatchEncoding:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				kwargs.get('''is_split_into_words'''							,  _A)

     assert self.add_prefix_space or not is_split_into_words, (
         f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
         "to use it with pretokenized inputs."
     )

     return super()._encode_plus(*_A							,  **_A)


 def  snake_case__				(	self							,  _A							,  _A = None) ->		Tuple[str]:

     """simple docstring"""



     _UpperCAmelCase				:      str			  =				self._tokenizer.model.save(_A							,  name=_A)
     return tuple(_A)


 def  snake_case__				(	self							,  _A							,  _A = None) ->		List[int]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				[self.sep_token_id]
     _UpperCAmelCase				:      str			  =				[self.cls_token_id]

     if token_ids_a is None:
         return len(cls + token_ids_a + sep) * [0]
     return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]


 def  snake_case__				(	self							,  _A							,  _A = None) ->		Optional[Any]:

     """simple docstring"""



     return token_ids_a + [self.eos_token_id]


 def  snake_case__				(	self							,  _A) ->		List[int]:

     """simple docstring"""



     _UpperCAmelCase				:      Dict			  =				[]
     for is_user, text in conversation.iter_texts():
         if is_user:
             # We need to space prefix as it's being done within blenderbot
             inputs.append(''' ''' + text)
         else:
             # Generated responses should contain them already.
             inputs.append(_A)

     _UpperCAmelCase				:      int			  =				'''  '''.join(_A)
     _UpperCAmelCase				:      Optional[int]			  =				self.encode(_A)
     if len(_A) > self.model_max_length:
         _UpperCAmelCase				:      str			  =				input_ids[-self.model_max_length :]
         logger.warning(f'''Trimmed input from conversation as it was longer than {self.model_max_length} tokens.''')
     return input_ids




