






import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
UpperCAmelCase__            =	logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=2.0.0", "To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt")
def 		_a					(   a				:Any			,							a				:List[Any]			,							a				:Any=0				)							->    Tuple:
 a							=   (size, size) if isinstance(a			,							a				) else size
 a						,  a							=   img.size
 a							=   size[1] - original_height if original_height < size[1] else 0
 a							=   size[0] - original_width if original_width < size[0] else 0
 a							=   functional.pad(a			,							(0, 0, pad_width, pad_height)			,							fill=a				)
 return img






class 	lowercase_      :






      '''simple docstring'''




      def __init__(   self   :		Optional[int]				,      __UpperCAmelCase   :		Dict						)					->Tuple:




       """simple docstring"""


       a							=   transforms







      def __call__(   self   :		Tuple				,      __UpperCAmelCase   :		List[str]				,      __UpperCAmelCase   :		Dict						)					->int:




       """simple docstring"""


       for t in self.transforms:
        a						,  a							=   t(__UpperCAmelCase				,      __UpperCAmelCase						)
       return image, target






class 	lowercase_      :






      '''simple docstring'''




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




       """simple docstring"""


       pass







      def __call__(   self   :		Optional[int]				,      __UpperCAmelCase   :		List[str]				,      __UpperCAmelCase   :		Any						)					->Union[str, Any]:




       """simple docstring"""


       return image, target






class 	lowercase_      :






      '''simple docstring'''




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




       """simple docstring"""


       a							=   size







      def __call__(   self   :		List[Any]				,      __UpperCAmelCase   :		List[Any]				,      __UpperCAmelCase   :		List[str]						)					->List[Any]:




       """simple docstring"""


       a							=   functional.resize(__UpperCAmelCase				,      self.size						)
       a							=   functional.resize(__UpperCAmelCase				,      self.size				,      interpolation=transforms.InterpolationMode.NEAREST						)
       return image, target






class 	lowercase_      :






      '''simple docstring'''




      def __init__(   self   :		Union[str, Any]				,      __UpperCAmelCase   :		List[str]				,      __UpperCAmelCase   :		Tuple=None						)					->Optional[Any]:




       """simple docstring"""


       a							=   min_size
       if max_size is None:
        a							=   min_size
       a							=   max_size







      def __call__(   self   :		int				,      __UpperCAmelCase   :		Any				,      __UpperCAmelCase   :		List[Any]						)					->Optional[Any]:




       """simple docstring"""


       a							=   random.randint(self.min_size				,      self.max_size						)
       a							=   functional.resize(__UpperCAmelCase				,      __UpperCAmelCase						)
       a							=   functional.resize(__UpperCAmelCase				,      __UpperCAmelCase				,      interpolation=transforms.InterpolationMode.NEAREST						)
       return image, target






class 	lowercase_      :






      '''simple docstring'''




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




       """simple docstring"""


       a							=   size if isinstance(__UpperCAmelCase				,      __UpperCAmelCase						) else (size, size)







      def __call__(   self   :		Any				,      __UpperCAmelCase   :		Optional[int]				,      __UpperCAmelCase   :		Tuple						)					->Tuple:




       """simple docstring"""


       a							=   pad_if_smaller(__UpperCAmelCase				,      self.size						)
       a							=   pad_if_smaller(__UpperCAmelCase				,      self.size				,      fill=255						)
       a							=   transforms.RandomCrop.get_params(__UpperCAmelCase				,      self.size						)
       a							=   functional.crop(__UpperCAmelCase				,      *__UpperCAmelCase						)
       a							=   functional.crop(__UpperCAmelCase				,      *__UpperCAmelCase						)
       return image, target






class 	lowercase_      :






      '''simple docstring'''




      def __init__(   self   :		Union[str, Any]				,      __UpperCAmelCase   :		Optional[int]						)					->Dict:




       """simple docstring"""


       a							=   flip_prob







      def __call__(   self   :		int				,      __UpperCAmelCase   :		int				,      __UpperCAmelCase   :		Optional[Any]						)					->Dict:




       """simple docstring"""


       if random.random() < self.flip_prob:
        a							=   functional.hflip(__UpperCAmelCase						)
        a							=   functional.hflip(__UpperCAmelCase						)
       return image, target






class 	lowercase_      :






      '''simple docstring'''




      def __call__(   self   :		List[str]				,      __UpperCAmelCase   :		Union[str, Any]				,      __UpperCAmelCase   :		List[str]						)					->Tuple:




       """simple docstring"""


       a							=   functional.pil_to_tensor(__UpperCAmelCase						)
       a							=   torch.as_tensor(np.array(__UpperCAmelCase						)				,      dtype=torch.intaa						)
       return image, target






class 	lowercase_      :






      '''simple docstring'''




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




       """simple docstring"""


       a							=   dtype







      def __call__(   self   :		int				,      __UpperCAmelCase   :		str				,      __UpperCAmelCase   :		int						)					->Union[str, Any]:




       """simple docstring"""


       a							=   functional.convert_image_dtype(__UpperCAmelCase				,      self.dtype						)
       return image, target






class 	lowercase_      :






      '''simple docstring'''




      def __init__(   self   :		List[str]				,      __UpperCAmelCase   :		Any				,      __UpperCAmelCase   :		int						)					->Dict:




       """simple docstring"""


       a							=   mean
       a							=   std







      def __call__(   self   :		Optional[Any]				,      __UpperCAmelCase   :		List[str]				,      __UpperCAmelCase   :		int						)					->Tuple:




       """simple docstring"""


       a							=   functional.normalize(__UpperCAmelCase				,      mean=self.mean				,      std=self.std						)
       return image, target






class 	lowercase_      :






      '''simple docstring'''




      def __call__(   self   :		Tuple				,      __UpperCAmelCase   :		Optional[int]				,      __UpperCAmelCase   :		Optional[int]						)					->str:




       """simple docstring"""


       if not isinstance(__UpperCAmelCase				,      np.ndarray						):
        a							=   np.array(__UpperCAmelCase						).astype(np.uinta						)
       # avoid using underflow conversion
       a							=   255
       a							=   target - 1
       a							=   255

       a							=   Image.fromarray(__UpperCAmelCase						)
       return image, target






@dataclass
class 	lowercase_      :






      '''simple docstring'''




      __snake_case  						=						field(
          default='''segments/sidewalk-semantic'''				,						metadata={
              '''help''': '''Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'''
          }				,						)
      __snake_case  						=						field(
          default=lowercase				,						metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}     )
      __snake_case  						=						field(
          default=0.1_5				,						metadata={'''help''': '''Percent to split off of train for validation.'''}     )
      __snake_case  						=						field(
          default=lowercase				,						metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of training examples to this '''
                  '''value if set.'''
              )
          }				,						)
      __snake_case  						=						field(
          default=lowercase				,						metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
                  '''value if set.'''
              )
          }				,						)
      __snake_case  						=						field(
          default=lowercase				,						metadata={'''help''': '''Whether or not to reduce all labels by 1 and replace background by 255.'''}				,						)







      def    __lowerCAmelCase      (   self   :		int						)					->List[Any]:




       """simple docstring"""


       if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
        raise ValueError(
            '''You must specify either a dataset name from the hub or a train and/or validation directory.'''						)






@dataclass
class 	lowercase_      :






      '''simple docstring'''




      __snake_case  						=						field(
          default='''nvidia/mit-b0'''				,						metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}				,						)
      __snake_case  						=						field(
          default=lowercase				,						metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}     )
      __snake_case  						=						field(
          default=lowercase				,						metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}     )
      __snake_case  						=						field(
          default='''main'''				,						metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}				,						)
      __snake_case  						=						field(default=lowercase				,						metadata={'''help''': '''Name or path of preprocessor config.'''}     )
      __snake_case  						=						field(
          default=lowercase				,						metadata={
              '''help''': (
                  '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
                  '''with private models).'''
              )
          }				,						)
def 		_a					(   )							->    List[Any]:
 # See all possible arguments in src/transformers/training_args.py
 # or by passing the --help flag to this script.
 # We now keep distinct sets of args, for a cleaner separation of concerns.

 a							=   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
 if len(sys.argv				) == 2 and sys.argv[1].endswith('''.json'''				):
  # If we pass only one argument to the script and it's the path to a json file,
  # let's parse it to get our arguments.
  a						,  a						,  a							=   parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
 else:
  a						,  a						,  a							=   parser.parse_args_into_dataclasses()

 # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
 # information sent is the one passed as arguments along with your Python/PyTorch versions.
 send_example_telemetry('''run_semantic_segmentation'''			,							a			,							a				)

 # Setup logging
 logging.basicConfig(
     format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''			,							datefmt='''%m/%d/%Y %H:%M:%S'''			,							handlers=[logging.StreamHandler(sys.stdout				)]			,							)

 if training_args.should_log:
  # The default of training_args.log_level is passive, so we set log level at info here to have that default.
  transformers.utils.logging.set_verbosity_info()

 a							=   training_args.get_process_log_level()
 logger.setLevel(a				)
 transformers.utils.logging.set_verbosity(a				)
 transformers.utils.logging.enable_default_handler()
 transformers.utils.logging.enable_explicit_format()

 # Log on each process the small summary:
 logger.warning(
     F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
     + F"""distributed training: {bool(training_args.local_rank != -1				)}, 16-bits training: {training_args.fpaa}"""				)
 logger.info(F"""Training/evaluation parameters {training_args}"""				)

 # Detecting last checkpoint.
 a							=   None
 if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
  a							=   get_last_checkpoint(training_args.output_dir				)
  if last_checkpoint is None and len(os.listdir(training_args.output_dir				)				) > 0:
   raise ValueError(
       F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
       '''Use --overwrite_output_dir to overcome.'''				)
  elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
   logger.info(
       F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
       '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''				)

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
 a							=   load_dataset(data_args.dataset_name			,							cache_dir=model_args.cache_dir				)

 # Rename column names to standardized names (only "image" and "label" need to be present)
 if "pixel_values" in dataset["train"].column_names:
  a							=   dataset.rename_columns({'''pixel_values''': '''image'''}				)
 if "annotation" in dataset["train"].column_names:
  a							=   dataset.rename_columns({'''annotation''': '''label'''}				)

 # If we don't have a validation split, split off a percentage of train as validation.
 a							=   None if '''validation''' in dataset.keys() else data_args.train_val_split
 if isinstance(data_args.train_val_split			,							a				) and data_args.train_val_split > 0.0:
  a							=   dataset['''train'''].train_test_split(data_args.train_val_split				)
  a							=   split['''train''']
  a							=   split['''test''']

 # Prepare label mappings.
 # We'll include these in the model's config to get human readable labels in the Inference API.
 if data_args.dataset_name == "scene_parse_150":
  a							=   '''huggingface/label-files'''
  a							=   '''ade20k-id2label.json'''
 else:
  a							=   data_args.dataset_name
  a							=   '''id2label.json'''
 a							=   json.load(open(hf_hub_download(a			,							a			,							repo_type='''dataset'''				)			,							'''r'''				)				)
 a							=   {int(a				): v for k, v in idalabel.items()}
 a							=   {v: str(a				) for k, v in idalabel.items()}

 # Load the mean IoU metric from the datasets package
 a							=   evaluate.load('''mean_iou'''				)

 # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
 # predictions and label_ids field) and has to return a dictionary string to float.
 @torch.no_grad()
 def compute_metrics(a				:Any				):
  a						,  a							=   eval_pred
  a							=   torch.from_numpy(a				)
  # scale the logits to the size of the label
  a							=   nn.functional.interpolate(
      a			,							size=labels.shape[-2:]			,							mode='''bilinear'''			,							align_corners=a			,							).argmax(dim=1				)

  a							=   logits_tensor.detach().cpu().numpy()
  a							=   metric.compute(
      predictions=a			,							references=a			,							num_labels=len(a				)			,							ignore_index=0			,							reduce_labels=image_processor.do_reduce_labels			,							)
  # add per category metrics as individual key-value pairs
  a							=   metrics.pop('''per_category_accuracy'''				).tolist()
  a							=   metrics.pop('''per_category_iou'''				).tolist()

  metrics.update({F"""accuracy_{idalabel[i]}""": v for i, v in enumerate(a				)}				)
  metrics.update({F"""iou_{idalabel[i]}""": v for i, v in enumerate(a				)}				)

  return metrics

 a							=   AutoConfig.from_pretrained(
     model_args.config_name or model_args.model_name_or_path			,							labelaid=a			,							idalabel=a			,							cache_dir=model_args.cache_dir			,							revision=model_args.model_revision			,							use_auth_token=True if model_args.use_auth_token else None			,							)
 a							=   AutoModelForSemanticSegmentation.from_pretrained(
     model_args.model_name_or_path			,							from_tf=bool('''.ckpt''' in model_args.model_name_or_path				)			,							config=a			,							cache_dir=model_args.cache_dir			,							revision=model_args.model_revision			,							use_auth_token=True if model_args.use_auth_token else None			,							)
 a							=   AutoImageProcessor.from_pretrained(
     model_args.image_processor_name or model_args.model_name_or_path			,							cache_dir=model_args.cache_dir			,							revision=model_args.model_revision			,							use_auth_token=True if model_args.use_auth_token else None			,							)

 # Define torchvision transforms to be applied to each image + target.
 # Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
 # Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
 if "shortest_edge" in image_processor.size:
  # We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
  a							=   (image_processor.size['''shortest_edge'''], image_processor.size['''shortest_edge'''])
 else:
  a							=   (image_processor.size['''height'''], image_processor.size['''width'''])
 a							=   Compose(
     [
         ReduceLabels() if data_args.reduce_labels else Identity(),
         RandomCrop(size=a				),
         RandomHorizontalFlip(flip_prob=0.5				),
         PILToTensor(),
         ConvertImageDtype(torch.float				),
         Normalize(mean=image_processor.image_mean			,							std=image_processor.image_std				),
     ]				)
 # Define torchvision transform to be applied to each image.
 # jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
 a							=   Compose(
     [
         ReduceLabels() if data_args.reduce_labels else Identity(),
         Resize(size=a				),
         PILToTensor(),
         ConvertImageDtype(torch.float				),
         Normalize(mean=image_processor.image_mean			,							std=image_processor.image_std				),
     ]				)

 def preprocess_train(a				:Optional[Any]				):
  a							=   []
  a							=   []
  for image, target in zip(example_batch['''image''']			,							example_batch['''label''']				):
   a						,  a							=   train_transforms(image.convert('''RGB'''				)			,							a				)
   pixel_values.append(a				)
   labels.append(a				)

  a							=   {}
  a							=   torch.stack(a				)
  a							=   torch.stack(a				)

  return encoding

 def preprocess_val(a				:Union[str, Any]				):
  a							=   []
  a							=   []
  for image, target in zip(example_batch['''image''']			,							example_batch['''label''']				):
   a						,  a							=   val_transforms(image.convert('''RGB'''				)			,							a				)
   pixel_values.append(a				)
   labels.append(a				)

  a							=   {}
  a							=   torch.stack(a				)
  a							=   torch.stack(a				)

  return encoding

 if training_args.do_train:
  if "train" not in dataset:
   raise ValueError('''--do_train requires a train dataset'''				)
  if data_args.max_train_samples is not None:
   a							=   (
       dataset['''train'''].shuffle(seed=training_args.seed				).select(range(data_args.max_train_samples				)				)
   )
  # Set the training transforms
  dataset["train"].set_transform(a				)

 if training_args.do_eval:
  if "validation" not in dataset:
   raise ValueError('''--do_eval requires a validation dataset'''				)
  if data_args.max_eval_samples is not None:
   a							=   (
       dataset['''validation'''].shuffle(seed=training_args.seed				).select(range(data_args.max_eval_samples				)				)
   )
  # Set the validation transforms
  dataset["validation"].set_transform(a				)

 # Initalize our trainer
 a							=   Trainer(
     model=a			,							args=a			,							train_dataset=dataset['''train'''] if training_args.do_train else None			,							eval_dataset=dataset['''validation'''] if training_args.do_eval else None			,							compute_metrics=a			,							tokenizer=a			,							data_collator=a			,							)

 # Training
 if training_args.do_train:
  a							=   None
  if training_args.resume_from_checkpoint is not None:
   a							=   training_args.resume_from_checkpoint
  elif last_checkpoint is not None:
   a							=   last_checkpoint
  a							=   trainer.train(resume_from_checkpoint=a				)
  trainer.save_model()
  trainer.log_metrics('''train'''			,							train_result.metrics				)
  trainer.save_metrics('''train'''			,							train_result.metrics				)
  trainer.save_state()

 # Evaluation
 if training_args.do_eval:
  a							=   trainer.evaluate()
  trainer.log_metrics('''eval'''			,							a				)
  trainer.save_metrics('''eval'''			,							a				)

 # Write model card and (optionally) push to hub
 a							=   {
     '''finetuned_from''': model_args.model_name_or_path,
     '''dataset''': data_args.dataset_name,
     '''tags''': ['''image-segmentation''', '''vision'''],
 }
 if training_args.push_to_hub:
  trainer.push_to_hub(**a				)
 else:
  trainer.create_model_card(**a				)


if __name__ == "__main__":
     main()










import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union






class 	lowercase_      (			enum.Enum     ):






      '''simple docstring'''




      __snake_case  						=						'''timm'''
      __snake_case  						=						'''transformers'''
def 		_a					(   a				:Optional[Iterable[str]]			,							a				:Optional[Iterable[int]]			,							a				:Optional[Iterable[str]]				)							->    Optional[Any]:
 if stage_names is None:
  raise ValueError('''Stage_names must be set for transformers backbones'''				)

 if out_features is not None:
  if not isinstance(a			,							(list,)				):
   raise ValueError(F"""out_features must be a list {type(a				)}"""				)
  if any(feat not in stage_names for feat in out_features				):
   raise ValueError(F"""out_features must be a subset of stage_names: {stage_names} got {out_features}"""				)

 if out_indices is not None:
  if not isinstance(a			,							(list, tuple)				):
   raise ValueError(F"""out_indices must be a list or tuple, got {type(a				)}"""				)
  if any(idx >= len(a				) for idx in out_indices				):
   raise ValueError('''out_indices must be valid indices for stage_names {stage_names}, got {out_indices}'''				)

 if out_features is not None and out_indices is not None:
  if len(a				) != len(a				):
   raise ValueError('''out_features and out_indices should have the same length if both are set'''				)
  if out_features != [stage_names[idx] for idx in out_indices]:
   raise ValueError('''out_features and out_indices should correspond to the same stages if both are set'''				)
def 		_a					(   a				:Optional[List[str]]			,							a				:Optional[Union[List[int], Tuple[int]]]			,							a				:List[str]			,							)							->    Union[str, Any]:
 if out_indices is None and out_features is None:
  a							=   [len(a				) - 1]
  a							=   [stage_names[-1]]
 elif out_indices is None and out_features is not None:
  a							=   [stage_names.index(a				) for layer in out_features]
 elif out_features is None and out_indices is not None:
  a							=   [stage_names[idx] for idx in out_indices]
 return out_features, out_indices
def 		_a					(   a				:Optional[List[str]]			,							a				:Optional[Union[List[int], Tuple[int]]]			,							a				:List[str]			,							)							->    Tuple[List[str], List[int]]:
 verify_out_features_out_indices(out_features=a			,							out_indices=a			,							stage_names=a				)
 a						,  a							=   _align_output_features_output_indices(
     out_features=a			,							out_indices=a			,							stage_names=a				)
 # Verify that the aligned out_features and out_indices are valid
 verify_out_features_out_indices(out_features=a			,							out_indices=a			,							stage_names=a				)
 return output_features, output_indices






class 	lowercase_      :






      '''simple docstring'''




      __snake_case  						=						None







      def    __lowerCAmelCase      (   self   :		Any				,      __UpperCAmelCase   :		Tuple						)					->None:




       """simple docstring"""


       if getattr(self				,      '''_backbone'''				,      __UpperCAmelCase						) is None:
        raise ValueError('''self._backbone must be set before calling _init_timm_backbone'''						)

       # These will diagree with the defaults for the transformers models e.g. for resnet50
       # the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
       # the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
       a							=   [stage['''module'''] for stage in self._backbone.feature_info.info]
       a							=   [stage['''num_chs'''] for stage in self._backbone.feature_info.info]
       a							=   self._backbone.feature_info.out_indices
       a							=   self._backbone.feature_info.module_name()

       # We verify the out indices and out features are valid
       verify_out_features_out_indices(
           out_features=__UpperCAmelCase				,      out_indices=__UpperCAmelCase				,      stage_names=self.stage_names						)
       a						,  a							=   out_features, out_indices







      def    __lowerCAmelCase      (   self   :		Any				,      __UpperCAmelCase   :		Tuple						)					->None:




       """simple docstring"""


       a							=   getattr(__UpperCAmelCase				,      '''stage_names'''						)
       a							=   getattr(__UpperCAmelCase				,      '''out_features'''				,      __UpperCAmelCase						)
       a							=   getattr(__UpperCAmelCase				,      '''out_indices'''				,      __UpperCAmelCase						)

       a							=   stage_names
       a						,  a							=   get_aligned_output_features_output_indices(
           out_features=__UpperCAmelCase				,      out_indices=__UpperCAmelCase				,      stage_names=__UpperCAmelCase						)
       # Number of channels for each stage. This is set in the transformer backbone model init
       a							=   None







      def    __lowerCAmelCase      (   self   :		str				,      __UpperCAmelCase   :		Union[str, Any]						)					->None:




       """simple docstring"""


       a							=   config

       a							=   getattr(__UpperCAmelCase				,      '''use_timm_backbone'''				,      __UpperCAmelCase						)
       a							=   BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

       if self.backbone_type == BackboneType.TIMM:
        self._init_timm_backbone(__UpperCAmelCase						)
       elif self.backbone_type == BackboneType.TRANSFORMERS:
        self._init_transformers_backbone(__UpperCAmelCase						)
       else:
        raise ValueError(F"""backbone_type {self.backbone_type} not supported."""						)







      @property
      def    __lowerCAmelCase      (   self   :		Dict						)					->Optional[Any]:




       """simple docstring"""


       return self._out_features







      @out_features.setter
      def    __lowerCAmelCase      (   self   :		Tuple				,      __UpperCAmelCase   :		List[str]						)					->List[Any]:




       """simple docstring"""


       a						,  a							=   get_aligned_output_features_output_indices(
           out_features=__UpperCAmelCase				,      out_indices=__UpperCAmelCase				,      stage_names=self.stage_names						)







      @property
      def    __lowerCAmelCase      (   self   :		Dict						)					->int:




       """simple docstring"""


       return self._out_indices







      @out_indices.setter
      def    __lowerCAmelCase      (   self   :		Tuple				,      __UpperCAmelCase   :		Union[Tuple[int], List[int]]						)					->List[str]:




       """simple docstring"""


       a						,  a							=   get_aligned_output_features_output_indices(
           out_features=__UpperCAmelCase				,      out_indices=__UpperCAmelCase				,      stage_names=self.stage_names						)







      @property
      def    __lowerCAmelCase      (   self   :		Tuple						)					->str:




       """simple docstring"""


       return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names						)}







      @property
      def    __lowerCAmelCase      (   self   :		int						)					->Optional[int]:




       """simple docstring"""


       return [self.out_feature_channels[name] for name in self.out_features]







      def    __lowerCAmelCase      (   self   :		Optional[Any]				,      *__UpperCAmelCase   :		List[str]				,      **__UpperCAmelCase   :		Optional[Any]						)					->Optional[int]:




       """simple docstring"""


       a							=   dict(inspect.signature(self.forward						).parameters						)
       a							=   {k: v for k, v in kwargs.items() if k in signature}
       return self(*__UpperCAmelCase				,      **__UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		List[str]				,      __UpperCAmelCase   :		Dict				,      __UpperCAmelCase   :		Optional[bool] = None				,      __UpperCAmelCase   :		Optional[bool] = None				,      __UpperCAmelCase   :		Optional[bool] = None				,      )					->int:




       """simple docstring"""


       raise NotImplementedError('''This method should be implemented by the derived class.'''						)







      def    __lowerCAmelCase      (   self   :		Union[str, Any]						)					->Optional[Any]:




       """simple docstring"""


       a							=   super().to_dict()
       a							=   output.pop('''_out_features'''						)
       a							=   output.pop('''_out_indices'''						)
       return output






class 	lowercase_      :






      '''simple docstring'''




      @property
      def    __lowerCAmelCase      (   self   :		List[str]						)					->Optional[int]:




       """simple docstring"""


       return self._out_features







      @out_features.setter
      def    __lowerCAmelCase      (   self   :		int				,      __UpperCAmelCase   :		List[str]						)					->int:




       """simple docstring"""


       a						,  a							=   get_aligned_output_features_output_indices(
           out_features=__UpperCAmelCase				,      out_indices=__UpperCAmelCase				,      stage_names=self.stage_names						)







      @property
      def    __lowerCAmelCase      (   self   :		str						)					->str:




       """simple docstring"""


       return self._out_indices







      @out_indices.setter
      def    __lowerCAmelCase      (   self   :		str				,      __UpperCAmelCase   :		Union[Tuple[int], List[int]]						)					->int:




       """simple docstring"""


       a						,  a							=   get_aligned_output_features_output_indices(
           out_features=__UpperCAmelCase				,      out_indices=__UpperCAmelCase				,      stage_names=self.stage_names						)







      def    __lowerCAmelCase      (   self   :		Dict						)					->List[Any]:




       """simple docstring"""


       a							=   super().to_dict()
       a							=   output.pop('''_out_features'''						)
       a							=   output.pop('''_out_indices'''						)
       return output


