




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


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

# General docstring
UpperCamelCase__					    =    """UperNetConfig"""
class     a__					(      nn.Module   ):






						def __init__(     self	,    _A	,    _A	,    _A	,    _A = 0	,    _A = False	,    _A = 1	,    ):




											"""simple docstring"""



											super().__init__()
											__lowerCAmelCase            = nn.Convad(
											    in_channels=_A	,    out_channels=_A	,    kernel_size=_A	,    padding=_A	,    bias=_A	,    dilation=_A	,    )
											__lowerCAmelCase            = nn.BatchNormad(_A    )
											__lowerCAmelCase            = nn.ReLU()






						def        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



											__lowerCAmelCase            = self.conv(_A    )
											__lowerCAmelCase            = self.batch_norm(_A    )
											__lowerCAmelCase            = self.activation(_A    )

											return output






class     a__					(      nn.Module   ):






						def __init__(     self	,    _A	,    _A	,    _A    ):




											"""simple docstring"""



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






						def        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



											__lowerCAmelCase            = input
											for layer in self.layers:
																__lowerCAmelCase            = layer(_A    )
											return hidden_state






class     a__					(      nn.Module   ):






						def __init__(     self	,    _A	,    _A	,    _A	,    _A    ):




											"""simple docstring"""



											super().__init__()
											__lowerCAmelCase            = pool_scales
											__lowerCAmelCase            = align_corners
											__lowerCAmelCase            = in_channels
											__lowerCAmelCase            = channels
											__lowerCAmelCase            = []
											for i, pool_scale in enumerate(_A    ):
																__lowerCAmelCase            = UperNetPyramidPoolingBlock(pool_scale=_A	,    in_channels=_A	,    channels=_A    )
																self.blocks.append(_A    )
																self.add_module(str(_A    )	,    _A    )






						def        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



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






class     a__					(      nn.Module   ):






						def __init__(     self	,    _A	,    _A    ):




											"""simple docstring"""



											super().__init__()

											__lowerCAmelCase            = config
											__lowerCAmelCase            = config.pool_scales  # e.g. (1, 2, 3, 6)
											__lowerCAmelCase            = in_channels
											__lowerCAmelCase            = config.hidden_size
											__lowerCAmelCase            = False
											__lowerCAmelCase            = nn.Convad(self.channels	,    config.num_labels	,    kernel_size=1    )

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

											__lowerCAmelCase            = UperNetConvModule(
											    len(self.in_channels    ) * self.channels	,    self.channels	,    kernel_size=3	,    padding=1	,    )






						def        __SCREAMING_SNAKE_CASE(     self    ):




											"""simple docstring"""



											self.apply(self._init_weights    )






						def        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



											if isinstance(_A	,    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	,    _A    ):




											"""simple docstring"""



											__lowerCAmelCase            = inputs[-1]
											__lowerCAmelCase            = [x]
											psp_outs.extend(self.psp_modules(_A    )    )
											__lowerCAmelCase            = torch.cat(_A	,    dim=1    )
											__lowerCAmelCase            = self.bottleneck(_A    )

											return output






						def        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



											__lowerCAmelCase            = [lateral_conv(encoder_hidden_states[i]    ) for i, lateral_conv in enumerate(self.lateral_convs    )]

											laterals.append(self.psp_forward(_A    )    )

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

											# build outputs
											__lowerCAmelCase            = [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            = nn.functional.interpolate(
																    fpn_outs[i]	,    size=fpn_outs[0].shape[2:]	,    mode="bilinear"	,    align_corners=self.align_corners    )
											__lowerCAmelCase            = torch.cat(_A	,    dim=1    )
											__lowerCAmelCase            = self.fpn_bottleneck(_A    )
											__lowerCAmelCase            = self.classifier(_A    )

											return output






class     a__					(      nn.Module   ):






						def __init__(     self	,    _A	,    _A = 2	,    _A = 3	,    _A = 1    ):




											"""simple docstring"""



											super().__init__()

											__lowerCAmelCase            = config
											__lowerCAmelCase            = config.auxiliary_in_channels
											__lowerCAmelCase            = config.auxiliary_channels
											__lowerCAmelCase            = config.auxiliary_num_convs
											__lowerCAmelCase            = config.auxiliary_concat_input
											__lowerCAmelCase            = in_index

											__lowerCAmelCase            = (kernel_size // 2) * dilation
											__lowerCAmelCase            = []
											convs.append(
											    UperNetConvModule(
											        self.in_channels	,    self.channels	,    kernel_size=_A	,    padding=_A	,    dilation=_A    )    )
											for i in range(self.num_convs - 1    ):
																convs.append(
																    UperNetConvModule(
																        self.channels	,    self.channels	,    kernel_size=_A	,    padding=_A	,    dilation=_A    )    )
											if self.num_convs == 0:
																__lowerCAmelCase            = nn.Identity()
											else:
																__lowerCAmelCase            = nn.Sequential(*_A    )
											if self.concat_input:
																__lowerCAmelCase            = UperNetConvModule(
																    self.in_channels + self.channels	,    self.channels	,    kernel_size=_A	,    padding=kernel_size // 2    )

											__lowerCAmelCase            = nn.Convad(self.channels	,    config.num_labels	,    kernel_size=1    )






						def        __SCREAMING_SNAKE_CASE(     self    ):




											"""simple docstring"""



											self.apply(self._init_weights    )






						def        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



											if isinstance(_A	,    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	,    _A    ):




											"""simple docstring"""



											__lowerCAmelCase            = encoder_hidden_states[self.in_index]
											__lowerCAmelCase            = self.convs(_A    )
											if self.concat_input:
																__lowerCAmelCase            = self.conv_cat(torch.cat([hidden_states, output]	,    dim=1    )    )
											__lowerCAmelCase            = self.classifier(_A    )
											return output






class     a__					(      snake_case__   ):
						_a							:					Optional[Any]      =					UperNetConfig
						_a							:					Tuple      =					"""pixel_values"""
						_a							:					Dict      =					True






						def        __SCREAMING_SNAKE_CASE(     self	,    _A    ):




											"""simple docstring"""



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






						def        __SCREAMING_SNAKE_CASE(     self    ):




											"""simple docstring"""



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






						def        __SCREAMING_SNAKE_CASE(     self	,    _A	,    _A=False    ):




											"""simple docstring"""



											if isinstance(_A	,    _A    ):
																__lowerCAmelCase            = value






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

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






						def __init__(     self	,    _A    ):




											"""simple docstring"""



											super().__init__(_A    )

											__lowerCAmelCase            = AutoBackbone.from_config(config.backbone_config    )

											# Semantic segmentation head(s)
											__lowerCAmelCase            = UperNetHead(_A	,    in_channels=self.backbone.channels    )
											__lowerCAmelCase            = UperNetFCNHead(_A    ) 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=_A	,    config_class=_CONFIG_FOR_DOC    )
						def        __SCREAMING_SNAKE_CASE(     self	,    _A = None	,    _A = None	,    _A = None	,    _A = None	,    _A = None	,    ):




											"""simple docstring"""



											__lowerCAmelCase            = return_dict if return_dict is not None else self.config.use_return_dict
											__lowerCAmelCase            = (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											__lowerCAmelCase            = output_attentions if output_attentions is not None else self.config.output_attentions

											__lowerCAmelCase            = self.backbone.forward_with_filtered_kwargs(
											    _A	,    output_hidden_states=_A	,    output_attentions=_A    )
											__lowerCAmelCase            = outputs.feature_maps

											__lowerCAmelCase            = self.decode_head(_A    )
											__lowerCAmelCase            = nn.functional.interpolate(_A	,    size=pixel_values.shape[2:]	,    mode="bilinear"	,    align_corners=_A    )

											__lowerCAmelCase            = None
											if self.auxiliary_head is not None:
																__lowerCAmelCase            = self.auxiliary_head(_A    )
																__lowerCAmelCase            = nn.functional.interpolate(
																    _A	,    size=pixel_values.shape[2:]	,    mode="bilinear"	,    align_corners=_A    )

											__lowerCAmelCase            = 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            = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index    )
																					__lowerCAmelCase            = loss_fct(_A	,    _A    )
																					__lowerCAmelCase            = loss_fct(_A	,    _A    )
																					__lowerCAmelCase            = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

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

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










def 			_a   (		SCREAMING_SNAKE_CASE_							:       int   ,   SCREAMING_SNAKE_CASE_							:       int  ):
					if b == 0:
										return 1
					if (b % 2) == 0:
										return actual_power(SCREAMING_SNAKE_CASE_   ,   int(b / 2  )  ) * actual_power(SCREAMING_SNAKE_CASE_   ,   int(b / 2  )  )
					else:
										return a * actual_power(SCREAMING_SNAKE_CASE_   ,   int(b / 2  )  ) * actual_power(SCREAMING_SNAKE_CASE_   ,   int(b / 2  )  )







def 			_a   (		SCREAMING_SNAKE_CASE_							:       int   ,   SCREAMING_SNAKE_CASE_							:       int  ):
					if b < 0:
										return 1 / actual_power(SCREAMING_SNAKE_CASE_   ,   SCREAMING_SNAKE_CASE_  )
					return actual_power(SCREAMING_SNAKE_CASE_   ,   SCREAMING_SNAKE_CASE_  )


if __name__ == "__main__":
					print(power(-2, -3))




