


"""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


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

# General docstring
__snake_case         =					"""UperNetConfig"""







class _lowerCAmelCase       (   nn.Module			):







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

       '''simple docstring'''




       super().__init__()
       snake_case					:   Optional[Any]         =					nn.Convad(
           in_channels=UpperCamelCase__		,			out_channels=UpperCamelCase__		,			kernel_size=UpperCamelCase__		,			padding=UpperCamelCase__		,			bias=UpperCamelCase__		,			dilation=UpperCamelCase__		,			)
       snake_case					:   Optional[int]         =					nn.BatchNormad(UpperCamelCase__		)
       snake_case					:   Any         =					nn.ReLU()







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	torch.Tensor:

       '''simple docstring'''




       snake_case					:   List[Any]         =					self.conv(UpperCamelCase__		)
       snake_case					:   Tuple         =					self.batch_norm(UpperCamelCase__		)
       snake_case					:   Optional[Any]         =					self.activation(UpperCamelCase__		)

       return output







class _lowerCAmelCase       (   nn.Module			):







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

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	torch.Tensor:

       '''simple docstring'''




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







class _lowerCAmelCase       (   nn.Module			):







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

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	List[torch.Tensor]:

       '''simple docstring'''




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







class _lowerCAmelCase       (   nn.Module			):







   def __init__(			self		,			UpperCamelCase__		,			UpperCamelCase__		)			->	Union[str, Any]:

       '''simple docstring'''




       super().__init__()

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

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

       snake_case					:   List[str]         =					UperNetConvModule(
           len(self.in_channels		) * self.channels		,			self.channels		,			kernel_size=3		,			padding=1		,			)







   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       self.apply(self._init_weights		)







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Union[str, Any]:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	int:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					inputs[-1]
       snake_case					:   Any         =					[x]
       psp_outs.extend(self.psp_modules(UpperCamelCase__		)		)
       snake_case					:   List[str]         =					torch.cat(UpperCamelCase__		,			dim=1		)
       snake_case					:   List[str]         =					self.bottleneck(UpperCamelCase__		)

       return output







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	torch.Tensor:

       '''simple docstring'''




       snake_case					:   Tuple         =					[lateral_conv(encoder_hidden_states[i]		) for i, lateral_conv in enumerate(self.lateral_convs		)]

       laterals.append(self.psp_forward(UpperCamelCase__		)		)

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

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

       return output







class _lowerCAmelCase       (   nn.Module			):







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

       '''simple docstring'''




       super().__init__()

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

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

       snake_case					:   Dict         =					nn.Convad(self.channels		,			config.num_labels		,			kernel_size=1		)







   def 				lowerCamelCase	(			self		)			->	str:

       '''simple docstring'''




       self.apply(self._init_weights		)







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Union[str, Any]:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	torch.Tensor:

       '''simple docstring'''




       snake_case					:   Tuple         =					encoder_hidden_states[self.in_index]
       snake_case					:   str         =					self.convs(UpperCamelCase__		)
       if self.concat_input:
           snake_case					:   str         =					self.conv_cat(torch.cat([hidden_states, output]		,			dim=1		)		)
       snake_case					:   List[Any]         =					self.classifier(UpperCamelCase__		)
       return output







class _lowerCAmelCase       (   snake_case_			):
   __UpperCAmelCase				: Optional[Any]													=						UperNetConfig
   __UpperCAmelCase				: List[Any]													=						'''pixel_values'''
   __UpperCAmelCase				: Tuple													=						True







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Optional[Any]:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		)			->	Optional[int]:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__=False		)			->	int:

       '''simple docstring'''




       if isinstance(UpperCamelCase__		,			UpperCamelCase__		):
           snake_case					:   Any         =					value



__snake_case         =					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.
"""

__snake_case         =					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 _lowerCAmelCase       (   snake_case_			):







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

       '''simple docstring'''




       super().__init__(UpperCamelCase__		)

       snake_case					:   Dict         =					AutoBackbone.from_config(config.backbone_config		)

       # Semantic segmentation head(s)
       snake_case					:   Optional[int]         =					UperNetHead(UpperCamelCase__		,			in_channels=self.backbone.channels		)
       snake_case					:   int         =					UperNetFCNHead(UpperCamelCase__		) if config.use_auxiliary_head else None

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







   @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"		)		)
   @replace_return_docstrings(output_type=UpperCamelCase__		,			config_class=_CONFIG_FOR_DOC		)
   def 				lowerCamelCase	(			self		,			UpperCamelCase__ = None		,			UpperCamelCase__ = None		,			UpperCamelCase__ = None		,			UpperCamelCase__ = None		,			UpperCamelCase__ = None		,			)			->	Union[tuple, SemanticSegmenterOutput]:

       '''simple docstring'''




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

       snake_case					:   Union[str, Any]         =					self.backbone.forward_with_filtered_kwargs(
           UpperCamelCase__		,			output_hidden_states=UpperCamelCase__		,			output_attentions=UpperCamelCase__		)
       snake_case					:   int         =					outputs.feature_maps

       snake_case					:   Dict         =					self.decode_head(UpperCamelCase__		)
       snake_case					:   int         =					nn.functional.interpolate(UpperCamelCase__		,			size=pixel_values.shape[2:]		,			mode="bilinear"		,			align_corners=UpperCamelCase__		)

       snake_case					:   List[Any]         =					None
       if self.auxiliary_head is not None:
           snake_case					:   Dict         =					self.auxiliary_head(UpperCamelCase__		)
           snake_case					:   Dict         =					nn.functional.interpolate(
               UpperCamelCase__		,			size=pixel_values.shape[2:]		,			mode="bilinear"		,			align_corners=UpperCamelCase__		)

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

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

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









"""simple docstring"""



from __future__ import annotations

__snake_case         =					list[tuple[int, int]]

__snake_case         =					[
    [0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 0, 0, 0],  # 0 are free path whereas 1's are obstacles
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0],
    [1, 0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0],
]

__snake_case         =					([-1, 0], [0, -1], [1, 0], [0, 1])  # up, left, down, right







class _lowerCAmelCase       :







   def __init__(			self		,			UpperCamelCase__		,			UpperCamelCase__		,			UpperCamelCase__		,			UpperCamelCase__		,			UpperCamelCase__		,			UpperCamelCase__		,			)			->	str:

       '''simple docstring'''




       snake_case					:   int         =					pos_x
       snake_case					:   List[str]         =					pos_y
       snake_case					:   List[Any]         =					(pos_y, pos_x)
       snake_case					:   Optional[int]         =					goal_x
       snake_case					:   Dict         =					goal_y
       snake_case					:   Any         =					g_cost
       snake_case					:   List[Any]         =					parent
       snake_case					:   Union[str, Any]         =					self.calculate_heuristic()







   def 				lowerCamelCase	(			self		)			->	float:

       '''simple docstring'''




       snake_case					:   Optional[Any]         =					abs(self.pos_x - self.goal_x		)
       snake_case					:   Dict         =					abs(self.pos_y - self.goal_y		)
       return dx + dy







   def __lt__(			self		,			UpperCamelCase__		)			->	bool:

       '''simple docstring'''




       return self.f_cost < other.f_cost







class _lowerCAmelCase       :







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

       '''simple docstring'''




       snake_case					:   int         =					Node(start[1]		,			start[0]		,			goal[1]		,			goal[0]		,			0		,			UpperCamelCase__		)
       snake_case					:   List[Any]         =					Node(goal[1]		,			goal[0]		,			goal[1]		,			goal[0]		,			9_9999		,			UpperCamelCase__		)

       snake_case					:   Tuple         =					[self.start]
       snake_case					:   list[Node]         =					[]

       snake_case					:   Dict         =					False







   def 				lowerCamelCase	(			self		)			->	Path | None:

       '''simple docstring'''




       while self.open_nodes:
           # Open Nodes are sorted using __lt__
           self.open_nodes.sort()
           snake_case					:   str         =					self.open_nodes.pop(0		)

           if current_node.pos == self.target.pos:
               snake_case					:   Tuple         =					True
               return self.retrace_path(UpperCamelCase__		)

           self.closed_nodes.append(UpperCamelCase__		)
           snake_case					:   Optional[Any]         =					self.get_successors(UpperCamelCase__		)

           for child_node in successors:
               if child_node in self.closed_nodes:
                   continue

               if child_node not in self.open_nodes:
                   self.open_nodes.append(UpperCamelCase__		)
               else:
                   # retrieve the best current path
                   snake_case					:   Dict         =					self.open_nodes.pop(self.open_nodes.index(UpperCamelCase__		)		)

                   if child_node.g_cost < better_node.g_cost:
                       self.open_nodes.append(UpperCamelCase__		)
                   else:
                       self.open_nodes.append(UpperCamelCase__		)

       if not self.reached:
           return [self.start.pos]
       return None







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	list[Node]:

       '''simple docstring'''




       snake_case					:   Dict         =					[]
       for action in delta:
           snake_case					:   Union[str, Any]         =					parent.pos_x + action[1]
           snake_case					:   str         =					parent.pos_y + action[0]

           if not (0 <= pos_x <= len(grid[0]		) - 1 and 0 <= pos_y <= len(UpperCamelCase__		) - 1):
               continue

           if grid[pos_y][pos_x] != 0:
               continue

           successors.append(
               Node(
                   UpperCamelCase__		,			UpperCamelCase__		,			self.target.pos_y		,			self.target.pos_x		,			parent.g_cost + 1		,			UpperCamelCase__		,			)		)
       return successors







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Path:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					node
       snake_case					:   int         =					[]
       while current_node is not None:
           path.append((current_node.pos_y, current_node.pos_x)		)
           snake_case					:   Any         =					current_node.parent
       path.reverse()
       return path


if __name__ == "__main__":
  __snake_case         =					(0, 0)
  __snake_case         =					(len(grid) - 1, len(grid[0]) - 1)
  for elem in grid:
    print(elem)

  print("""------""")

  __snake_case         =					GreedyBestFirst(init, goal)
  __snake_case         =					greedy_bf.search()
  if path:
    for pos_x, pos_y in path:
      __snake_case         =					2

    for elem in grid:
      print(elem)





