


"""simple docstring"""







import argparse
import os
import re

import packaging.version


a__    :							str            =					'''examples/'''
a__    :							Dict            =					{
    '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''),
    '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''),
    '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''),
    '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''),
}
a__    :							Dict            =					{
    '''init''': '''src/diffusers/__init__.py''',
    '''setup''': '''setup.py''',
}
a__    :							List[Any]            =					'''README.md'''




def        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_       ):




					'''simple docstring'''


					with open(lowerCAmelCase_  ,						"r"  ,						encoding="utf-8"  ,						newline="\n"       ) as f:
										__SCREAMING_SNAKE_CASE						       =    f.read()
					__SCREAMING_SNAKE_CASE       ,  __SCREAMING_SNAKE_CASE						       =    REPLACE_PATTERNS[pattern]
					__SCREAMING_SNAKE_CASE						       =    replace.replace("VERSION"  ,						lowerCAmelCase_       )
					__SCREAMING_SNAKE_CASE						       =    re_pattern.sub(lowerCAmelCase_  ,						lowerCAmelCase_       )
					with open(lowerCAmelCase_  ,						"w"  ,						encoding="utf-8"  ,						newline="\n"       ) as f:
										f.write(lowerCAmelCase_       )




def        UpperCAmelCase__	(lowerCAmelCase_       ):




					'''simple docstring'''


					for folder, directories, fnames in os.walk(lowerCAmelCase_       ):
										# Removing some of the folders with non-actively maintained examples from the walk
										if "research_projects" in directories:
															directories.remove("research_projects"       )
										if "legacy" in directories:
															directories.remove("legacy"       )
										for fname in fnames:
															if fname.endswith(".py"       ):
																				update_version_in_file(os.path.join(lowerCAmelCase_  ,						lowerCAmelCase_       )  ,						lowerCAmelCase_  ,						pattern="examples"       )




def        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_=False       ):




					'''simple docstring'''


					for pattern, fname in REPLACE_FILES.items():
										update_version_in_file(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_       )
					if not patch:
										update_version_in_examples(lowerCAmelCase_       )




def        UpperCAmelCase__	():




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    "🤗 Transformers currently provides the following architectures"
					__SCREAMING_SNAKE_CASE						       =    "1. Want to contribute a new model?"
					with open(lowerCAmelCase_  ,						"r"  ,						encoding="utf-8"  ,						newline="\n"       ) as f:
										__SCREAMING_SNAKE_CASE						       =    f.readlines()

					# Find the start of the list.
					__SCREAMING_SNAKE_CASE						       =    0
					while not lines[start_index].startswith(_start_prompt       ):
										start_index += 1
					start_index += 1

					__SCREAMING_SNAKE_CASE						       =    start_index
					# Update the lines in the model list.
					while not lines[index].startswith(_end_prompt       ):
										if lines[index].startswith("1."       ):
															__SCREAMING_SNAKE_CASE						       =    lines[index].replace(
															    "https://huggingface.co/docs/diffusers/main/model_doc"  ,						"https://huggingface.co/docs/diffusers/model_doc"  ,						)
										index += 1

					with open(lowerCAmelCase_  ,						"w"  ,						encoding="utf-8"  ,						newline="\n"       ) as f:
										f.writelines(lowerCAmelCase_       )




def        UpperCAmelCase__	():




					'''simple docstring'''


					with open(REPLACE_FILES["init"]  ,						"r"       ) as f:
										__SCREAMING_SNAKE_CASE						       =    f.read()
					__SCREAMING_SNAKE_CASE						       =    REPLACE_PATTERNS["init"][0].search(lowerCAmelCase_       ).groups()[0]
					return packaging.version.parse(lowerCAmelCase_       )




def        UpperCAmelCase__	(lowerCAmelCase_=False       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    get_version()
					if patch and default_version.is_devrelease:
										raise ValueError("Can't create a patch version from the dev branch, checkout a released version!"       )
					if default_version.is_devrelease:
										__SCREAMING_SNAKE_CASE						       =    default_version.base_version
					elif patch:
										__SCREAMING_SNAKE_CASE						       =    f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
					else:
										__SCREAMING_SNAKE_CASE						       =    f"""{default_version.major}.{default_version.minor + 1}.0"""

					# Now let's ask nicely if that's the right one.
					__SCREAMING_SNAKE_CASE						       =    input(f"""Which version are you releasing? [{default_version}]"""       )
					if len(lowerCAmelCase_       ) == 0:
										__SCREAMING_SNAKE_CASE						       =    default_version

					print(f"""Updating version to {version}."""       )
					global_version_update(lowerCAmelCase_  ,						patch=lowerCAmelCase_       )




def        UpperCAmelCase__	():




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    get_version()
					__SCREAMING_SNAKE_CASE						       =    f"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
					__SCREAMING_SNAKE_CASE						       =    current_version.base_version

					# Check with the user we got that right.
					__SCREAMING_SNAKE_CASE						       =    input(f"""Which version are we developing now? [{dev_version}]"""       )
					if len(lowerCAmelCase_       ) == 0:
										__SCREAMING_SNAKE_CASE						       =    dev_version

					print(f"""Updating version to {version}."""       )
					global_version_update(lowerCAmelCase_       )


#    print("Cleaning main README, don't forget to run `make fix-copies`.")
#    clean_main_ref_in_model_list()


if __name__ == "__main__":
		a__    :							Optional[int]            =					argparse.ArgumentParser()
		parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''')
		parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''')
		a__    :							Optional[int]            =					parser.parse_args()
		if not args.post_release:
				pre_release_work(patch=args.patch)
		elif args.patch:
				print('''Nothing to do after a patch :-)''')
		else:
				post_release_work()




"""simple docstring"""







import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
		import jax

		from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel




class 			UpperCamelCase_     (			unittest.TestCase):

	"""simple docstring"""





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

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




	def   UpperCAmelCase_				(			self      :    Union[str, Any]       )	->     Tuple:
						__SCREAMING_SNAKE_CASE						       =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

						__SCREAMING_SNAKE_CASE						       =    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=UpperCAmelCase__      ,      initializer_range=self.initializer_range      ,      )

						return config, pixel_values




	def   UpperCAmelCase_				(			self      :    Tuple      ,      UpperCAmelCase__      :    str      ,      UpperCAmelCase__      :    List[str]       )	->     Any:
						__SCREAMING_SNAKE_CASE						       =    FlaxViTModel(config=UpperCAmelCase__       )
						__SCREAMING_SNAKE_CASE						       =    model(UpperCAmelCase__       )
						# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
						__SCREAMING_SNAKE_CASE						       =    (self.image_size, self.image_size)
						__SCREAMING_SNAKE_CASE						       =    (self.patch_size, self.patch_size)
						__SCREAMING_SNAKE_CASE						       =    (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
						self.parent.assertEqual(result.last_hidden_state.shape      ,      (self.batch_size, num_patches + 1, self.hidden_size)       )




	def   UpperCAmelCase_				(			self      :    str      ,      UpperCAmelCase__      :    List[str]      ,      UpperCAmelCase__      :    Tuple       )	->     Tuple:
						__SCREAMING_SNAKE_CASE						       =    self.type_sequence_label_size
						__SCREAMING_SNAKE_CASE						       =    FlaxViTForImageClassification(config=UpperCAmelCase__       )
						__SCREAMING_SNAKE_CASE						       =    model(UpperCAmelCase__       )
						self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.type_sequence_label_size)       )

						# test greyscale images
						__SCREAMING_SNAKE_CASE						       =    1
						__SCREAMING_SNAKE_CASE						       =    FlaxViTForImageClassification(UpperCAmelCase__       )

						__SCREAMING_SNAKE_CASE						       =    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
						__SCREAMING_SNAKE_CASE						       =    model(UpperCAmelCase__       )




	def   UpperCAmelCase_				(			self      :    Union[str, Any]       )	->     List[Any]:
						__SCREAMING_SNAKE_CASE						       =    self.prepare_config_and_inputs()
						(
						    (
						    __SCREAMING_SNAKE_CASE
						)       ,  (
						    __SCREAMING_SNAKE_CASE
						)       ,  
						)						       =    config_and_inputs
						__SCREAMING_SNAKE_CASE						       =    {"pixel_values": pixel_values}
						return config, inputs_dict




@require_flax
class 			UpperCamelCase_     (			UpperCamelCase      ,  unittest.TestCase):

	"""simple docstring"""





	snake_case__    :  List[str]    =      (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()




	def   UpperCAmelCase_				(			self      :    int       )	->     None:
						__SCREAMING_SNAKE_CASE						       =    FlaxViTModelTester(self       )
						__SCREAMING_SNAKE_CASE						       =    ConfigTester(self      ,      config_class=UpperCAmelCase__      ,      has_text_modality=UpperCAmelCase__      ,      hidden_size=3_7       )




	def   UpperCAmelCase_				(			self      :    int       )	->     Union[str, Any]:
						self.config_tester.run_common_tests()




	def   UpperCAmelCase_				(			self      :    Tuple       )	->     List[str]:
						__SCREAMING_SNAKE_CASE						       =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCAmelCase__       )




	def   UpperCAmelCase_				(			self      :    Dict       )	->     Dict:
						__SCREAMING_SNAKE_CASE						       =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__       )




	def   UpperCAmelCase_				(			self      :    Tuple       )	->     Any:
						__SCREAMING_SNAKE_CASE       ,  __SCREAMING_SNAKE_CASE						       =    self.model_tester.prepare_config_and_inputs_for_common()

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

											__SCREAMING_SNAKE_CASE						       =    ["pixel_values"]
											self.assertListEqual(arg_names[:1]      ,      UpperCAmelCase__       )




	def   UpperCAmelCase_				(			self      :    Any       )	->     List[Any]:
						__SCREAMING_SNAKE_CASE       ,  __SCREAMING_SNAKE_CASE						       =    self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											with self.subTest(model_class.__name__       ):
																__SCREAMING_SNAKE_CASE						       =    self._prepare_for_class(UpperCAmelCase__      ,      UpperCAmelCase__       )
																__SCREAMING_SNAKE_CASE						       =    model_class(UpperCAmelCase__       )

																@jax.jit
																def model_jitted(UpperCAmelCase__      :    Optional[int]      ,      **UpperCAmelCase__      :    Any       ):
																					return model(pixel_values=UpperCAmelCase__      ,      **UpperCAmelCase__       )

																with self.subTest("JIT Enabled"       ):
																					__SCREAMING_SNAKE_CASE						       =    model_jitted(**UpperCAmelCase__       ).to_tuple()

																with self.subTest("JIT Disabled"       ):
																					with jax.disable_jit():
																										__SCREAMING_SNAKE_CASE						       =    model_jitted(**UpperCAmelCase__       ).to_tuple()

																self.assertEqual(len(UpperCAmelCase__       )      ,      len(UpperCAmelCase__       )       )
																for jitted_output, output in zip(UpperCAmelCase__      ,      UpperCAmelCase__       ):
																					self.assertEqual(jitted_output.shape      ,      output.shape       )




	@slow
	def   UpperCAmelCase_				(			self      :    int       )	->     Union[str, Any]:
						for model_class_name in self.all_model_classes:
											__SCREAMING_SNAKE_CASE						       =    model_class_name.from_pretrained("google/vit-base-patch16-224"       )
											__SCREAMING_SNAKE_CASE						       =    model(np.ones((1, 3, 2_2_4, 2_2_4)       )       )
											self.assertIsNotNone(UpperCAmelCase__       )
