



"""simple docstring"""





# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation

import warnings

from .state import AcceleratorState, GradientState


warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''')



class    _lowerCAmelCase    :





		"""simple docstring"""






		def __init__(					self							,    _lowercase							,    _lowercase							,    _lowercase = True							,    _lowercase = False   ) ->						List[Any]:







								'''simple docstring'''

								snake_case_   : Optional[Any]						=			scheduler
								snake_case_   : str						=			optimizers if isinstance(_lowercase							,    (list, tuple)   ) else [optimizers]
								snake_case_   : str						=			split_batches
								snake_case_   : Tuple						=			step_with_optimizer
								snake_case_   : List[Any]						=			GradientState()





		def    UpperCAmelCase__							(					self							,    *_lowercase							,    **_lowercase   ) ->						List[str]:







								'''simple docstring'''

								if not self.step_with_optimizer:
														# No link between scheduler and optimizer -> just step
														self.scheduler.step(*_lowercase							,    **_lowercase   )
														return

								# Otherwise, first make sure the optimizer was stepped.
								if not self.gradient_state.sync_gradients:
														if self.gradient_state.adjust_scheduler:
																				self.scheduler._step_count += 1
														return

								for opt in self.optimizers:
														if opt.step_was_skipped:
																				return
								if self.split_batches:
														# Split batches -> the training dataloader batch size is not changed so one step per training step
														self.scheduler.step(*_lowercase							,    **_lowercase   )
								else:
														# Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
														# num_processes steps per training step
														snake_case_   : Optional[int]						=			AcceleratorState().num_processes
														for _ in range(_lowercase   ):
																				# Special case when using OneCycle and `drop_last` was not used
																				if hasattr(self.scheduler							,    """total_steps"""   ):
																										if self.scheduler._step_count <= self.scheduler.total_steps:
																																self.scheduler.step(*_lowercase							,    **_lowercase   )
																				else:
																										self.scheduler.step(*_lowercase							,    **_lowercase   )





		def    UpperCAmelCase__							(					self   ) ->						Dict:







								'''simple docstring'''

								return self.scheduler.get_last_lr()





		def    UpperCAmelCase__							(					self   ) ->						Dict:







								'''simple docstring'''

								return self.scheduler.state_dict()





		def    UpperCAmelCase__							(					self							,    _lowercase   ) ->						Optional[Any]:







								'''simple docstring'''

								self.scheduler.load_state_dict(_lowercase   )





		def    UpperCAmelCase__							(					self   ) ->						Tuple:







								'''simple docstring'''

								return self.scheduler.get_lr()





		def    UpperCAmelCase__							(					self							,    *_lowercase							,    **_lowercase   ) ->						List[Any]:







								'''simple docstring'''

								return self.scheduler.print_lr(*_lowercase							,    **_lowercase   )






"""simple docstring"""





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


__lowerCAmelCase       :					str      					=					logging.get_logger(__name__)

__lowerCAmelCase       :					Tuple      					=					{
    '''shi-labs/nat-mini-in1k-224''': '''https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json''',
    # See all Nat models at https://huggingface.co/models?filter=nat
}



class    _lowerCAmelCase    (				SCREAMING_SNAKE_CASE__  ,				SCREAMING_SNAKE_CASE__		):





		"""simple docstring"""






		_lowerCamelCase			  =       '''nat'''

		_lowerCamelCase			  =       {
		    '''num_attention_heads''': '''num_heads''',
		    '''num_hidden_layers''': '''num_layers''',
		}





		def __init__(					self							,    _lowercase=4							,    _lowercase=3							,    _lowercase=6_4							,    _lowercase=[3, 4, 6, 5]							,    _lowercase=[2, 4, 8, 1_6]							,    _lowercase=7							,    _lowercase=3.0							,    _lowercase=True							,    _lowercase=0.0							,    _lowercase=0.0							,    _lowercase=0.1							,    _lowercase="gelu"							,    _lowercase=0.02							,    _lowercase=1E-5							,    _lowercase=0.0							,    _lowercase=None							,    _lowercase=None							,    **_lowercase							,    ) ->						Optional[Any]:







								'''simple docstring'''

								super().__init__(**_lowercase   )

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

