



import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
				from test_module.custom_tokenization_fast import CustomTokenizerFast



class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __UpperCamelCase						(							self      :  Any       )		->     Tuple:
											# A mock response for an HTTP head request to emulate server down
											A      						=    mock.Mock()
											A      						=    500
											A      						=    {}
											A      						=    HTTPError
											A      						=    {}

											# Download this model to make sure it's in the cache.
											A      						=    BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert'       )

											# Under the mock environment we get a 500 error when trying to reach the tokenizer.
											with mock.patch('requests.Session.request'						, return_value=__UpperCamelCase       ) as mock_head:
																		A      						=    BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert'       )
																		# This check we did call the fake head request
																		mock_head.assert_called()


				@require_tokenizers
				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Union[str, Any]:
											# A mock response for an HTTP head request to emulate server down
											A      						=    mock.Mock()
											A      						=    500
											A      						=    {}
											A      						=    HTTPError
											A      						=    {}

											# Download this model to make sure it's in the cache.
											A      						=    GPTaTokenizerFast.from_pretrained('gpt2'       )

											# Under the mock environment we get a 500 error when trying to reach the tokenizer.
											with mock.patch('requests.Session.request'						, return_value=__UpperCamelCase       ) as mock_head:
																		A      						=    GPTaTokenizerFast.from_pretrained('gpt2'       )
																		# This check we did call the fake head request
																		mock_head.assert_called()


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     List[str]:
											# This test is for deprecated behavior and can be removed in v5
											try:
																		A      						=    tempfile.mktemp()
																		with open(__UpperCamelCase						, 'wb'       ) as f:
																									http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model'						, __UpperCamelCase       )

																		A      						=    AlbertTokenizer.from_pretrained(__UpperCamelCase       )
											finally:
																		os.remove(__UpperCamelCase       )

											# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
											# the current folder and have the right name.
											if os.path.isfile('tokenizer.json'       ):
																		# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
																		return
											try:
																		with open('tokenizer.json'						, 'wb'       ) as f:
																									http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json'						, __UpperCamelCase       )
																		A      						=    AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'       )
																		# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
																		self.assertEqual(tokenizer.vocab_size						, 1_000       )
																		# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

											finally:
																		os.remove('tokenizer.json'       )


				def __UpperCamelCase						(							self      :  str       )		->     int:
											# This test is for deprecated behavior and can be removed in v5
											A      						=    AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model'       )





@is_staging_test
class        lowerCAmelCase__					(  unittest.TestCase       ):
				A_   :     str								=     ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']


				@classmethod
				def __UpperCamelCase						(							cls      :  Tuple       )		->     Dict:
											A      						=    TOKEN
											HfFolder.save_token(__UpperCamelCase       )


				@classmethod
				def __UpperCamelCase						(							cls      :  Any       )		->     Dict:
											try:
																		delete_repo(token=cls._token						, repo_id='test-tokenizer'       )
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						, repo_id='valid_org/test-tokenizer-org'       )
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						, repo_id='test-dynamic-tokenizer'       )
											except HTTPError:
																		pass


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     List[str]:
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    BertTokenizer(__UpperCamelCase       )

											tokenizer.push_to_hub('test-tokenizer'						, use_auth_token=self._token       )
											A      						=    BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer'''       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )

											# Reset repo
											delete_repo(token=self._token						, repo_id='test-tokenizer'       )

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																		tokenizer.save_pretrained(__UpperCamelCase						, repo_id='test-tokenizer'						, push_to_hub=__UpperCamelCase						, use_auth_token=self._token       )

											A      						=    BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer'''       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )


				def __UpperCamelCase						(							self      :  List[str]       )		->     Tuple:
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    BertTokenizer(__UpperCamelCase       )

											tokenizer.push_to_hub('valid_org/test-tokenizer-org'						, use_auth_token=self._token       )
											A      						=    BertTokenizer.from_pretrained('valid_org/test-tokenizer-org'       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )

											# Reset repo
											delete_repo(token=self._token						, repo_id='valid_org/test-tokenizer-org'       )

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																		tokenizer.save_pretrained(
																		    __UpperCamelCase						, repo_id='valid_org/test-tokenizer-org'						, push_to_hub=__UpperCamelCase						, use_auth_token=self._token       )

											A      						=    BertTokenizer.from_pretrained('valid_org/test-tokenizer-org'       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )


				@require_tokenizers
				def __UpperCamelCase						(							self      :  Any       )		->     Union[str, Any]:
											CustomTokenizer.register_for_auto_class()
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    CustomTokenizer(__UpperCamelCase       )

											# No fast custom tokenizer
											tokenizer.push_to_hub('test-dynamic-tokenizer'						, use_auth_token=self._token       )

											A      						=    AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer'''						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizer'       )

											# Fast and slow custom tokenizer
											CustomTokenizerFast.register_for_auto_class()
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )

																		A      						=    BertTokenizerFast.from_pretrained(__UpperCamelCase       )
																		bert_tokenizer.save_pretrained(__UpperCamelCase       )
																		A      						=    CustomTokenizerFast.from_pretrained(__UpperCamelCase       )

											tokenizer.push_to_hub('test-dynamic-tokenizer'						, use_auth_token=self._token       )

											A      						=    AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer'''						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizerFast'       )
											A      						=    AutoTokenizer.from_pretrained(
											    f'''{USER}/test-dynamic-tokenizer'''						, use_fast=__UpperCamelCase						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizer'       )





class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __UpperCamelCase						(							self      :  List[Any]       )		->     Any:
											A      						=    Trie()
											trie.add('Hello 友達'       )
											self.assertEqual(trie.data						, {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}}       )
											trie.add('Hello'       )
											trie.data
											self.assertEqual(trie.data						, {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}}       )


				def __UpperCamelCase						(							self      :  Dict       )		->     Tuple:
											A      						=    Trie()
											self.assertEqual(trie.split('[CLS] This is a extra_id_100'       )						, ['[CLS] This is a extra_id_100']       )
											trie.add('[CLS]'       )
											trie.add('extra_id_1'       )
											trie.add('extra_id_100'       )
											self.assertEqual(trie.split('[CLS] This is a extra_id_100'       )						, ['[CLS]', ' This is a ', 'extra_id_100']       )


				def __UpperCamelCase						(							self      :  Any       )		->     Optional[int]:
											A      						=    Trie()
											trie.add('A'       )
											self.assertEqual(trie.split('ABC'       )						, ['A', 'BC']       )
											self.assertEqual(trie.split('BCA'       )						, ['BC', 'A']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     str:
											A      						=    Trie()
											trie.add('TOKEN]'       )
											trie.add('[SPECIAL_TOKEN]'       )
											self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]'       )						, ['This is something ', '[SPECIAL_TOKEN]']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Tuple:
											A      						=    Trie()
											trie.add('A'       )
											trie.add('P'       )
											trie.add('[SPECIAL_TOKEN]'       )
											self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]'       )						, ['This is something ', '[SPECIAL_TOKEN]']       )


				def __UpperCamelCase						(							self      :  List[str]       )		->     Tuple:
											A      						=    Trie()
											trie.add('AB'       )
											trie.add('B'       )
											trie.add('C'       )
											self.assertEqual(trie.split('ABC'       )						, ['AB', 'C']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     List[Any]:
											A      						=    Trie()
											trie.add('ABC'       )
											trie.add('B'       )
											trie.add('CD'       )
											self.assertEqual(trie.split('ABCD'       )						, ['ABC', 'D']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     List[Any]:
											# Even if the offsets are wrong, we necessarily output correct string
											# parts.
											A      						=    Trie()
											A      						=    trie.cut_text('ABC'						, [0, 0, 2, 1, 2, 3]       )
											self.assertEqual(__UpperCamelCase						, ['AB', 'C']       )

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_    :			List[Any]    =	[
    """openmmlab/upernet-convnext-tiny""",
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
lowerCamelCase_    :			int    =	"""UperNetConfig"""

class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

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




			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							torch.Tensor   ):
							UpperCamelCase_:				str						=    self.conv(snake_case_   )
							UpperCamelCase_:				str						=    self.batch_norm(snake_case_   )
							UpperCamelCase_:				Any						=    self.activation(snake_case_   )

							return output




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Optional[int]    ,						snake_case_			:							int    ,						snake_case_			:							int    ,						snake_case_			:							int   ):
							super().__init__()
							UpperCamelCase_:				Any						=    [
							    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    lowerCAmelCase__						(							self			:							Dict    ,						snake_case_			:							torch.Tensor   ):
							UpperCamelCase_:				str						=    input
							for layer in self.layers:
											UpperCamelCase_:				int						=    layer(snake_case_   )
							return hidden_state




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							List[Any]    ,						snake_case_			:							Tuple[int, ...]    ,						snake_case_			:							int    ,						snake_case_			:							int    ,						snake_case_			:							bool   ):
							super().__init__()
							UpperCamelCase_:				Any						=    pool_scales
							UpperCamelCase_:				List[str]						=    align_corners
							UpperCamelCase_:				Dict						=    in_channels
							UpperCamelCase_:				int						=    channels
							UpperCamelCase_:				Union[str, Any]						=    []
							for i, pool_scale in enumerate(snake_case_   ):
											UpperCamelCase_:				Dict						=    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    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							torch.Tensor   ):
							UpperCamelCase_:				Optional[int]						=    []
							for ppm in self.blocks:
											UpperCamelCase_:				int						=    ppm(snake_case_   )
											UpperCamelCase_:				Optional[int]						=    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 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							int    ,						snake_case_			:							Tuple    ,						snake_case_			:							Any   ):
							super().__init__()

							UpperCamelCase_:				Tuple						=    config
							UpperCamelCase_:				Dict						=    config.pool_scales  # e.g. (1, 2, 3, 6)
							UpperCamelCase_:				Tuple						=    in_channels
							UpperCamelCase_:				Dict						=    config.hidden_size
							UpperCamelCase_:				str						=    False
							UpperCamelCase_:				int						=    nn.Convad(self.channels    ,						config.num_labels    ,						kernel_size=1   )

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

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

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

			def    lowerCAmelCase__						(							self			:							List[str]    ,						snake_case_			:							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    lowerCAmelCase__						(							self			:							List[Any]    ,						snake_case_			:							Optional[int]   ):
							UpperCamelCase_:				Tuple						=    inputs[-1]
							UpperCamelCase_:				str						=    [x]
							psp_outs.extend(self.psp_modules(snake_case_   )   )
							UpperCamelCase_:				Union[str, Any]						=    torch.cat(snake_case_    ,						dim=1   )
							UpperCamelCase_:				int						=    self.bottleneck(snake_case_   )

							return output




			def    lowerCAmelCase__						(							self			:							str    ,						snake_case_			:							torch.Tensor   ):
							# build laterals
							UpperCamelCase_:				Union[str, Any]						=    [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
							UpperCamelCase_:				List[Any]						=    len(snake_case_   )
							for i in range(used_backbone_levels - 1    ,						0    ,						-1   ):
											UpperCamelCase_:				Union[str, Any]						=    laterals[i - 1].shape[2:]
											UpperCamelCase_:				Union[str, Any]						=    laterals[i - 1] + nn.functional.interpolate(
											    laterals[i]    ,						size=snake_case_    ,						mode="""bilinear"""    ,						align_corners=self.align_corners   )

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

							return output




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Optional[int]    ,						snake_case_			:							List[str]    ,						snake_case_			:							int = 2    ,						snake_case_			:							int = 3    ,						snake_case_			:							Union[int, Tuple[int, int]] = 1   ):
							super().__init__()

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

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

							UpperCamelCase_:				str						=    nn.Convad(self.channels    ,						config.num_labels    ,						kernel_size=1   )

			def    lowerCAmelCase__						(							self			:							Any   ):
							self.apply(self._init_weights   )

			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							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    lowerCAmelCase__						(							self			:							str    ,						snake_case_			:							torch.Tensor   ):
							# just take the relevant feature maps
							UpperCamelCase_:				Tuple						=    encoder_hidden_states[self.in_index]
							UpperCamelCase_:				Optional[int]						=    self.convs(snake_case_   )
							if self.concat_input:
											UpperCamelCase_:				Optional[int]						=    self.conv_cat(torch.cat([hidden_states, output]    ,						dim=1   )   )
							UpperCamelCase_:				Optional[Any]						=    self.classifier(snake_case_   )
							return output




class 							_UpperCamelCase					(       _A	):






			'''simple docstring'''

			__UpperCamelCase   :    List[Any]          =			UperNetConfig
			__UpperCamelCase   :    Union[str, Any]          =			"""pixel_values"""
			__UpperCamelCase   :    Dict          =			True

			def    lowerCAmelCase__						(							self			:							Optional[int]    ,						snake_case_			:							str   ):
							if isinstance(snake_case_    ,						snake_case_   ):
											module.backbone.init_weights()
											module.decode_head.init_weights()
											module.auxiliary_head.init_weights()

			def    lowerCAmelCase__						(							self			:							Dict   ):
							self.backbone.init_weights()
							self.decode_head.init_weights()
							self.auxiliary_head.init_weights()




			def    lowerCAmelCase__						(							self			:							str    ,						snake_case_			:							Tuple    ,						snake_case_			:							Tuple=False   ):
							if isinstance(snake_case_    ,						snake_case_   ):
											UpperCamelCase_:				Union[str, Any]						=    value




lowerCamelCase_    :			Dict    =	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.
"""

lowerCamelCase_    :			Tuple    =	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."""  ,							_A  ,							)
class 							_UpperCamelCase					(       _A	):






			'''simple docstring'''

			def __init__(							self			:							int    ,						snake_case_			:							Dict   ):
							super().__init__(snake_case_   )

							UpperCamelCase_:				int						=    AutoBackbone.from_config(config.backbone_config   )

							# Semantic segmentation head(s)
							UpperCamelCase_:				Optional[Any]						=    UperNetHead(snake_case_    ,						in_channels=self.backbone.channels   )
							UpperCamelCase_:				List[str]						=    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    lowerCAmelCase__						(							self			:							Union[str, Any]    ,						snake_case_			:							Optional[torch.Tensor] = None    ,						snake_case_			:							Optional[bool] = None    ,						snake_case_			:							Optional[bool] = None    ,						snake_case_			:							Optional[torch.Tensor] = None    ,						snake_case_			:							Optional[bool] = None    ,						):
							UpperCamelCase_:				Union[str, Any]						=    return_dict if return_dict is not None else self.config.use_return_dict
							UpperCamelCase_:				Union[str, Any]						=    (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							UpperCamelCase_:				int						=    output_attentions if output_attentions is not None else self.config.output_attentions

							UpperCamelCase_:				Dict						=    self.backbone.forward_with_filtered_kwargs(
							    snake_case_    ,						output_hidden_states=snake_case_    ,						output_attentions=snake_case_   )
							UpperCamelCase_:				Any						=    outputs.feature_maps

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

							UpperCamelCase_:				Dict						=    None
							if self.auxiliary_head is not None:
											UpperCamelCase_:				List[str]						=    self.auxiliary_head(snake_case_   )
											UpperCamelCase_:				Optional[int]						=    nn.functional.interpolate(
											    snake_case_    ,						size=pixel_values.shape[2:]    ,						mode="""bilinear"""    ,						align_corners=snake_case_   )

							UpperCamelCase_:				List[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
															UpperCamelCase_:				List[Any]						=    CrossEntropyLoss(ignore_index=self.config.loss_ignore_index   )
															UpperCamelCase_:				Dict						=    loss_fct(snake_case_    ,						snake_case_   )
															UpperCamelCase_:				Tuple						=    loss_fct(snake_case_    ,						snake_case_   )
															UpperCamelCase_:				List[Any]						=    main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

							if not return_dict:
											if output_hidden_states:
															UpperCamelCase_:				Tuple						=    (logits,) + outputs[1:]
											else:
															UpperCamelCase_:				Union[str, Any]						=    (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    ,						)






