

import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_deberta import DebertaTokenizer


if TYPE_CHECKING:
  from transformers.pipelines.conversational import Conversation


_a									=  logging.get_logger(__name__)

_a									=  {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}

_a									=  {
    '''vocab_file''': {
        '''microsoft/deberta-base''': '''https://huggingface.co/microsoft/deberta-base/resolve/main/vocab.json''',
        '''microsoft/deberta-large''': '''https://huggingface.co/microsoft/deberta-large/resolve/main/vocab.json''',
        '''microsoft/deberta-xlarge''': '''https://huggingface.co/microsoft/deberta-xlarge/resolve/main/vocab.json''',
        '''microsoft/deberta-base-mnli''': '''https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/vocab.json''',
        '''microsoft/deberta-large-mnli''': '''https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/vocab.json''',
        '''microsoft/deberta-xlarge-mnli''': (
            '''https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/vocab.json'''
        ),
    },
    '''merges_file''': {
        '''microsoft/deberta-base''': '''https://huggingface.co/microsoft/deberta-base/resolve/main/merges.txt''',
        '''microsoft/deberta-large''': '''https://huggingface.co/microsoft/deberta-large/resolve/main/merges.txt''',
        '''microsoft/deberta-xlarge''': '''https://huggingface.co/microsoft/deberta-xlarge/resolve/main/merges.txt''',
        '''microsoft/deberta-base-mnli''': '''https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/merges.txt''',
        '''microsoft/deberta-large-mnli''': '''https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/merges.txt''',
        '''microsoft/deberta-xlarge-mnli''': (
            '''https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/merges.txt'''
        ),
    },
}

_a									=  {
    '''microsoft/deberta-base''': 5_1_2,
    '''microsoft/deberta-large''': 5_1_2,
    '''microsoft/deberta-xlarge''': 5_1_2,
    '''microsoft/deberta-base-mnli''': 5_1_2,
    '''microsoft/deberta-large-mnli''': 5_1_2,
    '''microsoft/deberta-xlarge-mnli''': 5_1_2,
}

_a									=  {
    '''microsoft/deberta-base''': {'''do_lower_case''': False},
    '''microsoft/deberta-large''': {'''do_lower_case''': False},
}






class 				A_					(						snake_case__   ):
     _lowercase     :	Any        =      VOCAB_FILES_NAMES
     _lowercase     :	Tuple        =      PRETRAINED_VOCAB_FILES_MAP
     _lowercase     :	Optional[Any]        =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     _lowercase     :	Optional[Any]        =      ['input_ids', 'attention_mask', 'token_type_ids']
     _lowercase     :	Tuple        =      DebertaTokenizer


     def __init__(				self     :						Optional[Any]     ,    UpperCAmelCase     :						List[Any]=None     ,    UpperCAmelCase     :						Dict=None     ,    UpperCAmelCase     :						List[str]=None     ,    UpperCAmelCase     :						List[str]="replace"     ,    UpperCAmelCase     :						Dict="[CLS]"     ,    UpperCAmelCase     :						Optional[Any]="[SEP]"     ,    UpperCAmelCase     :						List[Any]="[SEP]"     ,    UpperCAmelCase     :						str="[CLS]"     ,    UpperCAmelCase     :						Optional[Any]="[UNK]"     ,    UpperCAmelCase     :						Optional[int]="[PAD]"     ,    UpperCAmelCase     :						Tuple="[MASK]"     ,    UpperCAmelCase     :						Dict=False     ,    **UpperCAmelCase     :						Any     ,    )				->      Union[str, Any]:
      super().__init__(
          UpperCAmelCase     ,    UpperCAmelCase     ,    tokenizer_file=UpperCAmelCase     ,    errors=UpperCAmelCase     ,    bos_token=UpperCAmelCase     ,    eos_token=UpperCAmelCase     ,    unk_token=UpperCAmelCase     ,    sep_token=UpperCAmelCase     ,    cls_token=UpperCAmelCase     ,    pad_token=UpperCAmelCase     ,    mask_token=UpperCAmelCase     ,    add_prefix_space=UpperCAmelCase     ,    **UpperCAmelCase     ,    )
      __lowerCAmelCase:  Optional[int]        = kwargs.pop('add_bos_token'     ,    UpperCAmelCase   )

      __lowerCAmelCase:  str        = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()   )
      if pre_tok_state.get('add_prefix_space'     ,    UpperCAmelCase   ) != add_prefix_space:
       __lowerCAmelCase:  Optional[int]        = getattr(UpperCAmelCase     ,    pre_tok_state.pop('type'   )   )
       __lowerCAmelCase:  Dict        = add_prefix_space
       __lowerCAmelCase:  Dict        = pre_tok_class(**UpperCAmelCase   )

      __lowerCAmelCase:  Optional[int]        = add_prefix_space


     @property
     def     UpperCAmelCase    (				self     :						List[str]   )				->      str:
      if self._mask_token is None:
       if self.verbose:
        logger.error('Using mask_token, but it is not set yet.'   )
       return None
      return str(self._mask_token   )


     @mask_token.setter
     def     UpperCAmelCase    (				self     :						Tuple     ,    UpperCAmelCase     :						Tuple   )				->      Any:
      __lowerCAmelCase:  List[str]        = AddedToken(UpperCAmelCase     ,    lstrip=UpperCAmelCase     ,    rstrip=UpperCAmelCase   ) if isinstance(UpperCAmelCase     ,    UpperCAmelCase   ) else value
      __lowerCAmelCase:  Dict        = value


     def     UpperCAmelCase    (				self     :						str     ,    UpperCAmelCase     :						List[int]     ,    UpperCAmelCase     :						Optional[List[int]] = None   )				->      List[int]:
      if token_ids_a is None:
       return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
      __lowerCAmelCase:  Optional[Any]        = [self.cls_token_id]
      __lowerCAmelCase:  Any        = [self.sep_token_id]
      return cls + token_ids_a + sep + token_ids_a + sep


     def     UpperCAmelCase    (				self     :						Union[str, Any]     ,    UpperCAmelCase     :						List[int]     ,    UpperCAmelCase     :						Optional[List[int]] = None   )				->      List[int]:
      __lowerCAmelCase:  List[str]        = [self.sep_token_id]
      __lowerCAmelCase:  str        = [self.cls_token_id]

      if token_ids_a is None:
       return len(cls + token_ids_a + sep   ) * [0]
      return len(cls + token_ids_a + sep   ) * [0] + len(token_ids_a + sep   ) * [1]


     def     UpperCAmelCase    (				self     :						Any     ,    *UpperCAmelCase     :						Any     ,    **UpperCAmelCase     :						List[Any]   )				->      BatchEncoding:
      __lowerCAmelCase:  Any        = kwargs.get('is_split_into_words'     ,    UpperCAmelCase   )
      assert self.add_prefix_space or not is_split_into_words, (
          F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
          "to use it with pretokenized inputs."
      )

      return super()._batch_encode_plus(*UpperCAmelCase     ,    **UpperCAmelCase   )


     def     UpperCAmelCase    (				self     :						Optional[int]     ,    *UpperCAmelCase     :						List[Any]     ,    **UpperCAmelCase     :						List[Any]   )				->      BatchEncoding:
      __lowerCAmelCase:  Union[str, Any]        = kwargs.get('is_split_into_words'     ,    UpperCAmelCase   )

      assert self.add_prefix_space or not is_split_into_words, (
          F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
          "to use it with pretokenized inputs."
      )

      return super()._encode_plus(*UpperCAmelCase     ,    **UpperCAmelCase   )


     def     UpperCAmelCase    (				self     :						Dict     ,    UpperCAmelCase     :						str     ,    UpperCAmelCase     :						Optional[str] = None   )				->      Tuple[str]:
      __lowerCAmelCase:  Any        = self._tokenizer.model.save(UpperCAmelCase     ,    name=UpperCAmelCase   )
      return tuple(UpperCAmelCase   )


     def     UpperCAmelCase    (				self     :						List[Any]     ,    UpperCAmelCase     :						"Conversation"   )				->      List[int]:
      __lowerCAmelCase:  int        = []
      for is_user, text in conversation.iter_texts():
       input_ids.extend(self.encode(UpperCAmelCase     ,    add_special_tokens=UpperCAmelCase   ) + [self.eos_token_id]   )

      if len(UpperCAmelCase   ) > self.model_max_length:
       __lowerCAmelCase:  Optional[int]        = input_ids[-self.model_max_length :]
      return input_ids








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
_a									=  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					(			SCREAMING_SNAKE_CASE						:     Dict       ,   SCREAMING_SNAKE_CASE						:     Optional[int]       ,   SCREAMING_SNAKE_CASE						:     Tuple=0						)       ->       Optional[int]:

 """simple docstring"""






 __lowerCAmelCase:  List[str]        = (size, size) if isinstance(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						) else size
 __lowerCAmelCase      ,				__lowerCAmelCase:  List[Any]        = img.size
 __lowerCAmelCase:  Union[str, Any]        = size[1] - original_height if original_height < size[1] else 0
 __lowerCAmelCase:  Tuple        = size[0] - original_width if original_width < size[0] else 0
 __lowerCAmelCase:  Optional[int]        = functional.pad(SCREAMING_SNAKE_CASE       ,   (0, 0, pad_width, pad_height)       ,   fill=SCREAMING_SNAKE_CASE						)
 return img






class 				A_					:


     def __init__(				self     :						List[Any]     ,    UpperCAmelCase     :						int   )				->      Any:
      __lowerCAmelCase:  str        = transforms


     def __call__(				self     :						Dict     ,    UpperCAmelCase     :						str     ,    UpperCAmelCase     :						Optional[int]   )				->      Dict:
      for t in self.transforms:
       __lowerCAmelCase      ,				__lowerCAmelCase:  Optional[Any]        = t(UpperCAmelCase     ,    UpperCAmelCase   )
      return image, target







class 				A_					:


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


     def __call__(				self     :						int     ,    UpperCAmelCase     :						Optional[Any]     ,    UpperCAmelCase     :						List[str]   )				->      Dict:
      return image, target







class 				A_					:


     def __init__(				self     :						int     ,    UpperCAmelCase     :						Any   )				->      Optional[int]:
      __lowerCAmelCase:  int        = size


     def __call__(				self     :						Optional[int]     ,    UpperCAmelCase     :						Dict     ,    UpperCAmelCase     :						Optional[Any]   )				->      Dict:
      __lowerCAmelCase:  Dict        = functional.resize(UpperCAmelCase     ,    self.size   )
      __lowerCAmelCase:  Optional[int]        = functional.resize(UpperCAmelCase     ,    self.size     ,    interpolation=transforms.InterpolationMode.NEAREST   )
      return image, target







class 				A_					:


     def __init__(				self     :						Optional[int]     ,    UpperCAmelCase     :						str     ,    UpperCAmelCase     :						str=None   )				->      Dict:
      __lowerCAmelCase:  Optional[int]        = min_size
      if max_size is None:
       __lowerCAmelCase:  str        = min_size
      __lowerCAmelCase:  str        = max_size


     def __call__(				self     :						Optional[Any]     ,    UpperCAmelCase     :						Union[str, Any]     ,    UpperCAmelCase     :						Tuple   )				->      Union[str, Any]:
      __lowerCAmelCase:  Optional[Any]        = random.randint(self.min_size     ,    self.max_size   )
      __lowerCAmelCase:  List[str]        = functional.resize(UpperCAmelCase     ,    UpperCAmelCase   )
      __lowerCAmelCase:  Optional[Any]        = functional.resize(UpperCAmelCase     ,    UpperCAmelCase     ,    interpolation=transforms.InterpolationMode.NEAREST   )
      return image, target







class 				A_					:


     def __init__(				self     :						Union[str, Any]     ,    UpperCAmelCase     :						List[Any]   )				->      int:
      __lowerCAmelCase:  List[Any]        = size if isinstance(UpperCAmelCase     ,    UpperCAmelCase   ) else (size, size)


     def __call__(				self     :						Dict     ,    UpperCAmelCase     :						List[Any]     ,    UpperCAmelCase     :						Dict   )				->      Union[str, Any]:
      __lowerCAmelCase:  Optional[Any]        = pad_if_smaller(UpperCAmelCase     ,    self.size   )
      __lowerCAmelCase:  str        = pad_if_smaller(UpperCAmelCase     ,    self.size     ,    fill=2_5_5   )
      __lowerCAmelCase:  List[Any]        = transforms.RandomCrop.get_params(UpperCAmelCase     ,    self.size   )
      __lowerCAmelCase:  Union[str, Any]        = functional.crop(UpperCAmelCase     ,    *UpperCAmelCase   )
      __lowerCAmelCase:  Optional[Any]        = functional.crop(UpperCAmelCase     ,    *UpperCAmelCase   )
      return image, target







class 				A_					:


     def __init__(				self     :						Optional[int]     ,    UpperCAmelCase     :						Optional[int]   )				->      Optional[Any]:
      __lowerCAmelCase:  Optional[Any]        = flip_prob


     def __call__(				self     :						List[Any]     ,    UpperCAmelCase     :						Any     ,    UpperCAmelCase     :						Union[str, Any]   )				->      Union[str, Any]:
      if random.random() < self.flip_prob:
       __lowerCAmelCase:  Optional[int]        = functional.hflip(UpperCAmelCase   )
       __lowerCAmelCase:  Dict        = functional.hflip(UpperCAmelCase   )
      return image, target







class 				A_					:


     def __call__(				self     :						Optional[Any]     ,    UpperCAmelCase     :						Any     ,    UpperCAmelCase     :						int   )				->      Any:
      __lowerCAmelCase:  List[Any]        = functional.pil_to_tensor(UpperCAmelCase   )
      __lowerCAmelCase:  Tuple        = torch.as_tensor(np.array(UpperCAmelCase   )     ,    dtype=torch.intaa   )
      return image, target







class 				A_					:


     def __init__(				self     :						str     ,    UpperCAmelCase     :						Tuple   )				->      Any:
      __lowerCAmelCase:  int        = dtype


     def __call__(				self     :						Optional[Any]     ,    UpperCAmelCase     :						str     ,    UpperCAmelCase     :						str   )				->      List[Any]:
      __lowerCAmelCase:  Optional[int]        = functional.convert_image_dtype(UpperCAmelCase     ,    self.dtype   )
      return image, target







class 				A_					:


     def __init__(				self     :						Optional[int]     ,    UpperCAmelCase     :						Tuple     ,    UpperCAmelCase     :						Optional[Any]   )				->      Tuple:
      __lowerCAmelCase:  Optional[int]        = mean
      __lowerCAmelCase:  Optional[Any]        = std


     def __call__(				self     :						Union[str, Any]     ,    UpperCAmelCase     :						str     ,    UpperCAmelCase     :						Optional[int]   )				->      str:
      __lowerCAmelCase:  Tuple        = functional.normalize(UpperCAmelCase     ,    mean=self.mean     ,    std=self.std   )
      return image, target







class 				A_					:


     def __call__(				self     :						List[Any]     ,    UpperCAmelCase     :						Dict     ,    UpperCAmelCase     :						List[str]   )				->      List[Any]:
      if not isinstance(UpperCAmelCase     ,    np.ndarray   ):
       __lowerCAmelCase:  Union[str, Any]        = np.array(UpperCAmelCase   ).astype(np.uinta   )
      # avoid using underflow conversion
      __lowerCAmelCase:  Dict        = 2_5_5
      __lowerCAmelCase:  List[Any]        = target - 1
      __lowerCAmelCase:  List[str]        = 2_5_5

      __lowerCAmelCase:  Tuple        = Image.fromarray(UpperCAmelCase   )
      return image, target







@dataclass
class 				A_					:
     _lowercase     :	Optional[str]        =      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).'
         }				,      )
     _lowercase     :	Optional[str]        =      field(
         default=snake_case__				,      metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}   )
     _lowercase     :	Optional[float]        =      field(
         default=0.15				,      metadata={'help': 'Percent to split off of train for validation.'}   )
     _lowercase     :	Optional[int]        =      field(
         default=snake_case__				,      metadata={
             'help': (
                 'For debugging purposes or quicker training, truncate the number of training examples to this '
                 'value if set.'
             )
         }				,      )
     _lowercase     :	Optional[int]        =      field(
         default=snake_case__				,      metadata={
             'help': (
                 'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
                 'value if set.'
             )
         }				,      )
     _lowercase     :	Optional[bool]        =      field(
         default=snake_case__				,      metadata={'help': 'Whether or not to reduce all labels by 1 and replace background by 255.'}				,      )


     def     UpperCAmelCase    (				self     :						Union[str, Any]   )				->      Optional[Any]:
      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 				A_					:
     _lowercase     :	str        =      field(
         default='nvidia/mit-b0'				,      metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}				,      )
     _lowercase     :	Optional[str]        =      field(
         default=snake_case__				,      metadata={'help': 'Pretrained config name or path if not the same as model_name'}   )
     _lowercase     :	Optional[str]        =      field(
         default=snake_case__				,      metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'}   )
     _lowercase     :	str        =      field(
         default='main'				,      metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}				,      )
     _lowercase     :	str        =      field(default=snake_case__				,      metadata={'help': 'Name or path of preprocessor config.'}   )
     _lowercase     :	bool        =      field(
         default=snake_case__				,      metadata={
             'help': (
                 'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
                 'with private models).'
             )
         }				,      )







def _a					(			)       ->       Any:

 """simple docstring"""






 __lowerCAmelCase:  Any        = 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.
  __lowerCAmelCase      ,				__lowerCAmelCase      ,				__lowerCAmelCase:  Tuple        = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
 else:
  __lowerCAmelCase      ,				__lowerCAmelCase      ,				__lowerCAmelCase:  Optional[Any]        = 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'       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)

 # 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()

 __lowerCAmelCase:  Any        = training_args.get_process_log_level()
 logger.setLevel(SCREAMING_SNAKE_CASE						)
 transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE						)
 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.
 __lowerCAmelCase:  Optional[Any]        = None
 if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
  __lowerCAmelCase:  Optional[int]        = 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
 __lowerCAmelCase:  List[str]        = 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:
  __lowerCAmelCase:  Union[str, Any]        = dataset.rename_columns({'pixel_values': 'image'}						)
 if "annotation" in dataset["train"].column_names:
  __lowerCAmelCase:  Tuple        = dataset.rename_columns({'annotation': 'label'}						)

 # If we don't have a validation split, split off a percentage of train as validation.
 __lowerCAmelCase:  Dict        = None if 'validation' in dataset.keys() else data_args.train_val_split
 if isinstance(data_args.train_val_split       ,   SCREAMING_SNAKE_CASE						) and data_args.train_val_split > 0.0:
  __lowerCAmelCase:  List[Any]        = dataset['train'].train_test_split(data_args.train_val_split						)
  __lowerCAmelCase:  Tuple        = split['train']
  __lowerCAmelCase:  int        = 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":
  __lowerCAmelCase:  Union[str, Any]        = 'huggingface/label-files'
  __lowerCAmelCase:  Tuple        = 'ade20k-id2label.json'
 else:
  __lowerCAmelCase:  Any        = data_args.dataset_name
  __lowerCAmelCase:  Any        = 'id2label.json'
 __lowerCAmelCase:  Dict        = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   repo_type='dataset'						)       ,   'r'						)						)
 __lowerCAmelCase:  Optional[Any]        = {int(SCREAMING_SNAKE_CASE						): v for k, v in idalabel.items()}
 __lowerCAmelCase:  List[str]        = {v: str(SCREAMING_SNAKE_CASE						) for k, v in idalabel.items()}

 # Load the mean IoU metric from the datasets package
 __lowerCAmelCase:  List[str]        = 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(SCREAMING_SNAKE_CASE						:     str						):
  __lowerCAmelCase      ,				__lowerCAmelCase:  List[Any]        = eval_pred
  __lowerCAmelCase:  Dict        = torch.from_numpy(SCREAMING_SNAKE_CASE						)
  # scale the logits to the size of the label
  __lowerCAmelCase:  Union[str, Any]        = nn.functional.interpolate(
      SCREAMING_SNAKE_CASE       ,   size=labels.shape[-2:]       ,   mode='bilinear'       ,   align_corners=SCREAMING_SNAKE_CASE       ,   ).argmax(dim=1						)

  __lowerCAmelCase:  Tuple        = logits_tensor.detach().cpu().numpy()
  __lowerCAmelCase:  Dict        = metric.compute(
      predictions=SCREAMING_SNAKE_CASE       ,   references=SCREAMING_SNAKE_CASE       ,   num_labels=len(SCREAMING_SNAKE_CASE						)       ,   ignore_index=0       ,   reduce_labels=image_processor.do_reduce_labels       ,   )
  # add per category metrics as individual key-value pairs
  __lowerCAmelCase:  List[str]        = metrics.pop('per_category_accuracy'						).tolist()
  __lowerCAmelCase:  Optional[int]        = metrics.pop('per_category_iou'						).tolist()

  metrics.update({f'''accuracy_{idalabel[i]}''': v for i, v in enumerate(SCREAMING_SNAKE_CASE						)}						)
  metrics.update({f'''iou_{idalabel[i]}''': v for i, v in enumerate(SCREAMING_SNAKE_CASE						)}						)

  return metrics

 __lowerCAmelCase:  Union[str, Any]        = AutoConfig.from_pretrained(
     model_args.config_name or model_args.model_name_or_path       ,   labelaid=SCREAMING_SNAKE_CASE       ,   idalabel=SCREAMING_SNAKE_CASE       ,   cache_dir=model_args.cache_dir       ,   revision=model_args.model_revision       ,   use_auth_token=True if model_args.use_auth_token else None       ,   )
 __lowerCAmelCase:  Union[str, Any]        = AutoModelForSemanticSegmentation.from_pretrained(
     model_args.model_name_or_path       ,   from_tf=bool('.ckpt' in model_args.model_name_or_path						)       ,   config=SCREAMING_SNAKE_CASE       ,   cache_dir=model_args.cache_dir       ,   revision=model_args.model_revision       ,   use_auth_token=True if model_args.use_auth_token else None       ,   )
 __lowerCAmelCase:  Optional[Any]        = 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.
  __lowerCAmelCase:  List[str]        = (image_processor.size['shortest_edge'], image_processor.size['shortest_edge'])
 else:
  __lowerCAmelCase:  str        = (image_processor.size['height'], image_processor.size['width'])
 __lowerCAmelCase:  List[Any]        = Compose(
     [
         ReduceLabels() if data_args.reduce_labels else Identity(),
         RandomCrop(size=SCREAMING_SNAKE_CASE						),
         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)
 __lowerCAmelCase:  Optional[Any]        = Compose(
     [
         ReduceLabels() if data_args.reduce_labels else Identity(),
         Resize(size=SCREAMING_SNAKE_CASE						),
         PILToTensor(),
         ConvertImageDtype(torch.float						),
         Normalize(mean=image_processor.image_mean       ,   std=image_processor.image_std						),
     ]						)

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

  __lowerCAmelCase:  Any        = {}
  __lowerCAmelCase:  List[str]        = torch.stack(SCREAMING_SNAKE_CASE						)
  __lowerCAmelCase:  Dict        = torch.stack(SCREAMING_SNAKE_CASE						)

  return encoding

 def preprocess_val(SCREAMING_SNAKE_CASE						:     List[str]						):
  __lowerCAmelCase:  Optional[Any]        = []
  __lowerCAmelCase:  Optional[int]        = []
  for image, target in zip(example_batch['image']       ,   example_batch['label']						):
   __lowerCAmelCase      ,				__lowerCAmelCase:  Optional[int]        = val_transforms(image.convert('RGB'						)       ,   SCREAMING_SNAKE_CASE						)
   pixel_values.append(SCREAMING_SNAKE_CASE						)
   labels.append(SCREAMING_SNAKE_CASE						)

  __lowerCAmelCase:  Any        = {}
  __lowerCAmelCase:  Any        = torch.stack(SCREAMING_SNAKE_CASE						)
  __lowerCAmelCase:  Tuple        = torch.stack(SCREAMING_SNAKE_CASE						)

  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:
   __lowerCAmelCase:  int        = (
       dataset['train'].shuffle(seed=training_args.seed						).select(range(data_args.max_train_samples						)						)
   )
  # Set the training transforms
  dataset["train"].set_transform(SCREAMING_SNAKE_CASE						)

 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:
   __lowerCAmelCase:  Optional[Any]        = (
       dataset['validation'].shuffle(seed=training_args.seed						).select(range(data_args.max_eval_samples						)						)
   )
  # Set the validation transforms
  dataset["validation"].set_transform(SCREAMING_SNAKE_CASE						)

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

 # Training
 if training_args.do_train:
  __lowerCAmelCase:  Tuple        = None
  if training_args.resume_from_checkpoint is not None:
   __lowerCAmelCase:  Tuple        = training_args.resume_from_checkpoint
  elif last_checkpoint is not None:
   __lowerCAmelCase:  Optional[int]        = last_checkpoint
  __lowerCAmelCase:  List[str]        = trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE						)
  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:
  __lowerCAmelCase:  List[str]        = trainer.evaluate()
  trainer.log_metrics('eval'       ,   SCREAMING_SNAKE_CASE						)
  trainer.save_metrics('eval'       ,   SCREAMING_SNAKE_CASE						)

 # Write model card and (optionally) push to hub
 __lowerCAmelCase:  List[Any]        = {
     '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(**SCREAMING_SNAKE_CASE						)
 else:
  trainer.create_model_card(**SCREAMING_SNAKE_CASE						)


if __name__ == "__main__":
  main()





