

import argparse
import os

import torch

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)


_UpperCamelCase					     =						{
    "sample_size": 32,
    "in_channels": 3,
    "out_channels": 3,
    "layers_per_block": 2,
    "num_class_embeds": 1000,
    "block_out_channels": [32, 64],
    "attention_head_dim": 8,
    "down_block_types": [
        "ResnetDownsampleBlock2D",
        "AttnDownBlock2D",
    ],
    "up_block_types": [
        "AttnUpBlock2D",
        "ResnetUpsampleBlock2D",
    ],
    "resnet_time_scale_shift": "scale_shift",
    "upsample_type": "resnet",
    "downsample_type": "resnet",
}

_UpperCamelCase					     =						{
    "sample_size": 64,
    "in_channels": 3,
    "out_channels": 3,
    "layers_per_block": 3,
    "num_class_embeds": 1000,
    "block_out_channels": [192, 192 * 2, 192 * 3, 192 * 4],
    "attention_head_dim": 64,
    "down_block_types": [
        "ResnetDownsampleBlock2D",
        "AttnDownBlock2D",
        "AttnDownBlock2D",
        "AttnDownBlock2D",
    ],
    "up_block_types": [
        "AttnUpBlock2D",
        "AttnUpBlock2D",
        "AttnUpBlock2D",
        "ResnetUpsampleBlock2D",
    ],
    "resnet_time_scale_shift": "scale_shift",
    "upsample_type": "resnet",
    "downsample_type": "resnet",
}

_UpperCamelCase					     =						{
    "sample_size": 256,
    "in_channels": 3,
    "out_channels": 3,
    "layers_per_block": 2,
    "num_class_embeds": None,
    "block_out_channels": [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4],
    "attention_head_dim": 64,
    "down_block_types": [
        "ResnetDownsampleBlock2D",
        "ResnetDownsampleBlock2D",
        "ResnetDownsampleBlock2D",
        "AttnDownBlock2D",
        "AttnDownBlock2D",
        "AttnDownBlock2D",
    ],
    "up_block_types": [
        "AttnUpBlock2D",
        "AttnUpBlock2D",
        "AttnUpBlock2D",
        "ResnetUpsampleBlock2D",
        "ResnetUpsampleBlock2D",
        "ResnetUpsampleBlock2D",
    ],
    "resnet_time_scale_shift": "default",
    "upsample_type": "resnet",
    "downsample_type": "resnet",
}

_UpperCamelCase					     =						{
    "num_train_timesteps": 40,
    "sigma_min": 0.0_02,
    "sigma_max": 80.0,
}

_UpperCamelCase					     =						{
    "num_train_timesteps": 201,
    "sigma_min": 0.0_02,
    "sigma_max": 80.0,
}

_UpperCamelCase					     =						{
    "num_train_timesteps": 151,
    "sigma_min": 0.0_02,
    "sigma_max": 80.0,
}







def 						_lowercase					(	lowercase__		):




      if isinstance(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE		):
            return v
      if v.lower() in ("yes", "true", "t", "y", "1"):
            return True
      elif v.lower() in ("no", "false", "f", "n", "0"):
            return False
      else:
            raise argparse.ArgumentTypeError('''boolean value expected'''		)







def 						_lowercase					(	lowercase__  ,      lowercase__  ,      lowercase__  ,      lowercase__  ,      lowercase__=False		):
      __lowerCAmelCase   :		Tuple   =   checkpoint[f"""{old_prefix}.in_layers.0.weight"""]
      __lowerCAmelCase   :		Tuple   =   checkpoint[f"""{old_prefix}.in_layers.0.bias"""]
      __lowerCAmelCase   :		Union[str, Any]   =   checkpoint[f"""{old_prefix}.in_layers.2.weight"""]
      __lowerCAmelCase   :		Union[str, Any]   =   checkpoint[f"""{old_prefix}.in_layers.2.bias"""]
      __lowerCAmelCase   :		str   =   checkpoint[f"""{old_prefix}.emb_layers.1.weight"""]
      __lowerCAmelCase   :		int   =   checkpoint[f"""{old_prefix}.emb_layers.1.bias"""]
      __lowerCAmelCase   :		Optional[Any]   =   checkpoint[f"""{old_prefix}.out_layers.0.weight"""]
      __lowerCAmelCase   :		Optional[Any]   =   checkpoint[f"""{old_prefix}.out_layers.0.bias"""]
      __lowerCAmelCase   :		int   =   checkpoint[f"""{old_prefix}.out_layers.3.weight"""]
      __lowerCAmelCase   :		str   =   checkpoint[f"""{old_prefix}.out_layers.3.bias"""]

      if has_skip:
            __lowerCAmelCase   :		str   =   checkpoint[f"""{old_prefix}.skip_connection.weight"""]
            __lowerCAmelCase   :		Tuple   =   checkpoint[f"""{old_prefix}.skip_connection.bias"""]

      return new_checkpoint







def 						_lowercase					(	lowercase__  ,      lowercase__  ,      lowercase__  ,      lowercase__  ,      lowercase__=None		):
      __lowerCAmelCase,				__lowerCAmelCase,				__lowerCAmelCase   :		Optional[int]   =   checkpoint[f"""{old_prefix}.qkv.weight"""].chunk(3  ,      dim=0		)
      __lowerCAmelCase,				__lowerCAmelCase,				__lowerCAmelCase   :		Dict   =   checkpoint[f"""{old_prefix}.qkv.bias"""].chunk(3  ,      dim=0		)

      __lowerCAmelCase   :		Optional[Any]   =   checkpoint[f"""{old_prefix}.norm.weight"""]
      __lowerCAmelCase   :		Dict   =   checkpoint[f"""{old_prefix}.norm.bias"""]

      __lowerCAmelCase   :		Any   =   weight_q.squeeze(-1		).squeeze(-1		)
      __lowerCAmelCase   :		Tuple   =   bias_q.squeeze(-1		).squeeze(-1		)
      __lowerCAmelCase   :		int   =   weight_k.squeeze(-1		).squeeze(-1		)
      __lowerCAmelCase   :		Dict   =   bias_k.squeeze(-1		).squeeze(-1		)
      __lowerCAmelCase   :		int   =   weight_v.squeeze(-1		).squeeze(-1		)
      __lowerCAmelCase   :		Tuple   =   bias_v.squeeze(-1		).squeeze(-1		)

      __lowerCAmelCase   :		Union[str, Any]   =   (
          checkpoint[f"""{old_prefix}.proj_out.weight"""].squeeze(-1		).squeeze(-1		)
      )
      __lowerCAmelCase   :		Dict   =   checkpoint[f"""{old_prefix}.proj_out.bias"""].squeeze(-1		).squeeze(-1		)

      return new_checkpoint







def 						_lowercase					(	lowercase__  ,      lowercase__		):
      __lowerCAmelCase   :		Tuple   =   torch.load(_SCREAMING_SNAKE_CASE  ,      map_location='''cpu'''		)
      __lowerCAmelCase   :		Optional[int]   =   {}

      __lowerCAmelCase   :		Any   =   checkpoint['''time_embed.0.weight''']
      __lowerCAmelCase   :		Optional[Any]   =   checkpoint['''time_embed.0.bias''']
      __lowerCAmelCase   :		Dict   =   checkpoint['''time_embed.2.weight''']
      __lowerCAmelCase   :		Dict   =   checkpoint['''time_embed.2.bias''']

      if unet_config["num_class_embeds"] is not None:
            __lowerCAmelCase   :		Dict   =   checkpoint['''label_emb.weight''']

      __lowerCAmelCase   :		List[str]   =   checkpoint['''input_blocks.0.0.weight''']
      __lowerCAmelCase   :		int   =   checkpoint['''input_blocks.0.0.bias''']

      __lowerCAmelCase   :		Dict   =   unet_config['''down_block_types''']
      __lowerCAmelCase   :		List[Any]   =   unet_config['''layers_per_block''']
      __lowerCAmelCase   :		List[Any]   =   unet_config['''attention_head_dim''']
      __lowerCAmelCase   :		List[str]   =   unet_config['''block_out_channels''']
      __lowerCAmelCase   :		Any   =   1
      __lowerCAmelCase   :		Any   =   channels_list[0]

      for i, layer_type in enumerate(_SCREAMING_SNAKE_CASE		):
            __lowerCAmelCase   :		Optional[int]   =   channels_list[i]
            __lowerCAmelCase   :		List[Any]   =   current_channels != prev_channels
            if layer_type == "ResnetDownsampleBlock2D":
                  for j in range(_SCREAMING_SNAKE_CASE		):
                        __lowerCAmelCase   :		Tuple   =   f"""down_blocks.{i}.resnets.{j}"""
                        __lowerCAmelCase   :		Tuple   =   f"""input_blocks.{current_layer}.0"""
                        __lowerCAmelCase   :		Optional[Any]   =   True if j == 0 and downsample_block_has_skip else False
                        __lowerCAmelCase   :		int   =   convert_resnet(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      has_skip=_SCREAMING_SNAKE_CASE		)
                        current_layer += 1

            elif layer_type == "AttnDownBlock2D":
                  for j in range(_SCREAMING_SNAKE_CASE		):
                        __lowerCAmelCase   :		List[Any]   =   f"""down_blocks.{i}.resnets.{j}"""
                        __lowerCAmelCase   :		Optional[Any]   =   f"""input_blocks.{current_layer}.0"""
                        __lowerCAmelCase   :		int   =   True if j == 0 and downsample_block_has_skip else False
                        __lowerCAmelCase   :		Union[str, Any]   =   convert_resnet(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      has_skip=_SCREAMING_SNAKE_CASE		)
                        __lowerCAmelCase   :		int   =   f"""down_blocks.{i}.attentions.{j}"""
                        __lowerCAmelCase   :		Optional[int]   =   f"""input_blocks.{current_layer}.1"""
                        __lowerCAmelCase   :		List[Any]   =   convert_attention(
                            _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE		)
                        current_layer += 1

            if i != len(_SCREAMING_SNAKE_CASE		) - 1:
                  __lowerCAmelCase   :		List[str]   =   f"""down_blocks.{i}.downsamplers.0"""
                  __lowerCAmelCase   :		str   =   f"""input_blocks.{current_layer}.0"""
                  __lowerCAmelCase   :		Dict   =   convert_resnet(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE		)
                  current_layer += 1

            __lowerCAmelCase   :		Optional[int]   =   current_channels

      # hardcoded the mid-block for now
      __lowerCAmelCase   :		Dict   =   '''mid_block.resnets.0'''
      __lowerCAmelCase   :		List[Any]   =   '''middle_block.0'''
      __lowerCAmelCase   :		Optional[int]   =   convert_resnet(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE		)
      __lowerCAmelCase   :		Union[str, Any]   =   '''mid_block.attentions.0'''
      __lowerCAmelCase   :		Optional[int]   =   '''middle_block.1'''
      __lowerCAmelCase   :		List[Any]   =   convert_attention(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE		)
      __lowerCAmelCase   :		Tuple   =   '''mid_block.resnets.1'''
      __lowerCAmelCase   :		Any   =   '''middle_block.2'''
      __lowerCAmelCase   :		str   =   convert_resnet(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE		)

      __lowerCAmelCase   :		Dict   =   0
      __lowerCAmelCase   :		Dict   =   unet_config['''up_block_types''']

      for i, layer_type in enumerate(_SCREAMING_SNAKE_CASE		):
            if layer_type == "ResnetUpsampleBlock2D":
                  for j in range(layers_per_block + 1		):
                        __lowerCAmelCase   :		List[Any]   =   f"""up_blocks.{i}.resnets.{j}"""
                        __lowerCAmelCase   :		int   =   f"""output_blocks.{current_layer}.0"""
                        __lowerCAmelCase   :		Dict   =   convert_resnet(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      has_skip=_SCREAMING_SNAKE_CASE		)
                        current_layer += 1

                  if i != len(_SCREAMING_SNAKE_CASE		) - 1:
                        __lowerCAmelCase   :		Union[str, Any]   =   f"""up_blocks.{i}.upsamplers.0"""
                        __lowerCAmelCase   :		List[str]   =   f"""output_blocks.{current_layer-1}.1"""
                        __lowerCAmelCase   :		Any   =   convert_resnet(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE		)
            elif layer_type == "AttnUpBlock2D":
                  for j in range(layers_per_block + 1		):
                        __lowerCAmelCase   :		str   =   f"""up_blocks.{i}.resnets.{j}"""
                        __lowerCAmelCase   :		str   =   f"""output_blocks.{current_layer}.0"""
                        __lowerCAmelCase   :		List[str]   =   convert_resnet(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      has_skip=_SCREAMING_SNAKE_CASE		)
                        __lowerCAmelCase   :		Union[str, Any]   =   f"""up_blocks.{i}.attentions.{j}"""
                        __lowerCAmelCase   :		Optional[Any]   =   f"""output_blocks.{current_layer}.1"""
                        __lowerCAmelCase   :		int   =   convert_attention(
                            _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE		)
                        current_layer += 1

                  if i != len(_SCREAMING_SNAKE_CASE		) - 1:
                        __lowerCAmelCase   :		Optional[Any]   =   f"""up_blocks.{i}.upsamplers.0"""
                        __lowerCAmelCase   :		Dict   =   f"""output_blocks.{current_layer-1}.2"""
                        __lowerCAmelCase   :		Optional[int]   =   convert_resnet(_SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE  ,      _SCREAMING_SNAKE_CASE		)

      __lowerCAmelCase   :		Dict   =   checkpoint['''out.0.weight''']
      __lowerCAmelCase   :		List[str]   =   checkpoint['''out.0.bias''']
      __lowerCAmelCase   :		str   =   checkpoint['''out.2.weight''']
      __lowerCAmelCase   :		List[Any]   =   checkpoint['''out.2.bias''']

      return new_checkpoint


if __name__ == "__main__":
 _UpperCamelCase					     =						argparse.ArgumentParser()

 parser.add_argument("--unet_path", default=None, type=str, required=True, help="Path to the unet.pt to convert.")
 parser.add_argument(
     "--dump_path", default=None, type=str, required=True, help="Path to output the converted UNet model."
 )
 parser.add_argument("--class_cond", default=True, type=str, help="Whether the model is class-conditional.")

 _UpperCamelCase					     =						parser.parse_args()
 _UpperCamelCase					     =						strabool(args.class_cond)

 _UpperCamelCase					     =						os.path.basename(args.unet_path)
 print(F"Checkpoint: {ckpt_name}")

 # Get U-Net config
 if "imagenet64" in ckpt_name:
  _UpperCamelCase					     =						IMAGENET_64_UNET_CONFIG
 elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)):
  _UpperCamelCase					     =						LSUN_256_UNET_CONFIG
 elif "test" in ckpt_name:
  _UpperCamelCase					     =						TEST_UNET_CONFIG
 else:
  raise ValueError(F"Checkpoint type {ckpt_name} is not currently supported.")

 if not args.class_cond:
  _UpperCamelCase					     =						None

 _UpperCamelCase					     =						con_pt_to_diffuser(args.unet_path, unet_config)

 _UpperCamelCase					     =						UNetaDModel(**unet_config)
 image_unet.load_state_dict(converted_unet_ckpt)

 # Get scheduler config
 if "cd" in ckpt_name or "test" in ckpt_name:
  _UpperCamelCase					     =						CD_SCHEDULER_CONFIG
 elif "ct" in ckpt_name and "imagenet64" in ckpt_name:
  _UpperCamelCase					     =						CT_IMAGENET_64_SCHEDULER_CONFIG
 elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)):
  _UpperCamelCase					     =						CT_LSUN_256_SCHEDULER_CONFIG
 else:
  raise ValueError(F"Checkpoint type {ckpt_name} is not currently supported.")

 _UpperCamelCase					     =						CMStochasticIterativeScheduler(**scheduler_config)

 _UpperCamelCase					     =						ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler)
 consistency_model.save_pretrained(args.dump_path)









from __future__ import annotations

import unittest

from transformers import EsmConfig, 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 numpy
 import tensorflow as tf

 from transformers.models.esm.modeling_tf_esm import (
     TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
     TFEsmForMaskedLM,
     TFEsmForSequenceClassification,
     TFEsmForTokenClassification,
     TFEsmModel,
 )







class      lowerCamelCase:
     '''simple docstring'''


     def __init__(    self				,     snake_case_				,     ):
         _A     =							parent
         _A     =							13
         _A     =							7
         _A     =							True
         _A     =							True
         _A     =							True
         _A     =							99
         _A     =							32
         _A     =							2
         _A     =							4
         _A     =							37
         _A     =							'gelu'
         _A     =							0.1
         _A     =							0.1
         _A     =							512
         _A     =							16
         _A     =							2
         _A     =							0.02
         _A     =							3
         _A     =							4
         _A     =							None




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

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

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

         _A     =							EsmConfig(
             vocab_size=self.vocab_size				,     hidden_size=self.hidden_size				,     num_hidden_layers=self.num_hidden_layers				,     pad_token_id=1				,     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, input_mask, sequence_labels, token_labels, choice_labels




     def        lowerCAmelCase__		(    self							):
         (
             (
             _A
         ),			(
             _A
         ),			(
             _A
         ),			(
             _A
         ),			(
             _A
         ),			(
             _A
         ),			
         )     =							self.prepare_config_and_inputs()

         _A     =							True
         _A     =							floats_tensor([self.batch_size, self.seq_length, self.hidden_size]							)
         _A     =							ids_tensor([self.batch_size, self.seq_length]				,     vocab_size=2							)

         return (
             config,
             input_ids,
             input_mask,
             sequence_labels,
             token_labels,
             choice_labels,
             encoder_hidden_states,
             encoder_attention_mask,
         )




     def        lowerCAmelCase__		(    self				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_							):
         _A     =							TFEsmModel(config=snake_case_							)
         _A     =							{'input_ids': input_ids, 'attention_mask': input_mask}
         _A     =							model(snake_case_							)

         _A     =							[input_ids, input_mask]
         _A     =							model(snake_case_							)

         _A     =							model(snake_case_							)

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




     def        lowerCAmelCase__		(    self				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     ):
         _A     =							True

         _A     =							TFEsmModel(config=snake_case_							)
         _A     =							{
             'input_ids': input_ids,
             'attention_mask': input_mask,
             'encoder_hidden_states': encoder_hidden_states,
             'encoder_attention_mask': encoder_attention_mask,
         }
         _A     =							model(snake_case_							)

         _A     =							[input_ids, input_mask]
         _A     =							model(snake_case_				,     encoder_hidden_states=snake_case_							)

         # Also check the case where encoder outputs are not passed
         _A     =							model(snake_case_				,     attention_mask=snake_case_							)

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




     def        lowerCAmelCase__		(    self				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_							):
         _A     =							TFEsmForMaskedLM(config=snake_case_							)
         _A     =							model([input_ids, input_mask]							)
         self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.seq_length, self.vocab_size)							)




     def        lowerCAmelCase__		(    self				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_							):
         _A     =							self.num_labels
         _A     =							TFEsmForTokenClassification(config=snake_case_							)
         _A     =							{'input_ids': input_ids, 'attention_mask': input_mask}
         _A     =							model(snake_case_							)
         self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.seq_length, self.num_labels)							)




     def        lowerCAmelCase__		(    self							):
         _A     =							self.prepare_config_and_inputs()
         (
             (
             _A
         ),			(
             _A
         ),			(
             _A
         ),			(
             _A
         ),			(
             _A
         ),			(
             _A
         ),			
         )     =							config_and_inputs
         _A     =							{'input_ids': input_ids, 'attention_mask': input_mask}
         return config, inputs_dict







@require_tf
class      lowerCamelCase(						__snake_case			, __snake_case			, unittest.TestCase	):
     '''simple docstring'''


     __magic_name__   =			(
         (
             TFEsmModel,
             TFEsmForMaskedLM,
             TFEsmForSequenceClassification,
             TFEsmForTokenClassification,
         )
         if is_tf_available()
         else ()
     )
     __magic_name__   =			(
         {
             'feature-extraction': TFEsmModel,
             'fill-mask': TFEsmForMaskedLM,
             'text-classification': TFEsmForSequenceClassification,
             'token-classification': TFEsmForTokenClassification,
             'zero-shot': TFEsmForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     __magic_name__   =			False
     __magic_name__   =			False




     def        lowerCAmelCase__		(    self							):
         _A     =							TFEsmModelTester(self							)
         _A     =							ConfigTester(self				,     config_class=snake_case_				,     hidden_size=37							)




     def        lowerCAmelCase__		(    self							):
         self.config_tester.run_common_tests()




     def        lowerCAmelCase__		(    self							):
         _A     =							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*snake_case_							)




     def        lowerCAmelCase__		(    self							):
         _A     =							self.model_tester.prepare_config_and_inputs_for_decoder()
         self.model_tester.create_and_check_model_as_decoder(*snake_case_							)




     def        lowerCAmelCase__		(    self							):
         _A     =							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*snake_case_							)




     def        lowerCAmelCase__		(    self							):
         _A     =							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*snake_case_							)




     @slow
     def        lowerCAmelCase__		(    self							):
         for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _A     =							TFEsmModel.from_pretrained(snake_case_							)
             self.assertIsNotNone(snake_case_							)




     @unittest.skip('Protein models do not support embedding resizing.'							)
     def        lowerCAmelCase__		(    self							):
         pass




     @unittest.skip('Protein models do not support embedding resizing.'							)
     def        lowerCAmelCase__		(    self							):
         pass




     def        lowerCAmelCase__		(    self							):
         _A,			_A     =							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             _A     =							model_class(snake_case_							)
             assert isinstance(model.get_input_embeddings()				,     tf.keras.layers.Layer							)
             if model_class is TFEsmForMaskedLM:
                 # Output embedding test differs from the main test because they're a matrix, not a layer
                 _A     =							model.get_bias()
                 assert isinstance(snake_case_				,     snake_case_							)
                 for k, v in name.items():
                     assert isinstance(snake_case_				,     tf.Variable							)
             else:
                 _A     =							model.get_output_embeddings()
                 assert x is None
                 _A     =							model.get_bias()
                 assert name is None







@require_tf
class      lowerCamelCase(						unittest.TestCase	):
     '''simple docstring'''


     @slow
     def        lowerCAmelCase__		(    self							):
         _A     =							TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D'							)

         _A     =							tf.constant([[0, 1, 2, 3, 4, 5]]							)
         _A     =							model(snake_case_							)[0]
         _A     =							[1, 6, 33]
         self.assertEqual(list(output.numpy().shape							)				,     snake_case_							)
         # compare the actual values for a slice.
         _A     =							tf.constant(
             [
                 [
                     [8.92_1518, -10.58_9814, -6.467_1307],
                     [-6.396_7156, -13.91_1377, -1.121_1915],
                     [-7.78_1247, -13.95_1557, -3.74_0592],
                 ]
             ]							)
         self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()				,     expected_slice.numpy()				,     atol=1E-2							)							)




     @slow
     def        lowerCAmelCase__		(    self							):
         _A     =							TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D'							)

         _A     =							tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]							)
         _A     =							model(snake_case_							)[0]
         # compare the actual values for a slice.
         _A     =							tf.constant(
             [
                 [
                     [0.1444_3092, 0.5412_5327, 0.324_7739],
                     [0.3034_0484, 0.0052_6676, 0.3107_7722],
                     [0.3227_8043, -0.2498_7096, 0.341_4628],
                 ]
             ]							)
         self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()				,     expected_slice.numpy()				,     atol=1E-4							)							)





