





"""simple docstring"""




import unittest

import torch

from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()

class  _UpperCAmelCase  (   UpperCAmelCase__			,   UpperCAmelCase__			,   unittest.TestCase		):



      '''simple docstring'''
      lowercase_      : Any	    =   VQModel
      lowercase_      : Dict	    =   """sample"""

      @property
      def 					lowerCamelCase_			(     self					,      snake_case_=(3_2, 3_2)  ):

        """simple docstring"""

        A_  :       Union[str, Any]										=  4
        A_  :       int										=  3

        A_  :       Union[str, Any]										=  floats_tensor((batch_size, num_channels) + sizes  ).to(snake_case_  )

        return {"sample": image}

      @property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        return (3, 3_2, 3_2)

      @property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        return (3, 3_2, 3_2)

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       int										=  {
            'block_out_channels': [3_2, 6_4],
            'in_channels': 3,
            'out_channels': 3,
            'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'],
            'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'],
            'latent_channels': 3,
        }
        A_  :       int										=  self.dummy_input
        return init_dict, inputs_dict

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        pass

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        pass

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_						,       A_  :       int										=  VQModel.from_pretrained('fusing/vqgan-dummy'					,      output_loading_info=snake_case_  )
        self.assertIsNotNone(snake_case_  )
        self.assertEqual(len(loading_info['missing_keys']  )					,      0  )

        model.to(snake_case_  )
        A_  :       Optional[Any]										=  model(**self.dummy_input  )

        assert image is not None, "Make sure output is not None"

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       int										=  VQModel.from_pretrained('fusing/vqgan-dummy'  )
        model.to(snake_case_  ).eval()

        torch.manual_seed(0  )
        if torch.cuda.is_available():
          torch.cuda.manual_seed_all(0  )

        A_  :       Optional[Any]										=  torch.randn(1					,      model.config.in_channels					,      model.config.sample_size					,      model.config.sample_size  )
        A_  :       Optional[Any]										=  image.to(snake_case_  )
        with torch.no_grad():
          A_  :       List[str]										=  model(snake_case_  ).sample

        A_  :       Optional[Any]										=  output[0, -1, -3:, -3:].flatten().cpu()
        # fmt: off
        A_  :       Optional[Any]										=  torch.tensor([-0.01_53, -0.40_44, -0.18_80, -0.51_61, -0.24_18, -0.40_72, -0.16_12, -0.06_33, -0.01_43]  )
        # fmt: on
        self.assertTrue(torch.allclose(snake_case_					,      snake_case_					,      atol=1E-3  )  )






"""simple docstring"""




import copy
import random

from transformers import CLIPTokenizer

class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''

      def __init__(     self					,      *snake_case_					,      **snake_case_  ):

        """simple docstring"""

        super().__init__(*snake_case_					,      **snake_case_  )
        A_  :       Tuple										=  {}

      def 					lowerCamelCase_			(     self					,      snake_case_					,      *snake_case_					,      **snake_case_  ):

        """simple docstring"""

        A_  :       str										=  super().add_tokens(snake_case_					,      *snake_case_					,      **snake_case_  )
        if num_added_tokens == 0:
          raise ValueError(
              F"""The tokenizer already contains the token {placeholder_token}. Please pass a different"""
              ' `placeholder_token` that is not already in the tokenizer.'  )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      *snake_case_					,      snake_case_=1					,      **snake_case_  ):

        """simple docstring"""

        A_  :       Tuple										=  []
        if num_vec_per_token == 1:
          self.try_adding_tokens(snake_case_					,      *snake_case_					,      **snake_case_  )
          output.append(snake_case_  )
        else:
          A_  :       Tuple										=  []
          for i in range(snake_case_  ):
            A_  :       List[str]										=  placeholder_token + F"""_{i}"""
            self.try_adding_tokens(snake_case_					,      *snake_case_					,      **snake_case_  )
            output.append(snake_case_  )
        # handle cases where there is a new placeholder token that contains the current placeholder token but is larger
        for token in self.token_map:
          if token in placeholder_token:
            raise ValueError(
                F"""The tokenizer already has placeholder token {token} that can get confused with"""
                F""" {placeholder_token}keep placeholder tokens independent"""  )
        A_  :       Any										=  output

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_=False					,      snake_case_=1.0  ):

        """simple docstring"""

        if isinstance(snake_case_					,      snake_case_  ):
          A_  :       Optional[Any]										=  []
          for i in range(len(snake_case_  )  ):
            output.append(self.replace_placeholder_tokens_in_text(text[i]					,      vector_shuffle=snake_case_  )  )
          return output
        for placeholder_token in self.token_map:
          if placeholder_token in text:
            A_  :       List[Any]										=  self.token_map[placeholder_token]
            A_  :       Optional[int]										=  tokens[: 1 + int(len(snake_case_  ) * prop_tokens_to_load  )]
            if vector_shuffle:
              A_  :       Optional[Any]										=  copy.copy(snake_case_  )
              random.shuffle(snake_case_  )
            A_  :       List[str]										=  text.replace(snake_case_					,      ' '.join(snake_case_  )  )
        return text

      def __call__(     self					,      snake_case_					,      *snake_case_					,      snake_case_=False					,      snake_case_=1.0					,      **snake_case_  ):

        """simple docstring"""

        return super().__call__(
            self.replace_placeholder_tokens_in_text(
                snake_case_					,      vector_shuffle=snake_case_					,      prop_tokens_to_load=snake_case_  )					,      *snake_case_					,      **snake_case_					,      )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      *snake_case_					,      snake_case_=False					,      snake_case_=1.0					,      **snake_case_  ):

        """simple docstring"""

        return super().encode(
            self.replace_placeholder_tokens_in_text(
                snake_case_					,      vector_shuffle=snake_case_					,      prop_tokens_to_load=snake_case_  )					,      *snake_case_					,      **snake_case_					,      )