





'''simple docstring'''





import argparse
import os.path as osp
import re

import torch
from safetensors.torch import load_file, save_file


# =================#
# UNet Conversion #
# =================#

UpperCAmelCase_  							=				[
    # (stable-diffusion, HF Diffusers)
    ('time_embed.0.weight', 'time_embedding.linear_1.weight'),
    ('time_embed.0.bias', 'time_embedding.linear_1.bias'),
    ('time_embed.2.weight', 'time_embedding.linear_2.weight'),
    ('time_embed.2.bias', 'time_embedding.linear_2.bias'),
    ('input_blocks.0.0.weight', 'conv_in.weight'),
    ('input_blocks.0.0.bias', 'conv_in.bias'),
    ('out.0.weight', 'conv_norm_out.weight'),
    ('out.0.bias', 'conv_norm_out.bias'),
    ('out.2.weight', 'conv_out.weight'),
    ('out.2.bias', 'conv_out.bias'),
]

UpperCAmelCase_  							=				[
    # (stable-diffusion, HF Diffusers)
    ('in_layers.0', 'norm1'),
    ('in_layers.2', 'conv1'),
    ('out_layers.0', 'norm2'),
    ('out_layers.3', 'conv2'),
    ('emb_layers.1', 'time_emb_proj'),
    ('skip_connection', 'conv_shortcut'),
]

UpperCAmelCase_  							=				[]
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
  # loop over downblocks/upblocks

  for j in range(2):
    # loop over resnets/attentions for downblocks
    UpperCAmelCase_  							=				F'''down_blocks.{i}.resnets.{j}.'''
    UpperCAmelCase_  							=				F'''input_blocks.{3*i + j + 1}.0.'''
    unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))

    if i < 3:
      # no attention layers in down_blocks.3
      UpperCAmelCase_  							=				F'''down_blocks.{i}.attentions.{j}.'''
      UpperCAmelCase_  							=				F'''input_blocks.{3*i + j + 1}.1.'''
      unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))

  for j in range(3):
    # loop over resnets/attentions for upblocks
    UpperCAmelCase_  							=				F'''up_blocks.{i}.resnets.{j}.'''
    UpperCAmelCase_  							=				F'''output_blocks.{3*i + j}.0.'''
    unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))

    if i > 0:
      # no attention layers in up_blocks.0
      UpperCAmelCase_  							=				F'''up_blocks.{i}.attentions.{j}.'''
      UpperCAmelCase_  							=				F'''output_blocks.{3*i + j}.1.'''
      unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))

  if i < 3:
    # no downsample in down_blocks.3
    UpperCAmelCase_  							=				F'''down_blocks.{i}.downsamplers.0.conv.'''
    UpperCAmelCase_  							=				F'''input_blocks.{3*(i+1)}.0.op.'''
    unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))

    # no upsample in up_blocks.3
    UpperCAmelCase_  							=				F'''up_blocks.{i}.upsamplers.0.'''
    UpperCAmelCase_  							=				F'''output_blocks.{3*i + 2}.{1 if i == 0 else 2}.'''
    unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))

UpperCAmelCase_  							=				'mid_block.attentions.0.'
UpperCAmelCase_  							=				'middle_block.1.'
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))

for j in range(2):
  UpperCAmelCase_  							=				F'''mid_block.resnets.{j}.'''
  UpperCAmelCase_  							=				F'''middle_block.{2*j}.'''
  unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))




def 	lowerCAmelCase_					(						__UpperCAmelCase:    int   )   ->			str:
    # buyer beware: this is a *brittle* function,
    # and correct output requires that all of these pieces interact in
    # the exact order in which I have arranged them.
    UpperCamelCase__							:       List[Any]      =   {k: k for k in unet_state_dict.keys()}
    for sd_name, hf_name in unet_conversion_map:
        UpperCamelCase__							:       Tuple      =   sd_name
    for k, v in mapping.items():
        if "resnets" in k:
            for sd_part, hf_part in unet_conversion_map_resnet:
                UpperCamelCase__							:       Optional[int]      =   v.replace(__UpperCAmelCase	,     __UpperCAmelCase   )
            UpperCamelCase__							:       str      =   v
    for k, v in mapping.items():
        for sd_part, hf_part in unet_conversion_map_layer:
            UpperCamelCase__							:       List[Any]      =   v.replace(__UpperCAmelCase	,     __UpperCAmelCase   )
        UpperCamelCase__							:       List[str]      =   v
    UpperCamelCase__							:       Tuple      =   {v: unet_state_dict[k] for k, v in mapping.items()}
    return new_state_dict


# ================#
# VAE Conversion #
# ================#

UpperCAmelCase_  							=				[
    # (stable-diffusion, HF Diffusers)
    ('nin_shortcut', 'conv_shortcut'),
    ('norm_out', 'conv_norm_out'),
    ('mid.attn_1.', 'mid_block.attentions.0.'),
]

for i in range(4):
  # down_blocks have two resnets
  for j in range(2):
    UpperCAmelCase_  							=				F'''encoder.down_blocks.{i}.resnets.{j}.'''
    UpperCAmelCase_  							=				F'''encoder.down.{i}.block.{j}.'''
    vae_conversion_map.append((sd_down_prefix, hf_down_prefix))

  if i < 3:
    UpperCAmelCase_  							=				F'''down_blocks.{i}.downsamplers.0.'''
    UpperCAmelCase_  							=				F'''down.{i}.downsample.'''
    vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))

    UpperCAmelCase_  							=				F'''up_blocks.{i}.upsamplers.0.'''
    UpperCAmelCase_  							=				F'''up.{3-i}.upsample.'''
    vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))

  # up_blocks have three resnets
  # also, up blocks in hf are numbered in reverse from sd
  for j in range(3):
    UpperCAmelCase_  							=				F'''decoder.up_blocks.{i}.resnets.{j}.'''
    UpperCAmelCase_  							=				F'''decoder.up.{3-i}.block.{j}.'''
    vae_conversion_map.append((sd_up_prefix, hf_up_prefix))

# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
  UpperCAmelCase_  							=				F'''mid_block.resnets.{i}.'''
  UpperCAmelCase_  							=				F'''mid.block_{i+1}.'''
  vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))


UpperCAmelCase_  							=				[
    # (stable-diffusion, HF Diffusers)
    ('norm.', 'group_norm.'),
    ('q.', 'query.'),
    ('k.', 'key.'),
    ('v.', 'value.'),
    ('proj_out.', 'proj_attn.'),
]




def 	lowerCAmelCase_					(						__UpperCAmelCase:    Optional[int]   )   ->			List[Any]:
    # convert HF linear weights to SD conv2d weights
    return w.reshape(*w.shape	,     1	,     1   )




def 	lowerCAmelCase_					(						__UpperCAmelCase:    int   )   ->			List[Any]:
    UpperCamelCase__							:       List[str]      =   {k: k for k in vae_state_dict.keys()}
    for k, v in mapping.items():
        for sd_part, hf_part in vae_conversion_map:
            UpperCamelCase__							:       List[str]      =   v.replace(__UpperCAmelCase	,     __UpperCAmelCase   )
        UpperCamelCase__							:       Optional[int]      =   v
    for k, v in mapping.items():
        if "attentions" in k:
            for sd_part, hf_part in vae_conversion_map_attn:
                UpperCamelCase__							:       Any      =   v.replace(__UpperCAmelCase	,     __UpperCAmelCase   )
            UpperCamelCase__							:       str      =   v
    UpperCamelCase__							:       Any      =   {v: vae_state_dict[k] for k, v in mapping.items()}
    UpperCamelCase__							:       Any      =   ['''q''', '''k''', '''v''', '''proj_out''']
    for k, v in new_state_dict.items():
        for weight_name in weights_to_convert:
            if f"mid.attn_1.{weight_name}.weight" in k:
                print(f"Reshaping {k} for SD format"   )
                UpperCamelCase__							:       Dict      =   reshape_weight_for_sd(__UpperCAmelCase   )
    return new_state_dict


# =========================#
# Text Encoder Conversion #
# =========================#


UpperCAmelCase_  							=				[
    # (stable-diffusion, HF Diffusers)
    ('resblocks.', 'text_model.encoder.layers.'),
    ('ln_1', 'layer_norm1'),
    ('ln_2', 'layer_norm2'),
    ('.c_fc.', '.fc1.'),
    ('.c_proj.', '.fc2.'),
    ('.attn', '.self_attn'),
    ('ln_final.', 'transformer.text_model.final_layer_norm.'),
    ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'),
    ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'),
]
UpperCAmelCase_  							=				{re.escape(x[1]): x[0] for x in textenc_conversion_lst}
UpperCAmelCase_  							=				re.compile('|'.join(protected.keys()))

# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
UpperCAmelCase_  							=				{'q': 0, 'k': 1, 'v': 2}




def 	lowerCAmelCase_					(						__UpperCAmelCase:    Union[str, Any]   )   ->			Dict:
    UpperCamelCase__							:       Tuple      =   {}
    UpperCamelCase__							:       Any      =   {}
    UpperCamelCase__							:       Dict      =   {}
    for k, v in text_enc_dict.items():
        if (
            k.endswith('''.self_attn.q_proj.weight'''   )
            or k.endswith('''.self_attn.k_proj.weight'''   )
            or k.endswith('''.self_attn.v_proj.weight'''   )
        ):
            UpperCamelCase__							:       Union[str, Any]      =   k[: -len('''.q_proj.weight'''   )]
            UpperCamelCase__							:       Tuple      =   k[-len('''q_proj.weight'''   )]
            if k_pre not in capture_qkv_weight:
                UpperCamelCase__							:       str      =   [None, None, None]
            UpperCamelCase__							:       List[str]      =   v
            continue

        if (
            k.endswith('''.self_attn.q_proj.bias'''   )
            or k.endswith('''.self_attn.k_proj.bias'''   )
            or k.endswith('''.self_attn.v_proj.bias'''   )
        ):
            UpperCamelCase__							:       Optional[Any]      =   k[: -len('''.q_proj.bias'''   )]
            UpperCamelCase__							:       Union[str, Any]      =   k[-len('''q_proj.bias'''   )]
            if k_pre not in capture_qkv_bias:
                UpperCamelCase__							:       Any      =   [None, None, None]
            UpperCamelCase__							:       Dict      =   v
            continue

        UpperCamelCase__							:       List[Any]      =   textenc_pattern.sub(lambda __UpperCAmelCase   : protected[re.escape(m.group(0   )   )]	,     __UpperCAmelCase   )
        UpperCamelCase__							:       Dict      =   v

    for k_pre, tensors in capture_qkv_weight.items():
        if None in tensors:
            raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing'''   )
        UpperCamelCase__							:       Optional[Any]      =   textenc_pattern.sub(lambda __UpperCAmelCase   : protected[re.escape(m.group(0   )   )]	,     __UpperCAmelCase   )
        UpperCamelCase__							:       str      =   torch.cat(__UpperCAmelCase   )

    for k_pre, tensors in capture_qkv_bias.items():
        if None in tensors:
            raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing'''   )
        UpperCamelCase__							:       List[str]      =   textenc_pattern.sub(lambda __UpperCAmelCase   : protected[re.escape(m.group(0   )   )]	,     __UpperCAmelCase   )
        UpperCamelCase__							:       str      =   torch.cat(__UpperCAmelCase   )

    return new_state_dict




def 	lowerCAmelCase_					(						__UpperCAmelCase:    Union[str, Any]   )   ->			List[str]:
    return text_enc_dict


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

  parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.')
  parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.')
  parser.add_argument('--half', action='store_true', help='Save weights in half precision.')
  parser.add_argument(
      '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.'
  )

  UpperCAmelCase_  							=				parser.parse_args()

  assert args.model_path is not None, "Must provide a model path!"

  assert args.checkpoint_path is not None, "Must provide a checkpoint path!"

  # Path for safetensors
  UpperCAmelCase_  							=				osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors')
  UpperCAmelCase_  							=				osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors')
  UpperCAmelCase_  							=				osp.join(args.model_path, 'text_encoder', 'model.safetensors')

  # Load models from safetensors if it exists, if it doesn't pytorch
  if osp.exists(unet_path):
    UpperCAmelCase_  							=				load_file(unet_path, device='cpu')
  else:
    UpperCAmelCase_  							=				osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin')
    UpperCAmelCase_  							=				torch.load(unet_path, map_location='cpu')

  if osp.exists(vae_path):
    UpperCAmelCase_  							=				load_file(vae_path, device='cpu')
  else:
    UpperCAmelCase_  							=				osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin')
    UpperCAmelCase_  							=				torch.load(vae_path, map_location='cpu')

  if osp.exists(text_enc_path):
    UpperCAmelCase_  							=				load_file(text_enc_path, device='cpu')
  else:
    UpperCAmelCase_  							=				osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin')
    UpperCAmelCase_  							=				torch.load(text_enc_path, map_location='cpu')

  # Convert the UNet model
  UpperCAmelCase_  							=				convert_unet_state_dict(unet_state_dict)
  UpperCAmelCase_  							=				{'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()}

  # Convert the VAE model
  UpperCAmelCase_  							=				convert_vae_state_dict(vae_state_dict)
  UpperCAmelCase_  							=				{'first_stage_model.' + k: v for k, v in vae_state_dict.items()}

  # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
  UpperCAmelCase_  							=				'text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict

  if is_vaa_model:
    # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
    UpperCAmelCase_  							=				{'transformer.' + k: v for k, v in text_enc_dict.items()}
    UpperCAmelCase_  							=				convert_text_enc_state_dict_vaa(text_enc_dict)
    UpperCAmelCase_  							=				{'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()}
  else:
    UpperCAmelCase_  							=				convert_text_enc_state_dict(text_enc_dict)
    UpperCAmelCase_  							=				{'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()}

  # Put together new checkpoint
  UpperCAmelCase_  							=				{**unet_state_dict, **vae_state_dict, **text_enc_dict}
  if args.half:
    UpperCAmelCase_  							=				{k: v.half() for k, v in state_dict.items()}

  if args.use_safetensors:
    save_file(state_dict, args.checkpoint_path)
  else:
    UpperCAmelCase_  							=				{'state_dict': state_dict}
    torch.save(state_dict, args.checkpoint_path)








import inspect
import unittest
from typing import List

import numpy as np

from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
  import tensorflow as tf

  from transformers import (
      TFEfficientFormerForImageClassification,
      TFEfficientFormerForImageClassificationWithTeacher,
      TFEfficientFormerModel,
  )
  from transformers.models.efficientformer.modeling_tf_efficientformer import (
      TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
  )


if is_vision_available():
  from PIL import Image

  from transformers import EfficientFormerImageProcessor






class 					lowercase__ :

   '''simple docstring'''


   def __init__(					self,	__magic_name__,	__magic_name__ = 13,	__magic_name__ = 64,	__magic_name__ = 2,	__magic_name__ = 3,	__magic_name__ = 3,	__magic_name__ = True,	__magic_name__ = True,	__magic_name__ = 128,	__magic_name__=[16, 32, 64, 128],	__magic_name__ = 7,	__magic_name__ = 4,	__magic_name__ = 37,	__magic_name__ = "gelu",	__magic_name__ = 0.1,	__magic_name__ = 0.1,	__magic_name__ = 10,	__magic_name__ = 0.02,	__magic_name__ = 2,	__magic_name__ = 1,	__magic_name__ = 128,	__magic_name__ = [2, 2, 2, 2],	__magic_name__ = 2,	__magic_name__ = 2,	)				->   List[str]:






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   parent
       UpperCamelCase__							:       Optional[int]      =   batch_size
       UpperCamelCase__							:       Optional[Any]      =   image_size
       UpperCamelCase__							:       Optional[int]      =   patch_size
       UpperCamelCase__							:       Any      =   num_channels
       UpperCamelCase__							:       int      =   is_training
       UpperCamelCase__							:       str      =   use_labels
       UpperCamelCase__							:       Optional[Any]      =   hidden_size
       UpperCamelCase__							:       Tuple      =   num_hidden_layers
       UpperCamelCase__							:       str      =   num_attention_heads
       UpperCamelCase__							:       Any      =   intermediate_size
       UpperCamelCase__							:       int      =   hidden_act
       UpperCamelCase__							:       Dict      =   hidden_dropout_prob
       UpperCamelCase__							:       str      =   attention_probs_dropout_prob
       UpperCamelCase__							:       Tuple      =   type_sequence_label_size
       UpperCamelCase__							:       Optional[Any]      =   initializer_range
       UpperCamelCase__							:       Optional[int]      =   encoder_stride
       UpperCamelCase__							:       Any      =   num_attention_outputs
       UpperCamelCase__							:       Dict      =   embed_dim
       UpperCamelCase__							:       str      =   embed_dim + 1
       UpperCamelCase__							:       int      =   resolution
       UpperCamelCase__							:       List[str]      =   depths
       UpperCamelCase__							:       str      =   hidden_sizes
       UpperCamelCase__							:       Tuple      =   dim
       UpperCamelCase__							:       Optional[int]      =   mlp_expansion_ratio




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






       """simple docstring"""
       UpperCamelCase__							:       Union[str, Any]      =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

       UpperCamelCase__							:       Dict      =   None
       if self.use_labels:
           UpperCamelCase__							:       Optional[Any]      =   ids_tensor([self.batch_size],	self.type_sequence_label_size							)

       UpperCamelCase__							:       int      =   self.get_config()

       return config, pixel_values, labels




   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       return EfficientFormerConfig(
           image_size=self.image_size,	patch_size=self.patch_size,	num_channels=self.num_channels,	hidden_size=self.hidden_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,	is_decoder=__magic_name__,	initializer_range=self.initializer_range,	encoder_stride=self.encoder_stride,	resolution=self.resolution,	depths=self.depths,	hidden_sizes=self.hidden_sizes,	dim=self.dim,	mlp_expansion_ratio=self.mlp_expansion_ratio,	)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Any:






       """simple docstring"""
       UpperCamelCase__							:       Dict      =   TFEfficientFormerModel(config=__magic_name__							)
       UpperCamelCase__							:       str      =   model(__magic_name__,	training=__magic_name__							)
       self.parent.assertEqual(result.last_hidden_state.shape,	(self.batch_size, self.seq_length, self.hidden_size)							)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Optional[int]:






       """simple docstring"""
       UpperCamelCase__							:       Optional[int]      =   self.type_sequence_label_size
       UpperCamelCase__							:       Dict      =   TFEfficientFormerForImageClassification(__magic_name__							)
       UpperCamelCase__							:       Any      =   model(__magic_name__,	labels=__magic_name__,	training=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.type_sequence_label_size)							)

       # test greyscale images
       UpperCamelCase__							:       Optional[Any]      =   1
       UpperCamelCase__							:       List[str]      =   TFEfficientFormerForImageClassification(__magic_name__							)

       UpperCamelCase__							:       List[Any]      =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
       UpperCamelCase__							:       Union[str, Any]      =   model(__magic_name__,	labels=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.type_sequence_label_size)							)




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






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   self.prepare_config_and_inputs()
       UpperCamelCase__     ,UpperCamelCase__     ,UpperCamelCase__							:       Dict      =   config_and_inputs
       UpperCamelCase__							:       Any      =   {'''pixel_values''': pixel_values}
       return config, inputs_dict






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

   '''simple docstring'''


   a		:							int     	=	(
       (
           TFEfficientFormerModel,
           TFEfficientFormerForImageClassificationWithTeacher,
           TFEfficientFormerForImageClassification,
       )
       if is_tf_available()
       else ()
   )
   a		:							Union[str, Any]     	=	(
       {
           "feature-extraction": TFEfficientFormerModel,
           "image-classification": (
               TFEfficientFormerForImageClassification,
               TFEfficientFormerForImageClassificationWithTeacher,
           ),
       }
       if is_tf_available()
       else {}
   )

   a		:							Any     	=	False

   a		:							Tuple     	=	False
   a		:							Any     	=	False
   a		:							int     	=	False
   a		:							Tuple     	=	False




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






       """simple docstring"""
       UpperCamelCase__							:       Optional[Any]      =   TFEfficientFormerModelTester(self							)
       UpperCamelCase__							:       int      =   ConfigTester(
           self,	config_class=__magic_name__,	has_text_modality=__magic_name__,	hidden_size=37							)




   def    UpperCamelCase__						(					self							)				->   str:






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




   @unittest.skip(reason='''EfficientFormer does not use inputs_embeds'''							)
   def    UpperCamelCase__						(					self							)				->   Any:






       """simple docstring"""
       pass




   @unittest.skip(reason='''EfficientFormer does not support input and output embeddings'''							)
   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       pass




   def    UpperCamelCase__						(					self							)				->   int:






       """simple docstring"""
       UpperCamelCase__     ,UpperCamelCase__							:       Any      =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase__							:       List[str]      =   model_class(__magic_name__							)
           UpperCamelCase__							:       List[Any]      =   inspect.signature(model.call							)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           UpperCamelCase__							:       List[str]      =   [*signature.parameters.keys()]

           UpperCamelCase__							:       int      =   ['''pixel_values''']
           self.assertListEqual(arg_names[:1],	__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       def check_hidden_states_output(__magic_name__,	__magic_name__,	__magic_name__							):
           UpperCamelCase__							:       Union[str, Any]      =   model_class(__magic_name__							)

           UpperCamelCase__							:       str      =   model(**self._prepare_for_class(__magic_name__,	__magic_name__							),	training=__magic_name__							)
           UpperCamelCase__							:       Tuple      =   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           UpperCamelCase__							:       Optional[int]      =   getattr(
               self.model_tester,	'''expected_num_hidden_layers''',	self.model_tester.num_hidden_layers + 1							)
           self.assertEqual(len(__magic_name__							),	__magic_name__							)

           if hasattr(self.model_tester,	'''encoder_seq_length'''							):
               UpperCamelCase__							:       Dict      =   self.model_tester.encoder_seq_length
               if hasattr(self.model_tester,	'''chunk_length'''							) and self.model_tester.chunk_length > 1:
                   UpperCamelCase__							:       Tuple      =   seq_length * self.model_tester.chunk_length
           else:
               UpperCamelCase__							:       Optional[Any]      =   self.model_tester.seq_length

           self.assertListEqual(
               list(hidden_states[-1].shape[-2:]							),	[seq_length, self.model_tester.hidden_size],	)

           if config.is_encoder_decoder:
               UpperCamelCase__							:       List[str]      =   outputs.decoder_hidden_states

               self.asseretIsInstance(__magic_name__,	(list, tuple)							)
               self.assertEqual(len(__magic_name__							),	__magic_name__							)
               UpperCamelCase__							:       str      =   getattr(self.model_tester,	'''seq_length''',	__magic_name__							)
               UpperCamelCase__							:       Optional[Any]      =   getattr(self.model_tester,	'''decoder_seq_length''',	__magic_name__							)

               self.assertListEqual(
                   list(hidden_states[-1].shape[-2:]							),	[decoder_seq_length, self.model_tester.hidden_size],	)

       UpperCamelCase__     ,UpperCamelCase__							:       str      =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase__							:       List[str]      =   True
           check_hidden_states_output(__magic_name__,	__magic_name__,	__magic_name__							)

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           UpperCamelCase__							:       List[Any]      =   True

           check_hidden_states_output(__magic_name__,	__magic_name__,	__magic_name__							)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__=False							)				->   Any:






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   super()._prepare_for_class(__magic_name__,	__magic_name__,	return_labels=__magic_name__							)

       if return_labels:
           if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
               del inputs_dict["labels"]

       return inputs_dict




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






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__magic_name__							)




   @unittest.skip(reason='''EfficientFormer does not implement masked image modeling yet'''							)
   def    UpperCamelCase__						(					self							)				->   Union[str, Any]:






       """simple docstring"""
       UpperCamelCase__							:       Optional[int]      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*__magic_name__							)




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






       """simple docstring"""
       UpperCamelCase__							:       List[Any]      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__magic_name__							)




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






       """simple docstring"""
       for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__							:       Dict      =   TFEfficientFormerModel.from_pretrained(__magic_name__							)
           self.assertIsNotNone(__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__     ,UpperCamelCase__							:       str      =   self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__							:       Dict      =   True

       UpperCamelCase__							:       Optional[Any]      =   getattr(self.model_tester,	'''seq_length''',	__magic_name__							)
       UpperCamelCase__							:       Any      =   getattr(self.model_tester,	'''encoder_seq_length''',	__magic_name__							)
       UpperCamelCase__							:       Tuple      =   getattr(self.model_tester,	'''key_length''',	__magic_name__							)
       UpperCamelCase__							:       Union[str, Any]      =   getattr(self.model_tester,	'''chunk_length''',	__magic_name__							)

       if chunk_length is not None and hasattr(self.model_tester,	'''num_hashes'''							):
           UpperCamelCase__							:       Dict      =   encoder_seq_length * self.model_tester.num_hashes

       for model_class in self.all_model_classes:
           UpperCamelCase__							:       Dict      =   True
           UpperCamelCase__							:       Optional[int]      =   False
           UpperCamelCase__							:       Any      =   True
           UpperCamelCase__							:       str      =   model_class(__magic_name__							)

           UpperCamelCase__							:       Optional[int]      =   model(**self._prepare_for_class(__magic_name__,	__magic_name__							),	training=__magic_name__							)
           UpperCamelCase__							:       List[str]      =   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
           self.assertEqual(len(__magic_name__							),	self.model_tester.num_attention_outputs							)

           # check that output_attentions also work using config
           del inputs_dict["output_attentions"]
           UpperCamelCase__							:       Optional[int]      =   True
           UpperCamelCase__							:       int      =   model_class(__magic_name__							)
           UpperCamelCase__							:       str      =   model(**self._prepare_for_class(__magic_name__,	__magic_name__							),	training=__magic_name__							)

           UpperCamelCase__							:       List[str]      =   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
           self.assertEqual(len(__magic_name__							),	self.model_tester.num_attention_outputs							)

           if chunk_length is not None:
               self.assertListEqual(
                   list(attentions[0].shape[-4:]							),	[self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length],	)
           else:
               self.assertListEqual(
                   list(attentions[0].shape[-3:]							),	[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],	)




   def    UpperCamelCase__						(					self							)				->   Dict:






       """simple docstring"""
       # We use a simplified version of this test for EfficientFormer because it requires training=False
       # and Keras refuses to let us force that during functional construction
       UpperCamelCase__     ,UpperCamelCase__							:       str      =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           # Prepare our model
           UpperCamelCase__							:       str      =   model_class(__magic_name__							)
           # These are maximally general inputs for the model, with multiple None dimensions
           # Hopefully this will catch any conditionals that fail for flexible shapes
           UpperCamelCase__							:       Tuple      =   {
               key: tf.keras.Input(shape=val.shape[1:],	dtype=val.dtype,	name=__magic_name__							)
               for key, val in model.input_signature.items()
               if key in model.dummy_inputs
           }
           UpperCamelCase__							:       str      =   model(__magic_name__							)
           self.assertTrue(outputs_dict is not None							)




def 	lowerCAmelCase_					(						)   ->			List[str]:
    UpperCamelCase__							:       Any      =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
    return image






@require_tf
@require_vision
class 					lowercase__ (			unittest.TestCase       ):

   '''simple docstring'''


   @cached_property
   def    UpperCamelCase__						(					self							)				->   Union[str, Any]:






       """simple docstring"""
       return (
           EfficientFormerImageProcessor.from_pretrained('''snap-research/efficientformer-l1-300'''							)
           if is_vision_available()
           else None
       )




   @slow
   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:       Optional[Any]      =   TFEfficientFormerForImageClassification.from_pretrained('''snap-research/efficientformer-l1-300'''							)
       UpperCamelCase__							:       Dict      =   self.default_image_processor
       UpperCamelCase__							:       List[str]      =   prepare_img()
       UpperCamelCase__							:       str      =   image_processor(images=__magic_name__,	return_tensors='''tf'''							)
       # forward pass
       UpperCamelCase__							:       Dict      =   model(**__magic_name__,	training=__magic_name__							)
       # verify the logits
       UpperCamelCase__							:       Tuple      =   tf.TensorShape((1, 1000)							)
       self.assertEqual(outputs.logits.shape,	__magic_name__							)
       UpperCamelCase__							:       List[str]      =   tf.constant([-0.0555, 0.4825, -0.0852]							)
       self.assertTrue(np.allclose(outputs.logits[0, :3],	__magic_name__,	atol=1E-4							)							)




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






       """simple docstring"""
       UpperCamelCase__							:       str      =   TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
           '''snap-research/efficientformer-l1-300'''							)
       UpperCamelCase__							:       List[str]      =   self.default_image_processor
       UpperCamelCase__							:       Union[str, Any]      =   prepare_img()
       UpperCamelCase__							:       int      =   image_processor(images=__magic_name__,	return_tensors='''tf'''							)
       # forward pass
       UpperCamelCase__							:       Tuple      =   model(**__magic_name__,	training=__magic_name__							)
       # verify the logits
       UpperCamelCase__							:       Tuple      =   tf.TensorShape((1, 1000)							)
       self.assertEqual(outputs.logits.shape,	__magic_name__							)
       UpperCamelCase__							:       Optional[int]      =   tf.constant([-0.1312, 0.4353, -1.0499]							)
       self.assertTrue(np.allclose(outputs.logits[0, :3],	__magic_name__,	atol=1E-4							)							)

