


import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
		from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import ViTImageProcessor




class        _UpperCamelCase			:







							'''simple docstring'''







							def __init__(		self	:					Union[str, Any]		,					SCREAMING_SNAKE_CASE_	:					Optional[int]		,					SCREAMING_SNAKE_CASE_	:					List[Any]=1_3		,					SCREAMING_SNAKE_CASE_	:					List[Any]=3_0		,					SCREAMING_SNAKE_CASE_	:					Optional[Any]=2		,					SCREAMING_SNAKE_CASE_	:					Dict=3		,					SCREAMING_SNAKE_CASE_	:					Any=True		,					SCREAMING_SNAKE_CASE_	:					Optional[int]=True		,					SCREAMING_SNAKE_CASE_	:					Tuple=3_2		,					SCREAMING_SNAKE_CASE_	:					Optional[Any]=5		,					SCREAMING_SNAKE_CASE_	:					Optional[int]=4		,					SCREAMING_SNAKE_CASE_	:					Union[str, Any]=3_7		,					SCREAMING_SNAKE_CASE_	:					Tuple="gelu"		,					SCREAMING_SNAKE_CASE_	:					Any=0.1		,					SCREAMING_SNAKE_CASE_	:					str=0.1		,					SCREAMING_SNAKE_CASE_	:					Union[str, Any]=1_0		,					SCREAMING_SNAKE_CASE_	:					Any=0.02		,					SCREAMING_SNAKE_CASE_	:					str=None		,					SCREAMING_SNAKE_CASE_	:					Union[str, Any]=2		,					):
													_a     			=      parent
													_a     			=      batch_size
													_a     			=      image_size
													_a     			=      patch_size
													_a     			=      num_channels
													_a     			=      is_training
													_a     			=      use_labels
													_a     			=      hidden_size
													_a     			=      num_hidden_layers
													_a     			=      num_attention_heads
													_a     			=      intermediate_size
													_a     			=      hidden_act
													_a     			=      hidden_dropout_prob
													_a     			=      attention_probs_dropout_prob
													_a     			=      type_sequence_label_size
													_a     			=      initializer_range
													_a     			=      scope
													_a     			=      encoder_stride

													# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
													_a     			=      (image_size // patch_size) ** 2
													_a     			=      num_patches + 1







							def 		_UpperCAmelCase						(		self	:					Optional[int]		):
													_a     			=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

													_a     			=      None
													if self.use_labels:
																			_a     			=      ids_tensor([self.batch_size]		,					self.type_sequence_label_size		)

													_a     			=      self.get_config()

													return config, pixel_values, labels







							def 		_UpperCAmelCase						(		self	:					Union[str, Any]		):
													return ViTConfig(
													    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=snake_case__		,					initializer_range=self.initializer_range		,					encoder_stride=self.encoder_stride		,					)







							def 		_UpperCAmelCase						(		self	:					Any		,					SCREAMING_SNAKE_CASE_	:					Union[str, Any]		,					SCREAMING_SNAKE_CASE_	:					Any		,					SCREAMING_SNAKE_CASE_	:					List[Any]		):
													_a     			=      ViTModel(config=snake_case__		)
													model.to(snake_case__		)
													model.eval()
													_a     			=      model(snake_case__		)
													self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size)		)







							def 		_UpperCAmelCase						(		self	:					Optional[Any]		,					SCREAMING_SNAKE_CASE_	:					List[str]		,					SCREAMING_SNAKE_CASE_	:					Optional[Any]		,					SCREAMING_SNAKE_CASE_	:					str		):
													_a     			=      ViTForMaskedImageModeling(config=snake_case__		)
													model.to(snake_case__		)
													model.eval()
													_a     			=      model(snake_case__		)
													self.parent.assertEqual(
													    result.reconstruction.shape		,					(self.batch_size, self.num_channels, self.image_size, self.image_size)		)

													# test greyscale images
													_a     			=      1
													_a     			=      ViTForMaskedImageModeling(snake_case__		)
													model.to(snake_case__		)
													model.eval()

													_a     			=      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
													_a     			=      model(snake_case__		)
													self.parent.assertEqual(result.reconstruction.shape		,					(self.batch_size, 1, self.image_size, self.image_size)		)







							def 		_UpperCAmelCase						(		self	:					Union[str, Any]		,					SCREAMING_SNAKE_CASE_	:					Optional[int]		,					SCREAMING_SNAKE_CASE_	:					List[str]		,					SCREAMING_SNAKE_CASE_	:					Optional[int]		):
													_a     			=      self.type_sequence_label_size
													_a     			=      ViTForImageClassification(snake_case__		)
													model.to(snake_case__		)
													model.eval()
													_a     			=      model(snake_case__		,					labels=snake_case__		)
													self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.type_sequence_label_size)		)

													# test greyscale images
													_a     			=      1
													_a     			=      ViTForImageClassification(snake_case__		)
													model.to(snake_case__		)
													model.eval()

													_a     			=      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
													_a     			=      model(snake_case__		)
													self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.type_sequence_label_size)		)







							def 		_UpperCAmelCase						(		self	:					Any		):
													_a     			=      self.prepare_config_and_inputs()
													(
													    _a  
													)     			=      config_and_inputs
													_a     			=      {'pixel_values': pixel_values}
													return config, inputs_dict




@require_torch
class        _UpperCamelCase			(   SCREAMING_SNAKE_CASE_      ,				SCREAMING_SNAKE_CASE_      ,				unittest.TestCase						):







							'''simple docstring'''
							_A						=	(
							    (
							        ViTModel,
							        ViTForImageClassification,
							        ViTForMaskedImageModeling,
							    )
							    if is_torch_available()
							    else ()
							)
							_A						=	(
							    {"feature-extraction": ViTModel, "image-classification": ViTForImageClassification}
							    if is_torch_available()
							    else {}
							)
							_A						=	True

							_A						=	False
							_A						=	False
							_A						=	False







							def 		_UpperCAmelCase						(		self	:					Tuple		):
													_a     			=      ViTModelTester(self		)
													_a     			=      ConfigTester(self		,					config_class=snake_case__		,					has_text_modality=snake_case__		,					hidden_size=3_7		)







							def 		_UpperCAmelCase						(		self	:					Optional[Any]		):
													self.config_tester.run_common_tests()







							@unittest.skip(reason='ViT does not use inputs_embeds'		)
							def 		_UpperCAmelCase						(		self	:					List[str]		):
													pass







							def 		_UpperCAmelCase						(		self	:					Optional[Any]		):
													_a     			=      self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																			_a     			=      model_class(snake_case__		)
																			self.assertIsInstance(model.get_input_embeddings()		,					(nn.Module)		)
																			_a     			=      model.get_output_embeddings()
																			self.assertTrue(x is None or isinstance(snake_case__		,					nn.Linear		)		)







							def 		_UpperCAmelCase						(		self	:					Tuple		):
													_a     			=      self.model_tester.prepare_config_and_inputs_for_common()

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

																			_a     			=      ['pixel_values']
																			self.assertListEqual(arg_names[:1]		,					snake_case__		)







							def 		_UpperCAmelCase						(		self	:					int		):
													_a     			=      self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*snake_case__		)







							def 		_UpperCAmelCase						(		self	:					str		):
													_a     			=      self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_masked_image_modeling(*snake_case__		)







							def 		_UpperCAmelCase						(		self	:					Dict		):
													_a     			=      self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*snake_case__		)







							@slow
							def 		_UpperCAmelCase						(		self	:					str		):

													for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			_a     			=      ViTModel.from_pretrained(snake_case__		)
																			self.assertIsNotNone(snake_case__		)




def 				SCREAMING_SNAKE_CASE       (	)     ->	Optional[Any]:
						_a     			=      Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
						return image






@require_torch
@require_vision
class        _UpperCamelCase			(   unittest.TestCase						):







							'''simple docstring'''







							@cached_property
							def 		_UpperCAmelCase						(		self	:					Optional[int]		):
													return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224'		) if is_vision_available() else None







							@slow
							def 		_UpperCAmelCase						(		self	:					Optional[Any]		):
													_a     			=      ViTForImageClassification.from_pretrained('google/vit-base-patch16-224'		).to(snake_case__		)

													_a     			=      self.default_image_processor
													_a     			=      prepare_img()
													_a     			=      image_processor(images=snake_case__		,					return_tensors='pt'		).to(snake_case__		)

													# forward pass
													with torch.no_grad():
																			_a     			=      model(**snake_case__		)

													# verify the logits
													_a     			=      torch.Size((1, 1_0_0_0)		)
													self.assertEqual(outputs.logits.shape		,					snake_case__		)

													_a     			=      torch.tensor([-0.2744, 0.8215, -0.0836]		).to(snake_case__		)

													self.assertTrue(torch.allclose(outputs.logits[0, :3]		,					snake_case__		,					atol=1e-4		)		)







							@slow
							def 		_UpperCAmelCase						(		self	:					int		):
													_a     			=      ViTModel.from_pretrained('facebook/dino-vits8'		).to(snake_case__		)

													_a     			=      ViTImageProcessor.from_pretrained('facebook/dino-vits8'		,					size=4_8_0		)
													_a     			=      prepare_img()
													_a     			=      image_processor(images=snake_case__		,					return_tensors='pt'		)
													_a     			=      inputs.pixel_values.to(snake_case__		)

													# forward pass
													with torch.no_grad():
																			_a     			=      model(snake_case__		,					interpolate_pos_encoding=snake_case__		)

													# verify the logits
													_a     			=      torch.Size((1, 3_6_0_1, 3_8_4)		)
													self.assertEqual(outputs.last_hidden_state.shape		,					snake_case__		)

													_a     			=      torch.tensor(
													    [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]		).to(snake_case__		)

													self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]		,					snake_case__		,					atol=1e-4		)		)







							@slow
							@require_accelerate
							@require_torch_gpu
							def 		_UpperCAmelCase						(		self	:					List[str]		):
													_a     			=      ViTModel.from_pretrained('facebook/dino-vits8'		,					torch_dtype=torch.floataa		,					device_map='auto'		)
													_a     			=      self.default_image_processor

													_a     			=      prepare_img()
													_a     			=      image_processor(images=snake_case__		,					return_tensors='pt'		)
													_a     			=      inputs.pixel_values.to(snake_case__		)

													# forward pass to make sure inference works in fp16
													with torch.no_grad():
																			_a     			=      model(snake_case__		)






'''simple docstring'''







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

import numpy as np

from ...utils import is_tf_available, is_torch_available, logging


if TYPE_CHECKING:
       if is_torch_available():
              import torch
       if is_tf_available():
              import tensorflow as tf

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer


lowerCAmelCase     :  Optional[int]											=    logging.get_logger(__name__)

lowerCAmelCase     :  Union[str, Any]											=    {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

lowerCAmelCase     :  Optional[Any]											=    {
    """vocab_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """Salesforce/codegen-350M-mono""": (
            """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json"""
        ),
    },
}

lowerCAmelCase     :  List[str]											=    {
    """Salesforce/codegen-350M-mono""": 20_48,
}
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_						):



     """simple docstring"""






     __magic_name__           =     VOCAB_FILES_NAMES
     __magic_name__           =     PRETRAINED_VOCAB_FILES_MAP
     __magic_name__           =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __magic_name__           =     ["input_ids", "attention_mask"]
     __magic_name__           =     CodeGenTokenizer







     def __init__(			self   ,						snake_case__=None   ,						snake_case__=None   ,						snake_case__=None   ,						snake_case__="<|endoftext|>"   ,						snake_case__="<|endoftext|>"   ,						snake_case__="<|endoftext|>"   ,						snake_case__=False   ,						**snake_case__   ,						):

            '''simple docstring'''

            super().__init__(
                snake_case__   ,						snake_case__   ,						tokenizer_file=snake_case__   ,						unk_token=snake_case__   ,						bos_token=snake_case__   ,						eos_token=snake_case__   ,						add_prefix_space=snake_case__   ,						**snake_case__   ,						)

            if kwargs.pop('add_bos_token'   ,						snake_case__ ):
                   _lowerCAmelCase     :				Tuple       =							kwargs.pop('name_or_path'   ,						'' )
                   raise ValueError(
                       'Currenty GPT2\'s fast tokenizer does NOT support adding a BOS token.'
                       'Instead you should use GPT2\'s slow tokenizer class `CodeGenTokenizer` as follows: \n'
                       F'`CodeGenTokenizer.from_pretrained(\'{model_id}\')`\nor\n'
                       F'`AutoTokenizer.from_pretrained(\'{model_id}\', use_fast=False)`\n'
                       'This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.'
                       ' so that the fast tokenizer works correctly.' )

            _lowerCAmelCase     :				List[str]       =							json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
            if pre_tok_state.get('add_prefix_space'   ,						snake_case__ ) != add_prefix_space:
                   _lowerCAmelCase     :				List[Any]       =							getattr(snake_case__   ,						pre_tok_state.pop('type' ) )
                   _lowerCAmelCase     :				Dict       =							add_prefix_space
                   _lowerCAmelCase     :				List[Any]       =							pre_tok_class(**snake_case__ )

            _lowerCAmelCase     :				Tuple       =							add_prefix_space







     def a						(			self   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				Union[str, Any]       =							kwargs.get('is_split_into_words'   ,						snake_case__ )
            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(*snake_case__   ,						**snake_case__ )







     def a						(			self   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							kwargs.get('is_split_into_words'   ,						snake_case__ )

            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(*snake_case__   ,						**snake_case__ )







     def a						(			self   ,						snake_case__   ,						snake_case__ = None ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self._tokenizer.model.save(snake_case__   ,						name=snake_case__ )
            return tuple(snake_case__ )







     def a						(			self   ,						snake_case__   ,						snake_case__ = False   ,						snake_case__ = None   ,						snake_case__ = None   ,						**snake_case__   ,						):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							super().decode(
                token_ids=snake_case__   ,						skip_special_tokens=snake_case__   ,						clean_up_tokenization_spaces=snake_case__   ,						**snake_case__   ,						)

            if truncate_before_pattern is not None and len(snake_case__ ) > 0:
                   _lowerCAmelCase     :				Optional[int]       =							self.truncate(snake_case__   ,						snake_case__ )

            return decoded_text







     def a						(			self   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            def find_re(snake_case__   ,						snake_case__   ,						snake_case__ ):
                   _lowerCAmelCase     :				List[Any]       =							pattern.search(snake_case__   ,						snake_case__ )
                   return m.start() if m else -1

            _lowerCAmelCase     :				Any       =							[re.compile(snake_case__   ,						re.MULTILINE ) for pattern in truncate_before_pattern]

            _lowerCAmelCase     :				Dict       =							list(re.finditer('^print'   ,						snake_case__   ,						re.MULTILINE ) )

            if len(snake_case__ ) > 1:
                   _lowerCAmelCase     :				Optional[int]       =							completion[: prints[1].start()]

            _lowerCAmelCase     :				Optional[int]       =							list(re.finditer('^def'   ,						snake_case__   ,						re.MULTILINE ) )

            if len(snake_case__ ) > 1:
                   _lowerCAmelCase     :				Optional[Any]       =							completion[: defs[1].start()]

            _lowerCAmelCase     :				int       =							0

            _lowerCAmelCase     :				Tuple       =							[
                pos for pos in [find_re(snake_case__   ,						snake_case__   ,						snake_case__ ) for terminal in terminals] if pos != -1
            ]

            if len(snake_case__ ) > 0:
                   return completion[: min(snake_case__ )]
            else:
                   return completion

