





"""simple docstring"""
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

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


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

lowerCamelCase_								=		"\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\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], \"corgi_3d.gif\")\n        ```\n"






@dataclass
class 					_SCREAMING_SNAKE_CASE(   A  ):
       SCREAMING_SNAKE_CASE_   :      Union[PIL.Image.Image, np.ndarray]






class 					_SCREAMING_SNAKE_CASE(   A  ):




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,)			->      Union[str, Any]:





             """simple docstring"""






             super().__init__()

             self.register_modules(
                 prior=SCREAMING_SNAKE_CASE__		,image_encoder=SCREAMING_SNAKE_CASE__		,image_processor=SCREAMING_SNAKE_CASE__		,scheduler=SCREAMING_SNAKE_CASE__		,renderer=SCREAMING_SNAKE_CASE__		,)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)			->      str:





             """simple docstring"""






             if latents is None:
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  randn_tensor(SCREAMING_SNAKE_CASE__		,generator=SCREAMING_SNAKE_CASE__		,device=SCREAMING_SNAKE_CASE__		,dtype=SCREAMING_SNAKE_CASE__							)
             else:
                   if latents.shape != shape:
                         raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''							)
                   __SCREAMING_SNAKE_CASE   :str						=  latents.to(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Tuple						=  latents * scheduler.init_noise_sigma
             return latents




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__=0							)			->      Any:





             """simple docstring"""






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

             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  torch.device(f'''cuda:{gpu_id}'''							)

             __SCREAMING_SNAKE_CASE   :int						=  [self.image_encoder, self.prior]
             for cpu_offloaded_model in models:
                   if cpu_offloaded_model is not None:
                         cpu_offload(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @property
       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






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





             """simple docstring"""






             if isinstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							) and isinstance(image[0]		,torch.Tensor							):
                   __SCREAMING_SNAKE_CASE   :Tuple						=  torch.cat(SCREAMING_SNAKE_CASE__		,axis=0							) if image[0].ndim == 4 else torch.stack(SCREAMING_SNAKE_CASE__		,axis=0							)

             if not isinstance(SCREAMING_SNAKE_CASE__		,torch.Tensor							):
                   __SCREAMING_SNAKE_CASE   :Tuple						=  self.image_processor(SCREAMING_SNAKE_CASE__		,return_tensors='''pt'''							).pixel_values[0].unsqueeze(0							)

             __SCREAMING_SNAKE_CASE   :Optional[int]						=  image.to(dtype=self.image_encoder.dtype		,device=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Dict						=  self.image_encoder(SCREAMING_SNAKE_CASE__							)['''last_hidden_state''']
             __SCREAMING_SNAKE_CASE   :Tuple						=  image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

             __SCREAMING_SNAKE_CASE   :Tuple						=  image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE__		,dim=0							)

             if do_classifier_free_guidance:
                   __SCREAMING_SNAKE_CASE   :List[str]						=  torch.zeros_like(SCREAMING_SNAKE_CASE__							)

                   # 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
                   __SCREAMING_SNAKE_CASE   :List[str]						=  torch.cat([negative_image_embeds, image_embeds]							)

             return image_embeds




       @torch.no_grad()
       @replace_example_docstring(SCREAMING_SNAKE_CASE__							)
       def __call__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = 1		,SCREAMING_SNAKE_CASE__ = 25		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = 4.0		,SCREAMING_SNAKE_CASE__ = 64		,SCREAMING_SNAKE_CASE__ = "pil"		,SCREAMING_SNAKE_CASE__ = True		,)			->      str:





             """simple docstring"""






             if isinstance(SCREAMING_SNAKE_CASE__		,PIL.Image.Image							):
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  1
             elif isinstance(SCREAMING_SNAKE_CASE__		,torch.Tensor							):
                   __SCREAMING_SNAKE_CASE   :Any						=  image.shape[0]
             elif isinstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							) and isinstance(image[0]		,(torch.Tensor, PIL.Image.Image)							):
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  len(SCREAMING_SNAKE_CASE__							)
             else:
                   raise ValueError(
                       f'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(SCREAMING_SNAKE_CASE__							)}'''							)

             __SCREAMING_SNAKE_CASE   :Any						=  self._execution_device

             __SCREAMING_SNAKE_CASE   :str						=  batch_size * num_images_per_prompt

             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  guidance_scale > 1.0
             __SCREAMING_SNAKE_CASE   :List[Any]						=  self._encode_image(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             # prior

             self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE__		,device=SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  self.scheduler.timesteps

             __SCREAMING_SNAKE_CASE   :List[Any]						=  self.prior.config.num_embeddings
             __SCREAMING_SNAKE_CASE   :Dict						=  self.prior.config.embedding_dim

             __SCREAMING_SNAKE_CASE   :List[str]						=  self.prepare_latents(
                 (batch_size, num_embeddings * embedding_dim)		,image_embeds.dtype		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,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
             __SCREAMING_SNAKE_CASE   :Any						=  latents.reshape(latents.shape[0]		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

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

                   __SCREAMING_SNAKE_CASE   :Tuple						=  self.prior(
                       SCREAMING_SNAKE_CASE__		,timestep=SCREAMING_SNAKE_CASE__		,proj_embedding=SCREAMING_SNAKE_CASE__		,).predicted_image_embedding

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

                   if do_classifier_free_guidance is not None:
                         __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Union[str, Any]						=  noise_pred.chunk(2							)
                         __SCREAMING_SNAKE_CASE   :int						=  noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

                   __SCREAMING_SNAKE_CASE   :List[Any]						=  self.scheduler.step(
                       SCREAMING_SNAKE_CASE__		,timestep=SCREAMING_SNAKE_CASE__		,sample=SCREAMING_SNAKE_CASE__		,).prev_sample

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

             __SCREAMING_SNAKE_CASE   :str						=  []
             for i, latent in enumerate(SCREAMING_SNAKE_CASE__							):
                   print()
                   __SCREAMING_SNAKE_CASE   :Dict						=  self.renderer.decode(
                       latent[None, :]		,SCREAMING_SNAKE_CASE__		,size=SCREAMING_SNAKE_CASE__		,ray_batch_size=40_96		,n_coarse_samples=64		,n_fine_samples=1_28		,)

                   images.append(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :List[Any]						=  torch.stack(SCREAMING_SNAKE_CASE__							)

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

             __SCREAMING_SNAKE_CASE   :Tuple						=  images.cpu().numpy()

             if output_type == "pil":
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  [self.numpy_to_pil(SCREAMING_SNAKE_CASE__							) 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=SCREAMING_SNAKE_CASE__							)






"""simple docstring"""
from __future__ import annotations

import copy
import tempfile
import unittest

from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available
from transformers.testing_utils import (
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tensorflow_probability,
    require_tf,
    slow,
)

from ..bert.test_modeling_bert import BertModelTester


if is_tf_available():
  from transformers import (
      TFAutoModel,
      TFAutoModelForCausalLM,
      TFAutoModelForMaskedLM,
      TFAutoModelForPreTraining,
      TFAutoModelForQuestionAnswering,
      TFAutoModelForSeqaSeqLM,
      TFAutoModelForSequenceClassification,
      TFAutoModelForTableQuestionAnswering,
      TFAutoModelForTokenClassification,
      TFAutoModelWithLMHead,
      TFBertForMaskedLM,
      TFBertForPreTraining,
      TFBertForQuestionAnswering,
      TFBertForSequenceClassification,
      TFBertModel,
      TFFunnelBaseModel,
      TFFunnelModel,
      TFGPTaLMHeadModel,
      TFRobertaForMaskedLM,
      TFTaForConditionalGeneration,
      TFTapasForQuestionAnswering,
  )
  from transformers.models.auto.modeling_tf_auto import (
      TF_MODEL_FOR_CAUSAL_LM_MAPPING,
      TF_MODEL_FOR_MASKED_LM_MAPPING,
      TF_MODEL_FOR_PRETRAINING_MAPPING,
      TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
      TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
      TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
      TF_MODEL_MAPPING,
  )
  from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
  from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
  from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
  from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST






class 					_SCREAMING_SNAKE_CASE(   A  ):
       SCREAMING_SNAKE_CASE_   :      int							=  '''new-model'''


if is_tf_available():






  class 					_SCREAMING_SNAKE_CASE(   A  ):
         SCREAMING_SNAKE_CASE_   :      Union[str, Any]							=  NewModelConfig






@require_tf
class 					_SCREAMING_SNAKE_CASE(   unittest.TestCase  ):




       @slow
       def     _UpperCamelCase     (						self							)			->      List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  '''bert-base-cased'''
             __SCREAMING_SNAKE_CASE   :int						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :List[str]						=  TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  '''bert-base-cased'''
             __SCREAMING_SNAKE_CASE   :List[str]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  TFAutoModelForPreTraining.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :List[str]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Dict						=  TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :List[str]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Any						=  TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




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





             """simple docstring"""






             for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Tuple						=  TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Tuple						=  TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :str						=  TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[int]						=  TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             for model_name in ["bert-base-uncased"]:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :List[str]						=  TFAutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             for model_name in ["bert-base-uncased"]:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModelForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       @require_tensorflow_probability
       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]:
                   __SCREAMING_SNAKE_CASE   :int						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TFAutoModelForTableQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[int]						=  TFAutoModelForTableQuestionAnswering.from_pretrained(
                       SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :int						=  TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             self.assertEqual(model.num_parameters()		,1_44_10							)
             self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__							)		,1_44_10							)




       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             self.assertEqual(model.num_parameters()		,1_44_10							)
             self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__							)		,1_44_10							)




       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModel.from_pretrained('''sgugger/funnel-random-tiny'''							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  copy.deepcopy(model.config							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  ['''FunnelBaseModel''']
             __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_config(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             with tempfile.TemporaryDirectory() as tmp_dir:
                   model.save_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       def     _UpperCamelCase     (						self							)			->      Optional[Any]:





             """simple docstring"""






             try:
                   AutoConfig.register('''new-model'''		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Tuple						=  [
                       TFAutoModel,
                       TFAutoModelForCausalLM,
                       TFAutoModelForMaskedLM,
                       TFAutoModelForPreTraining,
                       TFAutoModelForQuestionAnswering,
                       TFAutoModelForSequenceClassification,
                       TFAutoModelForTokenClassification,
                   ]

                   for auto_class in auto_classes:
                         with self.subTest(auto_class.__name__							):
                               # Wrong config class will raise an error
                               with self.assertRaises(SCREAMING_SNAKE_CASE__							):
                                     auto_class.register(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
                               auto_class.register(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
                               # Trying to register something existing in the Transformers library will raise an error
                               with self.assertRaises(SCREAMING_SNAKE_CASE__							):
                                     auto_class.register(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                               # Now that the config is registered, it can be used as any other config with the auto-API
                               __SCREAMING_SNAKE_CASE   :Any						=  BertModelTester(self							).get_config()
                               __SCREAMING_SNAKE_CASE   :Dict						=  NewModelConfig(**tiny_config.to_dict()							)
                               __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  auto_class.from_config(SCREAMING_SNAKE_CASE__							)
                               self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                               with tempfile.TemporaryDirectory() as tmp_dir:
                                     model.save_pretrained(SCREAMING_SNAKE_CASE__							)
                                     __SCREAMING_SNAKE_CASE   :str						=  auto_class.from_pretrained(SCREAMING_SNAKE_CASE__							)
                                     self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             finally:
                   if "new-model" in CONFIG_MAPPING._extra_content:
                         del CONFIG_MAPPING._extra_content["new-model"]
                   for mapping in (
                       TF_MODEL_MAPPING,
                       TF_MODEL_FOR_PRETRAINING_MAPPING,
                       TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
                       TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
                       TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
                       TF_MODEL_FOR_CAUSAL_LM_MAPPING,
                       TF_MODEL_FOR_MASKED_LM_MAPPING,
                   ):
                         if NewModelConfig in mapping._extra_content:
                               del mapping._extra_content[NewModelConfig]




       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             with self.assertRaisesRegex(
                 SCREAMING_SNAKE_CASE__		,'''bert-base is not a local folder and is not a valid model identifier'''							):
                   __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_pretrained('''bert-base'''							)




       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             with self.assertRaisesRegex(
                 SCREAMING_SNAKE_CASE__		,R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''							):
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__		,revision='''aaaaaa'''							)




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





             """simple docstring"""






             with self.assertRaisesRegex(
                 SCREAMING_SNAKE_CASE__		,'''hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin'''		,):
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModel.from_pretrained('''hf-internal-testing/config-no-model'''							)




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





             """simple docstring"""






             with self.assertRaisesRegex(SCREAMING_SNAKE_CASE__		,'''Use `from_pt=True` to load this model'''							):
                   __SCREAMING_SNAKE_CASE   :List[str]						=  TFAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only'''							)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert'''							)
             with RequestCounter() as counter:
                   __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert'''							)
                   self.assertEqual(counter.get_request_count		,0							)
                   self.assertEqual(counter.head_request_count		,1							)
                   self.assertEqual(counter.other_request_count		,0							)

             # With a sharded checkpoint
             __SCREAMING_SNAKE_CASE   :Dict						=  TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded'''							)
             with RequestCounter() as counter:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded'''							)
                   self.assertEqual(counter.get_request_count		,0							)
                   self.assertEqual(counter.head_request_count		,1							)
                   self.assertEqual(counter.other_request_count		,0							)