




from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


_lowerCamelCase      :  Tuple    						=						[
    "openmmlab/upernet-convnext-tiny",
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
_lowerCamelCase      :  Optional[int]    						=						"UperNetConfig"
class        __snake_case  (nn.Module		):



				def __init__(      self      :		Dict		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		Union[int, Tuple[int, int]]		,	_UpperCAmelCase      :		Union[int, Tuple[int, int], str] = 0		,	_UpperCAmelCase      :		bool = False		,	_UpperCAmelCase      :		Union[int, Tuple[int, int]] = 1		,	)  ->    None:





								'''simple docstring'''




								super().__init__()
								_lowerCAmelCase    :    str										=      nn.Convad(
								    in_channels=_UpperCAmelCase		,	out_channels=_UpperCAmelCase		,	kernel_size=_UpperCAmelCase		,	padding=_UpperCAmelCase		,	bias=_UpperCAmelCase		,	dilation=_UpperCAmelCase		,	)
								_lowerCAmelCase    :    Union[str, Any]										=      nn.BatchNormad(_UpperCAmelCase      )
								_lowerCAmelCase    :    Optional[Any]										=      nn.ReLU()



				def       SCREAMING_SNAKE_CASE       (      self      :		str		,	_UpperCAmelCase      :		torch.Tensor      )  ->    torch.Tensor:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[Any]										=      self.conv(_UpperCAmelCase      )
								_lowerCAmelCase    :    int										=      self.batch_norm(_UpperCAmelCase      )
								_lowerCAmelCase    :    List[Any]										=      self.activation(_UpperCAmelCase      )

								return output






class        __snake_case  (nn.Module		):



				def __init__(      self      :		List[str]		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		int      )  ->    None:





								'''simple docstring'''




								super().__init__()
								_lowerCAmelCase    :    List[Any]										=      [
								    nn.AdaptiveAvgPoolad(_UpperCAmelCase      ),
								    UperNetConvModule(_UpperCAmelCase		,	_UpperCAmelCase		,	kernel_size=1      ),
								]
								for i, layer in enumerate(self.layers      ):
												self.add_module(str(_UpperCAmelCase      )		,	_UpperCAmelCase      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Dict		,	_UpperCAmelCase      :		torch.Tensor      )  ->    torch.Tensor:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[int]										=      input
								for layer in self.layers:
												_lowerCAmelCase    :    Optional[Any]										=      layer(_UpperCAmelCase      )
								return hidden_state






class        __snake_case  (nn.Module		):



				def __init__(      self      :		List[Any]		,	_UpperCAmelCase      :		Tuple[int, ...]		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		bool      )  ->    None:





								'''simple docstring'''




								super().__init__()
								_lowerCAmelCase    :    Any										=      pool_scales
								_lowerCAmelCase    :    int										=      align_corners
								_lowerCAmelCase    :    Optional[int]										=      in_channels
								_lowerCAmelCase    :    Any										=      channels
								_lowerCAmelCase    :    Optional[Any]										=      []
								for i, pool_scale in enumerate(_UpperCAmelCase      ):
												_lowerCAmelCase    :    Dict										=      UperNetPyramidPoolingBlock(pool_scale=_UpperCAmelCase		,	in_channels=_UpperCAmelCase		,	channels=_UpperCAmelCase      )
												self.blocks.append(_UpperCAmelCase      )
												self.add_module(str(_UpperCAmelCase      )		,	_UpperCAmelCase      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[int]		,	_UpperCAmelCase      :		torch.Tensor      )  ->    List[torch.Tensor]:





								'''simple docstring'''




								_lowerCAmelCase    :    Any										=      []
								for ppm in self.blocks:
												_lowerCAmelCase    :    Any										=      ppm(_UpperCAmelCase      )
												_lowerCAmelCase    :    Any										=      nn.functional.interpolate(
												    _UpperCAmelCase		,	size=x.size()[2:]		,	mode="""bilinear"""		,	align_corners=self.align_corners      )
												ppm_outs.append(_UpperCAmelCase      )
								return ppm_outs






class        __snake_case  (nn.Module		):



				def __init__(      self      :		Dict		,	_UpperCAmelCase      :		List[Any]		,	_UpperCAmelCase      :		List[str]      )  ->    Any:





								'''simple docstring'''




								super().__init__()

								_lowerCAmelCase    :    Tuple										=      config
								_lowerCAmelCase    :    str										=      config.pool_scales  # e.g. (1, 2, 3, 6)
								_lowerCAmelCase    :    Optional[int]										=      in_channels
								_lowerCAmelCase    :    List[Any]										=      config.hidden_size
								_lowerCAmelCase    :    str										=      False
								_lowerCAmelCase    :    Any										=      nn.Convad(self.channels		,	config.num_labels		,	kernel_size=1      )

								# PSP Module
								_lowerCAmelCase    :    List[Any]										=      UperNetPyramidPoolingModule(
								    self.pool_scales		,	self.in_channels[-1]		,	self.channels		,	align_corners=self.align_corners		,	)
								_lowerCAmelCase    :    Tuple										=      UperNetConvModule(
								    self.in_channels[-1] + len(self.pool_scales      ) * self.channels		,	self.channels		,	kernel_size=3		,	padding=1		,	)
								# FPN Module
								_lowerCAmelCase    :    int										=      nn.ModuleList()
								_lowerCAmelCase    :    Tuple										=      nn.ModuleList()
								for in_channels in self.in_channels[:-1]:  # skip the top layer
												_lowerCAmelCase    :    Any										=      UperNetConvModule(_UpperCAmelCase		,	self.channels		,	kernel_size=1      )
												_lowerCAmelCase    :    str										=      UperNetConvModule(self.channels		,	self.channels		,	kernel_size=3		,	padding=1      )
												self.lateral_convs.append(_UpperCAmelCase      )
												self.fpn_convs.append(_UpperCAmelCase      )

								_lowerCAmelCase    :    str										=      UperNetConvModule(
								    len(self.in_channels      ) * self.channels		,	self.channels		,	kernel_size=3		,	padding=1		,	)



				def       SCREAMING_SNAKE_CASE       (      self      :		List[str]      )  ->    Dict:





								'''simple docstring'''




								self.apply(self._init_weights      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[int]		,	_UpperCAmelCase      :		List[str]      )  ->    Any:





								'''simple docstring'''




								if isinstance(_UpperCAmelCase		,	nn.Convad      ):
												module.weight.data.normal_(mean=0.0		,	std=self.config.initializer_range      )
												if module.bias is not None:
																module.bias.data.zero_()



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[int]		,	_UpperCAmelCase      :		Dict      )  ->    str:





								'''simple docstring'''




								_lowerCAmelCase    :    Tuple										=      inputs[-1]
								_lowerCAmelCase    :    Optional[int]										=      [x]
								psp_outs.extend(self.psp_modules(_UpperCAmelCase      )      )
								_lowerCAmelCase    :    int										=      torch.cat(_UpperCAmelCase		,	dim=1      )
								_lowerCAmelCase    :    Optional[Any]										=      self.bottleneck(_UpperCAmelCase      )

								return output



				def       SCREAMING_SNAKE_CASE       (      self      :		int		,	_UpperCAmelCase      :		torch.Tensor      )  ->    torch.Tensor:





								'''simple docstring'''




								_lowerCAmelCase    :    List[str]										=      [lateral_conv(encoder_hidden_states[i]      ) for i, lateral_conv in enumerate(self.lateral_convs      )]

								laterals.append(self.psp_forward(_UpperCAmelCase      )      )

								# build top-down path
								_lowerCAmelCase    :    str										=      len(_UpperCAmelCase      )
								for i in range(used_backbone_levels - 1		,	0		,	-1      ):
												_lowerCAmelCase    :    Optional[Any]										=      laterals[i - 1].shape[2:]
												_lowerCAmelCase    :    Any										=      laterals[i - 1] + nn.functional.interpolate(
												    laterals[i]		,	size=_UpperCAmelCase		,	mode="""bilinear"""		,	align_corners=self.align_corners      )

								# build outputs
								_lowerCAmelCase    :    List[str]										=      [self.fpn_convs[i](laterals[i]      ) for i in range(used_backbone_levels - 1      )]
								# append psp feature
								fpn_outs.append(laterals[-1]      )

								for i in range(used_backbone_levels - 1		,	0		,	-1      ):
												_lowerCAmelCase    :    Dict										=      nn.functional.interpolate(
												    fpn_outs[i]		,	size=fpn_outs[0].shape[2:]		,	mode="""bilinear"""		,	align_corners=self.align_corners      )
								_lowerCAmelCase    :    Any										=      torch.cat(_UpperCAmelCase		,	dim=1      )
								_lowerCAmelCase    :    Dict										=      self.fpn_bottleneck(_UpperCAmelCase      )
								_lowerCAmelCase    :    int										=      self.classifier(_UpperCAmelCase      )

								return output






class        __snake_case  (nn.Module		):



				def __init__(      self      :		Union[str, Any]		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		int = 2		,	_UpperCAmelCase      :		int = 3		,	_UpperCAmelCase      :		Union[int, Tuple[int, int]] = 1      )  ->    None:





								'''simple docstring'''




								super().__init__()

								_lowerCAmelCase    :    Optional[int]										=      config
								_lowerCAmelCase    :    Dict										=      config.auxiliary_in_channels
								_lowerCAmelCase    :    int										=      config.auxiliary_channels
								_lowerCAmelCase    :    str										=      config.auxiliary_num_convs
								_lowerCAmelCase    :    List[str]										=      config.auxiliary_concat_input
								_lowerCAmelCase    :    str										=      in_index

								_lowerCAmelCase    :    int										=      (kernel_size // 2) * dilation
								_lowerCAmelCase    :    List[str]										=      []
								convs.append(
								    UperNetConvModule(
								        self.in_channels		,	self.channels		,	kernel_size=_UpperCAmelCase		,	padding=_UpperCAmelCase		,	dilation=_UpperCAmelCase      )      )
								for i in range(self.num_convs - 1      ):
												convs.append(
												    UperNetConvModule(
												        self.channels		,	self.channels		,	kernel_size=_UpperCAmelCase		,	padding=_UpperCAmelCase		,	dilation=_UpperCAmelCase      )      )
								if self.num_convs == 0:
												_lowerCAmelCase    :    Optional[int]										=      nn.Identity()
								else:
												_lowerCAmelCase    :    str										=      nn.Sequential(*_UpperCAmelCase      )
								if self.concat_input:
												_lowerCAmelCase    :    Union[str, Any]										=      UperNetConvModule(
												    self.in_channels + self.channels		,	self.channels		,	kernel_size=_UpperCAmelCase		,	padding=kernel_size // 2      )

								_lowerCAmelCase    :    int										=      nn.Convad(self.channels		,	config.num_labels		,	kernel_size=1      )



				def       SCREAMING_SNAKE_CASE       (      self      :		List[str]      )  ->    Dict:





								'''simple docstring'''




								self.apply(self._init_weights      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Any		,	_UpperCAmelCase      :		Dict      )  ->    str:





								'''simple docstring'''




								if isinstance(_UpperCAmelCase		,	nn.Convad      ):
												module.weight.data.normal_(mean=0.0		,	std=self.config.initializer_range      )
												if module.bias is not None:
																module.bias.data.zero_()



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[Any]		,	_UpperCAmelCase      :		torch.Tensor      )  ->    torch.Tensor:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[Any]										=      encoder_hidden_states[self.in_index]
								_lowerCAmelCase    :    Any										=      self.convs(_UpperCAmelCase      )
								if self.concat_input:
												_lowerCAmelCase    :    Dict										=      self.conv_cat(torch.cat([hidden_states, output]		,	dim=1      )      )
								_lowerCAmelCase    :    Dict										=      self.classifier(_UpperCAmelCase      )
								return output






class        __snake_case  (_a		):
				lowerCAmelCase__				=     UperNetConfig
				lowerCAmelCase__				=     "pixel_values"
				lowerCAmelCase__				=     True



				def       SCREAMING_SNAKE_CASE       (      self      :		List[Any]		,	_UpperCAmelCase      :		Union[str, Any]      )  ->    int:





								'''simple docstring'''




								if isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ):
												module.backbone.init_weights()
												module.decode_head.init_weights()
												module.auxiliary_head.init_weights()



				def       SCREAMING_SNAKE_CASE       (      self      :		str      )  ->    List[str]:





								'''simple docstring'''




								self.backbone.init_weights()
								self.decode_head.init_weights()
								self.auxiliary_head.init_weights()



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[int]		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		Tuple=False      )  ->    Tuple:





								'''simple docstring'''




								if isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ):
												_lowerCAmelCase    :    Tuple										=      value






_lowerCamelCase      :  int    						=						R"\n    Parameters:\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n        config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

_lowerCamelCase      :  int    						=						R"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n            `attentions` under returned tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n            returned tensors for more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"
@add_start_docstrings(
    "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes."						,	_a						,	)
class        __snake_case  (_a		):



				def __init__(      self      :		Optional[Any]		,	_UpperCAmelCase      :		Tuple      )  ->    Optional[Any]:





								'''simple docstring'''




								super().__init__(_UpperCAmelCase      )

								_lowerCAmelCase    :    List[Any]										=      AutoBackbone.from_config(config.backbone_config      )

								# Semantic segmentation head(s)
								_lowerCAmelCase    :    Any										=      UperNetHead(_UpperCAmelCase		,	in_channels=self.backbone.channels      )
								_lowerCAmelCase    :    Any										=      UperNetFCNHead(_UpperCAmelCase      ) if config.use_auxiliary_head else None

								# Initialize weights and apply final processing
								self.post_init()



				@add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("""batch_size, sequence_length"""      )      )
				@replace_return_docstrings(output_type=_UpperCAmelCase		,	config_class=_CONFIG_FOR_DOC      )
				def       SCREAMING_SNAKE_CASE       (      self      :		Dict		,	_UpperCAmelCase      :		Optional[torch.Tensor] = None		,	_UpperCAmelCase      :		Optional[bool] = None		,	_UpperCAmelCase      :		Optional[bool] = None		,	_UpperCAmelCase      :		Optional[torch.Tensor] = None		,	_UpperCAmelCase      :		Optional[bool] = None		,	)  ->    Union[tuple, SemanticSegmenterOutput]:





								'''simple docstring'''




								_lowerCAmelCase    :    List[str]										=      return_dict if return_dict is not None else self.config.use_return_dict
								_lowerCAmelCase    :    Union[str, Any]										=      (
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								_lowerCAmelCase    :    Optional[Any]										=      output_attentions if output_attentions is not None else self.config.output_attentions

								_lowerCAmelCase    :    Union[str, Any]										=      self.backbone.forward_with_filtered_kwargs(
								    _UpperCAmelCase		,	output_hidden_states=_UpperCAmelCase		,	output_attentions=_UpperCAmelCase      )
								_lowerCAmelCase    :    List[str]										=      outputs.feature_maps

								_lowerCAmelCase    :    Any										=      self.decode_head(_UpperCAmelCase      )
								_lowerCAmelCase    :    List[str]										=      nn.functional.interpolate(_UpperCAmelCase		,	size=pixel_values.shape[2:]		,	mode="""bilinear"""		,	align_corners=_UpperCAmelCase      )

								_lowerCAmelCase    :    int										=      None
								if self.auxiliary_head is not None:
												_lowerCAmelCase    :    Optional[int]										=      self.auxiliary_head(_UpperCAmelCase      )
												_lowerCAmelCase    :    Tuple										=      nn.functional.interpolate(
												    _UpperCAmelCase		,	size=pixel_values.shape[2:]		,	mode="""bilinear"""		,	align_corners=_UpperCAmelCase      )

								_lowerCAmelCase    :    Optional[Any]										=      None
								if labels is not None:
												if self.config.num_labels == 1:
																raise ValueError("""The number of labels should be greater than one"""      )
												else:
																# compute weighted loss
																_lowerCAmelCase    :    List[Any]										=      CrossEntropyLoss(ignore_index=self.config.loss_ignore_index      )
																_lowerCAmelCase    :    Union[str, Any]										=      loss_fct(_UpperCAmelCase		,	_UpperCAmelCase      )
																_lowerCAmelCase    :    Union[str, Any]										=      loss_fct(_UpperCAmelCase		,	_UpperCAmelCase      )
																_lowerCAmelCase    :    List[str]										=      main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

								if not return_dict:
												if output_hidden_states:
																_lowerCAmelCase    :    Dict										=      (logits,) + outputs[1:]
												else:
																_lowerCAmelCase    :    Dict										=      (logits,) + outputs[2:]
												return ((loss,) + output) if loss is not None else output

								return SemanticSegmenterOutput(
								    loss=_UpperCAmelCase		,	logits=_UpperCAmelCase		,	hidden_states=outputs.hidden_states		,	attentions=outputs.attentions		,	)







def 							_UpperCAmelCase  (UpperCamelCase_ : int       ):
				'''simple docstring'''
				_lowerCAmelCase    :    int										=      n ** (1 / 3)
				return (val * val * val) == n


if __name__ == "__main__":
	print(perfect_cube(2_7))
	print(perfect_cube(4))

