
"""simple docstring"""





from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers.models.xglm.modeling_tf_xglm import (
        TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFXGLMForCausalLM,
        TFXGLMModel,
    )


@require_tf
class A_	:




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__			:						Tuple       =		XGLMConfig
  SCREAMING_SNAKE_CASE__			:						Union[str, Any]       =		{}
  SCREAMING_SNAKE_CASE__			:						Optional[Any]       =		"""gelu"""







  def __init__(		self				,   lowercase_				,   lowercase_=14				,   lowercase_=7				,   lowercase_=True				,   lowercase_=True				,   lowercase_=True				,   lowercase_=99				,   lowercase_=32				,   lowercase_=2				,   lowercase_=4				,   lowercase_=37				,   lowercase_="gelu"				,   lowercase_=0.1				,   lowercase_=0.1				,   lowercase_=512				,   lowercase_=0.02				,   ):

     """simple docstring"""
     UpperCAmelCase_					:					Optional[int]			     =    parent
     UpperCAmelCase_					:					Tuple			     =    batch_size
     UpperCAmelCase_					:					Optional[int]			     =    seq_length
     UpperCAmelCase_					:					Union[str, Any]			     =    is_training
     UpperCAmelCase_					:					List[Any]			     =    use_input_mask
     UpperCAmelCase_					:					Tuple			     =    use_labels
     UpperCAmelCase_					:					List[Any]			     =    vocab_size
     UpperCAmelCase_					:					Union[str, Any]			     =    d_model
     UpperCAmelCase_					:					Optional[int]			     =    num_hidden_layers
     UpperCAmelCase_					:					List[Any]			     =    num_attention_heads
     UpperCAmelCase_					:					List[Any]			     =    ffn_dim
     UpperCAmelCase_					:					int			     =    activation_function
     UpperCAmelCase_					:					List[str]			     =    activation_dropout
     UpperCAmelCase_					:					List[Any]			     =    attention_dropout
     UpperCAmelCase_					:					List[str]			     =    max_position_embeddings
     UpperCAmelCase_					:					Optional[Any]			     =    initializer_range
     UpperCAmelCase_					:					Optional[Any]			     =    None
     UpperCAmelCase_					:					Dict			     =    0
     UpperCAmelCase_					:					List[str]			     =    2
     UpperCAmelCase_					:					Tuple			     =    1







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     return XGLMConfig.from_pretrained("facebook/xglm-564M"  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					Union[str, Any]			     =    tf.clip_by_value(
         ids_tensor([self.batch_size, self.seq_length]				,   self.vocab_size  )				,   clip_value_min=0				,   clip_value_max=3  )

     UpperCAmelCase_					:					Optional[int]			     =    None
     if self.use_input_mask:
        UpperCAmelCase_					:					str			     =    random_attention_mask([self.batch_size, self.seq_length]  )

     UpperCAmelCase_					:					Union[str, Any]			     =    self.get_config()

     UpperCAmelCase_					:					List[Any]			     =    floats_tensor([self.num_hidden_layers, self.num_attention_heads]				,   2  )

     return (
         config,
         input_ids,
         input_mask,
         head_mask,
     )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     return XGLMConfig(
         vocab_size=self.vocab_size				,   d_model=self.hidden_size				,   num_layers=self.num_hidden_layers				,   attention_heads=self.num_attention_heads				,   ffn_dim=self.ffn_dim				,   activation_function=self.activation_function				,   activation_dropout=self.activation_dropout				,   attention_dropout=self.attention_dropout				,   max_position_embeddings=self.max_position_embeddings				,   initializer_range=self.initializer_range				,   use_cache=lowercase_				,   bos_token_id=self.bos_token_id				,   eos_token_id=self.eos_token_id				,   pad_token_id=self.pad_token_id				,   return_dict=lowercase_				,   )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					List[Any]			     =    self.prepare_config_and_inputs()

     (
         (
         UpperCAmelCase_
     )     ,   (
         UpperCAmelCase_
     )     ,   (
         UpperCAmelCase_
     )     ,   (
         UpperCAmelCase_
     )     ,   
     )					:					Any			     =    config_and_inputs

     UpperCAmelCase_					:					List[str]			     =    {
         "input_ids": input_ids,
         "head_mask": head_mask,
     }

     return config, inputs_dict




@require_tf
class A_	(lowercase__				,lowercase__				,unittest.TestCase      ):




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__			:						Union[str, Any]       =		(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
  SCREAMING_SNAKE_CASE__			:						Tuple       =		(TFXGLMForCausalLM,) if is_tf_available() else ()
  SCREAMING_SNAKE_CASE__			:						List[str]       =		(
      {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {}
  )
  SCREAMING_SNAKE_CASE__			:						List[str]       =		False
  SCREAMING_SNAKE_CASE__			:						List[str]       =		False
  SCREAMING_SNAKE_CASE__			:						Tuple       =		False







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					str			     =    TFXGLMModelTester(self  )
     UpperCAmelCase_					:					Dict			     =    ConfigTester(self				,   config_class=lowercase_				,   n_embd=37  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     self.config_tester.run_common_tests()







  @slow
  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCAmelCase_					:					Union[str, Any]			     =    TFXGLMModel.from_pretrained(lowercase_  )
        self.assertIsNotNone(lowercase_  )







  @unittest.skip(reason="Currently, model embeddings are going to undergo a major refactor."  )
  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     super().test_resize_token_embeddings()




@require_tf
class A_	(unittest.TestCase      ):




  '''simple docstring'''







  @slow
  def        UpperCamelCase__					(		self				,   lowercase_=True  ):

     """simple docstring"""
     UpperCAmelCase_					:					List[Any]			     =    TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"  )
     UpperCAmelCase_					:					Union[str, Any]			     =    tf.convert_to_tensor([[2, 268, 9865]]				,   dtype=tf.intaa  )  # The dog
     # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
     # fmt: off
     UpperCAmelCase_					:					Tuple			     =    [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581]
     # fmt: on
     UpperCAmelCase_					:					List[str]			     =    model.generate(lowercase_				,   do_sample=lowercase_				,   num_beams=1  )
     if verify_outputs:
        self.assertListEqual(output_ids[0].numpy().tolist()				,   lowercase_  )







  @slow
  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					Any			     =    XGLMTokenizer.from_pretrained("facebook/xglm-564M"  )
     UpperCAmelCase_					:					Any			     =    TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"  )

     tf.random.set_seed(0  )
     UpperCAmelCase_					:					Optional[Any]			     =    tokenizer("Today is a nice day and"				,   return_tensors="tf"  )
     UpperCAmelCase_					:					Optional[Any]			     =    tokenized.input_ids
     # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
     with tf.device(":/CPU:0"  ):
        UpperCAmelCase_					:					List[Any]			     =    model.generate(lowercase_				,   do_sample=lowercase_				,   seed=[7, 0]  )
     UpperCAmelCase_					:					Dict			     =    tokenizer.decode(output_ids[0]				,   skip_special_tokens=lowercase_  )

     UpperCAmelCase_					:					Dict			     =    (
         "Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"
     )
     self.assertEqual(lowercase_				,   lowercase_  )







  @slow
  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					Any			     =    TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"  )
     UpperCAmelCase_					:					Tuple			     =    XGLMTokenizer.from_pretrained("facebook/xglm-564M"  )

     UpperCAmelCase_					:					Any			     =    "left"

     # use different length sentences to test batching
     UpperCAmelCase_					:					List[str]			     =    [
         "This is an extremelly long sentence that only exists to test the ability of the model to cope with "
         "left-padding, such as in batched generation. The output for the sequence below should be the same "
         "regardless of whether left padding is applied or not. When",
         "Hello, my dog is a little",
     ]

     UpperCAmelCase_					:					List[Any]			     =    tokenizer(lowercase_				,   return_tensors="tf"				,   padding=lowercase_  )
     UpperCAmelCase_					:					Optional[int]			     =    inputs["input_ids"]

     UpperCAmelCase_					:					Union[str, Any]			     =    model.generate(input_ids=lowercase_				,   attention_mask=inputs["attention_mask"]				,   max_new_tokens=12  )

     UpperCAmelCase_					:					Optional[int]			     =    tokenizer(sentences[0]				,   return_tensors="tf"  ).input_ids
     UpperCAmelCase_					:					Optional[Any]			     =    model.generate(input_ids=lowercase_				,   max_new_tokens=12  )

     UpperCAmelCase_					:					List[str]			     =    tokenizer(sentences[1]				,   return_tensors="tf"  ).input_ids
     UpperCAmelCase_					:					List[Any]			     =    model.generate(input_ids=lowercase_				,   max_new_tokens=12  )

     UpperCAmelCase_					:					Optional[int]			     =    tokenizer.batch_decode(lowercase_				,   skip_special_tokens=lowercase_  )
     UpperCAmelCase_					:					List[Any]			     =    tokenizer.decode(output_non_padded[0]				,   skip_special_tokens=lowercase_  )
     UpperCAmelCase_					:					List[Any]			     =    tokenizer.decode(output_padded[0]				,   skip_special_tokens=lowercase_  )

     UpperCAmelCase_					:					Tuple			     =    [
         "This is an extremelly long sentence that only exists to test the ability of the model to cope with "
         "left-padding, such as in batched generation. The output for the sequence below should be the same "
         "regardless of whether left padding is applied or not. When left padding is applied, the sequence will be "
         "a single",
         "Hello, my dog is a little bit of a shy one, but he is very friendly",
     ]
     self.assertListEqual(lowercase_				,   lowercase_  )
     self.assertListEqual(lowercase_				,   [non_padded_sentence, padded_sentence]  )










from typing import List, Optional, Union

import torch

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


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

lowercase  							=					"\n    Examples:\n        ```py\n        >>> import torch\n        >>> import numpy as np\n\n        >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n        >>> from transformers import pipeline\n        >>> from diffusers.utils import load_image\n\n\n        >>> def make_hint(image, depth_estimator):\n        ...     image = depth_estimator(image)[\"depth\"]\n        ...     image = np.array(image)\n        ...     image = image[:, :, None]\n        ...     image = np.concatenate([image, image, image], axis=2)\n        ...     detected_map = torch.from_numpy(image).float() / 255.0\n        ...     hint = detected_map.permute(2, 0, 1)\n        ...     return hint\n\n\n        >>> depth_estimator = pipeline(\"depth-estimation\")\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior = pipe_prior.to(\"cuda\")\n\n        >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16\n        ... )\n        >>> pipe = pipe.to(\"cuda\")\n\n\n        >>> img = load_image(\n        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n        ...     \"/kandinsky/cat.png\"\n        ... ).resize((768, 768))\n\n        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")\n\n        >>> prompt = \"A robot, 4k photo\"\n        >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"\n\n        >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)\n\n        >>> image_emb, zero_image_emb = pipe_prior(\n        ...     prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n        ... ).to_tuple()\n\n        >>> images = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     hint=hint,\n        ...     num_inference_steps=50,\n        ...     generator=generator,\n        ...     height=768,\n        ...     width=768,\n        ... ).images\n\n        >>> images[0].save(\"robot_cat.png\")\n        ```\n"





def 						__UpperCAmelCase			(     a_							,     a_							,     a_=8):
							snake_case_				=							height // scale_factor**2
							if height % scale_factor**2 != 0:
														new_height += 1
							snake_case_				=							width // scale_factor**2
							if width % scale_factor**2 != 0:
														new_width += 1
							return new_height * scale_factor, new_width * scale_factor




class  UpperCamelCase_      (			snake_case_				):



	'''simple docstring'''




	def __init__(       self       ,			a       ,			a       ,			a       ,			)       ->    Tuple:
								super().__init__()

								self.register_modules(
								    unet=a       ,			scheduler=a       ,			movq=a       ,			)
								snake_case_				=							2 ** (len(self.movq.config.block_out_channels					) - 1)




	def 							_UpperCamelCase			(       self       ,			a       ,			a       ,			a       ,			a       ,			a       ,			a					)       ->    Any:
								if latents is None:
															snake_case_				=							randn_tensor(a       ,			generator=a       ,			device=a       ,			dtype=a					)
								else:
															if latents.shape != shape:
																						raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''					)
															snake_case_				=							latents.to(a					)

								snake_case_				=							latents * scheduler.init_noise_sigma
								return latents




	def 							_UpperCamelCase			(       self       ,			a=0					)       ->    str:
								if is_accelerate_available():
															from accelerate import cpu_offload
								else:
															raise ImportError('Please install accelerate via `pip install accelerate`'					)

								snake_case_				=							torch.device(F'''cuda:{gpu_id}'''					)

								snake_case_				=							[
								    self.unet,
								    self.movq,
								]
								for cpu_offloaded_model in models:
															if cpu_offloaded_model is not None:
																						cpu_offload(a       ,			a					)




	def 							_UpperCamelCase			(       self       ,			a=0					)       ->    List[str]:
								if is_accelerate_available() and is_accelerate_version('>='       ,			'0.17.0.dev0'					):
															from accelerate import cpu_offload_with_hook
								else:
															raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'					)

								snake_case_				=							torch.device(F'''cuda:{gpu_id}'''					)

								if self.device.type != "cpu":
															self.to('cpu'       ,			silence_dtype_warnings=a					)
															torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

								snake_case_				=							None
								for cpu_offloaded_model in [self.unet, self.movq]:
															snake_case_			,		snake_case_				=							cpu_offload_with_hook(a       ,			a       ,			prev_module_hook=a					)

								# We'll offload the last model manually.
								snake_case_				=							hook




	@property
	# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
	def 							_UpperCamelCase			(       self					)       ->    Any:
								if not hasattr(self.unet       ,			'_hf_hook'					):
															return self.device
								for module in self.unet.modules():
															if (
															    hasattr(a       ,			'_hf_hook'					)
															    and hasattr(module._hf_hook       ,			'execution_device'					)
															    and module._hf_hook.execution_device is not None
															):
																						return torch.device(module._hf_hook.execution_device					)
								return self.device






	@torch.no_grad()
	@replace_example_docstring(a					)
	def __call__(       self       ,			a       ,			a       ,			a       ,			a = 5_12       ,			a = 5_12       ,			a = 1_00       ,			a = 4.0       ,			a = 1       ,			a = None       ,			a = None       ,			a = "pil"       ,			a = True       ,			)       ->    List[str]:
								snake_case_				=							self._execution_device

								snake_case_				=							guidance_scale > 1.0

								if isinstance(a       ,			a					):
															snake_case_				=							torch.cat(a       ,			dim=0					)
								if isinstance(a       ,			a					):
															snake_case_				=							torch.cat(a       ,			dim=0					)
								if isinstance(a       ,			a					):
															snake_case_				=							torch.cat(a       ,			dim=0					)

								snake_case_				=							image_embeds.shape[0] * num_images_per_prompt

								if do_classifier_free_guidance:
															snake_case_				=							image_embeds.repeat_interleave(a       ,			dim=0					)
															snake_case_				=							negative_image_embeds.repeat_interleave(a       ,			dim=0					)
															snake_case_				=							hint.repeat_interleave(a       ,			dim=0					)

								snake_case_				=							torch.cat([negative_image_embeds, image_embeds]       ,			dim=0					).to(dtype=self.unet.dtype       ,			device=a					)
								snake_case_				=							torch.cat([hint, hint]       ,			dim=0					).to(dtype=self.unet.dtype       ,			device=a					)
								self.scheduler.set_timesteps(a       ,			device=a					)
								snake_case_				=							self.scheduler.timesteps

								snake_case_				=							self.movq.config.latent_channels

								snake_case_			,		snake_case_				=							downscale_height_and_width(a       ,			a       ,			self.movq_scale_factor					)

								# create initial latent
								snake_case_				=							self.prepare_latents(
								    (batch_size, num_channels_latents, height, width)       ,			image_embeds.dtype       ,			a       ,			a       ,			a       ,			self.scheduler       ,			)

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

															snake_case_				=							{'image_embeds': image_embeds, 'hint': hint}
															snake_case_				=							self.unet(
															    sample=a       ,			timestep=a       ,			encoder_hidden_states=a       ,			added_cond_kwargs=a       ,			return_dict=a       ,			)[0]

															if do_classifier_free_guidance:
																						snake_case_			,		snake_case_				=							noise_pred.split(latents.shape[1]       ,			dim=1					)
																						snake_case_			,		snake_case_				=							noise_pred.chunk(2					)
																						snake_case_			,		snake_case_				=							variance_pred.chunk(2					)
																						snake_case_				=							noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
																						snake_case_				=							torch.cat([noise_pred, variance_pred_text]       ,			dim=1					)

															if not (
															    hasattr(self.scheduler.config       ,			'variance_type'					)
															    and self.scheduler.config.variance_type in ["learned", "learned_range"]
															):
																						snake_case_			,		snake_case_				=							noise_pred.split(latents.shape[1]       ,			dim=1					)

															# compute the previous noisy sample x_t -> x_t-1
															snake_case_				=							self.scheduler.step(
															    a       ,			a       ,			a       ,			generator=a       ,			)[0]
								# post-processing
								snake_case_				=							self.movq.decode(a       ,			force_not_quantize=a					)['sample']

								if output_type not in ["pt", "np", "pil"]:
															raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'''					)

								if output_type in ["np", "pil"]:
															snake_case_				=							image * 0.5 + 0.5
															snake_case_				=							image.clamp(0       ,			1					)
															snake_case_				=							image.cpu().permute(0       ,			2       ,			3       ,			1					).float().numpy()

								if output_type == "pil":
															snake_case_				=							self.numpy_to_pil(a					)

								if not return_dict:
															return (image,)

								return ImagePipelineOutput(images=a					)





