






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        _lowerCamelCase(      lowerCAmelCase__					:		Tuple     ,     lowerCAmelCase__					:		str     ,     lowerCAmelCase__					:		Any=0   ):





				'''simple docstring'''







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


class 				__a				:





		'''simple docstring'''



		def __init__(    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						str    				= transforms






		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						for t in self.transforms:
										SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						List[str]    				= t(UpperCamelCase__			,     UpperCamelCase__							)
						return image, target






class 				__a				:





		'''simple docstring'''



		def __init__(    self							):
						pass






		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						return image, target






class 				__a				:





		'''simple docstring'''



		def __init__(    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						str    				= size






		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= functional.resize(UpperCamelCase__			,     self.size							)
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= functional.resize(UpperCamelCase__			,     self.size			,     interpolation=transforms.InterpolationMode.NEAREST							)
						return image, target






class 				__a				:





		'''simple docstring'''



		def __init__(    self			,     UpperCamelCase__			,     UpperCamelCase__=None							):
						SCREAMING_SNAKE_CASE_ :						Tuple    				= min_size
						if max_size is None:
										SCREAMING_SNAKE_CASE_ :						int    				= min_size
						SCREAMING_SNAKE_CASE_ :						Dict    				= max_size






		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						int    				= random.randint(self.min_size			,     self.max_size							)
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= functional.resize(UpperCamelCase__			,     UpperCamelCase__							)
						SCREAMING_SNAKE_CASE_ :						Any    				= functional.resize(UpperCamelCase__			,     UpperCamelCase__			,     interpolation=transforms.InterpolationMode.NEAREST							)
						return image, target






class 				__a				:





		'''simple docstring'''



		def __init__(    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Dict    				= size if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else (size, size)






		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						int    				= pad_if_smaller(UpperCamelCase__			,     self.size							)
						SCREAMING_SNAKE_CASE_ :						List[str]    				= pad_if_smaller(UpperCamelCase__			,     self.size			,     fill=255							)
						SCREAMING_SNAKE_CASE_ :						int    				= transforms.RandomCrop.get_params(UpperCamelCase__			,     self.size							)
						SCREAMING_SNAKE_CASE_ :						List[str]    				= functional.crop(UpperCamelCase__			,     *UpperCamelCase__							)
						SCREAMING_SNAKE_CASE_ :						Dict    				= functional.crop(UpperCamelCase__			,     *UpperCamelCase__							)
						return image, target






class 				__a				:





		'''simple docstring'''



		def __init__(    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						int    				= flip_prob






		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						if random.random() < self.flip_prob:
										SCREAMING_SNAKE_CASE_ :						int    				= functional.hflip(UpperCamelCase__							)
										SCREAMING_SNAKE_CASE_ :						str    				= functional.hflip(UpperCamelCase__							)
						return image, target






class 				__a				:





		'''simple docstring'''



		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Tuple    				= functional.pil_to_tensor(UpperCamelCase__							)
						SCREAMING_SNAKE_CASE_ :						Dict    				= torch.as_tensor(np.array(UpperCamelCase__							)			,     dtype=torch.intaa							)
						return image, target






class 				__a				:





		'''simple docstring'''



		def __init__(    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= dtype






		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						str    				= functional.convert_image_dtype(UpperCamelCase__			,     self.dtype							)
						return image, target






class 				__a				:





		'''simple docstring'''



		def __init__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= mean
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= std






		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= functional.normalize(UpperCamelCase__			,     mean=self.mean			,     std=self.std							)
						return image, target






class 				__a				:





		'''simple docstring'''



		def __call__(    self			,     UpperCamelCase__			,     UpperCamelCase__							):
						if not isinstance(UpperCamelCase__			,     np.ndarray							):
										SCREAMING_SNAKE_CASE_ :						List[Any]    				= np.array(UpperCamelCase__							).astype(np.uinta							)
						# avoid using underflow conversion
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= 255
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= target - 1
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= 255

						SCREAMING_SNAKE_CASE_ :						Any    				= Image.fromarray(UpperCamelCase__							)
						return image, target






@dataclass
class 				__a				:





		'''simple docstring'''



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


		def 	__snake_case      (    self							):
						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				:





		'''simple docstring'''



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






def        _lowerCamelCase(      ):





				'''simple docstring'''







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

				SCREAMING_SNAKE_CASE_ :						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.
				SCREAMING_SNAKE_CASE_ :						int    				= None
				if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
								SCREAMING_SNAKE_CASE_ :						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
				SCREAMING_SNAKE_CASE_ :						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:
								SCREAMING_SNAKE_CASE_ :						Any    				= dataset.rename_columns({'pixel_values': 'image'}   )
				if "annotation" in dataset["train"].column_names:
								SCREAMING_SNAKE_CASE_ :						List[Any]    				= dataset.rename_columns({'annotation': 'label'}   )

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

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

								SCREAMING_SNAKE_CASE_ :						List[str]    				= logits_tensor.detach().cpu().numpy()
								SCREAMING_SNAKE_CASE_ :						Dict    				= 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
								SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= metrics.pop('per_category_accuracy'   ).tolist()
								SCREAMING_SNAKE_CASE_ :						Tuple    				= 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

				SCREAMING_SNAKE_CASE_ :						List[Any]    				= 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     ,     )
				SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= 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     ,     )
				SCREAMING_SNAKE_CASE_ :						str    				= 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.
								SCREAMING_SNAKE_CASE_ :						List[Any]    				= (image_processor.size['shortest_edge'], image_processor.size['shortest_edge'])
				else:
								SCREAMING_SNAKE_CASE_ :						List[str]    				= (image_processor.size['height'], image_processor.size['width'])
				SCREAMING_SNAKE_CASE_ :						Dict    				= 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)
				SCREAMING_SNAKE_CASE_ :						Optional[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__					:		str   ):
								SCREAMING_SNAKE_CASE_ :						Any    				= []
								SCREAMING_SNAKE_CASE_ :						Any    				= []
								for image, target in zip(example_batch['image']     ,     example_batch['label']   ):
												SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= train_transforms(image.convert('RGB'   )     ,     lowerCAmelCase__   )
												pixel_values.append(lowerCAmelCase__   )
												labels.append(lowerCAmelCase__   )

								SCREAMING_SNAKE_CASE_ :						int    				= {}
								SCREAMING_SNAKE_CASE_ :						List[Any]    				= torch.stack(lowerCAmelCase__   )
								SCREAMING_SNAKE_CASE_ :						List[Any]    				= torch.stack(lowerCAmelCase__   )

								return encoding

				def preprocess_val(lowerCAmelCase__					:		Optional[int]   ):
								SCREAMING_SNAKE_CASE_ :						str    				= []
								SCREAMING_SNAKE_CASE_ :						int    				= []
								for image, target in zip(example_batch['image']     ,     example_batch['label']   ):
												SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						Tuple    				= val_transforms(image.convert('RGB'   )     ,     lowerCAmelCase__   )
												pixel_values.append(lowerCAmelCase__   )
												labels.append(lowerCAmelCase__   )

								SCREAMING_SNAKE_CASE_ :						Tuple    				= {}
								SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= torch.stack(lowerCAmelCase__   )
								SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= 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:
												SCREAMING_SNAKE_CASE_ :						List[str]    				= (
												    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:
												SCREAMING_SNAKE_CASE_ :						int    				= (
												    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
				SCREAMING_SNAKE_CASE_ :						int    				= 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:
								SCREAMING_SNAKE_CASE_ :						int    				= None
								if training_args.resume_from_checkpoint is not None:
												SCREAMING_SNAKE_CASE_ :						Tuple    				= training_args.resume_from_checkpoint
								elif last_checkpoint is not None:
												SCREAMING_SNAKE_CASE_ :						Dict    				= last_checkpoint
								SCREAMING_SNAKE_CASE_ :						Tuple    				= 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:
								SCREAMING_SNAKE_CASE_ :						Tuple    				= trainer.evaluate()
								trainer.log_metrics('eval'     ,     lowerCAmelCase__   )
								trainer.save_metrics('eval'     ,     lowerCAmelCase__   )

				# Write model card and (optionally) push to hub
				SCREAMING_SNAKE_CASE_ :						int    				= {
				    '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()







import os
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
				from transformers.pipelines.conversational import Conversation

A										=      logging.get_logger(__name__)

A										=      {'vocab_file': 'tokenizer.model'}

A										=      {
    'vocab_file': {
        'hf-internal-testing/llama-tokenizer': 'https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model',
    },
    'tokenizer_file': {
        'hf-internal-testing/llama-tokenizer': 'https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json',
    },
}
A										=      {
    'hf-internal-testing/llama-tokenizer': 2048,
}
A										=      '▁'

A			,	A										=      '[INST]', '[/INST]'
A			,	A										=      '<<SYS>>\n', '\n<</SYS>>\n\n'

# fmt: off
A										=      'You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information.'


class 				__a				(	__A    ):





		'''simple docstring'''



		UpperCAmelCase__   :					Optional[int]					     =    VOCAB_FILES_NAMES
		UpperCAmelCase__   :					Dict					     =    PRETRAINED_VOCAB_FILES_MAP
		UpperCAmelCase__   :					int					     =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		UpperCAmelCase__   :					Union[str, Any]					     =    ["""input_ids""", """attention_mask"""]


		def __init__(    self			,     UpperCamelCase__			,     UpperCamelCase__="<unk>"			,     UpperCamelCase__="<s>"			,     UpperCamelCase__="</s>"			,     UpperCamelCase__=None			,     UpperCamelCase__ = None			,     UpperCamelCase__=True			,     UpperCamelCase__=False			,     UpperCamelCase__=False			,     UpperCamelCase__=True			,     **UpperCamelCase__			,     ):
						SCREAMING_SNAKE_CASE_ :						str    				= {} if sp_model_kwargs is None else sp_model_kwargs
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else bos_token
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else eos_token
						SCREAMING_SNAKE_CASE_ :						str    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else unk_token
						SCREAMING_SNAKE_CASE_ :						int    				= AddedToken(UpperCamelCase__			,     lstrip=UpperCamelCase__			,     rstrip=UpperCamelCase__							) if isinstance(UpperCamelCase__			,     UpperCamelCase__							) else pad_token
						super().__init__(
						    bos_token=UpperCamelCase__			,     eos_token=UpperCamelCase__			,     unk_token=UpperCamelCase__			,     pad_token=UpperCamelCase__			,     add_bos_token=UpperCamelCase__			,     add_eos_token=UpperCamelCase__			,     sp_model_kwargs=self.sp_model_kwargs			,     clean_up_tokenization_spaces=UpperCamelCase__			,     legacy=UpperCamelCase__			,     **UpperCamelCase__			,     )
						if legacy:
										logger.warning_once(
										    F'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
										    ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565'							)
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= legacy
						SCREAMING_SNAKE_CASE_ :						Dict    				= vocab_file
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= add_bos_token
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= add_eos_token
						SCREAMING_SNAKE_CASE_ :						Any    				= spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.Load(UpperCamelCase__							)


		def __getstate__(    self							):
						SCREAMING_SNAKE_CASE_ :						List[str]    				= self.__dict__.copy()
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= None
						SCREAMING_SNAKE_CASE_ :						Any    				= self.sp_model.serialized_model_proto()
						return state


		def __setstate__(    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						str    				= d
						SCREAMING_SNAKE_CASE_ :						str    				= spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.LoadFromSerializedProto(self.sp_model_proto							)


		@property
		def 	__snake_case      (    self							):
						return self.sp_model.get_piece_size()


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Tuple    				= {self.convert_ids_to_tokens(UpperCamelCase__							): i for i in range(self.vocab_size							)}
						vocab.update(self.added_tokens_encoder							)
						return vocab


		def 	__snake_case      (    self			,     UpperCamelCase__			,     **UpperCamelCase__							):
						# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
						# the beginning of the text
						if not self.legacy:
										SCREAMING_SNAKE_CASE_ :						List[str]    				= SPIECE_UNDERLINE + text.replace(UpperCamelCase__			,     ' '							)
						return super().tokenize(UpperCamelCase__			,     **UpperCamelCase__							)


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						if not self.legacy:
										SCREAMING_SNAKE_CASE_ :						Any    				= text.startswith(UpperCamelCase__							)
										if is_first:
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= text[1:]

						SCREAMING_SNAKE_CASE_ :						Tuple    				= self.sp_model.encode(UpperCamelCase__			,     out_type=UpperCamelCase__							)

						if not self.legacy and not is_first and not text.startswith(' '							) and tokens[0].startswith(UpperCamelCase__							):
										SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= ([tokens[0][1:]] if len(tokens[0]							) > 1 else []) + tokens[1:]
						return tokens


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						return self.sp_model.piece_to_id(UpperCamelCase__							)


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= self.sp_model.IdToPiece(UpperCamelCase__							)
						return token


		def 	__snake_case      (    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						List[str]    				= []
						SCREAMING_SNAKE_CASE_ :						int    				= ''
						SCREAMING_SNAKE_CASE_ :						List[str]    				= False
						for i, token in enumerate(UpperCamelCase__							):
										# make sure that special tokens are not decoded using sentencepiece model
										if token in self.all_special_tokens:
														if not prev_is_special and i != 0:
																		out_string += " "
														out_string += self.sp_model.decode(UpperCamelCase__							) + token
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= True
														SCREAMING_SNAKE_CASE_ :						str    				= []
										else:
														current_sub_tokens.append(UpperCamelCase__							)
														SCREAMING_SNAKE_CASE_ :						int    				= False
						out_string += self.sp_model.decode(UpperCamelCase__							)
						return out_string


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__ = None							):
						if not os.path.isdir(UpperCamelCase__							):
										logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''							)
										return
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= os.path.join(
						    UpperCamelCase__			,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']							)

						if os.path.abspath(self.vocab_file							) != os.path.abspath(UpperCamelCase__							) and os.path.isfile(self.vocab_file							):
										copyfile(self.vocab_file			,     UpperCamelCase__							)
						elif not os.path.isfile(self.vocab_file							):
										with open(UpperCamelCase__			,     'wb'							) as fi:
														SCREAMING_SNAKE_CASE_ :						Dict    				= self.sp_model.serialized_model_proto()
														fi.write(UpperCamelCase__							)

						return (out_vocab_file,)


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__=None							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= [self.bos_token_id] if self.add_bos_token else []
						SCREAMING_SNAKE_CASE_ :						List[str]    				= [self.eos_token_id] if self.add_eos_token else []

						SCREAMING_SNAKE_CASE_ :						int    				= bos_token_id + token_ids_a + eos_token_id

						if token_ids_a is not None:
										SCREAMING_SNAKE_CASE_ :						int    				= output + bos_token_id + token_ids_a + eos_token_id

						return output


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__ = None			,     UpperCamelCase__ = False							):
						if already_has_special_tokens:
										return super().get_special_tokens_mask(
										    token_ids_a=UpperCamelCase__			,     token_ids_a=UpperCamelCase__			,     already_has_special_tokens=UpperCamelCase__							)

						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= [1] if self.add_bos_token else []
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= [1] if self.add_eos_token else []

						if token_ids_a is None:
										return bos_token_id + ([0] * len(UpperCamelCase__							)) + eos_token_id
						return (
						    bos_token_id
						    + ([0] * len(UpperCamelCase__							))
						    + eos_token_id
						    + bos_token_id
						    + ([0] * len(UpperCamelCase__							))
						    + eos_token_id
						)


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__ = None							):
						SCREAMING_SNAKE_CASE_ :						Any    				= [self.bos_token_id] if self.add_bos_token else []
						SCREAMING_SNAKE_CASE_ :						Tuple    				= [self.eos_token_id] if self.add_eos_token else []

						SCREAMING_SNAKE_CASE_ :						Any    				= [0] * len(bos_token_id + token_ids_a + eos_token_id							)

						if token_ids_a is not None:
										output += [1] * len(bos_token_id + token_ids_a + eos_token_id							)

						return output






		def 	__snake_case      (    self			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						int    				= list(conversation.iter_texts()							)
						if not all([is_user for is_user, msg in dialogue[::2]]							) or not all(
						    [not is_user for is_user, msg in dialogue[1::2]]							):
										raise ValueError(
										    'The model only supports \'user\' and \'assistant\' roles, starting with user and alternating (u/a/u/a/u...)'							)

						SCREAMING_SNAKE_CASE_ :						List[int]    				= []
						if len(conversation.past_user_inputs							) > 0:
										if not conversation.past_user_inputs[0].startswith(UpperCamelCase__							) or E_SYS not in conversation.past_user_inputs[0]:
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= (
														    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
														)
						elif not dialogue[0][1].startswith(UpperCamelCase__							) or E_SYS not in dialogue[0][1]:
										SCREAMING_SNAKE_CASE_ :						Tuple    				= (dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

						dialog_tokens += sum(
						    [
						        [self.bos_token_id]
						        + self.encode(
						            F'''{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} '''			,     add_special_tokens=UpperCamelCase__							)
						        + [self.eos_token_id]
						        for prompt, answer in zip(dialogue[::2]			,     dialogue[1::2]							)
						    ]			,     []			,     )
						if not (dialogue[-1][0]):
										raise ValueError(F'''Last message must be from user, got {dialogue[-1]['role']}'''							)
						dialog_tokens += [self.bos_token_id] + self.encode(
						    F'''{B_INST} {(dialogue[-1][1]).strip()} {E_INST}'''			,     add_special_tokens=UpperCamelCase__							)
						return dialog_tokens