

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			:     List[Any]										=      logging.get_logger(__name__)  # pylint: disable=invalid-name



class lowerCamelCase			(  lowercase__	,						lowercase__						):



			'''simple docstring'''






			@register_to_config
			def __init__(				self	:						Optional[int]		,      lowerCAmelCase_	:						bool		,      lowerCAmelCase_	:						Optional[int] = None		,      lowerCAmelCase_	:						Optional[int] = None			)      ->		Tuple:





									'''simple docstring'''
									super().__init__()

									A__					:       List[Any]     =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"

															A__					:       Optional[Any]     =torch.zeros(_a		,      _a			)
									else:
															A__					:       Tuple     =None

									A__					:       Tuple     =torch.nn.Parameter(_a			)



class lowerCamelCase			(  lowercase__						):



			'''simple docstring'''






			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42


			def __init__(				self	:						Tuple		,      lowerCAmelCase_	:						VQModel		,      lowerCAmelCase_	:						CLIPTextModel		,      lowerCAmelCase_	:						CLIPTokenizer		,      lowerCAmelCase_	:						TransformeraDModel		,      lowerCAmelCase_	:						VQDiffusionScheduler		,      lowerCAmelCase_	:						LearnedClassifierFreeSamplingEmbeddings		,      )      ->		Any:





									'''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 lowercase__						(				self	:						Union[str, Any]		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						Optional[int]			)      ->		Optional[int]:





									'''simple docstring'''
									A__					:       Optional[int]     =len(_a			) if isinstance(_a		,      _a			) else 1

									# get prompt text embeddings
									A__					:       Optional[int]     =self.tokenizer(
									    _a		,      padding="""max_length"""		,      max_length=self.tokenizer.model_max_length		,      return_tensors="""pt"""		,      )
									A__					:       List[str]     =text_inputs.input_ids

									if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
															A__					:       Optional[int]     =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}"			)
															A__					:       Tuple     =text_input_ids[:, : self.tokenizer.model_max_length]
									A__					:       Optional[Any]     =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
									A__					:       List[Any]     =prompt_embeds / prompt_embeds.norm(dim=-1		,      keepdim=_a			)

									# duplicate text embeddings for each generation per prompt
									A__					:       int     =prompt_embeds.repeat_interleave(_a		,      dim=0			)

									if do_classifier_free_guidance:
															if self.learned_classifier_free_sampling_embeddings.learnable:
																					A__					:       List[Any]     =self.learned_classifier_free_sampling_embeddings.embeddings
																					A__					:       Union[str, Any]     =negative_prompt_embeds.unsqueeze(0			).repeat(_a		,      1		,      1			)
															else:
																					A__					:       int     =[''] * batch_size

																					A__					:       str     =text_input_ids.shape[-1]
																					A__					:       Any     =self.tokenizer(
																					    _a		,      padding="""max_length"""		,      max_length=_a		,      truncation=_a		,      return_tensors="""pt"""		,      )
																					A__					:       List[Any]     =self.text_encoder(uncond_input.input_ids.to(self.device			)			)[0]
																					# See comment for normalizing text embeddings
																					A__					:       int     =negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1		,      keepdim=_a			)

															# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
															A__					:       Union[str, Any]     =negative_prompt_embeds.shape[1]
															A__					:       List[Any]     =negative_prompt_embeds.repeat(1		,      _a		,      1			)
															A__					:       Optional[int]     =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
															A__					:       str     =torch.cat([negative_prompt_embeds, prompt_embeds]			)

									return prompt_embeds


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





									'''simple docstring'''






									if isinstance(_a		,      _a			):
															A__					:       Dict     =1
									elif isinstance(_a		,      _a			):
															A__					:       Optional[Any]     =len(_a			)
									else:
															raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(_a			)}"			)

									A__					:       Tuple     =batch_size * num_images_per_prompt

									A__					:       Any     =guidance_scale > 1.0

									A__					:       Union[str, Any]     =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

									A__					:       Optional[int]     =(batch_size, self.transformer.num_latent_pixels)
									if latents is None:
															A__					:       Dict     =self.transformer.num_vector_embeds - 1
															A__					:       Tuple     =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)."			)
															A__					:       Any     =latents.to(self.device			)

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

									A__					:       Union[str, Any]     =self.scheduler.timesteps.to(self.device			)

									A__					:       Tuple     =latents

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

															# predict the un-noised image
															# model_output == `log_p_x_0`
															A__					:       Tuple     =self.transformer(_a		,      encoder_hidden_states=_a		,      timestep=_a			).sample

															if do_classifier_free_guidance:
																					A__					:       List[Any]     =model_output.chunk(2			)
																					A__					:       List[str]     =model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
																					model_output -= torch.logsumexp(_a		,      dim=1		,      keepdim=_a			)

															A__					:       Dict     =self.truncate(_a		,      _a			)

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

															# compute the previous noisy sample x_t -> x_t-1
															A__					:       Dict     =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			)

									A__					:       str     =self.vqvae.config.vq_embed_dim
									A__					:       Tuple     =(batch_size, self.transformer.height, self.transformer.width, embedding_channels)
									A__					:       int     =self.vqvae.quantize.get_codebook_entry(_a		,      shape=_a			)
									A__					:       Union[str, Any]     =self.vqvae.decode(_a		,      force_not_quantize=_a			).sample

									A__					:       Dict     =(image / 2 + 0.5).clamp(0		,      1			)
									A__					:       Optional[Any]     =image.cpu().permute(0		,      2		,      3		,      1			).numpy()

									if output_type == "pil":
															A__					:       List[str]     =self.numpy_to_pil(_a			)

									if not return_dict:
															return (image,)

									return ImagePipelineOutput(images=_a			)



			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						torch.FloatTensor		,      lowerCAmelCase_	:						float			)      ->		Any:





									'''simple docstring'''
									A__					:       int     =torch.sort(_a		,      1		,      descending=_a			)
									A__					:       str     =torch.exp(_a			)
									A__					:       List[str]     =sorted_p_x_0.cumsum(dim=1			) < truncation_rate

									# Ensure that at least the largest probability is not zeroed out
									A__					:       Union[str, Any]     =torch.full_like(keep_mask[:, 0:1, :]		,      _a			)
									A__					:       Optional[int]     =torch.cat((all_true, keep_mask)		,      dim=1			)
									A__					:       int     =keep_mask[:, :-1, :]

									A__					:       Any     =keep_mask.gather(1		,      indices.argsort(1			)			)

									A__					:       Any     =log_p_x_0.clone()

									A__					:       List[Any]     =-torch.inf  # -inf = log(0)

									return rv




'''simple docstring'''



import os
import re
import shutil
import sys
import tempfile
import unittest

import black


__snake_case			:     List[str]										=      os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, 'utils'))

import check_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
__snake_case			:     Optional[int]										=      '    def __init__(self, config):\n        super().__init__()\n        self.transform = BertPredictionHeadTransform(config)\n\n        # The output weights are the same as the input embeddings, but there is\n        # an output-only bias for each token.\n        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n        self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n        self.decoder.bias = self.bias\n\n    def forward(self, hidden_states):\n        hidden_states = self.transform(hidden_states)\n        hidden_states = self.decoder(hidden_states)\n        return hidden_states\n'



class lowerCamelCase			(  unittest.TestCase						):



			'''simple docstring'''






			def lowercase__						(				self	:						Tuple			)      ->		Dict:





									'''simple docstring'''
									A__					:       Tuple     =tempfile.mkdtemp()
									os.makedirs(os.path.join(self.transformer_dir		,      """models/bert/"""			)			)
									A__					:       List[str]     =self.transformer_dir
									shutil.copy(
									    os.path.join(lowerCAmelCase_		,      """src/transformers/models/bert/modeling_bert.py"""			)		,      os.path.join(self.transformer_dir		,      """models/bert/modeling_bert.py"""			)		,      )


			def lowercase__						(				self	:						str			)      ->		List[str]:





									'''simple docstring'''
									A__					:       Union[str, Any]     ="""src/transformers"""
									shutil.rmtree(self.transformer_dir			)


			def lowercase__						(				self	:						Union[str, Any]		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						int=None			)      ->		Dict:





									'''simple docstring'''
									A__					:       Union[str, Any]     =comment + f"\nclass {class_name}(nn.Module):\n" + class_code
									if overwrite_result is not None:
															A__					:       Optional[Any]     =comment + f"\nclass {class_name}(nn.Module):\n" + overwrite_result
									A__					:       str     =black.Mode(target_versions={black.TargetVersion.PYaa}		,      line_length=1_19			)
									A__					:       Any     =black.format_str(lowerCAmelCase_		,      mode=lowerCAmelCase_			)
									A__					:       Union[str, Any]     =os.path.join(self.transformer_dir		,      """new_code.py"""			)
									with open(lowerCAmelCase_		,      """w"""		,      newline="""\n"""			) as f:
															f.write(lowerCAmelCase_			)
									if overwrite_result is None:
															self.assertTrue(len(check_copies.is_copy_consistent(lowerCAmelCase_			)			) == 0			)
									else:
															check_copies.is_copy_consistent(f.name		,      overwrite=lowerCAmelCase_			)
															with open(lowerCAmelCase_		,      """r"""			) as f:
																					self.assertTrue(f.read()		,      lowerCAmelCase_			)


			def lowercase__						(				self	:						Any			)      ->		Any:





									'''simple docstring'''
									A__					:       Dict     =check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead"""			)
									self.assertEqual(lowerCAmelCase_		,      lowerCAmelCase_			)


			def lowercase__						(				self	:						Dict			)      ->		List[Any]:





									'''simple docstring'''
									# Base copy consistency
									self.check_copy_consistency(
									    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"""		,      """BertLMPredictionHead"""		,      REFERENCE_CODE + """\n"""		,      )

									# With no empty line at the end
									self.check_copy_consistency(
									    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"""		,      """BertLMPredictionHead"""		,      lowerCAmelCase_		,      )

									# Copy consistency with rename
									self.check_copy_consistency(
									    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"""		,      """TestModelLMPredictionHead"""		,      re.sub("""Bert"""		,      """TestModel"""		,      lowerCAmelCase_			)		,      )

									# Copy consistency with a really long name
									A__					:       Tuple     ="""TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason"""
									self.check_copy_consistency(
									    f"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}"		,      f"{long_class_name}LMPredictionHead"		,      re.sub("""Bert"""		,      lowerCAmelCase_		,      lowerCAmelCase_			)		,      )

									# Copy consistency with overwrite
									self.check_copy_consistency(
									    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"""		,      """TestModelLMPredictionHead"""		,      lowerCAmelCase_		,      overwrite_result=re.sub("""Bert"""		,      """TestModel"""		,      lowerCAmelCase_			)		,      )



			def lowercase__						(				self	:						Optional[Any]			)      ->		Optional[int]:





									'''simple docstring'''
									A__					:       List[Any]     =check_copies.LOCALIZED_READMES["""README_zh-hans.md"""]

									A__					:       List[str]     =(
									    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"""
									    """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"""
									    """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"""
									    """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."""
									    """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"""
									    """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"""
									    """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"""
									    """ method has been applied to compress GPT2 into"""
									    """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"""
									    """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"""
									    """ Multilingual BERT into"""
									    """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"""
									    """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"""
									    """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"""
									    """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"""
									    """ Luong, Quoc V. Le, Christopher D. Manning."""
									)
									A__					:       Union[str, Any]     =(
									    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
									    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
									    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
									    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
									)
									A__					:       str     =(
									    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
									    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
									    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
									    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."""
									    """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"""
									    """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"""
									    """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"""
									    """ method has been applied to compress GPT2 into"""
									    """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"""
									    """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"""
									    """ Multilingual BERT into"""
									    """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"""
									    """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"""
									    """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"""
									    """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"""
									    """ Christopher D. Manning 发布。\n"""
									)

									A__   ,						A__					:       Optional[Any]     =check_copies.convert_to_localized_md(
									    lowerCAmelCase_		,      lowerCAmelCase_		,      localized_readme["""format_model_list"""]			)

									self.assertFalse(lowerCAmelCase_			)
									self.assertEqual(lowerCAmelCase_		,      lowerCAmelCase_			)

									A__   ,						A__					:       List[str]     =check_copies.convert_to_localized_md(
									    lowerCAmelCase_		,      lowerCAmelCase_		,      localized_readme["""format_model_list"""]			)

									# Check whether the number of models is equal to README.md after conversion.
									self.assertTrue(lowerCAmelCase_			)

									A__					:       Dict     =(
									    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"""
									    """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"""
									    """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"""
									    """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."""
									)
									A__					:       str     =(
									    """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"""
									    """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
									    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
									    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
									)
									A__					:       int     =(
									    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
									    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
									    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
									    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
									)

									A__   ,						A__					:       int     =check_copies.convert_to_localized_md(
									    lowerCAmelCase_		,      lowerCAmelCase_		,      localized_readme["""format_model_list"""]			)

									# Check if the model link is synchronized.
									self.assertEqual(lowerCAmelCase_		,      lowerCAmelCase_			)

