


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


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

# General docstring
a			:			Optional[Any]												=					'''UperNetConfig'''
class 						lowerCamelCase_							(					nn.Module					):



					'''simple docstring'''







					def __init__(					self			,							snake_case_			,							snake_case_			,							snake_case_			,							snake_case_ = 0			,							snake_case_ = False			,							snake_case_ = 1			,							) ->      None:







								'''simple docstring'''

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






					def A   (					self			,							snake_case_    ) ->      torch.Tensor:







								'''simple docstring'''

								__lowercase			       = self.conv(snake_case_    )
								__lowercase			       = self.batch_norm(snake_case_    )
								__lowercase			       = self.activation(snake_case_    )

								return output




class 						lowerCamelCase_							(					nn.Module					):



					'''simple docstring'''







					def __init__(					self			,							snake_case_			,							snake_case_			,							snake_case_    ) ->      None:







								'''simple docstring'''

								super().__init__()
								__lowercase			       = [
								    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			,							snake_case_    ) ->      torch.Tensor:







								'''simple docstring'''

								__lowercase			       = input
								for layer in self.layers:
											__lowercase			       = layer(snake_case_    )
								return hidden_state




class 						lowerCamelCase_							(					nn.Module					):



					'''simple docstring'''







					def __init__(					self			,							snake_case_			,							snake_case_			,							snake_case_			,							snake_case_    ) ->      None:







								'''simple docstring'''

								super().__init__()
								__lowercase			       = pool_scales
								__lowercase			       = align_corners
								__lowercase			       = in_channels
								__lowercase			       = channels
								__lowercase			       = []
								for i, pool_scale in enumerate(snake_case_    ):
											__lowercase			       = 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			,							snake_case_    ) ->      List[torch.Tensor]:







								'''simple docstring'''

								__lowercase			       = []
								for ppm in self.blocks:
											__lowercase			       = ppm(snake_case_    )
											__lowercase			       = 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 						lowerCamelCase_							(					nn.Module					):



					'''simple docstring'''







					def __init__(					self			,							snake_case_			,							snake_case_    ) ->      List[str]:







								'''simple docstring'''

								super().__init__()

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

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

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






					def A   (					self    ) ->      List[Any]:







								'''simple docstring'''

								self.apply(self._init_weights    )






					def A   (					self			,							snake_case_    ) ->      Optional[int]:







								'''simple docstring'''

								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			,							snake_case_    ) ->      Union[str, Any]:







								'''simple docstring'''

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

								return output






					def A   (					self			,							snake_case_    ) ->      torch.Tensor:







								'''simple docstring'''

								__lowercase			       = [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
								__lowercase			       = len(snake_case_    )
								for i in range(used_backbone_levels - 1			,							0			,							-1    ):
											__lowercase			       = laterals[i - 1].shape[2:]
											__lowercase			       = laterals[i - 1] + nn.functional.interpolate(
											    laterals[i]			,							size=snake_case_			,							mode='''bilinear'''			,							align_corners=self.align_corners    )

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

								return output




class 						lowerCamelCase_							(					nn.Module					):



					'''simple docstring'''







					def __init__(					self			,							snake_case_			,							snake_case_ = 2			,							snake_case_ = 3			,							snake_case_ = 1    ) ->      None:







								'''simple docstring'''

								super().__init__()

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

								__lowercase			       = (kernel_size // 2) * dilation
								__lowercase			       = []
								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:
											__lowercase			       = nn.Identity()
								else:
											__lowercase			       = nn.Sequential(*snake_case_    )
								if self.concat_input:
											__lowercase			       = UperNetConvModule(
											    self.in_channels + self.channels			,							self.channels			,							kernel_size=snake_case_			,							padding=kernel_size // 2    )

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






					def A   (					self    ) ->      Tuple:







								'''simple docstring'''

								self.apply(self._init_weights    )






					def A   (					self			,							snake_case_    ) ->      int:







								'''simple docstring'''

								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			,							snake_case_    ) ->      torch.Tensor:







								'''simple docstring'''

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




class 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					__UpperCAmelCase							  =					UperNetConfig
					__UpperCAmelCase							  =					"pixel_values"
					__UpperCAmelCase							  =					True






					def A   (					self			,							snake_case_    ) ->      Any:







								'''simple docstring'''

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






					def A   (					self    ) ->      Dict:







								'''simple docstring'''

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






					def A   (					self			,							snake_case_			,							snake_case_=False    ) ->      Optional[Any]:







								'''simple docstring'''

								if isinstance(snake_case_			,							snake_case_    ):
											__lowercase			       = value




a			:			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.
'''

a			:			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 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					def __init__(					self			,							snake_case_    ) ->      List[Any]:







								'''simple docstring'''

								super().__init__(snake_case_    )

								__lowercase			       = AutoBackbone.from_config(config.backbone_config    )

								# Semantic segmentation head(s)
								__lowercase			       = UperNetHead(snake_case_			,							in_channels=self.backbone.channels    )
								__lowercase			       = 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			,							snake_case_ = None			,							snake_case_ = None			,							snake_case_ = None			,							snake_case_ = None			,							snake_case_ = None			,							) ->      Union[tuple, SemanticSegmenterOutput]:







								'''simple docstring'''

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

								__lowercase			       = self.backbone.forward_with_filtered_kwargs(
								    snake_case_			,							output_hidden_states=snake_case_			,							output_attentions=snake_case_    )
								__lowercase			       = outputs.feature_maps

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

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

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

								if not return_dict:
											if output_hidden_states:
														__lowercase			       = (logits,) + outputs[1:]
											else:
														__lowercase			       = (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 copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


a			:			Optional[int]												=					logging.get_logger(__name__)

a			:			Dict												=					{
    '''google/pix2struct-textcaps-base''': (
        '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json'''
    ),
}
class 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					__UpperCAmelCase							  =					"pix2struct_text_model"
					__UpperCAmelCase							  =					["past_key_values"]
					__UpperCAmelCase							  =					{
					    "hidden_size": "hidden_size",
					    "num_attention_heads": "num_heads",
					    "num_hidden_layers": "num_layers",
					}






					def __init__(					self			,							snake_case_=5_0_2_4_4			,							snake_case_=7_6_8			,							snake_case_=6_4			,							snake_case_=2_0_4_8			,							snake_case_=1_2			,							snake_case_=1_2			,							snake_case_=3_2			,							snake_case_=1_2_8			,							snake_case_=0.1			,							snake_case_=1e-6			,							snake_case_=1.0			,							snake_case_="gelu_new"			,							snake_case_=0			,							snake_case_=False			,							snake_case_=0			,							snake_case_=1			,							snake_case_=False			,							snake_case_=True			,							**snake_case_			,							) ->      Optional[int]:







								'''simple docstring'''

								__lowercase			       = vocab_size
								__lowercase			       = hidden_size
								__lowercase			       = d_kv
								__lowercase			       = d_ff
								__lowercase			       = num_layers
								__lowercase			       = num_heads
								__lowercase			       = relative_attention_num_buckets
								__lowercase			       = relative_attention_max_distance
								__lowercase			       = dropout_rate
								__lowercase			       = layer_norm_epsilon
								__lowercase			       = initializer_factor
								__lowercase			       = use_cache

								__lowercase			       = eos_token_id
								__lowercase			       = decoder_start_token_id

								# for backwards compatibility
								__lowercase			       = dense_act_fn

								super().__init__(
								    pad_token_id=snake_case_			,							eos_token_id=snake_case_			,							decoder_start_token_id=snake_case_			,							tie_word_embeddings=snake_case_			,							is_decoder=snake_case_			,							**snake_case_			,							)






					@classmethod
					def A   (					cls			,							snake_case_			,							**snake_case_    ) ->      "PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_    )

								__lowercase       ,			__lowercase			       = cls.get_config_dict(snake_case_			,							**snake_case_    )

								# get the text config dict if we are loading from Pix2StructConfig
								if config_dict.get('''model_type'''    ) == "pix2struct":
											__lowercase			       = config_dict['''text_config''']

								if "model_type" in config_dict and hasattr(cls			,							'''model_type'''    ) and config_dict["model_type"] != cls.model_type:
											logger.warning(
											    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
											    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'    )

								return cls.from_dict(snake_case_			,							**snake_case_    )




class 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					__UpperCAmelCase							  =					"pix2struct_vision_model"






					def __init__(					self			,							snake_case_=7_6_8			,							snake_case_=7_6_8			,							snake_case_=2_0_4_8			,							snake_case_=6_4			,							snake_case_=1_2			,							snake_case_=1_2			,							snake_case_="gelu_new"			,							snake_case_=1e-6			,							snake_case_=0.0			,							snake_case_=0.0			,							snake_case_=1e-1_0			,							snake_case_=1.0			,							snake_case_=4_0_9_6			,							snake_case_=3_2			,							snake_case_=1_2_8			,							**snake_case_			,							) ->      Union[str, Any]:







								'''simple docstring'''

								super().__init__(**snake_case_    )

								__lowercase			       = hidden_size
								__lowercase			       = patch_embed_hidden_size
								__lowercase			       = d_ff
								__lowercase			       = dropout_rate
								__lowercase			       = num_hidden_layers
								__lowercase			       = num_attention_heads
								__lowercase			       = initializer_range
								__lowercase			       = initializer_factor
								__lowercase			       = attention_dropout
								__lowercase			       = layer_norm_eps
								__lowercase			       = dense_act_fn
								__lowercase			       = seq_len
								__lowercase			       = relative_attention_num_buckets
								__lowercase			       = relative_attention_max_distance
								__lowercase			       = d_kv






					@classmethod
					def A   (					cls			,							snake_case_			,							**snake_case_    ) ->      "PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_    )

								__lowercase       ,			__lowercase			       = cls.get_config_dict(snake_case_			,							**snake_case_    )

								# get the vision config dict if we are loading from Pix2StructConfig
								if config_dict.get('''model_type'''    ) == "pix2struct":
											__lowercase			       = config_dict['''vision_config''']

								if "model_type" in config_dict and hasattr(cls			,							'''model_type'''    ) and config_dict["model_type"] != cls.model_type:
											logger.warning(
											    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
											    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'    )

								return cls.from_dict(snake_case_			,							**snake_case_    )




class 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					__UpperCAmelCase							  =					"pix2struct"
					__UpperCAmelCase							  =					True






					def __init__(					self			,							snake_case_=None			,							snake_case_=None			,							snake_case_=1.0			,							snake_case_=0.0_2			,							snake_case_=False			,							snake_case_=False			,							snake_case_=True			,							**snake_case_			,							) ->      Optional[int]:







								'''simple docstring'''

								super().__init__(tie_word_embeddings=snake_case_			,							is_encoder_decoder=snake_case_			,							**snake_case_    )

								if text_config is None:
											__lowercase			       = {}
											logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.'''    )

								if vision_config is None:
											__lowercase			       = {}
											logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.'''    )

								__lowercase			       = PixaStructTextConfig(**snake_case_    )
								__lowercase			       = PixaStructVisionConfig(**snake_case_    )

								__lowercase			       = self.text_config.decoder_start_token_id
								__lowercase			       = self.text_config.pad_token_id
								__lowercase			       = self.text_config.eos_token_id

								__lowercase			       = initializer_factor
								__lowercase			       = initializer_range

								__lowercase			       = self.initializer_range
								__lowercase			       = self.initializer_range

								__lowercase			       = is_vqa






					@classmethod
					def A   (					cls			,							snake_case_			,							snake_case_			,							**snake_case_    ) ->      List[str]:







								'''simple docstring'''

								return cls(text_config=text_config.to_dict()			,							vision_config=vision_config.to_dict()			,							**snake_case_    )






					def A   (					self    ) ->      Tuple:







								'''simple docstring'''

								__lowercase			       = copy.deepcopy(self.__dict__    )
								__lowercase			       = self.text_config.to_dict()
								__lowercase			       = self.vision_config.to_dict()
								__lowercase			       = self.__class__.model_type
								return output


