code: 
  
  
  
  
  
  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
  _lowercase		:     List[Any] 					=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 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__=0	):
  		lowerCamelCase_  :    List[str]   	=			(size, size) if isinstance(lowerCAmelCase__       ,lowerCAmelCase__	) else size
  		lowerCamelCase_	,			lowerCamelCase_  :    str   	=			img.size
  		lowerCamelCase_  :    Tuple   	=			size[1] - original_height if original_height < size[1] else 0
  		lowerCamelCase_  :    Any   	=			size[0] - original_width if original_width < size[0] else 0
  		lowerCamelCase_  :    Optional[Any]   	=			functional.pad(lowerCAmelCase__       ,(0, 0, pad_width, pad_height)       ,fill=lowerCAmelCase__	)
  		return img
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    str					,			lowerCamelCase    :    Optional[int]	):
  							lowerCamelCase_  :    Tuple   	=			transforms
  
  
  
  
  
  					def __call__(		self    :    Any					,			lowerCamelCase    :    Optional[Any]					,			lowerCamelCase    :    Union[str, Any]	):
  							for t in self.transforms:
  									lowerCamelCase_	,			lowerCamelCase_  :    List[str]   	=			t(lowerCamelCase					,			lowerCamelCase	)
  							return image, target
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    Optional[Any]	):
  							pass
  
  
  
  
  
  					def __call__(		self    :    Tuple					,			lowerCamelCase    :    Optional[int]					,			lowerCamelCase    :    int	):
  							return image, target
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    List[Any]					,			lowerCamelCase    :    Dict	):
  							lowerCamelCase_  :    Union[str, Any]   	=			size
  
  
  
  
  
  					def __call__(		self    :    Union[str, Any]					,			lowerCamelCase    :    Tuple					,			lowerCamelCase    :    int	):
  							lowerCamelCase_  :    str   	=			functional.resize(lowerCamelCase					,			self.size	)
  							lowerCamelCase_  :    Any   	=			functional.resize(lowerCamelCase					,			self.size					,			interpolation=transforms.InterpolationMode.NEAREST	)
  							return image, target
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    List[Any]					,			lowerCamelCase    :    List[str]					,			lowerCamelCase    :    Union[str, Any]=None	):
  							lowerCamelCase_  :    List[Any]   	=			min_size
  							if max_size is None:
  									lowerCamelCase_  :    Tuple   	=			min_size
  							lowerCamelCase_  :    str   	=			max_size
  
  
  
  
  
  					def __call__(		self    :    Optional[int]					,			lowerCamelCase    :    Optional[Any]					,			lowerCamelCase    :    Optional[int]	):
  							lowerCamelCase_  :    Optional[Any]   	=			random.randint(self.min_size					,			self.max_size	)
  							lowerCamelCase_  :    Any   	=			functional.resize(lowerCamelCase					,			lowerCamelCase	)
  							lowerCamelCase_  :    List[str]   	=			functional.resize(lowerCamelCase					,			lowerCamelCase					,			interpolation=transforms.InterpolationMode.NEAREST	)
  							return image, target
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    Any					,			lowerCamelCase    :    Union[str, Any]	):
  							lowerCamelCase_  :    Tuple   	=			size if isinstance(lowerCamelCase					,			lowerCamelCase	) else (size, size)
  
  
  
  
  
  					def __call__(		self    :    Tuple					,			lowerCamelCase    :    Dict					,			lowerCamelCase    :    Any	):
  							lowerCamelCase_  :    Any   	=			pad_if_smaller(lowerCamelCase					,			self.size	)
  							lowerCamelCase_  :    Optional[int]   	=			pad_if_smaller(lowerCamelCase					,			self.size					,			fill=2_55	)
  							lowerCamelCase_  :    int   	=			transforms.RandomCrop.get_params(lowerCamelCase					,			self.size	)
  							lowerCamelCase_  :    Union[str, Any]   	=			functional.crop(lowerCamelCase					,			*lowerCamelCase	)
  							lowerCamelCase_  :    Union[str, Any]   	=			functional.crop(lowerCamelCase					,			*lowerCamelCase	)
  							return image, target
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    Optional[Any]					,			lowerCamelCase    :    int	):
  							lowerCamelCase_  :    List[Any]   	=			flip_prob
  
  
  
  
  
  					def __call__(		self    :    int					,			lowerCamelCase    :    int					,			lowerCamelCase    :    List[str]	):
  							if random.random() < self.flip_prob:
  									lowerCamelCase_  :    List[str]   	=			functional.hflip(lowerCamelCase	)
  									lowerCamelCase_  :    List[Any]   	=			functional.hflip(lowerCamelCase	)
  							return image, target
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __call__(		self    :    str					,			lowerCamelCase    :    int					,			lowerCamelCase    :    Dict	):
  							lowerCamelCase_  :    Dict   	=			functional.pil_to_tensor(lowerCamelCase	)
  							lowerCamelCase_  :    List[str]   	=			torch.as_tensor(np.array(lowerCamelCase	)					,			dtype=torch.intaa	)
  							return image, target
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    int					,			lowerCamelCase    :    Optional[Any]	):
  							lowerCamelCase_  :    str   	=			dtype
  
  
  
  
  
  					def __call__(		self    :    Optional[Any]					,			lowerCamelCase    :    int					,			lowerCamelCase    :    Any	):
  							lowerCamelCase_  :    Optional[Any]   	=			functional.convert_image_dtype(lowerCamelCase					,			self.dtype	)
  							return image, target
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    Optional[Any]					,			lowerCamelCase    :    int					,			lowerCamelCase    :    str	):
  							lowerCamelCase_  :    Optional[Any]   	=			mean
  							lowerCamelCase_  :    Any   	=			std
  
  
  
  
  
  					def __call__(		self    :    str					,			lowerCamelCase    :    Dict					,			lowerCamelCase    :    Optional[Any]	):
  							lowerCamelCase_  :    Optional[Any]   	=			functional.normalize(lowerCamelCase					,			mean=self.mean					,			std=self.std	)
  							return image, target
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __call__(		self    :    List[Any]					,			lowerCamelCase    :    Any					,			lowerCamelCase    :    List[Any]	):
  							if not isinstance(lowerCamelCase					,			np.ndarray	):
  									lowerCamelCase_  :    Tuple   	=			np.array(lowerCamelCase	).astype(np.uinta	)
  							# avoid using underflow conversion
  							lowerCamelCase_  :    Union[str, Any]   	=			2_55
  							lowerCamelCase_  :    Union[str, Any]   	=			target - 1
  							lowerCamelCase_  :    Union[str, Any]   	=			2_55
  
  							lowerCamelCase_  :    List[Any]   	=			Image.fromarray(lowerCamelCase	)
  							return image, target
  
  
  
  
  
  
  @dataclass
  class 	UpperCamelCase_     :
  					_a			:	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).'
  					    }     ,    )
  					_a			:	Optional[str]							=				field(
  					    default=snake_case__     ,    metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}       )
  					_a			:	Optional[float]							=				field(
  					    default=0.15     ,    metadata={'help': 'Percent to split off of train for validation.'}       )
  					_a			:	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.'
  					        )
  					    }     ,    )
  					_a			:	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.'
  					        )
  					    }     ,    )
  					_a			:	Optional[bool]							=				field(
  					    default=snake_case__     ,    metadata={'help': 'Whether or not to reduce all labels by 1 and replace background by 255.'}     ,    )
  
  
  
  					def      __a    (		self    :    Union[str, 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 	UpperCamelCase_     :
  					_a			:	str							=				field(
  					    default='nvidia/mit-b0'     ,    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}     ,    )
  					_a			:	Optional[str]							=				field(
  					    default=snake_case__     ,    metadata={'help': 'Pretrained config name or path if not the same as model_name'}       )
  					_a			:	Optional[str]							=				field(
  					    default=snake_case__     ,    metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'}       )
  					_a			:	str							=				field(
  					    default='main'     ,    metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}     ,    )
  					_a			:	str							=				field(default=snake_case__     ,    metadata={'help': 'Name or path of preprocessor config.'}       )
  					_a			:	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 		_SCREAMING_SNAKE_CASE    (   ):
  		# 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.
  
  		lowerCamelCase_  :    List[str]   	=			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_  :    int   	=			parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]	)	)
  		else:
  				lowerCamelCase_	,			lowerCamelCase_	,			lowerCamelCase_  :    Dict   	=			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'       ,lowerCAmelCase__       ,lowerCAmelCase__	)
  
  		# 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_  :    List[Any]   	=			training_args.get_process_log_level()
  		logger.setLevel(lowerCAmelCase__	)
  		transformers.utils.logging.set_verbosity(lowerCAmelCase__	)
  		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_  :    Union[str, Any]   	=			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_  :    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_  :    str   	=			dataset.rename_columns({'pixel_values': 'image'}	)
  		if "annotation" in dataset["train"].column_names:
  				lowerCamelCase_  :    int   	=			dataset.rename_columns({'annotation': 'label'}	)
  
  		# If we don't have a validation split, split off a percentage of train as validation.
  		lowerCamelCase_  :    List[Any]   	=			None if 'validation' in dataset.keys() else data_args.train_val_split
  		if isinstance(data_args.train_val_split       ,lowerCAmelCase__	) and data_args.train_val_split > 0.0:
  				lowerCamelCase_  :    Optional[int]   	=			dataset['train'].train_test_split(data_args.train_val_split	)
  				lowerCamelCase_  :    str   	=			split['train']
  				lowerCamelCase_  :    Any   	=			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_  :    Optional[Any]   	=			'huggingface/label-files'
  				lowerCamelCase_  :    List[str]   	=			'ade20k-id2label.json'
  		else:
  				lowerCamelCase_  :    Tuple   	=			data_args.dataset_name
  				lowerCamelCase_  :    Optional[Any]   	=			'id2label.json'
  		lowerCamelCase_  :    int   	=			json.load(open(hf_hub_download(lowerCAmelCase__       ,lowerCAmelCase__       ,repo_type='dataset'	)       ,'r'	)	)
  		lowerCamelCase_  :    Dict   	=			{int(lowerCAmelCase__	): v for k, v in idalabel.items()}
  		lowerCamelCase_  :    str   	=			{v: str(lowerCAmelCase__	) for k, v in idalabel.items()}
  
  		# Load the mean IoU metric from the datasets package
  		lowerCamelCase_  :    Optional[int]   	=			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(lowerCAmelCase__	):
  				lowerCamelCase_	,			lowerCamelCase_  :    List[Any]   	=			eval_pred
  				lowerCamelCase_  :    str   	=			torch.from_numpy(lowerCAmelCase__	)
  				# scale the logits to the size of the label
  				lowerCamelCase_  :    int   	=			nn.functional.interpolate(
  				    lowerCAmelCase__       ,size=labels.shape[-2:]       ,mode='bilinear'       ,align_corners=lowerCAmelCase__       ,).argmax(dim=1	)
  
  				lowerCamelCase_  :    int   	=			logits_tensor.detach().cpu().numpy()
  				lowerCamelCase_  :    Tuple   	=			metric.compute(
  				    predictions=lowerCAmelCase__       ,references=lowerCAmelCase__       ,num_labels=len(lowerCAmelCase__	)       ,ignore_index=0       ,reduce_labels=image_processor.do_reduce_labels       ,)
  				# add per category metrics as individual key-value pairs
  				lowerCamelCase_  :    Optional[Any]   	=			metrics.pop('per_category_accuracy'	).tolist()
  				lowerCamelCase_  :    str   	=			metrics.pop('per_category_iou'	).tolist()
  
  				metrics.update({F"accuracy_{idalabel[i]}": v for i, v in enumerate(lowerCAmelCase__	)}	)
  				metrics.update({F"iou_{idalabel[i]}": v for i, v in enumerate(lowerCAmelCase__	)}	)
  
  				return metrics
  
  		lowerCamelCase_  :    List[str]   	=			AutoConfig.from_pretrained(
  		    model_args.config_name or model_args.model_name_or_path       ,labelaid=lowerCAmelCase__       ,idalabel=lowerCAmelCase__       ,cache_dir=model_args.cache_dir       ,revision=model_args.model_revision       ,use_auth_token=True if model_args.use_auth_token else None       ,)
  		lowerCamelCase_  :    int   	=			AutoModelForSemanticSegmentation.from_pretrained(
  		    model_args.model_name_or_path       ,from_tf=bool('.ckpt' in model_args.model_name_or_path	)       ,config=lowerCAmelCase__       ,cache_dir=model_args.cache_dir       ,revision=model_args.model_revision       ,use_auth_token=True if model_args.use_auth_token else None       ,)
  		lowerCamelCase_  :    Tuple   	=			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_  :    int   	=			(image_processor.size['shortest_edge'], image_processor.size['shortest_edge'])
  		else:
  				lowerCamelCase_  :    Optional[Any]   	=			(image_processor.size['height'], image_processor.size['width'])
  		lowerCamelCase_  :    Any   	=			Compose(
  		    [
  		        ReduceLabels() if data_args.reduce_labels else Identity(),
  		        RandomCrop(size=lowerCAmelCase__	),
  		        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_  :    Any   	=			Compose(
  		    [
  		        ReduceLabels() if data_args.reduce_labels else Identity(),
  		        Resize(size=lowerCAmelCase__	),
  		        PILToTensor(),
  		        ConvertImageDtype(torch.float	),
  		        Normalize(mean=image_processor.image_mean       ,std=image_processor.image_std	),
  		    ]	)
  
  		def preprocess_train(lowerCAmelCase__	):
  				lowerCamelCase_  :    List[Any]   	=			[]
  				lowerCamelCase_  :    Optional[int]   	=			[]
  				for image, target in zip(example_batch['image']       ,example_batch['label']	):
  						lowerCamelCase_	,			lowerCamelCase_  :    str   	=			train_transforms(image.convert('RGB'	)       ,lowerCAmelCase__	)
  						pixel_values.append(lowerCAmelCase__	)
  						labels.append(lowerCAmelCase__	)
  
  				lowerCamelCase_  :    Tuple   	=			{}
  				lowerCamelCase_  :    List[str]   	=			torch.stack(lowerCAmelCase__	)
  				lowerCamelCase_  :    str   	=			torch.stack(lowerCAmelCase__	)
  
  				return encoding
  
  		def preprocess_val(lowerCAmelCase__	):
  				lowerCamelCase_  :    List[str]   	=			[]
  				lowerCamelCase_  :    Optional[int]   	=			[]
  				for image, target in zip(example_batch['image']       ,example_batch['label']	):
  						lowerCamelCase_	,			lowerCamelCase_  :    str   	=			val_transforms(image.convert('RGB'	)       ,lowerCAmelCase__	)
  						pixel_values.append(lowerCAmelCase__	)
  						labels.append(lowerCAmelCase__	)
  
  				lowerCamelCase_  :    Tuple   	=			{}
  				lowerCamelCase_  :    Optional[int]   	=			torch.stack(lowerCAmelCase__	)
  				lowerCamelCase_  :    int   	=			torch.stack(lowerCAmelCase__	)
  
  				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_  :    Optional[int]   	=			(
  						    dataset['train'].shuffle(seed=training_args.seed	).select(range(data_args.max_train_samples	)	)
  						)
  				# Set the training transforms
  				dataset["train"].set_transform(lowerCAmelCase__	)
  
  		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_  :    List[str]   	=			(
  						    dataset['validation'].shuffle(seed=training_args.seed	).select(range(data_args.max_eval_samples	)	)
  						)
  				# Set the validation transforms
  				dataset["validation"].set_transform(lowerCAmelCase__	)
  
  		# Initalize our trainer
  		lowerCamelCase_  :    List[str]   	=			Trainer(
  		    model=lowerCAmelCase__       ,args=lowerCAmelCase__       ,train_dataset=dataset['train'] if training_args.do_train else None       ,eval_dataset=dataset['validation'] if training_args.do_eval else None       ,compute_metrics=lowerCAmelCase__       ,tokenizer=lowerCAmelCase__       ,data_collator=lowerCAmelCase__       ,)
  
  		# Training
  		if training_args.do_train:
  				lowerCamelCase_  :    Union[str, Any]   	=			None
  				if training_args.resume_from_checkpoint is not None:
  						lowerCamelCase_  :    Dict   	=			training_args.resume_from_checkpoint
  				elif last_checkpoint is not None:
  						lowerCamelCase_  :    List[str]   	=			last_checkpoint
  				lowerCamelCase_  :    Dict   	=			trainer.train(resume_from_checkpoint=lowerCAmelCase__	)
  				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_  :    Optional[Any]   	=			trainer.evaluate()
  				trainer.log_metrics('eval'       ,lowerCAmelCase__	)
  				trainer.save_metrics('eval'       ,lowerCAmelCase__	)
  
  		# Write model card and (optionally) push to hub
  		lowerCamelCase_  :    Optional[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(**lowerCAmelCase__	)
  		else:
  				trainer.create_model_card(**lowerCAmelCase__	)
  
  
  if __name__ == "__main__":
  		main()
  
style_context: 
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    List[Any]					,			lowerCamelCase    :    int	):
  							lowerCamelCase_  :    Union[str, Any]   	=			val
  							# Number of nodes in left subtree
  							lowerCamelCase_  :    Dict   	=			0
  							lowerCamelCase_  :    str   	=			None
  							lowerCamelCase_  :    int   	=			None
  							lowerCamelCase_  :    Dict   	=			None
  
  
  
  
  
  					def      __a    (		self    :    Optional[int]					,			lowerCamelCase    :    List[Any]	):
  							assert self.left_tree_size == other.left_tree_size, "Unequal Sizes of Blocks"
  
  							if self.val < other.val:
  									lowerCamelCase_  :    int   	=			self.right
  									lowerCamelCase_  :    Any   	=			None
  									if self.right:
  											lowerCamelCase_  :    Optional[Any]   	=			other
  									lowerCamelCase_  :    Union[str, Any]   	=			other
  									lowerCamelCase_  :    List[Any]   	=			self.left_tree_size * 2 + 1
  									return self
  							else:
  									lowerCamelCase_  :    str   	=			other.right
  									lowerCamelCase_  :    List[Any]   	=			None
  									if other.right:
  											lowerCamelCase_  :    Union[str, Any]   	=			self
  									lowerCamelCase_  :    Optional[int]   	=			self
  									lowerCamelCase_  :    Optional[int]   	=			other.left_tree_size * 2 + 1
  									return other
  
  
  
  
  
  
  class 	UpperCamelCase_     :
  
  
  
  					def __init__(		self    :    List[str]					,			lowerCamelCase    :    Optional[int]=None					,			lowerCamelCase    :    str=None					,			lowerCamelCase    :    List[Any]=0	):
  							lowerCamelCase_  :    Any   	=			heap_size
  							lowerCamelCase_  :    int   	=			bottom_root
  							lowerCamelCase_  :    Any   	=			min_node
  
  
  
  					def      __a    (		self    :    int					,			lowerCamelCase    :    int	):
  
  							# Empty heaps corner cases
  							if other.size == 0:
  									return None
  							if self.size == 0:
  									lowerCamelCase_  :    List[str]   	=			other.size
  									lowerCamelCase_  :    Tuple   	=			other.bottom_root
  									lowerCamelCase_  :    Tuple   	=			other.min_node
  									return None
  							# Update size
  							lowerCamelCase_  :    Optional[Any]   	=			self.size + other.size
  
  							# Update min.node
  							if self.min_node.val > other.min_node.val:
  									lowerCamelCase_  :    Optional[Any]   	=			other.min_node
  							# Merge
  
  							# Order roots by left_subtree_size
  							lowerCamelCase_  :    Dict   	=			[]
  							lowerCamelCase_	,			lowerCamelCase_  :    Optional[Any]   	=			self.bottom_root, other.bottom_root
  							while i or j:
  									if i and ((not j) or i.left_tree_size < j.left_tree_size):
  											combined_roots_list.append((i, True)	)
  											lowerCamelCase_  :    Tuple   	=			i.parent
  									else:
  											combined_roots_list.append((j, False)	)
  											lowerCamelCase_  :    Optional[Any]   	=			j.parent
          # Insert links between them
  							for i in range(len(lowerCamelCase	) - 1	):
  									if combined_roots_list[i][1] != combined_roots_list[i + 1][1]:
  											lowerCamelCase_  :    Dict   	=			combined_roots_list[i + 1][0]
  											lowerCamelCase_  :    Optional[int]   	=			combined_roots_list[i][0]
          # Consecutively merge roots with same left_tree_size
  							lowerCamelCase_  :    Any   	=			combined_roots_list[0][0]
  							while i.parent:
  									if (
  									    (i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent)
  									) or (
  									    i.left_tree_size == i.parent.left_tree_size
  									    and i.left_tree_size != i.parent.parent.left_tree_size
  									):
  											# Neighbouring Nodes
  											lowerCamelCase_  :    Dict   	=			i.left
  											lowerCamelCase_  :    int   	=			i.parent.parent
  
  											# Merging trees
  											lowerCamelCase_  :    str   	=			i.merge_trees(i.parent	)
  
  											# Updating links
  											lowerCamelCase_  :    Union[str, Any]   	=			previous_node
  											lowerCamelCase_  :    List[Any]   	=			next_node
  											if previous_node:
  													lowerCamelCase_  :    List[str]   	=			i
  											if next_node:
  													lowerCamelCase_  :    Dict   	=			i
  									else:
  											lowerCamelCase_  :    List[str]   	=			i.parent
          # Updating self.bottom_root
  							while i.left:
  									lowerCamelCase_  :    Union[str, Any]   	=			i.left
  							lowerCamelCase_  :    Any   	=			i
  
  							# Update other
  							lowerCamelCase_  :    Optional[int]   	=			self.size
  							lowerCamelCase_  :    Optional[Any]   	=			self.bottom_root
  							lowerCamelCase_  :    str   	=			self.min_node
  
  							# Return the merged heap
  							return self
  
  
  
  					def      __a    (		self    :    Any					,			lowerCamelCase    :    Dict	):
  							if self.size == 0:
  									lowerCamelCase_  :    Tuple   	=			Node(lowerCamelCase	)
  									lowerCamelCase_  :    Optional[int]   	=			1
  									lowerCamelCase_  :    Optional[int]   	=			self.bottom_root
  							else:
  									# Create new node
  									lowerCamelCase_  :    List[Any]   	=			Node(lowerCamelCase	)
  
  									# Update size
  									self.size += 1
  
  									# update min_node
  									if val < self.min_node.val:
  											lowerCamelCase_  :    List[str]   	=			new_node
  									# Put new_node as a bottom_root in heap
  									lowerCamelCase_  :    int   	=			new_node
  									lowerCamelCase_  :    Tuple   	=			self.bottom_root
  									lowerCamelCase_  :    Any   	=			new_node
  
  									# Consecutively merge roots with same left_tree_size
  									while (
  									    self.bottom_root.parent
  									    and self.bottom_root.left_tree_size
  									    == self.bottom_root.parent.left_tree_size
  									):
  											# Next node
  											lowerCamelCase_  :    Any   	=			self.bottom_root.parent.parent
  
  											# Merge
  											lowerCamelCase_  :    int   	=			self.bottom_root.merge_trees(self.bottom_root.parent	)
  
  											# Update Links
  											lowerCamelCase_  :    Dict   	=			next_node
  											lowerCamelCase_  :    Optional[Any]   	=			None
  											if next_node:
  													lowerCamelCase_  :    Union[str, Any]   	=			self.bottom_root
  
  
  
  					def      __a    (		self    :    Dict	):
  							return self.min_node.val
  
  
  
  					def      __a    (		self    :    int	):
  							return self.size == 0
  
  
  
  					def      __a    (		self    :    List[Any]	):
  							lowerCamelCase_  :    Tuple   	=			self.min_node.val
  
  							# Last element in heap corner case
  							if self.size == 1:
  									# Update size
  									lowerCamelCase_  :    Optional[Any]   	=			0
  
  									# Update bottom root
  									lowerCamelCase_  :    Any   	=			None
  
  									# Update min_node
  									lowerCamelCase_  :    List[str]   	=			None
  
  									return min_value
  							# No right subtree corner case
  							# The structure of the tree implies that this should be the bottom root
  							# and there is at least one other root
  							if self.min_node.right is None:
  									# Update size
  									self.size -= 1
  
  									# Update bottom root
  									lowerCamelCase_  :    Union[str, Any]   	=			self.bottom_root.parent
  									lowerCamelCase_  :    Union[str, Any]   	=			None
  
  									# Update min_node
  									lowerCamelCase_  :    Union[str, Any]   	=			self.bottom_root
  									lowerCamelCase_  :    Union[str, Any]   	=			self.bottom_root.parent
  									while i:
  											if i.val < self.min_node.val:
  													lowerCamelCase_  :    Union[str, Any]   	=			i
  											lowerCamelCase_  :    Optional[int]   	=			i.parent
  									return min_value
  							# General case
  							# Find the BinomialHeap of the right subtree of min_node
  							lowerCamelCase_  :    Dict   	=			self.min_node.right
  							lowerCamelCase_  :    Dict   	=			None
  							lowerCamelCase_  :    Tuple   	=			bottom_of_new
  							lowerCamelCase_  :    Dict   	=			1
  
  							# Size, min_node and bottom_root
  							while bottom_of_new.left:
  									lowerCamelCase_  :    Any   	=			size_of_new * 2 + 1
  									lowerCamelCase_  :    Tuple   	=			bottom_of_new.left
  									if bottom_of_new.val < min_of_new.val:
  											lowerCamelCase_  :    int   	=			bottom_of_new
          # Corner case of single root on top left path
  							if (not self.min_node.left) and (not self.min_node.parent):
  									lowerCamelCase_  :    Union[str, Any]   	=			size_of_new
  									lowerCamelCase_  :    Union[str, Any]   	=			bottom_of_new
  									lowerCamelCase_  :    Tuple   	=			min_of_new
  									# print("Single root, multiple nodes case")
  									return min_value
  							# Remaining cases
  							# Construct heap of right subtree
  							lowerCamelCase_  :    Optional[Any]   	=			BinomialHeap(
  							    bottom_root=lowerCamelCase					,			min_node=lowerCamelCase					,			heap_size=lowerCamelCase	)
  
  							# Update size
  							lowerCamelCase_  :    Union[str, Any]   	=			self.size - 1 - size_of_new
  
  							# Neighbour nodes
  							lowerCamelCase_  :    Union[str, Any]   	=			self.min_node.left
  							lowerCamelCase_  :    Optional[Any]   	=			self.min_node.parent
  
  							# Initialize new bottom_root and min_node
  							lowerCamelCase_  :    Optional[int]   	=			previous_node or next_node
  							lowerCamelCase_  :    Tuple   	=			next_node
  
  							# Update links of previous_node and search below for new min_node and
  							# bottom_root
  							if previous_node:
  									lowerCamelCase_  :    Dict   	=			next_node
  
  									# Update bottom_root and search for min_node below
  									lowerCamelCase_  :    int   	=			previous_node
  									lowerCamelCase_  :    Tuple   	=			previous_node
  									while self.bottom_root.left:
  											lowerCamelCase_  :    Union[str, Any]   	=			self.bottom_root.left
  											if self.bottom_root.val < self.min_node.val:
  													lowerCamelCase_  :    Any   	=			self.bottom_root
  							if next_node:
  									lowerCamelCase_  :    Any   	=			previous_node
  
  									# Search for new min_node above min_node
  									lowerCamelCase_  :    List[str]   	=			next_node
  									while i:
  											if i.val < self.min_node.val:
  													lowerCamelCase_  :    List[Any]   	=			i
  											lowerCamelCase_  :    Dict   	=			i.parent
          # Merge heaps
  							self.merge_heaps(lowerCamelCase	)
  
  							return min_value
  
  
  
  					def      __a    (		self    :    Optional[int]	):
  							lowerCamelCase_  :    List[Any]   	=			self.bottom_root
  							while top_root.parent:
  									lowerCamelCase_  :    Tuple   	=			top_root.parent
  							# preorder
  							lowerCamelCase_  :    str   	=			[]
  							self.__traversal(lowerCamelCase					,			lowerCamelCase	)
  							return heap_pre_order
  
  
  
  					def      __a    (		self    :    Dict					,			lowerCamelCase    :    Tuple					,			lowerCamelCase    :    Dict					,			lowerCamelCase    :    List[str]=0	):
  							if curr_node:
  									preorder.append((curr_node.val, level)	)
  									self.__traversal(curr_node.left					,			lowerCamelCase					,			level + 1	)
  									self.__traversal(curr_node.right					,			lowerCamelCase					,			level + 1	)
  							else:
  									preorder.append(('#', level)	)
  
  
  
  
  
  					def __str__(		self    :    List[Any]	):
  							if self.is_empty():
  									return ""
  							lowerCamelCase_  :    str   	=			self.pre_order()
  
  							return "\n".join(('-' * level + str(lowerCamelCase	)) for value, level in preorder_heap	)
  
  
  # Unit Tests
  if __name__ == "__main__":
  		import doctest
  
  		doctest.testmod()
  