


from typing import Callable, List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModel, CLIPTokenizer

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


__snake_case   							=						logging.get_logger(__name__)  # pylint: disable=invalid-name



class 	__lowerCamelCase			(_a				,      _a						):







       @register_to_config
       def __init__(			self: str,A_: bool,A_: Optional[int] = None,A_: Optional[int] = None					):






            '''simple docstring'''




            super().__init__()

            __UpperCamelCase =			learnable

            if self.learnable:
                 assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
                 assert length is not None, "learnable=True requires `length` to be set"

                 __UpperCamelCase =			torch.zeros(A_,A_					)
            else:
                 __UpperCamelCase =			None

            __UpperCamelCase =			torch.nn.Parameter(A_					)



class 	__lowerCamelCase			(_a						):
       _lowercase											=     42
       _lowercase											=     42
       _lowercase											=     42
       _lowercase											=     42
       _lowercase											=     42
       _lowercase											=     42







       def __init__(			self: Any,A_: VQModel,A_: CLIPTextModel,A_: CLIPTokenizer,A_: TransformeraDModel,A_: VQDiffusionScheduler,A_: LearnedClassifierFreeSamplingEmbeddings,):






            '''simple docstring'''




            super().__init__()

            self.register_modules(
                vqvae=A_,transformer=A_,text_encoder=A_,tokenizer=A_,scheduler=A_,learned_classifier_free_sampling_embeddings=A_,)







       def 		snake_case_	(			self: Dict,A_: Optional[Any],A_: Any,A_: str					):






            '''simple docstring'''




            __UpperCamelCase =			len(A_					) if isinstance(A_,A_					) else 1

            # get prompt text embeddings
            __UpperCamelCase =			self.tokenizer(
                A_,padding='max_length',max_length=self.tokenizer.model_max_length,return_tensors='pt',)
            __UpperCamelCase =			text_inputs.input_ids

            if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
                 __UpperCamelCase =			self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]					)
                 logger.warning(
                     'The following part of your input was truncated because CLIP can only handle sequences up to'
                     F''' {self.tokenizer.model_max_length} tokens: {removed_text}'''					)
                 __UpperCamelCase =			text_input_ids[:, : self.tokenizer.model_max_length]
            __UpperCamelCase =			self.text_encoder(text_input_ids.to(self.device					)					)[0]

            # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
            # While CLIP does normalize the pooled output of the text transformer when combining
            # the image and text embeddings, CLIP does not directly normalize the last hidden state.
            #
            # CLIP normalizing the pooled output.
            # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
            __UpperCamelCase =			prompt_embeds / prompt_embeds.norm(dim=-1,keepdim=A_					)

            # duplicate text embeddings for each generation per prompt
            __UpperCamelCase =			prompt_embeds.repeat_interleave(A_,dim=0					)

            if do_classifier_free_guidance:
                 if self.learned_classifier_free_sampling_embeddings.learnable:
                      __UpperCamelCase =			self.learned_classifier_free_sampling_embeddings.embeddings
                      __UpperCamelCase =			negative_prompt_embeds.unsqueeze(0					).repeat(A_,1,1					)
                 else:
                      __UpperCamelCase =			[''] * batch_size

                      __UpperCamelCase =			text_input_ids.shape[-1]
                      __UpperCamelCase =			self.tokenizer(
                          A_,padding='max_length',max_length=A_,truncation=A_,return_tensors='pt',)
                      __UpperCamelCase =			self.text_encoder(uncond_input.input_ids.to(self.device					)					)[0]
                      # See comment for normalizing text embeddings
                      __UpperCamelCase =			negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1,keepdim=A_					)

                 # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
                 __UpperCamelCase =			negative_prompt_embeds.shape[1]
                 __UpperCamelCase =			negative_prompt_embeds.repeat(1,A_,1					)
                 __UpperCamelCase =			negative_prompt_embeds.view(batch_size * num_images_per_prompt,A_,-1					)

                 # For classifier free guidance, we need to do two forward passes.
                 # Here we concatenate the unconditional and text embeddings into a single batch
                 # to avoid doing two forward passes
                 __UpperCamelCase =			torch.cat([negative_prompt_embeds, prompt_embeds]					)

            return prompt_embeds







       @torch.no_grad()
       def __call__(			self: List[str],A_: Union[str, List[str]],A_: int = 100,A_: float = 5.0,A_: float = 1.0,A_: int = 1,A_: Optional[Union[torch.Generator, List[torch.Generator]]] = None,A_: Optional[torch.FloatTensor] = None,A_: Optional[str] = "pil",A_: bool = True,A_: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,A_: int = 1,):






            '''simple docstring'''




            if isinstance(A_,A_					):
                 __UpperCamelCase =			1
            elif isinstance(A_,A_					):
                 __UpperCamelCase =			len(A_					)
            else:
                 raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(A_					)}'''					)

            __UpperCamelCase =			batch_size * num_images_per_prompt

            __UpperCamelCase =			guidance_scale > 1.0

            __UpperCamelCase =			self._encode_prompt(A_,A_,A_					)

            if (callback_steps is None) or (
                callback_steps is not None and (not isinstance(A_,A_					) or callback_steps <= 0)
            ):
                 raise ValueError(
                     F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
                     F''' {type(A_					)}.'''					)

            # get the initial completely masked latents unless the user supplied it

            __UpperCamelCase =			(batch_size, self.transformer.num_latent_pixels)
            if latents is None:
                 __UpperCamelCase =			self.transformer.num_vector_embeds - 1
                 __UpperCamelCase =			torch.full(A_,A_					).to(self.device					)
            else:
                 if latents.shape != latents_shape:
                      raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}'''					)
                 if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
                      raise ValueError(
                          'Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,'
                          F''' {self.transformer.num_vector_embeds - 1} (inclusive).'''					)
                 __UpperCamelCase =			latents.to(self.device					)

            # set timesteps
            self.scheduler.set_timesteps(A_,device=self.device					)

            __UpperCamelCase =			self.scheduler.timesteps.to(self.device					)

            __UpperCamelCase =			latents

            for i, t in enumerate(self.progress_bar(A_					)					):
                 # expand the sample if we are doing classifier free guidance
                 __UpperCamelCase =			torch.cat([sample] * 2					) if do_classifier_free_guidance else sample

                 # predict the un-noised image
                 # model_output == `log_p_x_0`
                 __UpperCamelCase =			self.transformer(A_,encoder_hidden_states=A_,timestep=A_					).sample

                 if do_classifier_free_guidance:
                      __UpperCamelCase,    __UpperCamelCase =			model_output.chunk(2					)
                      __UpperCamelCase =			model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
                      model_output -= torch.logsumexp(A_,dim=1,keepdim=A_					)

                 __UpperCamelCase =			self.truncate(A_,A_					)

                 # remove `log(0)`'s (`-inf`s)
                 __UpperCamelCase =			model_output.clamp(-70					)

                 # compute the previous noisy sample x_t -> x_t-1
                 __UpperCamelCase =			self.scheduler.step(A_,timestep=A_,sample=A_,generator=A_					).prev_sample

                 # call the callback, if provided
                 if callback is not None and i % callback_steps == 0:
                      callback(A_,A_,A_					)

            __UpperCamelCase =			self.vqvae.config.vq_embed_dim
            __UpperCamelCase =			(batch_size, self.transformer.height, self.transformer.width, embedding_channels)
            __UpperCamelCase =			self.vqvae.quantize.get_codebook_entry(A_,shape=A_					)
            __UpperCamelCase =			self.vqvae.decode(A_,force_not_quantize=A_					).sample

            __UpperCamelCase =			(image / 2 + 0.5).clamp(0,1					)
            __UpperCamelCase =			image.cpu().permute(0,2,3,1					).numpy()

            if output_type == "pil":
                 __UpperCamelCase =			self.numpy_to_pil(A_					)

            if not return_dict:
                 return (image,)

            return ImagePipelineOutput(images=A_					)







       def 		snake_case_	(			self: int,A_: torch.FloatTensor,A_: float					):






            '''simple docstring'''




            __UpperCamelCase,    __UpperCamelCase =			torch.sort(A_,1,descending=A_					)
            __UpperCamelCase =			torch.exp(A_					)
            __UpperCamelCase =			sorted_p_x_0.cumsum(dim=1					) < truncation_rate

            # Ensure that at least the largest probability is not zeroed out
            __UpperCamelCase =			torch.full_like(keep_mask[:, 0:1, :],A_					)
            __UpperCamelCase =			torch.cat((all_true, keep_mask),dim=1					)
            __UpperCamelCase =			keep_mask[:, :-1, :]

            __UpperCamelCase =			keep_mask.gather(1,indices.argsort(1					)					)

            __UpperCamelCase =			log_p_x_0.clone()

            __UpperCamelCase =			-torch.inf  # -inf = log(0)

            return rv






from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__snake_case   							=						logging.get_logger(__name__)

__snake_case   							=						{
    '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/config.json''',
    '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/config.json''',
    '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/config.json''',
    '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/config.json''',
    '''bert-base-multilingual-uncased''': '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json''',
    '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json''',
    '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/config.json''',
    '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/config.json''',
    '''bert-large-uncased-whole-word-masking''': (
        '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json'''
    ),
    '''bert-large-cased-whole-word-masking''': (
        '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json'''
    ),
    '''bert-large-uncased-whole-word-masking-finetuned-squad''': (
        '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json'''
    ),
    '''bert-large-cased-whole-word-masking-finetuned-squad''': (
        '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json'''
    ),
    '''bert-base-cased-finetuned-mrpc''': '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json''',
    '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json''',
    '''bert-base-german-dbmdz-uncased''': '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json''',
    '''cl-tohoku/bert-base-japanese''': '''https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json''',
    '''cl-tohoku/bert-base-japanese-whole-word-masking''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json'''
    ),
    '''cl-tohoku/bert-base-japanese-char''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json'''
    ),
    '''cl-tohoku/bert-base-japanese-char-whole-word-masking''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json'''
    ),
    '''TurkuNLP/bert-base-finnish-cased-v1''': (
        '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json'''
    ),
    '''TurkuNLP/bert-base-finnish-uncased-v1''': (
        '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json'''
    ),
    '''wietsedv/bert-base-dutch-cased''': '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json''',
    # See all BERT models at https://huggingface.co/models?filter=bert
}



class 	__lowerCamelCase			(_a						):
       _lowercase											=     """bert"""







       def __init__(			self: Any,A_: Dict=3_0522,A_: Optional[Any]=768,A_: Union[str, Any]=12,A_: List[Any]=12,A_: Optional[int]=3072,A_: Union[str, Any]="gelu",A_: List[str]=0.1,A_: Dict=0.1,A_: Optional[int]=512,A_: Optional[Any]=2,A_: Union[str, Any]=0.0_2,A_: List[Any]=1E-12,A_: Optional[int]=0,A_: List[Any]="absolute",A_: str=True,A_: Union[str, Any]=None,**A_: int,):






            '''simple docstring'''




            super().__init__(pad_token_id=A_,**A_					)

            __UpperCamelCase =			vocab_size
            __UpperCamelCase =			hidden_size
            __UpperCamelCase =			num_hidden_layers
            __UpperCamelCase =			num_attention_heads
            __UpperCamelCase =			hidden_act
            __UpperCamelCase =			intermediate_size
            __UpperCamelCase =			hidden_dropout_prob
            __UpperCamelCase =			attention_probs_dropout_prob
            __UpperCamelCase =			max_position_embeddings
            __UpperCamelCase =			type_vocab_size
            __UpperCamelCase =			initializer_range
            __UpperCamelCase =			layer_norm_eps
            __UpperCamelCase =			position_embedding_type
            __UpperCamelCase =			use_cache
            __UpperCamelCase =			classifier_dropout



class 	__lowerCamelCase			(_a						):







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






            '''simple docstring'''




            if self.task == "multiple-choice":
                 __UpperCamelCase =			{0: 'batch', 1: 'choice', 2: 'sequence'}
            else:
                 __UpperCamelCase =			{0: 'batch', 1: 'sequence'}
            return OrderedDict(
                [
                    ('input_ids', dynamic_axis),
                    ('attention_mask', dynamic_axis),
                    ('token_type_ids', dynamic_axis),
                ]					)


