

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


A_       : Optional[Any]         =			logging.get_logger(__name__)



class     _a						(__magic_name__		,   __magic_name__				):


					'''simple docstring'''






					UpperCAmelCase__:   Any  							=       '''maskformer-swin'''

					UpperCAmelCase__:   Optional[Any]  							=       {
					    '''num_attention_heads''': '''num_heads''',
					    '''num_hidden_layers''': '''num_layers''',
					}






					def __init__( self    ,       A__=224    ,       A__=4    ,       A__=3    ,       A__=96    ,       A__=[2, 2, 6, 2]    ,       A__=[3, 6, 12, 24]    ,       A__=7    ,       A__=4.0    ,       A__=True    ,       A__=0.0    ,       A__=0.0    ,       A__=0.1    ,       A__="gelu"    ,       A__=False    ,       A__=0.0_2    ,       A__=1e-5    ,       A__=None    ,       A__=None    ,       **A__    ,       ):
						super().__init__(**A__			)

						A__							:    List[Any]        =		image_size
						A__							:    Any        =		patch_size
						A__							:    str        =		num_channels
						A__							:    Optional[Any]        =		embed_dim
						A__							:    int        =		depths
						A__							:    str        =		len(A__			)
						A__							:    Dict        =		num_heads
						A__							:    str        =		window_size
						A__							:    Optional[int]        =		mlp_ratio
						A__							:    Tuple        =		qkv_bias
						A__							:    Optional[Any]        =		hidden_dropout_prob
						A__							:    Optional[int]        =		attention_probs_dropout_prob
						A__							:    Optional[Any]        =		drop_path_rate
						A__							:    List[Any]        =		hidden_act
						A__							:    int        =		use_absolute_embeddings
						A__							:    Any        =		layer_norm_eps
						A__							:    int        =		initializer_range
						# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
						# this indicates the channel dimension after the last stage of the model
						A__							:    Tuple        =		int(embed_dim * 2 ** (len(A__			) - 1)			)
						A__							:    Dict        =		["""stem"""] + [F"""stage{idx}""" for idx in range(1    ,       len(A__			) + 1			)]
						A__   ,   A__							:    List[Any]        =		get_aligned_output_features_output_indices(
						    out_features=A__    ,       out_indices=A__    ,       stage_names=self.stage_names			)






import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length

def 						UpperCamelCase					(lowercase_: str					)     ->      Dict:
	A__							:    int        =		int(lowercase_					)
	A__   ,   A__   ,   A__							:    Tuple        =		t // 3600, (t // 60) % 60, t % 60
	return f"""{h}:{m:02d}:{s:02d}""" if h != 0 else f"""{m:02d}:{s:02d}"""

def 						UpperCamelCase					(lowercase_: str    ,      lowercase_: Optional[Any]    ,      lowercase_: Union[str, Any]    ,      lowercase_: Tuple    ,      lowercase_: Any=300					)     ->      Optional[int]:
	# docstyle-ignore
	return f"""
    <div>
      {prefix}
      <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress>
      {label}
    </div>
    """

def 						UpperCamelCase					(lowercase_: Tuple					)     ->      Optional[int]:
	A__							:    Tuple        =		"""<table border=\"1\" class=\"dataframe\">\n"""
	html_code += """  <thead>\n <tr style="text-align: left;">\n"""
	for i in items[0]:
		html_code += f"""      <th>{i}</th>\n"""
	html_code += "    </tr>\n  </thead>\n  <tbody>\n"
	for line in items[1:]:
		html_code += "    <tr>\n"
		for elt in line:
			A__							:    str        =		f"""{elt:.6f}""" if isinstance(lowercase_    ,      lowercase_					) else str(lowercase_					)
			html_code += f"""      <td>{elt}</td>\n"""
		html_code += "    </tr>\n"
	html_code += "  </tbody>\n</table><p>"
	return html_code



class     _a						:


					'''simple docstring'''






					UpperCAmelCase__:   str  							=       5
					UpperCAmelCase__:   int  							=       0.2






					def __init__( self    ,       A__    ,       A__ = None    ,       A__ = True    ,       A__ = None    ,       A__ = 300    ,       ):
						A__							:    Optional[int]        =		total
						A__							:    Tuple        =		"""""" if prefix is None else prefix
						A__							:    str        =		leave
						A__							:    str        =		parent
						A__							:    int        =		width
						A__							:    Dict        =		None
						A__							:    List[str]        =		None
						A__							:    Optional[int]        =		None






					def   __A			( self    ,       A__    ,       A__ = False    ,       A__ = None			):
						A__							:    Tuple        =		value
						if comment is not None:
							A__							:    Any        =		comment
						if self.last_value is None:
							A__							:    int        =		time.time()
							A__							:    Dict        =		value
							A__							:    int        =		None
							A__							:    int        =		self.warmup
							A__							:    str        =		1
							self.update_bar(A__			)
						elif value <= self.last_value and not force_update:
							return
						elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for    ,       self.total			):
							if self.first_calls > 0:
								self.first_calls -= 1
							A__							:    Any        =		time.time()
							A__							:    str        =		current_time - self.start_time
							# We could have value = self.start_value if the update is called twixe with the same start value.
							if value > self.start_value:
								A__							:    Dict        =		self.elapsed_time / (value - self.start_value)
							else:
								A__							:    List[str]        =		None
							if value >= self.total:
								A__							:    Optional[Any]        =		self.total
								A__							:    List[Any]        =		None
								if not self.leave:
									self.close()
							elif self.average_time_per_item is not None:
								A__							:    List[Any]        =		self.average_time_per_item * (self.total - value)
							self.update_bar(A__			)
							A__							:    Any        =		value
							A__							:    List[str]        =		current_time
							if self.average_time_per_item is None:
								A__							:    str        =		1
							else:
								A__							:    Optional[Any]        =		max(int(self.update_every / self.average_time_per_item			)    ,       1			)






					def   __A			( self    ,       A__    ,       A__=None			):
						A__							:    Tuple        =		""" """ * (len(str(self.total			)			) - len(str(A__			)			)) + str(A__			)
						if self.elapsed_time is None:
							A__							:    Union[str, Any]        =		F"""[{spaced_value}/{self.total} : < :"""
						elif self.predicted_remaining is None:
							A__							:    Tuple        =		F"""[{spaced_value}/{self.total} {format_time(self.elapsed_time			)}"""
						else:
							A__							:    Optional[int]        =		(
							    F"""[{spaced_value}/{self.total} {format_time(self.elapsed_time			)} <"""
							    F""" {format_time(self.predicted_remaining			)}"""
							)
							self.label += F""", {1/self.average_time_per_item:.2f} it/s"""
						self.label += "]" if self.comment is None or len(self.comment			) == 0 else F""", {self.comment}]"""
						self.display()






					def   __A			( self			):
						A__							:    str        =		html_progress_bar(self.value    ,       self.total    ,       self.prefix    ,       self.label    ,       self.width			)
						if self.parent is not None:
							# If this is a child bar, the parent will take care of the display.
							self.parent.display()
							return
						if self.output is None:
							A__							:    str        =		disp.display(disp.HTML(self.html_code			)    ,       display_id=A__			)
						else:
							self.output.update(disp.HTML(self.html_code			)			)






					def   __A			( self			):
						if self.parent is None and self.output is not None:
							self.output.update(disp.HTML(""""""			)			)



class     _a						(__magic_name__				):


					'''simple docstring'''






					def __init__( self    ,       A__    ,       A__=None			):
						super().__init__(A__			)
						A__							:    Optional[Any]        =		None if column_names is None else [column_names]
						A__							:    Optional[Any]        =		None






					def   __A			( self			):
						A__							:    List[str]        =		html_progress_bar(self.value    ,       self.total    ,       self.prefix    ,       self.label    ,       self.width			)
						if self.inner_table is not None:
							self.html_code += text_to_html_table(self.inner_table			)
						if self.child_bar is not None:
							self.html_code += self.child_bar.html_code
						if self.output is None:
							A__							:    Optional[int]        =		disp.display(disp.HTML(self.html_code			)    ,       display_id=A__			)
						else:
							self.output.update(disp.HTML(self.html_code			)			)






					def   __A			( self    ,       A__			):
						if self.inner_table is None:
							A__							:    List[str]        =		[list(values.keys()			), list(values.values()			)]
						else:
							A__							:    Optional[Any]        =		self.inner_table[0]
							if len(self.inner_table			) == 1:
								# We give a chance to update the column names at the first iteration
								for key in values.keys():
									if key not in columns:
										columns.append(A__			)
								A__							:    Any        =		columns
							self.inner_table.append([values[c] for c in columns]			)






					def   __A			( self    ,       A__    ,       A__=None    ,       A__=300			):
						A__							:    Optional[Any]        =		NotebookProgressBar(A__    ,       prefix=A__    ,       parent=self    ,       width=A__			)
						return self.child_bar






					def   __A			( self			):
						A__							:    List[str]        =		None
						self.display()



class     _a						(__magic_name__				):


					'''simple docstring'''






					def __init__( self			):
						A__							:    int        =		None
						A__							:    List[str]        =		None
						A__							:    Union[str, Any]        =		False






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       **A__			):
						A__							:    List[str]        =		"""Epoch""" if args.evaluation_strategy == IntervalStrategy.EPOCH else """Step"""
						A__							:    Dict        =		0
						A__							:    Tuple        =		0
						A__							:    Optional[int]        =		[self.first_column] + ["""Training Loss"""]
						if args.evaluation_strategy != IntervalStrategy.NO:
							column_names.append("""Validation Loss"""			)
						A__							:    Union[str, Any]        =		NotebookTrainingTracker(state.max_steps    ,       A__			)






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       **A__			):
						A__							:    Any        =		int(state.epoch			) if int(state.epoch			) == state.epoch else F"""{state.epoch:.2f}"""
						self.training_tracker.update(
						    state.global_step + 1    ,       comment=F"""Epoch {epoch}/{state.num_train_epochs}"""    ,       force_update=self._force_next_update    ,       )
						A__							:    str        =		False






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       A__=None    ,       **A__			):
						if not has_length(A__			):
							return
						if self.prediction_bar is None:
							if self.training_tracker is not None:
								A__							:    Union[str, Any]        =		self.training_tracker.add_child(len(A__			)			)
							else:
								A__							:    Tuple        =		NotebookProgressBar(len(A__			)			)
							self.prediction_bar.update(1			)
						else:
							self.prediction_bar.update(self.prediction_bar.value + 1			)






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       **A__			):
						if self.prediction_bar is not None:
							self.prediction_bar.close()
						A__							:    List[str]        =		None






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       A__=None    ,       **A__			):
						# Only for when there is no evaluation
						if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
							A__							:    Dict        =		{"""Training Loss""": logs["""loss"""]}
							# First column is necessarily Step sine we're not in epoch eval strategy
							A__							:    List[Any]        =		state.global_step
							self.training_tracker.write_line(A__			)






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       A__=None    ,       **A__			):
						if self.training_tracker is not None:
							A__							:    Tuple        =		{"""Training Loss""": """No log""", """Validation Loss""": """No log"""}
							for log in reversed(state.log_history			):
								if "loss" in log:
									A__							:    Dict        =		log["""loss"""]
									break

							if self.first_column == "Epoch":
								A__							:    List[Any]        =		int(state.epoch			)
							else:
								A__							:    Optional[Any]        =		state.global_step
							A__							:    Optional[Any]        =		"""eval"""
							for k in metrics:
								if k.endswith("""_loss"""			):
									A__							:    Optional[int]        =		re.sub(r"""\_loss$"""    ,       """"""    ,       A__			)
							A__							:    int        =		metrics.pop("""total_flos"""    ,       A__			)
							A__							:    int        =		metrics.pop("""epoch"""    ,       A__			)
							A__							:    Optional[int]        =		metrics.pop(F"""{metric_key_prefix}_runtime"""    ,       A__			)
							A__							:    Any        =		metrics.pop(F"""{metric_key_prefix}_samples_per_second"""    ,       A__			)
							A__							:    List[Any]        =		metrics.pop(F"""{metric_key_prefix}_steps_per_second"""    ,       A__			)
							A__							:    Optional[Any]        =		metrics.pop(F"""{metric_key_prefix}_jit_compilation_time"""    ,       A__			)
							for k, v in metrics.items():
								if k == F"""{metric_key_prefix}_loss""":
									A__							:    Any        =		v
								else:
									A__							:    Optional[Any]        =		k.split("""_"""			)
									A__							:    Any        =		""" """.join([part.capitalize() for part in splits[1:]]			)
									A__							:    List[str]        =		v
							self.training_tracker.write_line(A__			)
							self.training_tracker.remove_child()
							A__							:    Dict        =		None
							# Evaluation takes a long time so we should force the next update.
							A__							:    Union[str, Any]        =		True






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       **A__			):
						self.training_tracker.update(
						    state.global_step    ,       comment=F"""Epoch {int(state.epoch			)}/{state.num_train_epochs}"""    ,       force_update=A__			)
						A__							:    Optional[int]        =		None



