


"""simple docstring"""




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


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

# General docstring
__magic_name__						: Optional[Any]    =				'''UperNetConfig'''




class 			__snake_case   (nn.Module  ):




							def __init__(     self:    List[str]     ,							A_:    List[str]     ,							A_:    Optional[Any]     ,							A_:    Union[str, Any]     ,							A_:    int = 0     ,							A_:    Any = False     ,							A_:    Union[str, Any] = 1     ,							):
										super().__init__()
										__lowerCamelCase          =      nn.Convad(
										    in_channels=snake_case_     ,							out_channels=snake_case_     ,							kernel_size=snake_case_     ,							padding=snake_case_     ,							bias=snake_case_     ,							dilation=snake_case_     ,							)
										__lowerCamelCase          =      nn.BatchNormad(snake_case_   )
										__lowerCamelCase          =      nn.ReLU()




							def   __a   (     self:    Optional[int]     ,							A_:    List[str]   ):
										__lowerCamelCase          =      self.conv(snake_case_   )
										__lowerCamelCase          =      self.batch_norm(snake_case_   )
										__lowerCamelCase          =      self.activation(snake_case_   )

										return output




class 			__snake_case   (nn.Module  ):




							def __init__(     self:    int     ,							A_:    Union[str, Any]     ,							A_:    Union[str, Any]     ,							A_:    Optional[Any]   ):
										super().__init__()
										__lowerCamelCase          =      [
										    nn.AdaptiveAvgPoolad(snake_case_   ),
										    UperNetConvModule(snake_case_     ,							snake_case_     ,							kernel_size=1   ),
										]
										for i, layer in enumerate(self.layers   ):
													self.add_module(str(snake_case_   )     ,							snake_case_   )




							def   __a   (     self:    Optional[int]     ,							A_:    Optional[int]   ):
										__lowerCamelCase          =      input
										for layer in self.layers:
													__lowerCamelCase          =      layer(snake_case_   )
										return hidden_state




class 			__snake_case   (nn.Module  ):




							def __init__(     self:    List[str]     ,							A_:    Optional[Any]     ,							A_:    int     ,							A_:    List[Any]     ,							A_:    List[Any]   ):
										super().__init__()
										__lowerCamelCase          =      pool_scales
										__lowerCamelCase          =      align_corners
										__lowerCamelCase          =      in_channels
										__lowerCamelCase          =      channels
										__lowerCamelCase          =      []
										for i, pool_scale in enumerate(snake_case_   ):
													__lowerCamelCase          =      UperNetPyramidPoolingBlock(pool_scale=snake_case_     ,							in_channels=snake_case_     ,							channels=snake_case_   )
													self.blocks.append(snake_case_   )
													self.add_module(str(snake_case_   )     ,							snake_case_   )




							def   __a   (     self:    Optional[int]     ,							A_:    Optional[Any]   ):
										__lowerCamelCase          =      []
										for ppm in self.blocks:
													__lowerCamelCase          =      ppm(snake_case_   )
													__lowerCamelCase          =      nn.functional.interpolate(
													    snake_case_     ,							size=x.size()[2:]     ,							mode="""bilinear"""     ,							align_corners=self.align_corners   )
													ppm_outs.append(snake_case_   )
										return ppm_outs




class 			__snake_case   (nn.Module  ):




							def __init__(     self:    str     ,							A_:    List[str]     ,							A_:    List[Any]   ):
										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(snake_case_     ,							self.channels     ,							kernel_size=1   )
													__lowerCamelCase          =      UperNetConvModule(self.channels     ,							self.channels     ,							kernel_size=3     ,							padding=1   )
													self.lateral_convs.append(snake_case_   )
													self.fpn_convs.append(snake_case_   )

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




							def   __a   (     self:    List[str]   ):
										self.apply(self._init_weights   )




							def   __a   (     self:    Union[str, Any]     ,							A_:    Union[str, Any]   ):

										if isinstance(snake_case_     ,							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   __a   (     self:    Tuple     ,							A_:    Any   ):
										__lowerCamelCase          =      inputs[-1]
										__lowerCamelCase          =      [x]
										psp_outs.extend(self.psp_modules(snake_case_   )   )
										__lowerCamelCase          =      torch.cat(snake_case_     ,							dim=1   )
										__lowerCamelCase          =      self.bottleneck(snake_case_   )

										return output




							def   __a   (     self:    int     ,							A_:    Tuple   ):
										__lowerCamelCase          =      [lateral_conv(encoder_hidden_states[i]   ) for i, lateral_conv in enumerate(self.lateral_convs   )]

										laterals.append(self.psp_forward(snake_case_   )   )

										# build top-down path
										__lowerCamelCase          =      len(snake_case_   )
										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=snake_case_     ,							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(snake_case_     ,							dim=1   )
										__lowerCamelCase          =      self.fpn_bottleneck(snake_case_   )
										__lowerCamelCase          =      self.classifier(snake_case_   )

										return output




class 			__snake_case   (nn.Module  ):




							def __init__(     self:    Any     ,							A_:    Optional[int]     ,							A_:    Dict = 2     ,							A_:    str = 3     ,							A_:    Optional[Any] = 1   ):
										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=snake_case_     ,							padding=snake_case_     ,							dilation=snake_case_   )   )
										for i in range(self.num_convs - 1   ):
													convs.append(
													    UperNetConvModule(
													        self.channels     ,							self.channels     ,							kernel_size=snake_case_     ,							padding=snake_case_     ,							dilation=snake_case_   )   )
										if self.num_convs == 0:
													__lowerCamelCase          =      nn.Identity()
										else:
													__lowerCamelCase          =      nn.Sequential(*snake_case_   )
										if self.concat_input:
													__lowerCamelCase          =      UperNetConvModule(
													    self.in_channels + self.channels     ,							self.channels     ,							kernel_size=snake_case_     ,							padding=kernel_size // 2   )

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




							def   __a   (     self:    Dict   ):
										self.apply(self._init_weights   )




							def   __a   (     self:    Optional[Any]     ,							A_:    int   ):

										if isinstance(snake_case_     ,							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   __a   (     self:    List[Any]     ,							A_:    str   ):
										__lowerCamelCase          =      encoder_hidden_states[self.in_index]
										__lowerCamelCase          =      self.convs(snake_case_   )
										if self.concat_input:
													__lowerCamelCase          =      self.conv_cat(torch.cat([hidden_states, output]     ,							dim=1   )   )
										__lowerCamelCase          =      self.classifier(snake_case_   )
										return output




class 			__snake_case   (lowerCAmelCase__  ):
							__a					 =       UperNetConfig
							__a					 =       '''pixel_values'''
							__a					 =       True




							def   __a   (     self:    Tuple     ,							A_:    Union[str, Any]   ):

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




							def   __a   (     self:    Optional[int]   ):
										self.backbone.init_weights()
										self.decode_head.init_weights()
										self.auxiliary_head.init_weights()




							def   __a   (     self:    List[str]     ,							A_:    Optional[Any]     ,							A_:    Optional[int]=False   ):

										if isinstance(snake_case_     ,							snake_case_   ):
													__lowerCamelCase          =      value

__magic_name__						: Union[str, Any]    =				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.
'''

__magic_name__						: Optional[int]    =				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.'''			,		lowerCAmelCase__			,		)
class 			__snake_case   (lowerCAmelCase__  ):




							def __init__(     self:    Any     ,							A_:    str   ):
										super().__init__(snake_case_   )

										__lowerCamelCase          =      AutoBackbone.from_config(config.backbone_config   )

										# Semantic segmentation head(s)
										__lowerCamelCase          =      UperNetHead(snake_case_     ,							in_channels=self.backbone.channels   )
										__lowerCamelCase          =      UperNetFCNHead(snake_case_   ) 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=snake_case_     ,							config_class=_CONFIG_FOR_DOC   )
							def   __a   (     self:    Optional[int]     ,							A_:    Any = None     ,							A_:    Optional[int] = None     ,							A_:    List[Any] = None     ,							A_:    Optional[int] = None     ,							A_:    Optional[Any] = None     ,							):
										__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(
										    snake_case_     ,							output_hidden_states=snake_case_     ,							output_attentions=snake_case_   )
										__lowerCamelCase          =      outputs.feature_maps

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

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

										__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(snake_case_     ,							snake_case_   )
																__lowerCamelCase          =      loss_fct(snake_case_     ,							snake_case_   )
																__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=snake_case_     ,							logits=snake_case_     ,							hidden_states=outputs.hidden_states     ,							attentions=outputs.attentions     ,							)








import doctest
from collections import deque

import numpy as np
class 						lowerCamelCase_							:



					'''simple docstring'''







					def __init__(					self    ) ->      None:







								'''simple docstring'''

								__lowercase			       = [2, 1, 2, -1]
								__lowercase			       = [1, 2, 3, 4]






					def A   (					self    ) ->      list[float]:







								'''simple docstring'''

								__lowercase			       = len(self.first_signal    )
								__lowercase			       = len(self.second_signal    )

								__lowercase			       = max(snake_case_			,							snake_case_    )

								# create a zero matrix of max_length x max_length
								__lowercase			       = [[0] * max_length for i in range(snake_case_    )]

								# fills the smaller signal with zeros to make both signals of same length
								if length_first_signal < length_second_signal:
											self.first_signal += [0] * (max_length - length_first_signal)
								elif length_first_signal > length_second_signal:
											self.second_signal += [0] * (max_length - length_second_signal)
								for i in range(snake_case_    ):
											__lowercase			       = deque(self.second_signal    )
											rotated_signal.rotate(snake_case_    )
											for j, item in enumerate(snake_case_    ):
														matrix[i][j] += item

        # multiply the matrix with the first signal
								__lowercase			       = np.matmul(np.transpose(snake_case_    )			,							np.transpose(self.first_signal    )    )

								# rounding-off to two decimal places
								return [round(snake_case_			,							2    ) for i in final_signal]


if __name__ == "__main__":
	doctest.testmod()


