






'''simple docstring'''







from random import shuffle

import tensorflow as tf
from numpy import array





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase				)				->	str:
							lowerCamelCase__ :     Dict	  =	int(UpperCamelCase				)
							assert noofclusters < len(UpperCamelCase				)

							# Find out the dimensionality
							lowerCamelCase__ :     Any	  =	len(vectors[0]				)

							# Will help select random centroids from among the available vectors
							lowerCamelCase__ :     Any	  =	list(range(len(UpperCamelCase				)				)				)
							shuffle(UpperCamelCase				)

							# GRAPH OF COMPUTATION
							# We initialize a new graph and set it as the default during each run
							# of this algorithm. This ensures that as this function is called
							# multiple times, the default graph doesn't keep getting crowded with
							# unused ops and Variables from previous function calls.

							lowerCamelCase__ :     Optional[Any]	  =	tf.Graph()

							with graph.as_default():
														# SESSION OF COMPUTATION

														lowerCamelCase__ :     Tuple	  =	tf.Session()

														##CONSTRUCTING THE ELEMENTS OF COMPUTATION

														##First lets ensure we have a Variable vector for each centroid,
														##initialized to one of the vectors from the available data points
														lowerCamelCase__ :     Tuple	  =	[
														    tf.Variable(vectors[vector_indices[i]]				) for i in range(UpperCamelCase				)
														]
														##These nodes will assign the centroid Variables the appropriate
														##values
														lowerCamelCase__ :     Union[str, Any]	  =	tf.placeholder("""float64"""    ,      [dim]				)
														lowerCamelCase__ :     Optional[Any]	  =	[]
														for centroid in centroids:
																					cent_assigns.append(tf.assign(UpperCamelCase    ,      UpperCamelCase				)				)

														##Variables for cluster assignments of individual vectors(initialized
														##to 0 at first)
														lowerCamelCase__ :     str	  =	[tf.Variable(0				) for i in range(len(UpperCamelCase				)				)]
														##These nodes will assign an assignment Variable the appropriate
														##value
														lowerCamelCase__ :     Optional[Any]	  =	tf.placeholder("""int32"""				)
														lowerCamelCase__ :     Any	  =	[]
														for assignment in assignments:
																					cluster_assigns.append(tf.assign(UpperCamelCase    ,      UpperCamelCase				)				)

														##Now lets construct the node that will compute the mean
														# The placeholder for the input
														lowerCamelCase__ :     Any	  =	tf.placeholder("""float"""    ,      [None, dim]				)
														# The Node/op takes the input and computes a mean along the 0th
														# dimension, i.e. the list of input vectors
														lowerCamelCase__ :     int	  =	tf.reduce_mean(UpperCamelCase    ,      0				)

														##Node for computing Euclidean distances
														# Placeholders for input
														lowerCamelCase__ :     Tuple	  =	tf.placeholder("""float"""    ,      [dim]				)
														lowerCamelCase__ :     int	  =	tf.placeholder("""float"""    ,      [dim]				)
														lowerCamelCase__ :     Tuple	  =	tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(UpperCamelCase    ,      UpperCamelCase				)    ,      2				)				)				)

														##This node will figure out which cluster to assign a vector to,
														##based on Euclidean distances of the vector from the centroids.
														# Placeholder for input
														lowerCamelCase__ :     str	  =	tf.placeholder("""float"""    ,      [noofclusters]				)
														lowerCamelCase__ :     List[Any]	  =	tf.argmin(UpperCamelCase    ,      0				)

														##INITIALIZING STATE VARIABLES

														##This will help initialization of all Variables defined with respect
														##to the graph. The Variable-initializer should be defined after
														##all the Variables have been constructed, so that each of them
														##will be included in the initialization.
														lowerCamelCase__ :     List[Any]	  =	tf.initialize_all_variables()

														# Initialize all variables
														sess.run(UpperCamelCase				)

														##CLUSTERING ITERATIONS

														# Now perform the Expectation-Maximization steps of K-Means clustering
														# iterations. To keep things simple, we will only do a set number of
														# iterations, instead of using a Stopping Criterion.
														lowerCamelCase__ :     List[Any]	  =	100
														for _ in range(UpperCamelCase				):
																					##EXPECTATION STEP
																					##Based on the centroid locations till last iteration, compute
																					##the _expected_ centroid assignments.
																					# Iterate over each vector
																					for vector_n in range(len(UpperCamelCase				)				):
																												lowerCamelCase__ :     Tuple	  =	vectors[vector_n]
																												# Compute Euclidean distance between this vector and each
																												# centroid. Remember that this list cannot be named
																												#'centroid_distances', since that is the input to the
																												# cluster assignment node.
																												lowerCamelCase__ :     List[Any]	  =	[
																												    sess.run(UpperCamelCase    ,      feed_dict={va: vect, va: sess.run(UpperCamelCase				)}				)
																												    for centroid in centroids
																												]
																												# Now use the cluster assignment node, with the distances
																												# as the input
																												lowerCamelCase__ :     Optional[int]	  =	sess.run(
																												    UpperCamelCase    ,      feed_dict={centroid_distances: distances}				)
																												# Now assign the value to the appropriate state variable
																												sess.run(
																												    cluster_assigns[vector_n]    ,      feed_dict={assignment_value: assignment}				)

																					##MAXIMIZATION STEP
																					# Based on the expected state computed from the Expectation Step,
																					# compute the locations of the centroids so as to maximize the
																					# overall objective of minimizing within-cluster Sum-of-Squares
																					for cluster_n in range(UpperCamelCase				):
																												# Collect all the vectors assigned to this cluster
																												lowerCamelCase__ :     Any	  =	[
																												    vectors[i]
																												    for i in range(len(UpperCamelCase				)				)
																												    if sess.run(assignments[i]				) == cluster_n
																												]
																												# Compute new centroid location
																												lowerCamelCase__ :     Dict	  =	sess.run(
																												    UpperCamelCase    ,      feed_dict={mean_input: array(UpperCamelCase				)}				)
																												# Assign value to appropriate variable
																												sess.run(
																												    cent_assigns[cluster_n]    ,      feed_dict={centroid_value: new_location}				)

        # Return centroids and assignments
														lowerCamelCase__ :     Optional[int]	  =	sess.run(UpperCamelCase				)
														lowerCamelCase__ :     Tuple	  =	sess.run(UpperCamelCase				)
														return centroids, assignments









'''simple docstring'''







import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


_A     :      Union[str, Any]   					=logging.get_logger(__name__)

_A     :      List[Any]   					={
    '''SenseTime/deformable-detr''': '''https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json''',
    # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}

class _lowercase     (    _lowercase		):
							a    				=	"""deformable_detr"""
							a    				=	{
							    """hidden_size""": """d_model""",
							    """num_attention_heads""": """encoder_attention_heads""",
							}




							def __init__(							self:    Optional[int]      ,							UpperCamelCase__:    Tuple=True      ,							UpperCamelCase__:    Tuple=None      ,							UpperCamelCase__:    List[str]=3      ,							UpperCamelCase__:    Any=300      ,							UpperCamelCase__:    Optional[int]=1_024      ,							UpperCamelCase__:    int=6      ,							UpperCamelCase__:    str=1_024      ,							UpperCamelCase__:    Optional[Any]=8      ,							UpperCamelCase__:    Optional[Any]=6      ,							UpperCamelCase__:    Union[str, Any]=1_024      ,							UpperCamelCase__:    Tuple=8      ,							UpperCamelCase__:    str=0.0      ,							UpperCamelCase__:    Tuple=True      ,							UpperCamelCase__:    Any="relu"      ,							UpperCamelCase__:    Any=256      ,							UpperCamelCase__:    List[Any]=0.1      ,							UpperCamelCase__:    Optional[int]=0.0      ,							UpperCamelCase__:    Any=0.0      ,							UpperCamelCase__:    List[str]=0.02      ,							UpperCamelCase__:    str=1.0      ,							UpperCamelCase__:    Any=True      ,							UpperCamelCase__:    List[Any]=False      ,							UpperCamelCase__:    str="sine"      ,							UpperCamelCase__:    Optional[Any]="resnet50"      ,							UpperCamelCase__:    Optional[int]=True      ,							UpperCamelCase__:    Optional[int]=False      ,							UpperCamelCase__:    List[Any]=4      ,							UpperCamelCase__:    Any=4      ,							UpperCamelCase__:    int=4      ,							UpperCamelCase__:    int=False      ,							UpperCamelCase__:    Optional[Any]=300      ,							UpperCamelCase__:    str=False      ,							UpperCamelCase__:    int=1      ,							UpperCamelCase__:    Tuple=5      ,							UpperCamelCase__:    List[Any]=2      ,							UpperCamelCase__:    Optional[int]=1      ,							UpperCamelCase__:    int=1      ,							UpperCamelCase__:    Tuple=5      ,							UpperCamelCase__:    str=2      ,							UpperCamelCase__:    str=0.1      ,							UpperCamelCase__:    List[str]=0.25      ,							UpperCamelCase__:    Any=False      ,							**UpperCamelCase__:    Optional[Any]      ,							):
														if backbone_config is not None and use_timm_backbone:
																					raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`."""					)

														if not use_timm_backbone:
																					if backbone_config is None:
																												logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."""					)
																												lowerCamelCase__ :     Union[str, Any]	  =	CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""]					)
																					elif isinstance(UpperCamelCase__      ,							UpperCamelCase__					):
																												lowerCamelCase__ :     Tuple	  =	backbone_config.get("""model_type"""					)
																												lowerCamelCase__ :     Dict	  =	CONFIG_MAPPING[backbone_model_type]
																												lowerCamelCase__ :     Optional[Any]	  =	config_class.from_dict(UpperCamelCase__					)
														lowerCamelCase__ :     Tuple	  =	use_timm_backbone
														lowerCamelCase__ :     Tuple	  =	backbone_config
														lowerCamelCase__ :     Union[str, Any]	  =	num_channels
														lowerCamelCase__ :     str	  =	num_queries
														lowerCamelCase__ :     int	  =	max_position_embeddings
														lowerCamelCase__ :     str	  =	d_model
														lowerCamelCase__ :     Dict	  =	encoder_ffn_dim
														lowerCamelCase__ :     Union[str, Any]	  =	encoder_layers
														lowerCamelCase__ :     int	  =	encoder_attention_heads
														lowerCamelCase__ :     str	  =	decoder_ffn_dim
														lowerCamelCase__ :     Optional[Any]	  =	decoder_layers
														lowerCamelCase__ :     Optional[int]	  =	decoder_attention_heads
														lowerCamelCase__ :     int	  =	dropout
														lowerCamelCase__ :     Optional[Any]	  =	attention_dropout
														lowerCamelCase__ :     List[Any]	  =	activation_dropout
														lowerCamelCase__ :     List[Any]	  =	activation_function
														lowerCamelCase__ :     int	  =	init_std
														lowerCamelCase__ :     Dict	  =	init_xavier_std
														lowerCamelCase__ :     Tuple	  =	encoder_layerdrop
														lowerCamelCase__ :     str	  =	auxiliary_loss
														lowerCamelCase__ :     int	  =	position_embedding_type
														lowerCamelCase__ :     Tuple	  =	backbone
														lowerCamelCase__ :     Tuple	  =	use_pretrained_backbone
														lowerCamelCase__ :     Optional[int]	  =	dilation
														# deformable attributes
														lowerCamelCase__ :     Optional[int]	  =	num_feature_levels
														lowerCamelCase__ :     Tuple	  =	encoder_n_points
														lowerCamelCase__ :     Tuple	  =	decoder_n_points
														lowerCamelCase__ :     Dict	  =	two_stage
														lowerCamelCase__ :     int	  =	two_stage_num_proposals
														lowerCamelCase__ :     Any	  =	with_box_refine
														if two_stage is True and with_box_refine is False:
																					raise ValueError("""If two_stage is True, with_box_refine must be True."""					)
														# Hungarian matcher
														lowerCamelCase__ :     Optional[int]	  =	class_cost
														lowerCamelCase__ :     List[str]	  =	bbox_cost
														lowerCamelCase__ :     Any	  =	giou_cost
														# Loss coefficients
														lowerCamelCase__ :     Union[str, Any]	  =	mask_loss_coefficient
														lowerCamelCase__ :     Tuple	  =	dice_loss_coefficient
														lowerCamelCase__ :     int	  =	bbox_loss_coefficient
														lowerCamelCase__ :     Optional[Any]	  =	giou_loss_coefficient
														lowerCamelCase__ :     Dict	  =	eos_coefficient
														lowerCamelCase__ :     Any	  =	focal_alpha
														lowerCamelCase__ :     Optional[Any]	  =	disable_custom_kernels
														super().__init__(is_encoder_decoder=UpperCamelCase__      ,							**UpperCamelCase__					)




							@property
							def 		lowerCamelCase_    (							self:    Dict					):
														return self.encoder_attention_heads




							@property
							def 		lowerCamelCase_    (							self:    Any					):
														return self.d_model




							def 		lowerCamelCase_    (							self:    List[str]					):
														lowerCamelCase__ :     Optional[int]	  =	copy.deepcopy(self.__dict__					)
														if self.backbone_config is not None:
																					lowerCamelCase__ :     int	  =	self.backbone_config.to_dict()
														lowerCamelCase__ :     int	  =	self.__class__.model_type
														return output

