



"""simple docstring"""

import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


lowercase__			   =  logging.get_logger(__name__)


lowercase__			   =  {"vocab_file": "vocab.json", "merges_file": "merges.txt"}

# See all BART models at https://huggingface.co/models?filter=bart
lowercase__			   =  {
    "vocab_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
    },
    "merges_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
    },
}

lowercase__			   =  {
    "facebook/bart-base": 1024,
    "facebook/bart-large": 1024,
    "facebook/bart-large-mnli": 1024,
    "facebook/bart-large-cnn": 1024,
    "facebook/bart-large-xsum": 1024,
    "yjernite/bart_eli5": 1024,
}





@lru_cache()
def       __magic_name__    (   ):
							__a		:		Dict									=       (
							    list(range(ord("""!"""					)  ,       ord("""~"""					) + 1					)					) + list(range(ord("""¡"""					)  ,       ord("""¬"""					) + 1					)					) + list(range(ord("""®"""					)  ,       ord("""ÿ"""					) + 1					)					)
							)
							__a		:		Optional[Any]									=       bs[:]
							__a		:		Optional[int]									=       0
							for b in range(2**8					):
														if b not in bs:
																					bs.append(lowerCamelCase__					)
																					cs.append(2**8 + n					)
																					n += 1
							__a		:		Dict									=       [chr(lowerCamelCase__					) for n in cs]
							return dict(zip(lowerCamelCase__  ,       lowerCamelCase__					)					)





def       __magic_name__    (   _lowerCamelCase				: Tuple					):
							__a		:		Dict									=       set()
							__a		:		Union[str, Any]									=       word[0]
							for char in word[1:]:
														pairs.add((prev_char, char)					)
														__a		:		Optional[Any]									=       char
							return pairs







class SCREAMING_SNAKE_CASE__					(		__snake_case      ):
						_lowerCAmelCase							=					VOCAB_FILES_NAMES
						_lowerCAmelCase							=					PRETRAINED_VOCAB_FILES_MAP
						_lowerCAmelCase							=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						_lowerCAmelCase							=					["input_ids", "attention_mask"]



						def __init__(self						,     _lowercase						,     _lowercase						,     _lowercase="replace"						,     _lowercase="<s>"						,     _lowercase="</s>"						,     _lowercase="</s>"						,     _lowercase="<s>"						,     _lowercase="<unk>"						,     _lowercase="<pad>"						,     _lowercase="<mask>"						,     _lowercase=False						,     **_lowercase						,     ):





													'''simple docstring'''

													__a		:		str									=       AddedToken(UpperCamelCase_						,     lstrip=UpperCamelCase_						,     rstrip=UpperCamelCase_							) if isinstance(UpperCamelCase_						,     UpperCamelCase_							) else bos_token
													__a		:		List[str]									=       AddedToken(UpperCamelCase_						,     lstrip=UpperCamelCase_						,     rstrip=UpperCamelCase_							) if isinstance(UpperCamelCase_						,     UpperCamelCase_							) else eos_token
													__a		:		Optional[int]									=       AddedToken(UpperCamelCase_						,     lstrip=UpperCamelCase_						,     rstrip=UpperCamelCase_							) if isinstance(UpperCamelCase_						,     UpperCamelCase_							) else sep_token
													__a		:		int									=       AddedToken(UpperCamelCase_						,     lstrip=UpperCamelCase_						,     rstrip=UpperCamelCase_							) if isinstance(UpperCamelCase_						,     UpperCamelCase_							) else cls_token
													__a		:		Optional[int]									=       AddedToken(UpperCamelCase_						,     lstrip=UpperCamelCase_						,     rstrip=UpperCamelCase_							) if isinstance(UpperCamelCase_						,     UpperCamelCase_							) else unk_token
													__a		:		Dict									=       AddedToken(UpperCamelCase_						,     lstrip=UpperCamelCase_						,     rstrip=UpperCamelCase_							) if isinstance(UpperCamelCase_						,     UpperCamelCase_							) else pad_token

													# Mask token behave like a normal word, i.e. include the space before it
													__a		:		Union[str, Any]									=       AddedToken(UpperCamelCase_						,     lstrip=UpperCamelCase_						,     rstrip=UpperCamelCase_							) if isinstance(UpperCamelCase_						,     UpperCamelCase_							) else mask_token

													super().__init__(
													    errors=UpperCamelCase_						,     bos_token=UpperCamelCase_						,     eos_token=UpperCamelCase_						,     unk_token=UpperCamelCase_						,     sep_token=UpperCamelCase_						,     cls_token=UpperCamelCase_						,     pad_token=UpperCamelCase_						,     mask_token=UpperCamelCase_						,     add_prefix_space=UpperCamelCase_						,     **UpperCamelCase_						,     )

													with open(UpperCamelCase_						,     encoding="""utf-8"""							) as vocab_handle:
																				__a		:		int									=       json.load(UpperCamelCase_							)
													__a		:		Any									=       {v: k for k, v in self.encoder.items()}
													__a		:		Any									=       errors  # how to handle errors in decoding
													__a		:		str									=       bytes_to_unicode()
													__a		:		List[str]									=       {v: k for k, v in self.byte_encoder.items()}
													with open(UpperCamelCase_						,     encoding="""utf-8"""							) as merges_handle:
																				__a		:		str									=       merges_handle.read().split("""\n"""							)[1:-1]
													__a		:		List[str]									=       [tuple(merge.split()							) for merge in bpe_merges]
													__a		:		Union[str, Any]									=       dict(zip(UpperCamelCase_						,     range(len(UpperCamelCase_							)							)							)							)
													__a		:		Optional[int]									=       {}
													__a		:		Optional[int]									=       add_prefix_space

													# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
													__a		:		Dict									=       re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""							)



						@property
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													return len(self.encoder							)



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													return dict(self.encoder						,     **self.added_tokens_encoder							)



						def     lowerCAmelCase__(self						,     _lowercase							):





													'''simple docstring'''

													if token in self.cache:
																				return self.cache[token]
													__a		:		List[str]									=       tuple(UpperCamelCase_							)
													__a		:		str									=       get_pairs(UpperCamelCase_							)

													if not pairs:
																				return token

													while True:
																				__a		:		str									=       min(UpperCamelCase_						,     key=lambda _lowercase							: self.bpe_ranks.get(UpperCamelCase_						,     float("""inf"""							)							)							)
																				if bigram not in self.bpe_ranks:
																											break
																				__a		:		List[Any]									=       bigram
																				__a		:		Any									=       []
																				__a		:		List[str]									=       0
																				while i < len(UpperCamelCase_							):
																											try:
																																		__a		:		Union[str, Any]									=       word.index(UpperCamelCase_						,     UpperCamelCase_							)
																											except ValueError:
																																		new_word.extend(word[i:]							)
																																		break
																											else:
																																		new_word.extend(word[i:j]							)
																																		__a		:		str									=       j

																											if word[i] == first and i < len(UpperCamelCase_							) - 1 and word[i + 1] == second:
																																		new_word.append(first + second							)
																																		i += 2
																											else:
																																		new_word.append(word[i]							)
																																		i += 1
																				__a		:		Dict									=       tuple(UpperCamelCase_							)
																				__a		:		str									=       new_word
																				if len(UpperCamelCase_							) == 1:
																											break
																				else:
																											__a		:		int									=       get_pairs(UpperCamelCase_							)
													__a		:		Optional[int]									=       " ".join(UpperCamelCase_							)
													__a		:		Dict									=       word
													return word



						def     lowerCAmelCase__(self						,     _lowercase							):





													'''simple docstring'''

													__a		:		Optional[Any]									=       []
													for token in re.findall(self.pat						,     UpperCamelCase_							):
																				__a		:		Any									=       "".join(
																				    self.byte_encoder[b] for b in token.encode("""utf-8"""							)							)  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
																				bpe_tokens.extend(bpe_token for bpe_token in self.bpe(UpperCamelCase_							).split(""" """							)							)
													return bpe_tokens



						def     lowerCAmelCase__(self						,     _lowercase							):





													'''simple docstring'''

													return self.encoder.get(UpperCamelCase_						,     self.encoder.get(self.unk_token							)							)



						def     lowerCAmelCase__(self						,     _lowercase							):





													'''simple docstring'''

													return self.decoder.get(UpperCamelCase_							)



						def     lowerCAmelCase__(self						,     _lowercase							):





													'''simple docstring'''

													__a		:		List[str]									=       "".join(UpperCamelCase_							)
													__a		:		Union[str, Any]									=       bytearray([self.byte_decoder[c] for c in text]							).decode("""utf-8"""						,     errors=self.errors							)
													return text



						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase = None							):





													'''simple docstring'''

													if not os.path.isdir(UpperCamelCase_							):
																				logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''							)
																				return
													__a		:		Any									=       os.path.join(
													    UpperCamelCase_						,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]							)
													__a		:		Optional[int]									=       os.path.join(
													    UpperCamelCase_						,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]							)

													with open(UpperCamelCase_						,     """w"""						,     encoding="""utf-8"""							) as f:
																				f.write(json.dumps(self.encoder						,     indent=2						,     sort_keys=UpperCamelCase_						,     ensure_ascii=UpperCamelCase_							) + """\n"""							)

													__a		:		str									=       0
													with open(UpperCamelCase_						,     """w"""						,     encoding="""utf-8"""							) as writer:
																				writer.write("""#version: 0.2\n"""							)
																				for bpe_tokens, token_index in sorted(self.bpe_ranks.items()						,     key=lambda _lowercase							: kv[1]							):
																											if index != token_index:
																																		logger.warning(
																																		    F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
																																		    """ Please check that the tokenizer is not corrupted!"""							)
																																		__a		:		str									=       token_index
																											writer.write(""" """.join(UpperCamelCase_							) + """\n"""							)
																											index += 1

													return vocab_file, merge_file



						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase = None							):





													'''simple docstring'''

													if token_ids_a is None:
																				return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
													__a		:		List[Any]									=       [self.cls_token_id]
													__a		:		Tuple									=       [self.sep_token_id]
													return cls + token_ids_a + sep + sep + token_ids_a + sep



						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase = None						,     _lowercase = False							):





													'''simple docstring'''

													if already_has_special_tokens:
																				return super().get_special_tokens_mask(
																				    token_ids_a=UpperCamelCase_						,     token_ids_a=UpperCamelCase_						,     already_has_special_tokens=UpperCamelCase_							)

													if token_ids_a is None:
																				return [1] + ([0] * len(UpperCamelCase_							)) + [1]
													return [1] + ([0] * len(UpperCamelCase_							)) + [1, 1] + ([0] * len(UpperCamelCase_							)) + [1]



						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase = None							):





													'''simple docstring'''

													__a		:		int									=       [self.sep_token_id]
													__a		:		List[str]									=       [self.cls_token_id]

													if token_ids_a is None:
																				return len(cls + token_ids_a + sep							) * [0]
													return len(cls + token_ids_a + sep + sep + token_ids_a + sep							) * [0]





						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase=False						,     **_lowercase							):





													'''simple docstring'''

													__a		:		List[str]									=       kwargs.pop("""add_prefix_space"""						,     self.add_prefix_space							)
													if (is_split_into_words or add_prefix_space) and (len(UpperCamelCase_							) > 0 and not text[0].isspace()):
																				__a		:		Tuple									=       " " + text
													return (text, kwargs)






"""simple docstring"""

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 SCREAMING_SNAKE_CASE__					:



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





													'''simple docstring'''

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



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Union[str, Any]									=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

													__a		:		str									=       None
													if self.use_labels:
																				__a		:		List[str]									=       ids_tensor([self.batch_size]						,     self.type_sequence_label_size							)

													__a		:		List[str]									=       self.get_config()

													return config, pixel_values, labels



						def     lowerCAmelCase__(self							):





													'''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=_lowercase						,     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     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase							):





													'''simple docstring'''

													__a		:		Optional[Any]									=       TFEfficientFormerModel(config=_lowercase							)
													__a		:		List[Any]									=       model(_lowercase						,     training=_lowercase							)
													self.parent.assertEqual(result.last_hidden_state.shape						,     (self.batch_size, self.seq_length, self.hidden_size)							)



						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase							):





													'''simple docstring'''

													__a		:		Optional[Any]									=       self.type_sequence_label_size
													__a		:		Any									=       TFEfficientFormerForImageClassification(_lowercase							)
													__a		:		Union[str, Any]									=       model(_lowercase						,     labels=_lowercase						,     training=_lowercase							)
													self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.type_sequence_label_size)							)

													# test greyscale images
													__a		:		Optional[Any]									=       1
													__a		:		int									=       TFEfficientFormerForImageClassification(_lowercase							)

													__a		:		List[str]									=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
													__a		:		str									=       model(_lowercase						,     labels=_lowercase							)
													self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.type_sequence_label_size)							)





						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Any									=       self.prepare_config_and_inputs()
													__a							,     __a							,     __a		:		Tuple									=       config_and_inputs
													__a		:		Tuple									=       {"""pixel_values""": pixel_values}
													return config, inputs_dict







@require_tf
class SCREAMING_SNAKE_CASE__					(		__snake_case     ,					__snake_case     ,					unittest.TestCase      ):
						_lowerCAmelCase							=					(
						    (
						        TFEfficientFormerModel,
						        TFEfficientFormerForImageClassificationWithTeacher,
						        TFEfficientFormerForImageClassification,
						    )
						    if is_tf_available()
						    else ()
						)
						_lowerCAmelCase							=					(
						    {
						        "feature-extraction": TFEfficientFormerModel,
						        "image-classification": (
						            TFEfficientFormerForImageClassification,
						            TFEfficientFormerForImageClassificationWithTeacher,
						        ),
						    }
						    if is_tf_available()
						    else {}
						)

						_lowerCAmelCase							=					False

						_lowerCAmelCase							=					False
						_lowerCAmelCase							=					False
						_lowerCAmelCase							=					False
						_lowerCAmelCase							=					False



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Tuple									=       TFEfficientFormerModelTester(self							)
													__a		:		Any									=       ConfigTester(
													    self						,     config_class=_lowercase						,     has_text_modality=_lowercase						,     hidden_size=37							)



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													self.config_tester.run_common_tests()



						@unittest.skip(reason="""EfficientFormer does not use inputs_embeds"""							)
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													pass



						@unittest.skip(reason="""EfficientFormer does not support input and output embeddings"""							)
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													pass



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a							,     __a		:		Optional[int]									=       self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				__a		:		Dict									=       model_class(_lowercase							)
																				__a		:		Optional[Any]									=       inspect.signature(model.call							)
																				# signature.parameters is an OrderedDict => so arg_names order is deterministic
																				__a		:		Optional[Any]									=       [*signature.parameters.keys()]

																				__a		:		Union[str, Any]									=       ["""pixel_values"""]
																				self.assertListEqual(arg_names[:1]						,     _lowercase							)



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													def check_hidden_states_output(_lowercase						,     _lowercase						,     _lowercase							):
																				__a		:		Tuple									=       model_class(_lowercase							)

																				__a		:		int									=       model(**self._prepare_for_class(_lowercase						,     _lowercase							)						,     training=_lowercase							)
																				__a		:		Tuple									=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																				__a		:		str									=       getattr(
																				    self.model_tester						,     """expected_num_hidden_layers"""						,     self.model_tester.num_hidden_layers + 1							)
																				self.assertEqual(len(_lowercase							)						,     _lowercase							)

																				if hasattr(self.model_tester						,     """encoder_seq_length"""							):
																											__a		:		Any									=       self.model_tester.encoder_seq_length
																											if hasattr(self.model_tester						,     """chunk_length"""							) and self.model_tester.chunk_length > 1:
																																		__a		:		int									=       seq_length * self.model_tester.chunk_length
																				else:
																											__a		:		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:
																											__a		:		Optional[int]									=       outputs.decoder_hidden_states

																											self.asseretIsInstance(_lowercase						,     (list, tuple)							)
																											self.assertEqual(len(_lowercase							)						,     _lowercase							)
																											__a		:		Any									=       getattr(self.model_tester						,     """seq_length"""						,     _lowercase							)
																											__a		:		List[Any]									=       getattr(self.model_tester						,     """decoder_seq_length"""						,     _lowercase							)

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

													__a							,     __a		:		Union[str, Any]									=       self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				__a		:		Dict									=       True
																				check_hidden_states_output(_lowercase						,     _lowercase						,     _lowercase							)

																				# check that output_hidden_states also work using config
																				del inputs_dict["output_hidden_states"]
																				__a		:		int									=       True

																				check_hidden_states_output(_lowercase						,     _lowercase						,     _lowercase							)



						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase=False							):





													'''simple docstring'''

													__a		:		Any									=       super()._prepare_for_class(_lowercase						,     _lowercase						,     return_labels=_lowercase							)

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

													return inputs_dict



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Optional[Any]									=       self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*_lowercase							)



						@unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet"""							)
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Union[str, Any]									=       self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_masked_image_modeling(*_lowercase							)



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Optional[Any]									=       self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*_lowercase							)



						@slow
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				__a		:		Union[str, Any]									=       TFEfficientFormerModel.from_pretrained(_lowercase							)
																				self.assertIsNotNone(_lowercase							)



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a							,     __a		:		Optional[Any]									=       self.model_tester.prepare_config_and_inputs_for_common()
													__a		:		int									=       True

													__a		:		Optional[int]									=       getattr(self.model_tester						,     """seq_length"""						,     _lowercase							)
													__a		:		Dict									=       getattr(self.model_tester						,     """encoder_seq_length"""						,     _lowercase							)
													__a		:		Dict									=       getattr(self.model_tester						,     """key_length"""						,     _lowercase							)
													__a		:		int									=       getattr(self.model_tester						,     """chunk_length"""						,     _lowercase							)

													if chunk_length is not None and hasattr(self.model_tester						,     """num_hashes"""							):
																				__a		:		List[str]									=       encoder_seq_length * self.model_tester.num_hashes

													for model_class in self.all_model_classes:
																				__a		:		List[Any]									=       True
																				__a		:		Tuple									=       False
																				__a		:		List[Any]									=       True
																				__a		:		int									=       model_class(_lowercase							)

																				__a		:		List[Any]									=       model(**self._prepare_for_class(_lowercase						,     _lowercase							)						,     training=_lowercase							)
																				__a		:		Dict									=       outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
																				self.assertEqual(len(_lowercase							)						,     self.model_tester.num_attention_outputs							)

																				# check that output_attentions also work using config
																				del inputs_dict["output_attentions"]
																				__a		:		Optional[Any]									=       True
																				__a		:		List[str]									=       model_class(_lowercase							)
																				__a		:		Dict									=       model(**self._prepare_for_class(_lowercase						,     _lowercase							)						,     training=_lowercase							)

																				__a		:		int									=       outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
																				self.assertEqual(len(_lowercase							)						,     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     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a							,     __a		:		List[str]									=       self.model_tester.prepare_config_and_inputs_for_common()

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







def       __magic_name__    (   ):
							__a		:		int									=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
							return image







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



						@cached_property
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

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



						@slow
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

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





						@slow
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

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

