
import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

_UpperCAmelCase    			=					"\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = \"a shark\"\n\n        >>> images = pipe(\n        ...     prompt,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")\n        ```\n"

@dataclass
class 		__magic_name__				( _A					):


  """simple docstring"""





  _UpperCamelCase						 = 42







class 		__magic_name__				( _A					):


  """simple docstring"""





  def __init__(					self	,		a__	,		a__	,		a__	,		a__	,		a__	,		):
    super().__init__()

    self.register_modules(
        prior=__A	,		text_encoder=__A	,		tokenizer=__A	,		scheduler=__A	,		renderer=__A	,		)


  def     _UpperCAmelCase  (					self	,		a__	,		a__	,		a__	,		a__	,		a__	,		a__		):





    if latents is None:
      _lowerCamelCase      =						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}'''		)
      _lowerCamelCase      =						latents.to(__A		)

    _lowerCamelCase      =						latents * scheduler.init_noise_sigma
    return latents


  def     _UpperCAmelCase  (					self	,		a__=0		):





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

    _lowerCamelCase      =						torch.device(f'''cuda:{gpu_id}'''		)

    _lowerCamelCase      =						[self.text_encoder, self.prior]
    for cpu_offloaded_model in models:
      if cpu_offloaded_model is not None:
        cpu_offload(__A	,		__A		)


  def     _UpperCAmelCase  (					self	,		a__=0		):





    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      =						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      =						None
    for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
      _lowerCamelCase    ,    _lowerCamelCase      =						cpu_offload_with_hook(__A	,		__A	,		prev_module_hook=__A		)

    if self.safety_checker is not None:
      _lowerCamelCase    ,    _lowerCamelCase      =						cpu_offload_with_hook(self.safety_checker	,		__A	,		prev_module_hook=__A		)

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


  @property
  def     _UpperCAmelCase  (					self		):





    if self.device != torch.device('''meta'''		) or not hasattr(self.text_encoder	,		'''_hf_hook'''		):
      return self.device
    for module in self.text_encoder.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


  def     _UpperCAmelCase  (					self	,		a__	,		a__	,		a__	,		a__	,		):
    len(__A		) if isinstance(__A	,		__A		) else 1

    # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
    _lowerCamelCase      =						0
    # get prompt text embeddings
    _lowerCamelCase      =						self.tokenizer(
        __A	,		padding='''max_length'''	,		max_length=self.tokenizer.model_max_length	,		truncation=__A	,		return_tensors='''pt'''	,		)
    _lowerCamelCase      =						text_inputs.input_ids
    _lowerCamelCase      =						self.tokenizer(__A	,		padding='''longest'''	,		return_tensors='''pt'''		).input_ids

    if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__A	,		__A		):
      _lowerCamelCase      =						self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]		)
      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}'''		)

    _lowerCamelCase      =						self.text_encoder(text_input_ids.to(__A		)		)
    _lowerCamelCase      =						text_encoder_output.text_embeds

    _lowerCamelCase      =						prompt_embeds.repeat_interleave(__A	,		dim=0		)
    # in Shap-E it normalize the prompt_embeds and then later rescale it
    _lowerCamelCase      =						prompt_embeds / torch.linalg.norm(__A	,		dim=-1	,		keepdim=__A		)

    if do_classifier_free_guidance:
      _lowerCamelCase      =						torch.zeros_like(__A		)

      # 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
      _lowerCamelCase      =						torch.cat([negative_prompt_embeds, prompt_embeds]		)

    # Rescale the features to have unit variance
    _lowerCamelCase      =						math.sqrt(prompt_embeds.shape[1]		) * prompt_embeds

    return prompt_embeds


  @torch.no_grad()
  @replace_example_docstring(__A		)
  def __call__(					self	,		a__	,		a__ = 1	,		a__ = 25	,		a__ = None	,		a__ = None	,		a__ = 4.0	,		a__ = 64	,		a__ = "pil"	,		a__ = True	,		):





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

    _lowerCamelCase      =						self._execution_device

    _lowerCamelCase      =						batch_size * num_images_per_prompt

    _lowerCamelCase      =						guidance_scale > 1.0
    _lowerCamelCase      =						self._encode_prompt(__A	,		__A	,		__A	,		__A		)

    # prior

    self.scheduler.set_timesteps(__A	,		device=__A		)
    _lowerCamelCase      =						self.scheduler.timesteps

    _lowerCamelCase      =						self.prior.config.num_embeddings
    _lowerCamelCase      =						self.prior.config.embedding_dim

    _lowerCamelCase      =						self.prepare_latents(
        (batch_size, num_embeddings * embedding_dim)	,		prompt_embeds.dtype	,		__A	,		__A	,		__A	,		self.scheduler	,		)

    # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
    _lowerCamelCase      =						latents.reshape(latents.shape[0]	,		__A	,		__A		)

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

      _lowerCamelCase      =						self.prior(
          __A	,		timestep=__A	,		proj_embedding=__A	,		).predicted_image_embedding

      # remove the variance
      _lowerCamelCase    ,    _lowerCamelCase      =						noise_pred.split(
          scaled_model_input.shape[2]	,		dim=2		)  # batch_size, num_embeddings, embedding_dim

      if do_classifier_free_guidance is not None:
        _lowerCamelCase    ,    _lowerCamelCase      =						noise_pred.chunk(2		)
        _lowerCamelCase      =						noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

      _lowerCamelCase      =						self.scheduler.step(
          __A	,		timestep=__A	,		sample=__A	,		).prev_sample

    if output_type == "latent":
      return ShapEPipelineOutput(images=__A		)

    _lowerCamelCase      =						[]
    for i, latent in enumerate(__A		):
      _lowerCamelCase      =						self.renderer.decode(
          latent[None, :]	,		__A	,		size=__A	,		ray_batch_size=40_96	,		n_coarse_samples=64	,		n_fine_samples=1_28	,		)
      images.append(__A		)

    _lowerCamelCase      =						torch.stack(__A		)

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

    _lowerCamelCase      =						images.cpu().numpy()

    if output_type == "pil":
      _lowerCamelCase      =						[self.numpy_to_pil(__A		) for image in images]

    # Offload last model to CPU
    if hasattr(self	,		'''final_offload_hook'''		) and self.final_offload_hook is not None:
      self.final_offload_hook.offload()

    if not return_dict:
      return (images,)

    return ShapEPipelineOutput(images=__A		)









'''simple docstring'''







from __future__ import annotations

import unittest

from transformers import AlbertConfig, is_tf_available
from transformers.models.auto import get_values
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 import TF_MODEL_FOR_PRETRAINING_MAPPING
		from transformers.models.albert.modeling_tf_albert import (
		    TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFAlbertForMaskedLM,
		    TFAlbertForMultipleChoice,
		    TFAlbertForPreTraining,
		    TFAlbertForQuestionAnswering,
		    TFAlbertForSequenceClassification,
		    TFAlbertForTokenClassification,
		    TFAlbertModel,
		)

class      lowerCamelCase__     :






	'''simple docstring'''

	def __init__(  self		:  List[str]   ,		__A		:  Dict   ,		__A		:  Optional[Any]=13   ,		__A		:  Dict=7   ,		__A		:  Dict=True   ,		__A		:  Any=True   ,		__A		:  Any=True   ,		__A		:  List[str]=True   ,		__A		:  Union[str, Any]=99   ,		__A		:  Optional[int]=16   ,		__A		:  Tuple=32   ,		__A		:  Optional[int]=2   ,		__A		:  Dict=4   ,		__A		:  Dict=37   ,		__A		:  Any="gelu"   ,		__A		:  Union[str, Any]=0.1   ,		__A		:  List[str]=0.1   ,		__A		:  Any=512   ,		__A		:  Optional[Any]=16   ,		__A		:  List[str]=2   ,		__A		:  List[str]=0.0_2   ,		__A		:  List[str]=3   ,		__A		:  Dict=4   ,		__A		:  List[str]=None   ,		)     ->			int:




								'''simple docstring'''





								lowerCAmelCase__  =   parent
								lowerCAmelCase__  =   13
								lowerCAmelCase__  =   7
								lowerCAmelCase__  =   True
								lowerCAmelCase__  =   True
								lowerCAmelCase__  =   True
								lowerCAmelCase__  =   True
								lowerCAmelCase__  =   99
								lowerCAmelCase__  =   16
								lowerCAmelCase__  =   32
								lowerCAmelCase__  =   2
								lowerCAmelCase__  =   4
								lowerCAmelCase__  =   37
								lowerCAmelCase__  =   """gelu"""
								lowerCAmelCase__  =   0.1
								lowerCAmelCase__  =   0.1
								lowerCAmelCase__  =   512
								lowerCAmelCase__  =   16
								lowerCAmelCase__  =   2
								lowerCAmelCase__  =   0.0_2
								lowerCAmelCase__  =   3
								lowerCAmelCase__  =   4
								lowerCAmelCase__  =   None




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




								'''simple docstring'''





								lowerCAmelCase__  =   ids_tensor([self.batch_size, self.seq_length]   ,		self.vocab_size					)

								lowerCAmelCase__  =   None
								if self.use_input_mask:
															lowerCAmelCase__  =   random_attention_mask([self.batch_size, self.seq_length]					)

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

								lowerCAmelCase__  =   None
								lowerCAmelCase__  =   None
								lowerCAmelCase__  =   None
								if self.use_labels:
															lowerCAmelCase__  =   ids_tensor([self.batch_size]   ,		self.type_sequence_label_size					)
															lowerCAmelCase__  =   ids_tensor([self.batch_size, self.seq_length]   ,		self.num_labels					)
															lowerCAmelCase__  =   ids_tensor([self.batch_size]   ,		self.num_choices					)

								lowerCAmelCase__  =   AlbertConfig(
								    vocab_size=self.vocab_size   ,		hidden_size=self.hidden_size   ,		embedding_size=self.embedding_size   ,		num_hidden_layers=self.num_hidden_layers   ,		num_attention_heads=self.num_attention_heads   ,		intermediate_size=self.intermediate_size   ,		hidden_act=self.hidden_act   ,		hidden_dropout_prob=self.hidden_dropout_prob   ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,		max_position_embeddings=self.max_position_embeddings   ,		type_vocab_size=self.type_vocab_size   ,		initializer_range=self.initializer_range   ,		)

								return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




	def      lowercase__							(  self		:  Optional[Any]   ,		__A		:  Optional[Any]   ,		__A		:  Tuple   ,		__A		:  List[Any]   ,		__A		:  Tuple   ,		__A		:  Dict   ,		__A		:  Optional[int]   ,		__A		:  List[Any]					)     ->			Optional[int]:




								'''simple docstring'''





								lowerCAmelCase__  =   TFAlbertModel(config=__A					)
								# inputs = {'input_ids': input_ids,
								#           'attention_mask': input_mask,
								#           'token_type_ids': token_type_ids}
								# sequence_output, pooled_output = model(**inputs)
								lowerCAmelCase__  =   {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
								lowerCAmelCase__  =   model(__A					)

								lowerCAmelCase__  =   [input_ids, input_mask]
								lowerCAmelCase__  =   model(__A					)

								lowerCAmelCase__  =   model(__A					)

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




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.num_labels
								lowerCAmelCase__  =   TFAlbertForPreTraining(config=__A					)
								lowerCAmelCase__  =   {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
								lowerCAmelCase__  =   model(__A					)
								self.parent.assertEqual(result.prediction_logits.shape   ,		(self.batch_size, self.seq_length, self.vocab_size)					)
								self.parent.assertEqual(result.sop_logits.shape   ,		(self.batch_size, self.num_labels)					)




	def      lowercase__							(  self		:  str   ,		__A		:  Dict   ,		__A		:  Any   ,		__A		:  List[Any]   ,		__A		:  Tuple   ,		__A		:  Union[str, Any]   ,		__A		:  int   ,		__A		:  str					)     ->			str:




								'''simple docstring'''





								lowerCAmelCase__  =   TFAlbertForMaskedLM(config=__A					)
								lowerCAmelCase__  =   {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
								lowerCAmelCase__  =   model(__A					)
								self.parent.assertEqual(result.logits.shape   ,		(self.batch_size, self.seq_length, self.vocab_size)					)




	def      lowercase__							(  self		:  Dict   ,		__A		:  List[Any]   ,		__A		:  Union[str, Any]   ,		__A		:  Union[str, Any]   ,		__A		:  Optional[Any]   ,		__A		:  Optional[Any]   ,		__A		:  str   ,		__A		:  List[str]					)     ->			List[Any]:




								'''simple docstring'''





								lowerCAmelCase__  =   self.num_labels
								lowerCAmelCase__  =   TFAlbertForSequenceClassification(config=__A					)
								lowerCAmelCase__  =   {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
								lowerCAmelCase__  =   model(__A					)
								self.parent.assertEqual(result.logits.shape   ,		(self.batch_size, self.num_labels)					)




	def      lowercase__							(  self		:  Dict   ,		__A		:  Any   ,		__A		:  Tuple   ,		__A		:  Union[str, Any]   ,		__A		:  List[Any]   ,		__A		:  List[Any]   ,		__A		:  Any   ,		__A		:  Any					)     ->			Dict:




								'''simple docstring'''





								lowerCAmelCase__  =   TFAlbertForQuestionAnswering(config=__A					)
								lowerCAmelCase__  =   {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
								lowerCAmelCase__  =   model(__A					)
								self.parent.assertEqual(result.start_logits.shape   ,		(self.batch_size, self.seq_length)					)
								self.parent.assertEqual(result.end_logits.shape   ,		(self.batch_size, self.seq_length)					)




	def      lowercase__							(  self		:  List[Any]   ,		__A		:  Union[str, Any]   ,		__A		:  List[Any]   ,		__A		:  Tuple   ,		__A		:  Dict   ,		__A		:  Tuple   ,		__A		:  List[str]   ,		__A		:  Dict					)     ->			List[Any]:




								'''simple docstring'''





								lowerCAmelCase__  =   self.num_choices
								lowerCAmelCase__  =   TFAlbertForMultipleChoice(config=__A					)
								lowerCAmelCase__  =   tf.tile(tf.expand_dims(__A   ,		1					)   ,		(1, self.num_choices, 1)					)
								lowerCAmelCase__  =   tf.tile(tf.expand_dims(__A   ,		1					)   ,		(1, self.num_choices, 1)					)
								lowerCAmelCase__  =   tf.tile(tf.expand_dims(__A   ,		1					)   ,		(1, self.num_choices, 1)					)
								lowerCAmelCase__  =   {
								    """input_ids""": multiple_choice_inputs_ids,
								    """attention_mask""": multiple_choice_input_mask,
								    """token_type_ids""": multiple_choice_token_type_ids,
								}
								lowerCAmelCase__  =   model(__A					)
								self.parent.assertListEqual(list(result["""logits"""].shape					)   ,		[self.batch_size, self.num_choices]					)




	def      lowercase__							(  self		:  int   ,		__A		:  Tuple   ,		__A		:  Optional[Any]   ,		__A		:  Any   ,		__A		:  Union[str, Any]   ,		__A		:  Tuple   ,		__A		:  str   ,		__A		:  Optional[Any]					)     ->			str:




								'''simple docstring'''





								lowerCAmelCase__  =   self.num_labels
								lowerCAmelCase__  =   TFAlbertForTokenClassification(config=__A					)
								lowerCAmelCase__  =   {
								    """input_ids""": input_ids,
								    """attention_mask""": input_mask,
								    """token_type_ids""": token_type_ids,
								}
								lowerCAmelCase__  =   model(__A					)
								self.parent.assertListEqual(list(result["""logits"""].shape					)   ,		[self.batch_size, self.seq_length, self.num_labels]					)




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.prepare_config_and_inputs()
								(
								    (
								    lowerCAmelCase__
								)  ,(
								    lowerCAmelCase__
								)  ,(
								    lowerCAmelCase__
								)  ,(
								    lowerCAmelCase__
								)  ,(
								    lowerCAmelCase__
								)  ,(
								    lowerCAmelCase__
								)  ,(
								    lowerCAmelCase__
								)  ,
								)  =   config_and_inputs
								lowerCAmelCase__  =   {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
								return config, inputs_dict





@require_tf
class      lowerCamelCase__     (     _A,     _A,     unittest.TestCase				):






	'''simple docstring'''

	A__		=	(
	    (
	        TFAlbertModel,
	        TFAlbertForPreTraining,
	        TFAlbertForMaskedLM,
	        TFAlbertForSequenceClassification,
	        TFAlbertForQuestionAnswering,
	        TFAlbertForTokenClassification,
	        TFAlbertForMultipleChoice,
	    )
	    if is_tf_available()
	    else ()
	)
	A__		=	(
	    {
	        '''feature-extraction''': TFAlbertModel,
	        '''fill-mask''': TFAlbertForMaskedLM,
	        '''question-answering''': TFAlbertForQuestionAnswering,
	        '''text-classification''': TFAlbertForSequenceClassification,
	        '''token-classification''': TFAlbertForTokenClassification,
	        '''zero-shot''': TFAlbertForSequenceClassification,
	    }
	    if is_tf_available()
	    else {}
	)
	A__		=	False
	A__		=	False




	def      lowercase__							(  self		:  Any   ,		__A		:  List[str]   ,		__A		:  int   ,		__A		:  Union[str, Any]=False					)     ->			Optional[int]:




								'''simple docstring'''





								lowerCAmelCase__  =   super()._prepare_for_class(__A   ,		__A   ,		return_labels=__A					)

								if return_labels:
															if model_class in get_values(__A					):
																						lowerCAmelCase__  =   tf.zeros(self.model_tester.batch_size   ,		dtype=tf.intaa					)

								return inputs_dict




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




								'''simple docstring'''





								lowerCAmelCase__  =   TFAlbertModelTester(self					)
								lowerCAmelCase__  =   ConfigTester(self   ,		config_class=__A   ,		hidden_size=37					)




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




								'''simple docstring'''





								self.config_tester.run_common_tests()




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_albert_model(*__A					)




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_albert_for_pretraining(*__A					)




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_albert_for_masked_lm(*__A					)




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_albert_for_multiple_choice(*__A					)




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_albert_for_sequence_classification(*__A					)




	def      lowercase__							(  self		:  Any					)     ->			Any:




								'''simple docstring'''





								lowerCAmelCase__  =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_albert_for_question_answering(*__A					)




	@slow
	def      lowercase__							(  self		:  Tuple					)     ->			Dict:




								'''simple docstring'''





								for model_name in TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															lowerCAmelCase__  =   TFAlbertModel.from_pretrained(__A					)
															self.assertIsNotNone(__A					)





@require_tf
class      lowerCamelCase__     (     unittest.TestCase				):






	'''simple docstring'''

	@slow
	def      lowercase__							(  self		:  Optional[int]					)     ->			str:




								'''simple docstring'''





								lowerCAmelCase__  =   TFAlbertForPreTraining.from_pretrained("""albert-base-v2"""					)
								lowerCAmelCase__  =   tf.constant([[0, 1, 2, 3, 4, 5]]					)
								lowerCAmelCase__  =   model(__A					)[0]

								lowerCAmelCase__  =   [1, 6, 3_0000]
								self.assertEqual(output.shape   ,		__A					)

								lowerCAmelCase__  =   tf.constant(
								    [
								        [
								            [4.5_9_5_6_6_8, 0.7_4_4_6_2_7_5_4, -1.8_1_8_1_4_7],
								            [4.5_9_5_4_3_4_7, 0.7_4_5_4_1_8_4, -1.8_1_8_8_2_5_8],
								            [4.5_9_5_4_9_0_5, 0.7_4_4_8_2_3_5, -1.8_1_8_2_3_1_6],
								        ]
								    ]					)
								tf.debugging.assert_near(output[:, :3, :3]   ,		__A   ,		atol=1E-4					)





