

"""simple docstring"""


from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

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,
)


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

__A		     =    "\n    Examples:\n        ```py\n        >>> import torch\n        >>> import numpy as np\n\n        >>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline\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 = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior = pipe_prior.to(\"cuda\")\n\n        >>> pipe = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16\n        ... )\n        >>> pipe = pipe.to(\"cuda\")\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\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        >>> img_emb = pipe_prior(prompt=prompt, image=img, strength=0.85, generator=generator)\n        >>> negative_emb = pipe_prior(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)\n\n        >>> images = pipe(\n        ...     image=img,\n        ...     strength=0.5,\n        ...     image_embeds=img_emb.image_embeds,\n        ...     negative_image_embeds=negative_emb.image_embeds,\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 					a__					(					__SCREAMING_SNAKE_CASE      ,				__SCREAMING_SNAKE_CASE      ,				__SCREAMING_SNAKE_CASE=8				):
		__lowerCAmelCase: str					   =    height // scale_factor**2
		if height % scale_factor**2 != 0:
				new_height += 1
		__lowerCAmelCase: Optional[int]					   =    width // scale_factor**2
		if width % scale_factor**2 != 0:
				new_width += 1
		return new_height * scale_factor, new_width * scale_factor






def 					a__					(					__SCREAMING_SNAKE_CASE      ,				__SCREAMING_SNAKE_CASE=5_1_2      ,				__SCREAMING_SNAKE_CASE=5_1_2				):
		__lowerCAmelCase: List[Any]					   =    pil_image.resize((w, h)      ,				resample=Image.BICUBIC      ,				reducing_gap=1				)
		__lowerCAmelCase: Optional[int]					   =    np.array(pil_image.convert("RGB"				)				)
		__lowerCAmelCase: Tuple					   =    arr.astype(np.floataa				) / 1_2_7.5 - 1
		__lowerCAmelCase: Optional[Any]					   =    np.transpose(_UpperCamelCase      ,				[2, 0, 1]				)
		__lowerCAmelCase: List[Any]					   =    torch.from_numpy(_UpperCamelCase				).unsqueeze(0				)
		return image





class 					snake_case			(       SCREAMING_SNAKE_CASE__						):

				def __init__(			self							:       Optional[int]  ,						UpperCamelCase__							:       UNetaDConditionModel  ,						UpperCamelCase__							:       DDPMScheduler  ,						UpperCamelCase__							:       VQModel  ,						)->     Tuple:



						'''simple docstring'''


						super().__init__()

						self.register_modules(
						    unet=a_  ,						scheduler=a_  ,						movq=a_  ,						)
						__lowerCAmelCase: Tuple					   =    2 ** (len(self.movq.config.block_out_channels) - 1)

				def 							lowercase_  (			self							:       Dict  ,						UpperCamelCase__							:       Tuple  ,						UpperCamelCase__							:       Dict  ,						UpperCamelCase__							:       List[Any])->     List[Any]:



						'''simple docstring'''


						__lowerCAmelCase: Tuple					   =    min(int(num_inference_steps * strength)  ,						a_)

						__lowerCAmelCase: Dict					   =    max(num_inference_steps - init_timestep  ,						0)
						__lowerCAmelCase: List[str]					   =    self.scheduler.timesteps[t_start:]

						return timesteps, num_inference_steps - t_start

				def 							lowercase_  (			self							:       Tuple  ,						UpperCamelCase__							:       Any  ,						UpperCamelCase__							:       str  ,						UpperCamelCase__							:       Any  ,						UpperCamelCase__							:       str  ,						UpperCamelCase__							:       Optional[int]  ,						UpperCamelCase__							:       Tuple  ,						UpperCamelCase__							:       int=None)->     Optional[int]:



						'''simple docstring'''


						if not isinstance(a_  ,						(torch.Tensor, PIL.Image.Image, list)):
								raise ValueError(
								    f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(a_)}")

						__lowerCAmelCase: Any					   =    image.to(device=a_  ,						dtype=a_)

						__lowerCAmelCase: Optional[int]					   =    batch_size * num_images_per_prompt

						if image.shape[1] == 4:
								__lowerCAmelCase: Tuple					   =    image

						else:
								if isinstance(a_  ,						a_) and len(a_) != batch_size:
										raise ValueError(
										    f"You have passed a list of generators of length {len(a_)}, but requested an effective batch"
										    f" size of {batch_size}. Make sure the batch size matches the length of the generators.")

								elif isinstance(a_  ,						a_):
										__lowerCAmelCase: Any					   =    [
										    self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(a_)
										]
										__lowerCAmelCase: int					   =    torch.cat(a_  ,						dim=0)
								else:
										__lowerCAmelCase: Tuple					   =    self.movq.encode(a_).latent_dist.sample(a_)

								__lowerCAmelCase: int					   =    self.movq.config.scaling_factor * init_latents

						__lowerCAmelCase: Any					   =    torch.cat([init_latents]  ,						dim=0)

						__lowerCAmelCase: List[Any]					   =    init_latents.shape
						__lowerCAmelCase: Tuple					   =    randn_tensor(a_  ,						generator=a_  ,						device=a_  ,						dtype=a_)

						# get latents
						__lowerCAmelCase: Dict					   =    self.scheduler.add_noise(a_  ,						a_  ,						a_)

						__lowerCAmelCase: Union[str, Any]					   =    init_latents

						return latents

				def 							lowercase_  (			self							:       Union[str, Any]  ,						UpperCamelCase__							:       List[str]=0)->     List[Any]:



						'''simple docstring'''


						if is_accelerate_available():
								from accelerate import cpu_offload
						else:
								raise ImportError("Please install accelerate via `pip install accelerate`")

						__lowerCAmelCase: Dict					   =    torch.device(f"cuda:{gpu_id}")

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

				def 							lowercase_  (			self							:       Dict  ,						UpperCamelCase__							:       int=0)->     Tuple:



						'''simple docstring'''


						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.")

						__lowerCAmelCase: Optional[int]					   =    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)

						__lowerCAmelCase: Tuple					   =    None
						for cpu_offloaded_model in [self.unet, self.movq]:
								__lowerCAmelCase   ,				__lowerCAmelCase: List[str]					   =    cpu_offload_with_hook(a_  ,						a_  ,						prev_module_hook=a_)

						# We'll offload the last model manually.
						__lowerCAmelCase: List[str]					   =    hook

				@property
				# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
				def 							lowercase_  (			self							:       Tuple)->     Optional[int]:



						'''simple docstring'''


						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							:       Dict  ,						UpperCamelCase__							:       Union[torch.FloatTensor, List[torch.FloatTensor]]  ,						UpperCamelCase__							:       Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]]  ,						UpperCamelCase__							:       Union[torch.FloatTensor, List[torch.FloatTensor]]  ,						UpperCamelCase__							:       torch.FloatTensor  ,						UpperCamelCase__							:       int = 5_1_2  ,						UpperCamelCase__							:       int = 5_1_2  ,						UpperCamelCase__							:       int = 1_0_0  ,						UpperCamelCase__							:       float = 4.0  ,						UpperCamelCase__							:       float = 0.3  ,						UpperCamelCase__							:       int = 1  ,						UpperCamelCase__							:       Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,						UpperCamelCase__							:       Optional[str] = "pil"  ,						UpperCamelCase__							:       bool = True  ,						)->     Any:



						'''simple docstring'''


						__lowerCAmelCase: Optional[int]					   =    self._execution_device

						__lowerCAmelCase: Optional[Any]					   =    guidance_scale > 1.0

						if isinstance(a_  ,						a_):
								__lowerCAmelCase: Any					   =    torch.cat(a_  ,						dim=0)
						if isinstance(a_  ,						a_):
								__lowerCAmelCase: str					   =    torch.cat(a_  ,						dim=0)
						if isinstance(a_  ,						a_):
								__lowerCAmelCase: Any					   =    torch.cat(a_  ,						dim=0)

						__lowerCAmelCase: int					   =    image_embeds.shape[0]

						if do_classifier_free_guidance:
								__lowerCAmelCase: Any					   =    image_embeds.repeat_interleave(a_  ,						dim=0)
								__lowerCAmelCase: Tuple					   =    negative_image_embeds.repeat_interleave(a_  ,						dim=0)
								__lowerCAmelCase: Dict					   =    hint.repeat_interleave(a_  ,						dim=0)

						__lowerCAmelCase: Optional[Any]					   =    torch.cat([negative_image_embeds, image_embeds]  ,						dim=0).to(dtype=self.unet.dtype  ,						device=a_)
						__lowerCAmelCase: str					   =    torch.cat([hint, hint]  ,						dim=0).to(dtype=self.unet.dtype  ,						device=a_)

						if not isinstance(a_  ,						a_):
								__lowerCAmelCase: int					   =    [image]
						if not all(isinstance(a_  ,						(PIL.Image.Image, torch.Tensor)) for i in image):
								raise ValueError(
								    f"Input is in incorrect format: {[type(a_) for i in image]}. Currently, we only support  PIL image and pytorch tensor")

						__lowerCAmelCase: Any					   =    torch.cat([prepare_image(a_  ,						a_  ,						a_) for i in image]  ,						dim=0)
						__lowerCAmelCase: int					   =    image.to(dtype=image_embeds.dtype  ,						device=a_)

						__lowerCAmelCase: List[Any]					   =    self.movq.encode(a_)["latents"]
						__lowerCAmelCase: List[str]					   =    latents.repeat_interleave(a_  ,						dim=0)
						self.scheduler.set_timesteps(a_  ,						device=a_)
						__lowerCAmelCase   ,				__lowerCAmelCase: List[Any]					   =    self.get_timesteps(a_  ,						a_  ,						a_)
						__lowerCAmelCase: Tuple					   =    timesteps[:1].repeat(batch_size * num_images_per_prompt)
						__lowerCAmelCase   ,				__lowerCAmelCase: Optional[int]					   =    downscale_height_and_width(a_  ,						a_  ,						self.movq_scale_factor)
						__lowerCAmelCase: Dict					   =    self.prepare_latents(
						    a_  ,						a_  ,						a_  ,						a_  ,						image_embeds.dtype  ,						a_  ,						a_)
						for i, t in enumerate(self.progress_bar(a_)):
								# expand the latents if we are doing classifier free guidance
								__lowerCAmelCase: List[Any]					   =    torch.cat([latents] * 2) if do_classifier_free_guidance else latents

								__lowerCAmelCase: Optional[int]					   =    {"image_embeds": image_embeds, "hint": hint}
								__lowerCAmelCase: Tuple					   =    self.unet(
								    sample=a_  ,						timestep=a_  ,						encoder_hidden_states=a_  ,						added_cond_kwargs=a_  ,						return_dict=a_  ,						)[0]

								if do_classifier_free_guidance:
										__lowerCAmelCase   ,				__lowerCAmelCase: List[str]					   =    noise_pred.split(latents.shape[1]  ,						dim=1)
										__lowerCAmelCase   ,				__lowerCAmelCase: Any					   =    noise_pred.chunk(2)
										__lowerCAmelCase   ,				__lowerCAmelCase: List[Any]					   =    variance_pred.chunk(2)
										__lowerCAmelCase: str					   =    noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
										__lowerCAmelCase: Union[str, Any]					   =    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"]
								):
										__lowerCAmelCase   ,				__lowerCAmelCase: List[Any]					   =    noise_pred.split(latents.shape[1]  ,						dim=1)

								# compute the previous noisy sample x_t -> x_t-1

								__lowerCAmelCase: Union[str, Any]					   =    self.scheduler.step(
								    a_  ,						a_  ,						a_  ,						generator=a_  ,						)[0]

						# post-processing
						__lowerCAmelCase: Tuple					   =    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"]:
								__lowerCAmelCase: Any					   =    image * 0.5 + 0.5
								__lowerCAmelCase: Any					   =    image.clamp(0  ,						1)
								__lowerCAmelCase: List[Any]					   =    image.cpu().permute(0  ,						2  ,						3  ,						1).float().numpy()

						if output_type == "pil":
								__lowerCAmelCase: int					   =    self.numpy_to_pil(a_)

						if not return_dict:
								return (image,)

						return ImagePipelineOutput(images=a_)





"""simple docstring"""


from __future__ import annotations

import unittest

from transformers import OpenAIGPTConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
			import tensorflow as tf

			from transformers.models.openai.modeling_tf_openai import (
			    TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
			    TFOpenAIGPTDoubleHeadsModel,
			    TFOpenAIGPTForSequenceClassification,
			    TFOpenAIGPTLMHeadModel,
			    TFOpenAIGPTModel,
			)





class 					snake_case			:

				def __init__(			self							:       str  ,						UpperCamelCase__							:       Optional[int]  ,						)->     Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase: str					   =    parent
						__lowerCAmelCase: Union[str, Any]					   =    1_3
						__lowerCAmelCase: Union[str, Any]					   =    7
						__lowerCAmelCase: List[Any]					   =    True
						__lowerCAmelCase: Any					   =    True
						__lowerCAmelCase: List[Any]					   =    True
						__lowerCAmelCase: str					   =    True
						__lowerCAmelCase: List[Any]					   =    True
						__lowerCAmelCase: Tuple					   =    9_9
						__lowerCAmelCase: Dict					   =    3_2
						__lowerCAmelCase: Optional[Any]					   =    2
						__lowerCAmelCase: Union[str, Any]					   =    4
						__lowerCAmelCase: Union[str, Any]					   =    3_7
						__lowerCAmelCase: List[str]					   =    "gelu"
						__lowerCAmelCase: List[str]					   =    0.1
						__lowerCAmelCase: List[str]					   =    0.1
						__lowerCAmelCase: Union[str, Any]					   =    5_1_2
						__lowerCAmelCase: int					   =    1_6
						__lowerCAmelCase: int					   =    2
						__lowerCAmelCase: str					   =    0.02
						__lowerCAmelCase: Union[str, Any]					   =    3
						__lowerCAmelCase: str					   =    4
						__lowerCAmelCase: List[Any]					   =    None
						__lowerCAmelCase: int					   =    self.vocab_size - 1

				def 							lowercase_  (			self							:       Union[str, Any])->     Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase: Any					   =    ids_tensor([self.batch_size, self.seq_length]  ,						self.vocab_size)

						__lowerCAmelCase: str					   =    None
						if self.use_input_mask:
								__lowerCAmelCase: List[Any]					   =    random_attention_mask([self.batch_size, self.seq_length])

						__lowerCAmelCase: int					   =    None
						if self.use_token_type_ids:
								__lowerCAmelCase: Any					   =    ids_tensor([self.batch_size, self.seq_length]  ,						self.type_vocab_size)

						__lowerCAmelCase: Dict					   =    None
						if self.use_mc_token_ids:
								__lowerCAmelCase: Union[str, Any]					   =    ids_tensor([self.batch_size, self.num_choices]  ,						self.seq_length)

						__lowerCAmelCase: int					   =    None
						__lowerCAmelCase: Optional[Any]					   =    None
						__lowerCAmelCase: int					   =    None
						if self.use_labels:
								__lowerCAmelCase: Tuple					   =    ids_tensor([self.batch_size]  ,						self.type_sequence_label_size)
								__lowerCAmelCase: str					   =    ids_tensor([self.batch_size, self.seq_length]  ,						self.num_labels)
								__lowerCAmelCase: int					   =    ids_tensor([self.batch_size]  ,						self.num_choices)

						__lowerCAmelCase: int					   =    OpenAIGPTConfig(
						    vocab_size=self.vocab_size  ,						n_embd=self.hidden_size  ,						n_layer=self.num_hidden_layers  ,						n_head=self.num_attention_heads  ,						n_positions=self.max_position_embeddings  ,						pad_token_id=self.pad_token_id  ,						)

						__lowerCAmelCase: Union[str, Any]					   =    ids_tensor([self.num_hidden_layers, self.num_attention_heads]  ,						2)

						return (
						    config,
						    input_ids,
						    input_mask,
						    head_mask,
						    token_type_ids,
						    mc_token_ids,
						    sequence_labels,
						    token_labels,
						    choice_labels,
						)

				def 							lowercase_  (			self							:       Optional[int]  ,						UpperCamelCase__							:       int  ,						UpperCamelCase__							:       Any  ,						UpperCamelCase__							:       List[Any]  ,						UpperCamelCase__							:       int  ,						UpperCamelCase__							:       Dict  ,						*UpperCamelCase__							:       Dict)->     Union[str, Any]:



						'''simple docstring'''


						__lowerCAmelCase: List[str]					   =    TFOpenAIGPTModel(config=UpperCamelCase__)
						__lowerCAmelCase: Tuple					   =    {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
						__lowerCAmelCase: List[Any]					   =    model(UpperCamelCase__)

						__lowerCAmelCase: List[Any]					   =    [input_ids, input_mask]
						__lowerCAmelCase: Tuple					   =    model(UpperCamelCase__)

						__lowerCAmelCase: List[Any]					   =    model(UpperCamelCase__)

						self.parent.assertEqual(result.last_hidden_state.shape  ,						(self.batch_size, self.seq_length, self.hidden_size))

				def 							lowercase_  (			self							:       Dict  ,						UpperCamelCase__							:       List[str]  ,						UpperCamelCase__							:       Union[str, Any]  ,						UpperCamelCase__							:       List[Any]  ,						UpperCamelCase__							:       Optional[int]  ,						UpperCamelCase__							:       int  ,						*UpperCamelCase__							:       Optional[Any])->     Union[str, Any]:



						'''simple docstring'''


						__lowerCAmelCase: Any					   =    TFOpenAIGPTLMHeadModel(config=UpperCamelCase__)
						__lowerCAmelCase: int					   =    {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
						__lowerCAmelCase: Any					   =    model(UpperCamelCase__)
						self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.seq_length, self.vocab_size))

				def 							lowercase_  (			self							:       Tuple  ,						UpperCamelCase__							:       str  ,						UpperCamelCase__							:       Union[str, Any]  ,						UpperCamelCase__							:       Tuple  ,						UpperCamelCase__							:       Optional[int]  ,						UpperCamelCase__							:       List[str]  ,						UpperCamelCase__							:       Optional[Any]  ,						*UpperCamelCase__							:       Optional[Any])->     Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase: Union[str, Any]					   =    TFOpenAIGPTDoubleHeadsModel(config=UpperCamelCase__)

						__lowerCAmelCase: List[str]					   =    tf.tile(tf.expand_dims(UpperCamelCase__  ,						1)  ,						(1, self.num_choices, 1))
						__lowerCAmelCase: Union[str, Any]					   =    tf.tile(tf.expand_dims(UpperCamelCase__  ,						1)  ,						(1, self.num_choices, 1))
						__lowerCAmelCase: Optional[Any]					   =    tf.tile(tf.expand_dims(UpperCamelCase__  ,						1)  ,						(1, self.num_choices, 1))

						__lowerCAmelCase: str					   =    {
						    "input_ids": multiple_choice_inputs_ids,
						    "mc_token_ids": mc_token_ids,
						    "attention_mask": multiple_choice_input_mask,
						    "token_type_ids": multiple_choice_token_type_ids,
						}
						__lowerCAmelCase: Optional[int]					   =    model(UpperCamelCase__)
						self.parent.assertEqual(
						    result.logits.shape  ,						(self.batch_size, self.num_choices, self.seq_length, self.vocab_size))
						self.parent.assertEqual(result.mc_logits.shape  ,						(self.batch_size, self.num_choices))

				def 							lowercase_  (			self							:       List[str]  ,						UpperCamelCase__							:       List[Any]  ,						UpperCamelCase__							:       Optional[Any]  ,						UpperCamelCase__							:       Any  ,						UpperCamelCase__							:       str  ,						UpperCamelCase__							:       Optional[Any]  ,						*UpperCamelCase__							:       List[str])->     Any:



						'''simple docstring'''


						__lowerCAmelCase: str					   =    self.num_labels
						__lowerCAmelCase: Dict					   =    ids_tensor([self.batch_size]  ,						self.type_sequence_label_size)
						__lowerCAmelCase: List[str]					   =    {
						    "input_ids": input_ids,
						    "attention_mask": input_mask,
						    "token_type_ids": token_type_ids,
						    "labels": sequence_labels,
						}
						__lowerCAmelCase: str					   =    TFOpenAIGPTForSequenceClassification(UpperCamelCase__)
						__lowerCAmelCase: Optional[int]					   =    model(UpperCamelCase__)
						self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.num_labels))




				def 							lowercase_  (			self							:       Any)->     List[str]:



						'''simple docstring'''


						__lowerCAmelCase: List[str]					   =    self.prepare_config_and_inputs()

						(
						    (
						    __lowerCAmelCase
						)   ,				(
						    __lowerCAmelCase
						)   ,				(
						    __lowerCAmelCase
						)   ,				(
						    __lowerCAmelCase
						)   ,				(
						    __lowerCAmelCase
						)   ,				(
						    __lowerCAmelCase
						)   ,				(
						    __lowerCAmelCase
						)   ,				(
						    __lowerCAmelCase
						)   ,				(
						    __lowerCAmelCase
						)   ,				
						): List[Any]					   =    config_and_inputs

						__lowerCAmelCase: List[Any]					   =    {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
						return config, inputs_dict





@require_tf
class 					snake_case			(       __snake_case,							__snake_case,							unittest.TestCase						):
				SCREAMING_SNAKE_CASE_     :   Dict        =						(
				    (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification)
				    if is_tf_available()
				    else ()
				)
				SCREAMING_SNAKE_CASE_     :   List[str]        =						(
				    (TFOpenAIGPTLMHeadModel,) if is_tf_available() else ()
				)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
				SCREAMING_SNAKE_CASE_     :   int        =						(
				    {
				        """feature-extraction""": TFOpenAIGPTModel,
				        """text-classification""": TFOpenAIGPTForSequenceClassification,
				        """text-generation""": TFOpenAIGPTLMHeadModel,
				        """zero-shot""": TFOpenAIGPTForSequenceClassification,
				    }
				    if is_tf_available()
				    else {}
				)
				SCREAMING_SNAKE_CASE_     :   List[Any]        =						False
				SCREAMING_SNAKE_CASE_     :   Tuple        =						False

				def 							lowercase_  (			self							:       List[str]  ,						UpperCamelCase__							:       int  ,						UpperCamelCase__							:       Union[str, Any]  ,						UpperCamelCase__							:       Optional[int]  ,						UpperCamelCase__							:       Union[str, Any]  ,						UpperCamelCase__							:       Optional[Any])->     Union[str, Any]:



						'''simple docstring'''


						if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
								# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
								# `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
								# tiny config could not be created.
								return True

						return False

				def 							lowercase_  (			self							:       str)->     Tuple:



						'''simple docstring'''


						__lowerCAmelCase: Optional[int]					   =    TFOpenAIGPTModelTester(self)
						__lowerCAmelCase: List[Any]					   =    ConfigTester(self  ,						config_class=UpperCamelCase__  ,						n_embd=3_7)

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



						'''simple docstring'''


						self.config_tester.run_common_tests()

				def 							lowercase_  (			self							:       Tuple)->     Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase: Optional[Any]					   =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_openai_gpt_model(*UpperCamelCase__)

				def 							lowercase_  (			self							:       Union[str, Any])->     Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase: Optional[Any]					   =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_openai_gpt_lm_head(*UpperCamelCase__)

				def 							lowercase_  (			self							:       Optional[Any])->     Dict:



						'''simple docstring'''


						__lowerCAmelCase: List[Any]					   =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_openai_gpt_double_head(*UpperCamelCase__)

				def 							lowercase_  (			self							:       List[str])->     Tuple:



						'''simple docstring'''


						__lowerCAmelCase: Optional[int]					   =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*UpperCamelCase__)




				@slow
				def 							lowercase_  (			self							:       str)->     Dict:



						'''simple docstring'''


						for model_name in TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								__lowerCAmelCase: str					   =    TFOpenAIGPTModel.from_pretrained(UpperCamelCase__)
								self.assertIsNotNone(UpperCamelCase__)





@require_tf
class 					snake_case			(       unittest.TestCase						):

				@slow
				def 							lowercase_  (			self							:       Union[str, Any])->     List[str]:



						'''simple docstring'''


						__lowerCAmelCase: Optional[Any]					   =    TFOpenAIGPTLMHeadModel.from_pretrained("openai-gpt")
						__lowerCAmelCase: List[str]					   =    tf.convert_to_tensor([[4_8_1, 4_7_3_5, 5_4_4]]  ,						dtype=tf.intaa)  # the president is
						__lowerCAmelCase: Union[str, Any]					   =    [
						    4_8_1,
						    4_7_3_5,
						    5_4_4,
						    2_4_6,
						    9_6_3,
						    8_7_0,
						    7_6_2,
						    2_3_9,
						    2_4_4,
						    4_0_4_7_7,
						    2_4_4,
						    2_4_9,
						    7_1_9,
						    8_8_1,
						    4_8_7,
						    5_4_4,
						    2_4_0,
						    2_4_4,
						    6_0_3,
						    4_8_1,
						]  # the president is a very good man. " \n " i\'m sure he is, " said the

						__lowerCAmelCase: str					   =    model.generate(UpperCamelCase__  ,						do_sample=UpperCamelCase__)
						self.assertListEqual(output_ids[0].numpy().tolist()  ,						UpperCamelCase__)


