






'''simple docstring'''





from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


_UpperCamelCase						:						int  =					logging.get_logger(__name__)
def __UpperCAmelCase   (					A					:			Union[tf.Tensor, np.ndarray]		)    ->   List[int]:
			if isinstance(A			,       np.ndarray		):
						return list(tensor.shape		)

			UpperCAmelCase_      :       str          =       tf.shape(A		)

			if tensor.shape == tf.TensorShape(A		):
						return dynamic

			UpperCAmelCase_      :       Any          =       tensor.shape.as_list()

			return [dynamic[i] if s is None else s for i, s in enumerate(A		)]
def __UpperCAmelCase   (					A					:			tf.Tensor			,       A					:			Optional[int] = None			,       A					:			Optional[str] = None		)    ->   tf.Tensor:
			return tf.nn.softmax(logits=logits + 1e-9			,       axis=A			,       name=A		)
def __UpperCAmelCase   (					A					:			List[str]			,       A					:			Union[str, Any]			,       A					:			List[str]			,       A					:			str=1e-5			,       A					:			Dict=-1		)    ->   List[Any]:
			# This is a very simplified functional layernorm, designed to duplicate
			# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
			# models in Transformers.

			if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(A			,       A		):
						raise NotImplementedError('''Only 1D weight and bias tensors are supported for now, with only a single axis.'''		)

			# Get mean and variance on the axis to be normalized
			UpperCAmelCase_    ,      UpperCAmelCase_      :       int          =       tf.nn.moments(A			,       axes=[axis]			,       keepdims=A		)

			if axis != -1:
						# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
						# on every dimension except axis
						UpperCAmelCase_      :       Tuple          =       [1] * inputs.shape.rank
						UpperCAmelCase_      :       int          =       shape_list(A		)[axis]
						UpperCAmelCase_      :       Dict          =       tf.reshape(A			,       A		)
						UpperCAmelCase_      :       Optional[Any]          =       tf.reshape(A			,       A		)

			# Compute layer normalization using the batch_normalization
			# function.
			UpperCAmelCase_      :       Dict          =       tf.nn.batch_normalization(
			    A			,       A			,       A			,       offset=A			,       scale=A			,       variance_epsilon=A			,       )
			return outputs
def __UpperCAmelCase   (					A					:			Dict			,       A					:			int=0			,       A					:			Optional[int]=-1		)    ->   str:
			# Replicates the behavior of torch.flatten in TF

			# If end_dim or start_dim is negative, count them from the end
			if end_dim < 0:
						end_dim += input.shape.rank
			if start_dim < 0:
						start_dim += input.shape.rank

			if start_dim == end_dim:
						return input

			UpperCAmelCase_      :       Any          =       tf.shape(A		)
			UpperCAmelCase_      :       Dict          =       tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]		)
			UpperCAmelCase_      :       Optional[int]          =       tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]			,       axis=0		)
			return tf.reshape(A			,       A		)
def __UpperCAmelCase   (					A					:			tf.Tensor		)    ->   tf.Tensor:
			if not isinstance(A			,       tf.Tensor		):
						UpperCAmelCase_      :       Optional[Any]          =       tf.convert_to_tensor(A		)  # Catches stray NumPy inputs
			if encoder_attention_mask.shape.rank == 3:
						UpperCAmelCase_      :       Any          =       encoder_attention_mask[:, None, :, :]
			if encoder_attention_mask.shape.rank == 2:
						UpperCAmelCase_      :       Tuple          =       encoder_attention_mask[:, None, None, :]
			# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
			# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
			# /transformer/transformer_layers.py#L270
			# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
			# encoder_extended_attention_mask.transpose(-1, -2))
			UpperCAmelCase_      :       int          =       (
			    tf.cast(1			,       encoder_attention_mask.dtype		) - encoder_extended_attention_mask
			) * encoder_extended_attention_mask.dtype.min

			return encoder_extended_attention_mask
def __UpperCAmelCase   (					A					:			tf.Tensor			,       A					:			int			,       A					:			str = "input_ids"		)    ->   None:
			tf.debugging.assert_less(
			    A			,       tf.cast(A			,       dtype=tensor.dtype		)			,       message=(
			        F"The maximum value of {tensor_name} ({tf.math.reduce_max(A		)}) must be smaller than the embedding "
			        F"layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."
			    )			,       )
def __UpperCAmelCase   (					A					:			Dict			,       A					:			Tuple			,       A					:			List[str]		)    ->   Union[str, Any]:
			UpperCAmelCase_      :       List[Any]          =       6_4_5_1_2
			# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
			# because in that case even chunking the array would not make the saving
			# possible.
			UpperCAmelCase_      :       Tuple          =       [x for x in data if len(A		) > HDF5_OBJECT_HEADER_LIMIT]

			# Expecting this to never be true.
			if bad_attributes:
						raise RuntimeError(
						    '''The following attributes cannot be saved to HDF5 file because '''
						    F"they are larger than {HDF5_OBJECT_HEADER_LIMIT} "
						    F"bytes: {bad_attributes}"		)

			UpperCAmelCase_      :       Union[str, Any]          =       np.asarray(A		)

			UpperCAmelCase_      :       Optional[int]          =       1
			UpperCAmelCase_      :       str          =       np.array_split(A			,       A		)

			# This will never loop forever thanks to the test above.
			while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data		):
						num_chunks += 1
						UpperCAmelCase_      :       Dict          =       np.array_split(A			,       A		)

			if num_chunks > 1:
						for chunk_id, chunk_data in enumerate(A		):
									UpperCAmelCase_      :       int          =       chunk_data
			else:
						UpperCAmelCase_      :       List[Any]          =       data
def __UpperCAmelCase   (					A					:			int			,       A					:			Optional[Any]		)    ->   Tuple:
			if name in group.attrs:
						UpperCAmelCase_      :       Optional[int]          =       [n.decode('''utf8'''		) if hasattr(A			,       '''decode'''		) else n for n in group.attrs[name]]
			else:
						UpperCAmelCase_      :       Optional[int]          =       []
						UpperCAmelCase_      :       Optional[int]          =       0
						while "%s%d" % (name, chunk_id) in group.attrs:
									data.extend(
									    [n.decode('''utf8'''		) if hasattr(A			,       '''decode'''		) else n for n in group.attrs['''%s%d''' % (name, chunk_id)]]		)
									chunk_id += 1
			return data







def __UpperCAmelCase   (					A					:			Tuple		)    ->   str:

			def _expand_single_ad_tensor(A					:			int		):
						if isinstance(A			,       tf.Tensor		) and t.shape.rank == 1:
									return tf.expand_dims(A			,       axis=-1		)
						return t

			return tf.nest.map_structure(_expand_single_ad_tensor			,       A		)










'''simple docstring'''





import argparse
import os
import re

import packaging.version


_UpperCamelCase						:						Union[str, Any]  =					'examples/'
_UpperCamelCase						:						List[str]  =					{
    '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'),
}
_UpperCamelCase						:						Optional[Any]  =					{
    'init': 'src/diffusers/__init__.py',
    'setup': 'setup.py',
}
_UpperCamelCase						:						Any  =					'README.md'
def __UpperCAmelCase   (					A					:			Optional[int]			,       A					:			List[Any]			,       A					:			Tuple		)    ->   Dict:
			with open(A			,       '''r'''			,       encoding='''utf-8'''			,       newline='''\n'''		) as f:
						UpperCAmelCase_      :       int          =       f.read()
			UpperCAmelCase_    ,      UpperCAmelCase_      :       Union[str, Any]          =       REPLACE_PATTERNS[pattern]
			UpperCAmelCase_      :       Tuple          =       replace.replace('''VERSION'''			,       A		)
			UpperCAmelCase_      :       Tuple          =       re_pattern.sub(A			,       A		)
			with open(A			,       '''w'''			,       encoding='''utf-8'''			,       newline='''\n'''		) as f:
						f.write(A		)
def __UpperCAmelCase   (					A					:			List[str]		)    ->   Any:
			for folder, directories, fnames in os.walk(A		):
						# 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(A			,       A		)			,       A			,       pattern='''examples'''		)
def __UpperCAmelCase   (					A					:			Tuple			,       A					:			Optional[int]=False		)    ->   Tuple:
			for pattern, fname in REPLACE_FILES.items():
						update_version_in_file(A			,       A			,       A		)
			if not patch:
						update_version_in_examples(A		)
def __UpperCAmelCase   (					)    ->   int:
			UpperCAmelCase_      :       List[str]          =       '''🤗 Transformers currently provides the following architectures'''
			UpperCAmelCase_      :       int          =       '''1. Want to contribute a new model?'''
			with open(A			,       '''r'''			,       encoding='''utf-8'''			,       newline='''\n'''		) as f:
						UpperCAmelCase_      :       Optional[int]          =       f.readlines()

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

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

			with open(A			,       '''w'''			,       encoding='''utf-8'''			,       newline='''\n'''		) as f:
						f.writelines(A		)
def __UpperCAmelCase   (					)    ->   Dict:
			with open(REPLACE_FILES['''init''']			,       '''r'''		) as f:
						UpperCAmelCase_      :       Any          =       f.read()
			UpperCAmelCase_      :       Union[str, Any]          =       REPLACE_PATTERNS['''init'''][0].search(A		).groups()[0]
			return packaging.version.parse(A		)
def __UpperCAmelCase   (					A					:			str=False		)    ->   List[Any]:
			UpperCAmelCase_      :       Union[str, Any]          =       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:
						UpperCAmelCase_      :       Optional[int]          =       default_version.base_version
			elif patch:
						UpperCAmelCase_      :       Any          =       F"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
			else:
						UpperCAmelCase_      :       Optional[Any]          =       F"{default_version.major}.{default_version.minor + 1}.0"

			# Now let's ask nicely if that's the right one.
			UpperCAmelCase_      :       List[str]          =       input(F"Which version are you releasing? [{default_version}]"		)
			if len(A		) == 0:
						UpperCAmelCase_      :       Tuple          =       default_version

			print(F"Updating version to {version}."		)
			global_version_update(A			,       patch=A		)
def __UpperCAmelCase   (					)    ->   Optional[int]:
			UpperCAmelCase_      :       str          =       get_version()
			UpperCAmelCase_      :       Tuple          =       F"{current_version.major}.{current_version.minor + 1}.0.dev0"
			UpperCAmelCase_      :       Any          =       current_version.base_version

			# Check with the user we got that right.
			UpperCAmelCase_      :       List[Any]          =       input(F"Which version are we developing now? [{dev_version}]"		)
			if len(A		) == 0:
						UpperCAmelCase_      :       Optional[int]          =       dev_version

			print(F"Updating version to {version}."		)
			global_version_update(A		)


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


if __name__ == "__main__":
						_UpperCamelCase						:						Tuple  =					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.')
						_UpperCamelCase						:						Optional[Any]  =					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()


