
import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
							import torch

							from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin







class 				lowercase		:




							def __init__(				self   ,A__   ,A__=None   ,A__=None   ,A__=None   ,A__="resnet50"   ,A__=3   ,A__=3_2   ,A__=3   ,A__=True   ,A__=True   ,):
												lowercase							=						parent
												lowercase							=						out_indices if out_indices is not None else [4]
												lowercase							=						stage_names
												lowercase							=						out_features
												lowercase							=						backbone
												lowercase							=						batch_size
												lowercase							=						image_size
												lowercase							=						num_channels
												lowercase							=						use_pretrained_backbone
												lowercase							=						is_training




							def  A__      (				self):
												lowercase							=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
												lowercase							=						self.get_config()

												return config, pixel_values




							def  A__      (				self):
												return TimmBackboneConfig(
												    image_size=self.image_size   ,num_channels=self.num_channels   ,out_features=self.out_features   ,out_indices=self.out_indices   ,stage_names=self.stage_names   ,use_pretrained_backbone=self.use_pretrained_backbone   ,backbone=self.backbone   ,)




							def  A__      (				self   ,A__   ,A__):
												lowercase							=						TimmBackbone(config=A__)
												model.to(A__)
												model.eval()
												with torch.no_grad():
																	lowercase							=						model(A__)
												self.parent.assertEqual(
												    result.feature_map[-1].shape   ,(self.batch_size, model.channels[-1], 1_4, 1_4)   ,)





							def  A__      (				self):
												lowercase							=						self.prepare_config_and_inputs()
												lowercase	,						lowercase							=						config_and_inputs
												lowercase							=						{'''pixel_values''': pixel_values}
												return config, inputs_dict







@require_torch
@require_timm
class 				lowercase		(					SCREAMING_SNAKE_CASE__       ,  SCREAMING_SNAKE_CASE__       ,  SCREAMING_SNAKE_CASE__       ,  unittest.TestCase		):
							lowercase_       :       Union[str, Any]       					=(TimmBackbone,) if is_torch_available() else ()
							lowercase_       :       Optional[int]       					={'''feature-extraction''': TimmBackbone} if is_torch_available() else {}
							lowercase_       :       str       					=False
							lowercase_       :       Dict       					=False
							lowercase_       :       str       					=False
							lowercase_       :       Union[str, Any]       					=False




							def  A__      (				self):
												lowercase							=						TimmBackboneModelTester(self)
												lowercase							=						ConfigTester(self   ,config_class=A__   ,has_text_modality=A__)




							def  A__      (				self):
												self.config_tester.create_and_test_config_to_json_string()
												self.config_tester.create_and_test_config_to_json_file()
												self.config_tester.create_and_test_config_from_and_save_pretrained()
												self.config_tester.create_and_test_config_with_num_labels()
												self.config_tester.check_config_can_be_init_without_params()
												self.config_tester.check_config_arguments_init()




							def  A__      (				self):
												lowercase							=						'''resnet18'''
												lowercase							=						'''microsoft/resnet-18'''

												lowercase							=						AutoBackbone.from_pretrained(A__   ,use_timm_backbone=A__)
												lowercase							=						AutoBackbone.from_pretrained(A__)

												self.assertEqual(len(timm_model.out_features)   ,len(transformers_model.out_features))
												self.assertEqual(len(timm_model.stage_names)   ,len(transformers_model.stage_names))
												self.assertEqual(timm_model.channels   ,transformers_model.channels)
												# Out indices are set to the last layer by default. For timm models, we don't know
												# the number of layers in advance, so we set it to (-1,), whereas for transformers
												# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
												self.assertEqual(timm_model.out_indices   ,(-1,))
												self.assertEqual(transformers_model.out_indices   ,[len(timm_model.stage_names) - 1])

												lowercase							=						AutoBackbone.from_pretrained(A__   ,use_timm_backbone=A__   ,out_indices=[1, 2, 3])
												lowercase							=						AutoBackbone.from_pretrained(A__   ,out_indices=[1, 2, 3])

												self.assertEqual(timm_model.out_indices   ,transformers_model.out_indices)
												self.assertEqual(len(timm_model.out_features)   ,len(transformers_model.out_features))
												self.assertEqual(timm_model.channels   ,transformers_model.channels)




							@unittest.skip('''TimmBackbone doesn\'t support feed forward chunking''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone initialization is managed on the timm side''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint''')
							def  A__      (				self):
												pass




							@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''')
							def  A__      (				self):
												pass




							@unittest.skip('''model weights aren\'t tied in TimmBackbone.''')
							def  A__      (				self):
												pass




							@unittest.skip('''model weights aren\'t tied in TimmBackbone.''')
							def  A__      (				self):
												pass




							@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''')
							def  A__      (				self):
												pass




							@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.''')
							def  A__      (				self):
												pass




							@unittest.skip('''TimmBackbone doesn\'t support output_attentions.''')
							def  A__      (				self):
												pass




							@unittest.skip('''Safetensors is not supported by timm.''')
							def  A__      (				self):
												pass




							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
							def  A__      (				self):
												pass




							def  A__      (				self):
												lowercase	,						lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	lowercase							=						model_class(A__)
																	lowercase							=						inspect.signature(model.forward)
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	lowercase							=						[*signature.parameters.keys()]

																	lowercase							=						['''pixel_values''']
																	self.assertListEqual(arg_names[:1]   ,A__)




							def  A__      (				self):
												lowercase	,						lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()
												lowercase							=						True
												lowercase							=						self.has_attentions

												# no need to test all models as different heads yield the same functionality
												lowercase							=						self.all_model_classes[0]
												lowercase							=						model_class(A__)
												model.to(A__)

												lowercase							=						self._prepare_for_class(A__   ,A__)
												lowercase							=						model(**A__)
												lowercase							=						outputs[0][-1]

												# Encoder-/Decoder-only models
												lowercase							=						outputs.hidden_states[0]
												hidden_states.retain_grad()

												if self.has_attentions:
																	lowercase							=						outputs.attentions[0]
																	attentions.retain_grad()

												output.flatten()[0].backward(retain_graph=A__)

												self.assertIsNotNone(hidden_states.grad)

												if self.has_attentions:
																	self.assertIsNotNone(attentions.grad)





							def  A__      (				self):
												lowercase	,						lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	lowercase							=						model_class(A__)
																	model.to(A__)
																	model.eval()
																	lowercase							=						model(**A__)

																	self.assertEqual(len(result.feature_maps)   ,len(config.out_indices))
																	self.assertEqual(len(model.channels)   ,len(config.out_indices))

																	# Check output of last stage is taken if out_features=None, out_indices=None
																	lowercase							=						copy.deepcopy(A__)
																	lowercase							=						None
																	lowercase							=						model_class(A__)
																	model.to(A__)
																	model.eval()
																	lowercase							=						model(**A__)

																	self.assertEqual(len(result.feature_maps)   ,1)
																	self.assertEqual(len(model.channels)   ,1)

																	# Check backbone can be initialized with fresh weights
																	lowercase							=						copy.deepcopy(A__)
																	lowercase							=						False
																	lowercase							=						model_class(A__)
																	model.to(A__)
																	model.eval()
																	lowercase							=						model(**A__)






import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer


lowercase__		:List[Any]   =    logging.get_logger(__name__)

lowercase__		:Optional[Any]   =    {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

lowercase__		:Union[str, Any]   =    {
    "vocab_file": {
        "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt",
        "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt",
        "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/vocab.txt",
        "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/vocab.txt",
        "bert-base-multilingual-uncased": (
            "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt"
        ),
        "bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt",
        "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt",
        "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt",
        "bert-large-uncased-whole-word-masking": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt"
        ),
        "bert-large-cased-whole-word-masking": (
            "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt"
        ),
        "bert-large-uncased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
        ),
        "bert-large-cased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
        ),
        "bert-base-cased-finetuned-mrpc": (
            "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt"
        ),
        "bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt",
        "bert-base-german-dbmdz-uncased": (
            "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt"
        ),
        "TurkuNLP/bert-base-finnish-cased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt"
        ),
        "TurkuNLP/bert-base-finnish-uncased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt"
        ),
        "wietsedv/bert-base-dutch-cased": (
            "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json",
        "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json",
        "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json",
        "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json",
        "bert-base-multilingual-uncased": (
            "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json"
        ),
        "bert-base-multilingual-cased": (
            "https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json"
        ),
        "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json",
        "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json",
        "bert-large-uncased-whole-word-masking": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json"
        ),
        "bert-large-cased-whole-word-masking": (
            "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json"
        ),
        "bert-large-uncased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
        ),
        "bert-large-cased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
        ),
        "bert-base-cased-finetuned-mrpc": (
            "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json"
        ),
        "bert-base-german-dbmdz-cased": (
            "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json"
        ),
        "bert-base-german-dbmdz-uncased": (
            "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json"
        ),
        "TurkuNLP/bert-base-finnish-cased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json"
        ),
        "TurkuNLP/bert-base-finnish-uncased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json"
        ),
        "wietsedv/bert-base-dutch-cased": (
            "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json"
        ),
    },
}

lowercase__		:str   =    {
    "bert-base-uncased": 512,
    "bert-large-uncased": 512,
    "bert-base-cased": 512,
    "bert-large-cased": 512,
    "bert-base-multilingual-uncased": 512,
    "bert-base-multilingual-cased": 512,
    "bert-base-chinese": 512,
    "bert-base-german-cased": 512,
    "bert-large-uncased-whole-word-masking": 512,
    "bert-large-cased-whole-word-masking": 512,
    "bert-large-uncased-whole-word-masking-finetuned-squad": 512,
    "bert-large-cased-whole-word-masking-finetuned-squad": 512,
    "bert-base-cased-finetuned-mrpc": 512,
    "bert-base-german-dbmdz-cased": 512,
    "bert-base-german-dbmdz-uncased": 512,
    "TurkuNLP/bert-base-finnish-cased-v1": 512,
    "TurkuNLP/bert-base-finnish-uncased-v1": 512,
    "wietsedv/bert-base-dutch-cased": 512,
}

lowercase__		:Dict   =    {
    "bert-base-uncased": {"do_lower_case": True},
    "bert-large-uncased": {"do_lower_case": True},
    "bert-base-cased": {"do_lower_case": False},
    "bert-large-cased": {"do_lower_case": False},
    "bert-base-multilingual-uncased": {"do_lower_case": True},
    "bert-base-multilingual-cased": {"do_lower_case": False},
    "bert-base-chinese": {"do_lower_case": False},
    "bert-base-german-cased": {"do_lower_case": False},
    "bert-large-uncased-whole-word-masking": {"do_lower_case": True},
    "bert-large-cased-whole-word-masking": {"do_lower_case": False},
    "bert-large-uncased-whole-word-masking-finetuned-squad": {"do_lower_case": True},
    "bert-large-cased-whole-word-masking-finetuned-squad": {"do_lower_case": False},
    "bert-base-cased-finetuned-mrpc": {"do_lower_case": False},
    "bert-base-german-dbmdz-cased": {"do_lower_case": False},
    "bert-base-german-dbmdz-uncased": {"do_lower_case": True},
    "TurkuNLP/bert-base-finnish-cased-v1": {"do_lower_case": False},
    "TurkuNLP/bert-base-finnish-uncased-v1": {"do_lower_case": True},
    "wietsedv/bert-base-dutch-cased": {"do_lower_case": False},
}







class 				lowercase		(					SCREAMING_SNAKE_CASE__		):
							lowercase_       :       str       					=VOCAB_FILES_NAMES
							lowercase_       :       Dict       					=PRETRAINED_VOCAB_FILES_MAP
							lowercase_       :       Optional[int]       					=PRETRAINED_INIT_CONFIGURATION
							lowercase_       :       Tuple       					=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							lowercase_       :       Any       					=BertTokenizer




							def __init__(				self   ,A__=None   ,A__=None   ,A__=True   ,A__="[UNK]"   ,A__="[SEP]"   ,A__="[PAD]"   ,A__="[CLS]"   ,A__="[MASK]"   ,A__=True   ,A__=None   ,**A__   ,):
												super().__init__(
												    A__   ,tokenizer_file=A__   ,do_lower_case=A__   ,unk_token=A__   ,sep_token=A__   ,pad_token=A__   ,cls_token=A__   ,mask_token=A__   ,tokenize_chinese_chars=A__   ,strip_accents=A__   ,**A__   ,)

												lowercase							=						json.loads(self.backend_tokenizer.normalizer.__getstate__())
												if (
												    normalizer_state.get('''lowercase'''   ,A__) != do_lower_case
												    or normalizer_state.get('''strip_accents'''   ,A__) != strip_accents
												    or normalizer_state.get('''handle_chinese_chars'''   ,A__) != tokenize_chinese_chars
												):
																	lowercase							=						getattr(A__   ,normalizer_state.pop('''type'''))
																	lowercase							=						do_lower_case
																	lowercase							=						strip_accents
																	lowercase							=						tokenize_chinese_chars
																	lowercase							=						normalizer_class(**A__)

												lowercase							=						do_lower_case




							def  A__      (				self   ,A__   ,A__=None):
												lowercase							=						[self.cls_token_id] + token_ids_a + [self.sep_token_id]

												if token_ids_a:
																	output += token_ids_a + [self.sep_token_id]

												return output




							def  A__      (				self   ,A__   ,A__ = None):
												lowercase							=						[self.sep_token_id]
												lowercase							=						[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) * [0] + len(token_ids_a + sep) * [1]





							def  A__      (				self   ,A__   ,A__ = None):
												lowercase							=						self._tokenizer.model.save(A__   ,name=A__)
												return tuple(A__)




