

"""simple docstring"""


from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
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 TFCvtForImageClassification, TFCvtModel
			from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor





class     snake_case	(				__snake_case  ):

				def 							lowercase_     (	self							:				Tuple)->   Any:



						'''simple docstring'''


						__lowerCAmelCase:       Union[str, Any]          =			self.config_class(**self.inputs_dict)
						self.parent.assertTrue(hasattr(UpperCamelCase__     ,  "embed_dim"))
						self.parent.assertTrue(hasattr(UpperCamelCase__     ,  "num_heads"))





class     snake_case	:

				def __init__(	self							:				List[str]     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				Optional[int]=1_3     ,  UpperCamelCase__							:				Dict=6_4     ,  UpperCamelCase__							:				Optional[int]=3     ,  UpperCamelCase__							:				List[str]=[1_6, 4_8, 9_6]     ,  UpperCamelCase__							:				List[Any]=[1, 3, 6]     ,  UpperCamelCase__							:				int=[1, 2, 1_0]     ,  UpperCamelCase__							:				List[Any]=[7, 3, 3]     ,  UpperCamelCase__							:				Dict=[4, 2, 2]     ,  UpperCamelCase__							:				Dict=[2, 1, 1]     ,  UpperCamelCase__							:				Tuple=[2, 2, 2]     ,  UpperCamelCase__							:				str=[False, False, True]     ,  UpperCamelCase__							:				Dict=[0.0, 0.0, 0.0]     ,  UpperCamelCase__							:				Any=0.02     ,  UpperCamelCase__							:				Optional[int]=1e-12     ,  UpperCamelCase__							:				Any=True     ,  UpperCamelCase__							:				str=True     ,  UpperCamelCase__							:				List[Any]=2     ,  )->   Tuple:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			parent
						__lowerCAmelCase:       Optional[Any]          =			batch_size
						__lowerCAmelCase:       List[Any]          =			image_size
						__lowerCAmelCase:       int          =			patch_sizes
						__lowerCAmelCase:       Tuple          =			patch_stride
						__lowerCAmelCase:       Union[str, Any]          =			patch_padding
						__lowerCAmelCase:       List[str]          =			is_training
						__lowerCAmelCase:       Union[str, Any]          =			use_labels
						__lowerCAmelCase:       Any          =			num_labels
						__lowerCAmelCase:       Tuple          =			num_channels
						__lowerCAmelCase:       Dict          =			embed_dim
						__lowerCAmelCase:       Any          =			num_heads
						__lowerCAmelCase:       List[Any]          =			stride_kv
						__lowerCAmelCase:       Tuple          =			depth
						__lowerCAmelCase:       List[Any]          =			cls_token
						__lowerCAmelCase:       Union[str, Any]          =			attention_drop_rate
						__lowerCAmelCase:       int          =			initializer_range
						__lowerCAmelCase:       Optional[Any]          =			layer_norm_eps

				def 							lowercase_     (	self							:				List[str])->   List[Any]:



						'''simple docstring'''


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

						__lowerCAmelCase:       Optional[Any]          =			None
						if self.use_labels:
								# create a random int32 tensor of given shape
								__lowerCAmelCase:       int          =			ids_tensor([self.batch_size]     ,  self.num_labels)

						__lowerCAmelCase:       int          =			self.get_config()
						return config, pixel_values, labels

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



						'''simple docstring'''


						return CvtConfig(
						    image_size=self.image_size     ,  num_labels=self.num_labels     ,  num_channels=self.num_channels     ,  embed_dim=self.embed_dim     ,  num_heads=self.num_heads     ,  patch_sizes=self.patch_sizes     ,  patch_padding=self.patch_padding     ,  patch_stride=self.patch_stride     ,  stride_kv=self.stride_kv     ,  depth=self.depth     ,  cls_token=self.cls_token     ,  attention_drop_rate=self.attention_drop_rate     ,  initializer_range=self.initializer_range     ,  )

				def 							lowercase_     (	self							:				Optional[int]     ,  UpperCamelCase__							:				Optional[Any]     ,  UpperCamelCase__							:				Optional[int]     ,  UpperCamelCase__							:				Dict)->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			TFCvtModel(config=UpperCamelCase__)
						__lowerCAmelCase:       Union[str, Any]          =			model(UpperCamelCase__     ,  training=UpperCamelCase__)
						__lowerCAmelCase:       str          =			(self.image_size, self.image_size)
						__lowerCAmelCase      , __lowerCAmelCase:       List[str]          =			image_size[0], image_size[1]
						for i in range(len(self.depth)):
								__lowerCAmelCase:       Union[str, Any]          =			floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
								__lowerCAmelCase:       List[str]          =			floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
						self.parent.assertEqual(result.last_hidden_state.shape     ,  (self.batch_size, self.embed_dim[-1], height, width))

				def 							lowercase_     (	self							:				Union[str, Any]     ,  UpperCamelCase__							:				Dict     ,  UpperCamelCase__							:				Any     ,  UpperCamelCase__							:				List[str])->   Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			self.num_labels
						__lowerCAmelCase:       Tuple          =			TFCvtForImageClassification(UpperCamelCase__)
						__lowerCAmelCase:       Optional[Any]          =			model(UpperCamelCase__     ,  labels=UpperCamelCase__     ,  training=UpperCamelCase__)
						self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.num_labels))




				def 							lowercase_     (	self							:				str)->   int:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			self.prepare_config_and_inputs()
						__lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase:       Optional[Any]          =			config_and_inputs
						__lowerCAmelCase:       List[Any]          =			{"pixel_values": pixel_values}
						return config, inputs_dict





@require_tf
class     snake_case	(				__snake_case,							__snake_case,							unittest.TestCase  ):
				SCREAMING_SNAKE_CASE_   :      Optional[int]         =  (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
				SCREAMING_SNAKE_CASE_   :      Optional[Any]         =  (
				    {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
				    if is_tf_available()
				    else {}
				)
				SCREAMING_SNAKE_CASE_   :      Optional[int]         =  False
				SCREAMING_SNAKE_CASE_   :      int         =  False
				SCREAMING_SNAKE_CASE_   :      int         =  False
				SCREAMING_SNAKE_CASE_   :      Optional[Any]         =  False
				SCREAMING_SNAKE_CASE_   :      int         =  False

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



						'''simple docstring'''


						__lowerCAmelCase:       Optional[Any]          =			TFCvtModelTester(self)
						__lowerCAmelCase:       Tuple          =			TFCvtConfigTester(self     ,  config_class=UpperCamelCase__     ,  has_text_modality=UpperCamelCase__     ,  hidden_size=3_7)

				def 							lowercase_     (	self							:				Any)->   Tuple:



						'''simple docstring'''


						self.config_tester.create_and_test_config_common_properties()
						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()

				@unittest.skip(reason="Cvt does not output attentions")
				def 							lowercase_     (	self							:				str)->   Any:



						'''simple docstring'''


						pass

				@unittest.skip(reason="Cvt does not use inputs_embeds")
				def 							lowercase_     (	self							:				int)->   Any:



						'''simple docstring'''


						pass

				@unittest.skip(reason="Cvt does not support input and output embeddings")
				def 							lowercase_     (	self							:				Any)->   List[Any]:



						'''simple docstring'''


						pass

				@unittest.skipIf(
				    not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0     ,  reason="TF does not support backprop for grouped convolutions on CPU."     ,  )
				def 							lowercase_     (	self							:				Tuple)->   Dict:



						'''simple docstring'''


						super().test_dataset_conversion()

				@unittest.skipIf(
				    not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0     ,  reason="TF does not support backprop for grouped convolutions on CPU."     ,  )
				@slow
				def 							lowercase_     (	self							:				Tuple)->   Optional[int]:



						'''simple docstring'''


						super().test_keras_fit()

				@unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8")
				def 							lowercase_     (	self							:				Optional[Any])->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       str          =			tf.keras.mixed_precision.Policy("mixed_float16")
						tf.keras.mixed_precision.set_global_policy(UpperCamelCase__)
						super().test_keras_fit()
						tf.keras.mixed_precision.set_global_policy("float32")

				def 							lowercase_     (	self							:				Dict)->   str:



						'''simple docstring'''


						__lowerCAmelCase      , __lowerCAmelCase:       Any          =			self.model_tester.prepare_config_and_inputs_for_common()

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

								__lowerCAmelCase:       Optional[Any]          =			["pixel_values"]
								self.assertListEqual(arg_names[:1]     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				List[Any])->   Dict:



						'''simple docstring'''


						def check_hidden_states_output(UpperCamelCase__							:				Union[str, Any]     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				Dict):
								__lowerCAmelCase:       str          =			model_class(UpperCamelCase__)

								__lowerCAmelCase:       Optional[Any]          =			model(**self._prepare_for_class(UpperCamelCase__     ,  UpperCamelCase__))
								__lowerCAmelCase:       List[Any]          =			outputs.hidden_states

								__lowerCAmelCase:       Any          =			len(self.model_tester.depth)
								self.assertEqual(len(UpperCamelCase__)     ,  UpperCamelCase__)

								# verify the first hidden states (first block)
								self.assertListEqual(
								    list(hidden_states[0].shape[-3:])     ,  [
								        self.model_tester.embed_dim[0],
								        self.model_tester.image_size // 4,
								        self.model_tester.image_size // 4,
								    ]     ,  )

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

						for model_class in self.all_model_classes:
								__lowerCAmelCase:       Optional[Any]          =			True
								check_hidden_states_output(UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__)

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

								check_hidden_states_output(UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__)

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



						'''simple docstring'''


						__lowerCAmelCase:       str          =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCamelCase__)

				def 							lowercase_     (	self							:				str)->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       int          =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__)




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



						'''simple docstring'''


						for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								__lowerCAmelCase:       Tuple          =			TFCvtModel.from_pretrained(UpperCamelCase__)
								self.assertIsNotNone(UpperCamelCase__)






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





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

				@cached_property
				def 							lowercase_     (	self							:				int)->   Tuple:



						'''simple docstring'''


						return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])




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



						'''simple docstring'''


						__lowerCAmelCase:       Any          =			TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])

						__lowerCAmelCase:       int          =			self.default_image_processor
						__lowerCAmelCase:       Tuple          =			prepare_img()
						__lowerCAmelCase:       Dict          =			image_processor(images=UpperCamelCase__     ,  return_tensors="tf")

						# forward pass
						__lowerCAmelCase:       List[str]          =			model(**UpperCamelCase__)

						# verify the logits
						__lowerCAmelCase:       str          =			tf.TensorShape((1, 1_0_0_0))
						self.assertEqual(outputs.logits.shape     ,  UpperCamelCase__)

						__lowerCAmelCase:       int          =			tf.constant([0.9285, 0.9015, -0.3150])
						self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()     ,  UpperCamelCase__     ,  atol=1e-4))





"""simple docstring"""


import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_blenderbot import BlenderbotTokenizer


if TYPE_CHECKING:
			from transformers.pipelines.conversational import Conversation

__A						   =			logging.get_logger(__name__)


__A						   =			{
    "vocab_file": "vocab.json",
    "merges_file": "merges.txt",
    "tokenizer_config_file": "tokenizer_config.json",
}

__A						   =			{
    "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"},
    "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"},
    "tokenizer_config_file": {
        "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json"
    },
}

__A						   =			{"facebook/blenderbot-3B": 128}





class     snake_case	(				__snake_case  ):
				SCREAMING_SNAKE_CASE_   :      Dict         =  VOCAB_FILES_NAMES
				SCREAMING_SNAKE_CASE_   :      str         =  PRETRAINED_VOCAB_FILES_MAP
				SCREAMING_SNAKE_CASE_   :      Optional[Any]         =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				SCREAMING_SNAKE_CASE_   :      Optional[int]         =  ["""input_ids""", """attention_mask"""]
				SCREAMING_SNAKE_CASE_   :      List[Any]         =  BlenderbotTokenizer

				def __init__(	self							:				Any     ,  UpperCamelCase__							:				str=None     ,  UpperCamelCase__							:				Tuple=None     ,  UpperCamelCase__							:				List[Any]=None     ,  UpperCamelCase__							:				Optional[Any]="replace"     ,  UpperCamelCase__							:				int="<s>"     ,  UpperCamelCase__							:				str="</s>"     ,  UpperCamelCase__							:				List[Any]="</s>"     ,  UpperCamelCase__							:				Union[str, Any]="<s>"     ,  UpperCamelCase__							:				List[str]="<unk>"     ,  UpperCamelCase__							:				Dict="<pad>"     ,  UpperCamelCase__							:				List[Any]="<mask>"     ,  UpperCamelCase__							:				Any=False     ,  UpperCamelCase__							:				int=True     ,  **UpperCamelCase__							:				Union[str, Any]     ,  )->   int:



						'''simple docstring'''


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

						__lowerCAmelCase:       Any          =			json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
						if pre_tok_state.get("add_prefix_space"     ,  UpperCamelCase__) != add_prefix_space:
								__lowerCAmelCase:       Dict          =			getattr(UpperCamelCase__     ,  pre_tok_state.pop("type"))
								__lowerCAmelCase:       int          =			add_prefix_space
								__lowerCAmelCase:       str          =			pre_tok_class(**UpperCamelCase__)

						__lowerCAmelCase:       List[Any]          =			add_prefix_space

						__lowerCAmelCase:       Union[str, Any]          =			"post_processor"
						__lowerCAmelCase:       Tuple          =			getattr(self.backend_tokenizer     ,  UpperCamelCase__     ,  UpperCamelCase__)
						if tokenizer_component_instance:
								__lowerCAmelCase:       List[Any]          =			json.loads(tokenizer_component_instance.__getstate__())

								# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
								if "sep" in state:
										__lowerCAmelCase:       str          =			tuple(state["sep"])
								if "cls" in state:
										__lowerCAmelCase:       Any          =			tuple(state["cls"])

								__lowerCAmelCase:       int          =			False

								if state.get("add_prefix_space"     ,  UpperCamelCase__) != add_prefix_space:
										__lowerCAmelCase:       Dict          =			add_prefix_space
										__lowerCAmelCase:       Optional[Any]          =			True

								if state.get("trim_offsets"     ,  UpperCamelCase__) != trim_offsets:
										__lowerCAmelCase:       Dict          =			trim_offsets
										__lowerCAmelCase:       Tuple          =			True

								if changes_to_apply:
										__lowerCAmelCase:       Dict          =			getattr(UpperCamelCase__     ,  state.pop("type"))
										__lowerCAmelCase:       str          =			component_class(**UpperCamelCase__)
										setattr(self.backend_tokenizer     ,  UpperCamelCase__     ,  UpperCamelCase__)

				@property
				# Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot
				def 							lowercase_     (	self							:				Optional[Any])->   str:



						'''simple docstring'''


						if self._mask_token is None:
								if self.verbose:
										logger.error("Using mask_token, but it is not set yet.")
								return None
						return str(self._mask_token)

				@mask_token.setter
				def 							lowercase_     (	self							:				str     ,  UpperCamelCase__							:				Union[str, Any])->   Tuple:



						'''simple docstring'''


						__lowerCAmelCase:       int          =			AddedToken(UpperCamelCase__     ,  lstrip=UpperCamelCase__     ,  rstrip=UpperCamelCase__) if isinstance(UpperCamelCase__     ,  UpperCamelCase__) else value
						__lowerCAmelCase:       Any          =			value

				def 							lowercase_     (	self							:				Union[str, Any]     ,  *UpperCamelCase__							:				List[str]     ,  **UpperCamelCase__							:				Optional[int])->   BatchEncoding:



						'''simple docstring'''


						__lowerCAmelCase:       List[str]          =			kwargs.get("is_split_into_words"     ,  UpperCamelCase__)
						assert self.add_prefix_space or not is_split_into_words, (
						    f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
						    "to use it with pretokenized inputs."
						)

						return super()._batch_encode_plus(*UpperCamelCase__     ,  **UpperCamelCase__)

				def 							lowercase_     (	self							:				Any     ,  *UpperCamelCase__							:				Optional[int]     ,  **UpperCamelCase__							:				int)->   BatchEncoding:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			kwargs.get("is_split_into_words"     ,  UpperCamelCase__)

						assert self.add_prefix_space or not is_split_into_words, (
						    f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
						    "to use it with pretokenized inputs."
						)

						return super()._encode_plus(*UpperCamelCase__     ,  **UpperCamelCase__)

				def 							lowercase_     (	self							:				List[str]     ,  UpperCamelCase__							:				str     ,  UpperCamelCase__							:				Optional[str] = None)->   Tuple[str]:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[int]          =			self._tokenizer.model.save(UpperCamelCase__     ,  name=UpperCamelCase__)
						return tuple(UpperCamelCase__)

				def 							lowercase_     (	self							:				str     ,  UpperCamelCase__							:				List[int]     ,  UpperCamelCase__							:				Optional[List[int]] = None)->   List[int]:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			[self.sep_token_id]
						__lowerCAmelCase:       Any          =			[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 							lowercase_     (	self							:				Union[str, Any]     ,  UpperCamelCase__							:				List[int]     ,  UpperCamelCase__							:				Optional[List[int]] = None)->   List[Any]:



						'''simple docstring'''


						return token_ids_a + [self.eos_token_id]




				def 							lowercase_     (	self							:				Dict     ,  UpperCamelCase__							:				"Conversation")->   List[int]:



						'''simple docstring'''


						__lowerCAmelCase:       str          =			[]
						for is_user, text in conversation.iter_texts():
								if is_user:
										# We need to space prefix as it's being done within blenderbot
										inputs.append(" " + text)
								else:
										# Generated responses should contain them already.
										inputs.append(UpperCamelCase__)

						__lowerCAmelCase:       Optional[int]          =			"  ".join(UpperCamelCase__)
						__lowerCAmelCase:       Tuple          =			self.encode(UpperCamelCase__)
						if len(UpperCamelCase__) > self.model_max_length:
								__lowerCAmelCase:       int          =			input_ids[-self.model_max_length :]
								logger.warning(f"Trimmed input from conversation as it was longer than {self.model_max_length} tokens.")
						return input_ids


