

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
lowerCAmelCase							:						str     			=		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_   (					_UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase=0					):
						SCREAMING_SNAKE_CASE_:				int							= (size, size) if isinstance(_UpperCAmelCase       ,			_UpperCAmelCase					) else size
						SCREAMING_SNAKE_CASE_	,					SCREAMING_SNAKE_CASE_:				Dict							= img.size
						SCREAMING_SNAKE_CASE_:				List[Any]							= size[1] - original_height if original_height < size[1] else 0
						SCREAMING_SNAKE_CASE_:				Any							= size[0] - original_width if original_width < size[0] else 0
						SCREAMING_SNAKE_CASE_:				Union[str, Any]							= functional.pad(_UpperCAmelCase       ,			(0, 0, pad_width, pad_height)       ,			fill=_UpperCAmelCase					)
						return img



class 						__lowercase       :




			"""simple docstring"""







			def __init__(				self						:  int     ,		lowerCAmelCase__						:  Dict):
									SCREAMING_SNAKE_CASE_:				List[Any]							= transforms




			def __call__(				self						:  Tuple     ,		lowerCAmelCase__						:  Union[str, Any]     ,		lowerCAmelCase__						:  Dict):
									for t in self.transforms:
															SCREAMING_SNAKE_CASE_	,					SCREAMING_SNAKE_CASE_:				Any							= t(lowerCAmelCase__     ,		lowerCAmelCase__)
									return image, target







class 						__lowercase       :




			"""simple docstring"""







			def __init__(				self						:  int):
									pass




			def __call__(				self						:  Dict     ,		lowerCAmelCase__						:  Union[str, Any]     ,		lowerCAmelCase__						:  Optional[Any]):
									return image, target







class 						__lowercase       :




			"""simple docstring"""







			def __init__(				self						:  List[Any]     ,		lowerCAmelCase__						:  List[Any]):
									SCREAMING_SNAKE_CASE_:				Optional[Any]							= size




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







class 						__lowercase       :




			"""simple docstring"""







			def __init__(				self						:  Any     ,		lowerCAmelCase__						:  List[str]     ,		lowerCAmelCase__						:  List[str]=None):
									SCREAMING_SNAKE_CASE_:				int							= min_size
									if max_size is None:
															SCREAMING_SNAKE_CASE_:				str							= min_size
									SCREAMING_SNAKE_CASE_:				List[str]							= max_size




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







class 						__lowercase       :




			"""simple docstring"""







			def __init__(				self						:  Dict     ,		lowerCAmelCase__						:  Union[str, Any]):
									SCREAMING_SNAKE_CASE_:				Tuple							= size if isinstance(lowerCAmelCase__     ,		lowerCAmelCase__) else (size, size)




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







class 						__lowercase       :




			"""simple docstring"""







			def __init__(				self						:  List[Any]     ,		lowerCAmelCase__						:  Tuple):
									SCREAMING_SNAKE_CASE_:				Union[str, Any]							= flip_prob




			def __call__(				self						:  Tuple     ,		lowerCAmelCase__						:  Optional[int]     ,		lowerCAmelCase__						:  str):
									if random.random() < self.flip_prob:
															SCREAMING_SNAKE_CASE_:				int							= functional.hflip(lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_:				List[str]							= functional.hflip(lowerCAmelCase__)
									return image, target







class 						__lowercase       :




			"""simple docstring"""







			def __call__(				self						:  Tuple     ,		lowerCAmelCase__						:  Optional[Any]     ,		lowerCAmelCase__						:  Optional[int]):
									SCREAMING_SNAKE_CASE_:				int							= functional.pil_to_tensor(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:				Optional[int]							= torch.as_tensor(np.array(lowerCAmelCase__)     ,		dtype=torch.intaa)
									return image, target







class 						__lowercase       :




			"""simple docstring"""







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




			def __call__(				self						:  int     ,		lowerCAmelCase__						:  Optional[Any]     ,		lowerCAmelCase__						:  Any):
									SCREAMING_SNAKE_CASE_:				int							= functional.convert_image_dtype(lowerCAmelCase__     ,		self.dtype)
									return image, target







class 						__lowercase       :




			"""simple docstring"""







			def __init__(				self						:  Dict     ,		lowerCAmelCase__						:  Optional[int]     ,		lowerCAmelCase__						:  Tuple):
									SCREAMING_SNAKE_CASE_:				List[Any]							= mean
									SCREAMING_SNAKE_CASE_:				Any							= std




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







class 						__lowercase       :




			"""simple docstring"""







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

									SCREAMING_SNAKE_CASE_:				Union[str, Any]							= Image.fromarray(lowerCAmelCase__)
									return image, target







@dataclass
class 						__lowercase       :




			"""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=UpperCAmelCase_	, 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=UpperCAmelCase_	, metadata={
			        '''help''': (
			            '''For debugging purposes or quicker training, truncate the number of training examples to this '''
			            '''value if set.'''
			        )
			    }	, )
			_UpperCAmelCase     :							Optional[int]    							=  field(
			    default=UpperCAmelCase_	, metadata={
			        '''help''': (
			            '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
			            '''value if set.'''
			        )
			    }	, )
			_UpperCAmelCase     :							Optional[bool]    							=  field(
			    default=UpperCAmelCase_	, metadata={'''help''': '''Whether or not to reduce all labels by 1 and replace background by 255.'''}	, )



			def  _SCREAMING_SNAKE_CASE    (				self						:  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 						__lowercase       :




			"""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=UpperCAmelCase_	, metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}			)
			_UpperCAmelCase     :							Optional[str]    							=  field(
			    default=UpperCAmelCase_	, 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=UpperCAmelCase_	, metadata={'''help''': '''Name or path of preprocessor config.'''}			)
			_UpperCAmelCase     :							bool    							=  field(
			    default=UpperCAmelCase_	, metadata={
			        '''help''': (
			            '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
			            '''with private models).'''
			        )
			    }	, )







def     A_   (					):
						# 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.

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

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

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

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

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

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

												return metrics

						SCREAMING_SNAKE_CASE_:				Dict							= AutoConfig.from_pretrained(
						    model_args.config_name or model_args.model_name_or_path       ,			labelaid=_UpperCAmelCase       ,			idalabel=_UpperCAmelCase       ,			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							= AutoModelForSemanticSegmentation.from_pretrained(
						    model_args.model_name_or_path       ,			from_tf=bool(".ckpt" in model_args.model_name_or_path					)       ,			config=_UpperCAmelCase       ,			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_:				Optional[int]							= 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[str]							= (image_processor.size["shortest_edge"], image_processor.size["shortest_edge"])
						else:
												SCREAMING_SNAKE_CASE_:				Dict							= (image_processor.size["height"], image_processor.size["width"])
						SCREAMING_SNAKE_CASE_:				Optional[Any]							= Compose(
						    [
						        ReduceLabels() if data_args.reduce_labels else Identity(),
						        RandomCrop(size=_UpperCAmelCase					),
						        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_:				Union[str, Any]							= Compose(
						    [
						        ReduceLabels() if data_args.reduce_labels else Identity(),
						        Resize(size=_UpperCAmelCase					),
						        PILToTensor(),
						        ConvertImageDtype(torch.float					),
						        Normalize(mean=image_processor.image_mean       ,			std=image_processor.image_std					),
						    ]					)

						def preprocess_train(_UpperCAmelCase					):
												SCREAMING_SNAKE_CASE_:				Optional[Any]							= []
												SCREAMING_SNAKE_CASE_:				List[str]							= []
												for image, target in zip(example_batch["image"]       ,			example_batch["label"]					):
																		SCREAMING_SNAKE_CASE_	,					SCREAMING_SNAKE_CASE_:				Optional[int]							= train_transforms(image.convert("RGB"					)       ,			_UpperCAmelCase					)
																		pixel_values.append(_UpperCAmelCase					)
																		labels.append(_UpperCAmelCase					)

												SCREAMING_SNAKE_CASE_:				Dict							= {}
												SCREAMING_SNAKE_CASE_:				Any							= torch.stack(_UpperCAmelCase					)
												SCREAMING_SNAKE_CASE_:				List[str]							= torch.stack(_UpperCAmelCase					)

												return encoding

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

												SCREAMING_SNAKE_CASE_:				Optional[int]							= {}
												SCREAMING_SNAKE_CASE_:				str							= torch.stack(_UpperCAmelCase					)
												SCREAMING_SNAKE_CASE_:				Optional[int]							= torch.stack(_UpperCAmelCase					)

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

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

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

						# Training
						if training_args.do_train:
												SCREAMING_SNAKE_CASE_:				List[Any]							= None
												if training_args.resume_from_checkpoint is not None:
																		SCREAMING_SNAKE_CASE_:				List[str]							= training_args.resume_from_checkpoint
												elif last_checkpoint is not None:
																		SCREAMING_SNAKE_CASE_:				Any							= last_checkpoint
												SCREAMING_SNAKE_CASE_:				str							= trainer.train(resume_from_checkpoint=_UpperCAmelCase					)
												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_:				Optional[Any]							= trainer.evaluate()
												trainer.log_metrics("eval"       ,			_UpperCAmelCase					)
												trainer.save_metrics("eval"       ,			_UpperCAmelCase					)

						# Write model card and (optionally) push to hub
						SCREAMING_SNAKE_CASE_:				Union[str, 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(**_UpperCAmelCase					)
						else:
												trainer.create_model_card(**_UpperCAmelCase					)


if __name__ == "__main__":
						main()









import argparse
import json
import os

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ConvNextImageProcessor, ConvNextVaConfig, ConvNextVaForImageClassification
from transformers.image_utils import PILImageResampling
from transformers.utils import logging


logging.set_verbosity_info()
lowerCAmelCase							:						Optional[Any]     			=		logging.get_logger(__name__)







def     A_   (					_UpperCAmelCase					):
						SCREAMING_SNAKE_CASE_:				Tuple							= ConvNextVaConfig()

						if "atto" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				str							= [2, 2, 6, 2]
												SCREAMING_SNAKE_CASE_:				str							= [40, 80, 1_60, 3_20]
						if "femto" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				List[str]							= [2, 2, 6, 2]
												SCREAMING_SNAKE_CASE_:				Dict							= [48, 96, 1_92, 3_84]
						if "pico" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				Any							= [2, 2, 6, 2]
												SCREAMING_SNAKE_CASE_:				Dict							= [64, 1_28, 2_56, 5_12]
						if "nano" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				Tuple							= [2, 2, 8, 2]
												SCREAMING_SNAKE_CASE_:				str							= [80, 1_60, 3_20, 6_40]
						if "tiny" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				List[str]							= [3, 3, 9, 3]
												SCREAMING_SNAKE_CASE_:				Dict							= [96, 1_92, 3_84, 7_68]
						if "base" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				List[Any]							= [3, 3, 27, 3]
												SCREAMING_SNAKE_CASE_:				Tuple							= [1_28, 2_56, 5_12, 10_24]
						if "large" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				str							= [3, 3, 27, 3]
												SCREAMING_SNAKE_CASE_:				str							= [1_92, 3_84, 7_68, 15_36]
						if "huge" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				List[str]							= [3, 3, 27, 3]
												SCREAMING_SNAKE_CASE_:				Tuple							= [3_52, 7_04, 14_08, 28_16]

						SCREAMING_SNAKE_CASE_:				Optional[Any]							= 10_00
						SCREAMING_SNAKE_CASE_:				List[Any]							= "imagenet-1k-id2label.json"
						SCREAMING_SNAKE_CASE_:				str							= (1, 10_00)

						SCREAMING_SNAKE_CASE_:				Tuple							= "huggingface/label-files"
						SCREAMING_SNAKE_CASE_:				List[str]							= num_labels
						SCREAMING_SNAKE_CASE_:				Optional[Any]							= json.load(open(hf_hub_download(_UpperCAmelCase       ,			_UpperCAmelCase       ,			repo_type="dataset"					)       ,			"r"					)					)
						SCREAMING_SNAKE_CASE_:				Any							= {int(_UpperCAmelCase					): v for k, v in idalabel.items()}

						SCREAMING_SNAKE_CASE_:				List[Any]							= idalabel
						SCREAMING_SNAKE_CASE_:				Union[str, Any]							= {v: k for k, v in idalabel.items()}
						SCREAMING_SNAKE_CASE_:				Any							= hidden_sizes
						SCREAMING_SNAKE_CASE_:				Tuple							= depths

						return config, expected_shape







def     A_   (					_UpperCAmelCase					):
						if "downsample_layers.0.0" in name:
												SCREAMING_SNAKE_CASE_:				int							= name.replace("downsample_layers.0.0"       ,			"embeddings.patch_embeddings"					)
						if "downsample_layers.0.1" in name:
												SCREAMING_SNAKE_CASE_:				Optional[int]							= name.replace("downsample_layers.0.1"       ,			"embeddings.norm"					)  # we rename to layernorm later on
						if "downsample_layers.1.0" in name:
												SCREAMING_SNAKE_CASE_:				Optional[int]							= name.replace("downsample_layers.1.0"       ,			"stages.1.downsampling_layer.0"					)
						if "downsample_layers.1.1" in name:
												SCREAMING_SNAKE_CASE_:				Optional[Any]							= name.replace("downsample_layers.1.1"       ,			"stages.1.downsampling_layer.1"					)
						if "downsample_layers.2.0" in name:
												SCREAMING_SNAKE_CASE_:				Optional[int]							= name.replace("downsample_layers.2.0"       ,			"stages.2.downsampling_layer.0"					)
						if "downsample_layers.2.1" in name:
												SCREAMING_SNAKE_CASE_:				Optional[Any]							= name.replace("downsample_layers.2.1"       ,			"stages.2.downsampling_layer.1"					)
						if "downsample_layers.3.0" in name:
												SCREAMING_SNAKE_CASE_:				Dict							= name.replace("downsample_layers.3.0"       ,			"stages.3.downsampling_layer.0"					)
						if "downsample_layers.3.1" in name:
												SCREAMING_SNAKE_CASE_:				List[str]							= name.replace("downsample_layers.3.1"       ,			"stages.3.downsampling_layer.1"					)
						if "stages" in name and "downsampling_layer" not in name:
												# stages.0.0. for instance should be renamed to stages.0.layers.0.
												SCREAMING_SNAKE_CASE_:				List[Any]							= name[: len("stages.0"					)] + ".layers" + name[len("stages.0"					) :]
						if "gamma" in name:
												SCREAMING_SNAKE_CASE_:				int							= name.replace("gamma"       ,			"weight"					)
						if "beta" in name:
												SCREAMING_SNAKE_CASE_:				Any							= name.replace("beta"       ,			"bias"					)
						if "stages" in name:
												SCREAMING_SNAKE_CASE_:				Dict							= name.replace("stages"       ,			"encoder.stages"					)
						if "norm" in name:
												SCREAMING_SNAKE_CASE_:				List[str]							= name.replace("norm"       ,			"layernorm"					)
						if "head" in name:
												SCREAMING_SNAKE_CASE_:				Dict							= name.replace("head"       ,			"classifier"					)

						return name







def     A_   (					):
						SCREAMING_SNAKE_CASE_:				Optional[int]							= "http://images.cocodataset.org/val2017/000000039769.jpg"
						SCREAMING_SNAKE_CASE_:				Optional[int]							= Image.open(requests.get(_UpperCAmelCase       ,			stream=_UpperCAmelCase					).raw					)
						return im







def     A_   (					_UpperCAmelCase					):
						if "224" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				Tuple							= 2_24
												SCREAMING_SNAKE_CASE_:				Optional[int]							= 2_24 / 2_56
						elif "384" in checkpoint_url:
												SCREAMING_SNAKE_CASE_:				Any							= 3_84
												SCREAMING_SNAKE_CASE_:				Tuple							= None
						else:
												SCREAMING_SNAKE_CASE_:				Tuple							= 5_12
												SCREAMING_SNAKE_CASE_:				Optional[Any]							= None

						return ConvNextImageProcessor(
						    size=_UpperCAmelCase       ,			crop_pct=_UpperCAmelCase       ,			image_mean=[0.4_8_5, 0.4_5_6, 0.4_0_6]       ,			image_std=[0.2_2_9, 0.2_2_4, 0.2_2_5]       ,			resample=PILImageResampling.BICUBIC       ,			)







@torch.no_grad()
def     A_   (					_UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase					):
						print("Downloading original model from checkpoint..."					)
						# define ConvNeXTV2 configuration based on URL
						SCREAMING_SNAKE_CASE_	,					SCREAMING_SNAKE_CASE_:				Optional[int]							= get_convnextva_config(_UpperCAmelCase					)
						# load original state_dict from URL
						SCREAMING_SNAKE_CASE_:				List[str]							= torch.hub.load_state_dict_from_url(_UpperCAmelCase					)["model"]

						print("Converting model parameters..."					)
						# rename keys
						for key in state_dict.copy().keys():
												SCREAMING_SNAKE_CASE_:				List[str]							= state_dict.pop(_UpperCAmelCase					)
												SCREAMING_SNAKE_CASE_:				str							= val
						# add prefix to all keys expect classifier head
						for key in state_dict.copy().keys():
												SCREAMING_SNAKE_CASE_:				str							= state_dict.pop(_UpperCAmelCase					)
												if not key.startswith("classifier"					):
																		SCREAMING_SNAKE_CASE_:				Union[str, Any]							= "convnextv2." + key
												SCREAMING_SNAKE_CASE_:				Dict							= val

						# load HuggingFace model
						SCREAMING_SNAKE_CASE_:				Tuple							= ConvNextVaForImageClassification(_UpperCAmelCase					)
						model.load_state_dict(_UpperCAmelCase					)
						model.eval()

						# Check outputs on an image, prepared by ConvNextImageProcessor
						SCREAMING_SNAKE_CASE_:				Union[str, Any]							= convert_preprocessor(_UpperCAmelCase					)
						SCREAMING_SNAKE_CASE_:				int							= preprocessor(images=prepare_img()       ,			return_tensors="pt"					)
						SCREAMING_SNAKE_CASE_:				Optional[int]							= model(**_UpperCAmelCase					).logits

						# note: the logits below were obtained without center cropping
						if checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_atto_1k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				int							= torch.tensor([-0.3_9_3_0, 0.1_7_4_7, -0.5_2_4_6, 0.4_1_7_7, 0.4_2_9_5]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_femto_1k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				List[str]							= torch.tensor([-0.1_7_2_7, -0.5_3_4_1, -0.7_8_1_8, -0.4_7_4_5, -0.6_5_6_6]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_pico_1k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				List[Any]							= torch.tensor([-0.0_3_3_3, 0.1_5_6_3, -0.9_1_3_7, 0.1_0_5_4, 0.0_3_8_1]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_nano_1k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				List[str]							= torch.tensor([-0.1_7_4_4, -0.1_5_5_5, -0.0_7_1_3, 0.0_9_5_0, -0.1_4_3_1]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_tiny_1k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				Optional[int]							= torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6, -0.3_4_7_2, 0.6_6_6_1]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_base_1k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				Any							= torch.tensor([-0.2_5_5_3, -0.6_7_0_8, -0.1_3_5_9, 0.2_5_1_8, -0.2_4_8_8]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_large_1k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				Union[str, Any]							= torch.tensor([-0.0_6_7_3, -0.5_6_2_7, -0.3_7_5_3, -0.2_7_2_2, 0.0_1_7_8]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_huge_1k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				Optional[Any]							= torch.tensor([-0.6_3_7_7, -0.7_4_5_8, -0.2_1_5_0, 0.1_1_8_4, -0.0_5_9_7]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_nano_22k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				int							= torch.tensor([1.0_7_9_9, 0.2_3_2_2, -0.8_8_6_0, 1.0_2_1_9, 0.6_2_3_1]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_nano_22k_384_ema.pt":
												SCREAMING_SNAKE_CASE_:				Any							= torch.tensor([0.3_7_6_6, 0.4_9_1_7, -1.1_4_2_6, 0.9_9_4_2, 0.6_0_2_4]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_tiny_22k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				int							= torch.tensor([0.4_2_2_0, -0.6_9_1_9, -0.4_3_1_7, -0.2_8_8_1, -0.6_6_0_9]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_tiny_22k_384_ema.pt":
												SCREAMING_SNAKE_CASE_:				Any							= torch.tensor([0.1_0_8_2, -0.8_2_8_6, -0.5_0_9_5, 0.4_6_8_1, -0.8_0_8_5]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_base_22k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				Optional[int]							= torch.tensor([-0.2_4_1_9, -0.6_2_2_1, 0.2_1_7_6, -0.0_9_8_0, -0.7_5_2_7]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_base_22k_384_ema.pt":
												SCREAMING_SNAKE_CASE_:				str							= torch.tensor([0.0_3_9_1, -0.4_3_7_1, 0.3_7_8_6, 0.1_2_5_1, -0.2_7_8_4]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_large_22k_224_ema.pt":
												SCREAMING_SNAKE_CASE_:				Any							= torch.tensor([-0.0_5_0_4, 0.5_6_3_6, -0.1_7_2_9, -0.6_5_0_7, -0.3_9_4_9]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_large_22k_384_ema.pt":
												SCREAMING_SNAKE_CASE_:				Dict							= torch.tensor([0.3_5_6_0, 0.9_4_8_6, 0.3_1_4_9, -0.2_6_6_7, -0.5_1_3_8]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_huge_22k_384_ema.pt":
												SCREAMING_SNAKE_CASE_:				Tuple							= torch.tensor([-0.2_4_6_9, -0.4_5_5_0, -0.5_8_5_3, -0.0_8_1_0, 0.0_3_0_9]					)
						elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_huge_22k_512_ema.pt":
												SCREAMING_SNAKE_CASE_:				str							= torch.tensor([-0.3_0_9_0, 0.0_8_0_2, -0.0_6_8_2, -0.1_9_7_9, -0.2_8_2_6]					)
						else:
												raise ValueError(f"Unknown URL: {checkpoint_url}"					)

						assert torch.allclose(logits[0, :5]       ,			_UpperCAmelCase       ,			atol=1e-3					)
						assert logits.shape == expected_shape
						print("Model outputs match the original results!"					)

						if save_model:
												print("Saving model to local..."					)
												# Create folder to save model
												if not os.path.isdir(_UpperCAmelCase					):
																		os.mkdir(_UpperCAmelCase					)

												model.save_pretrained(_UpperCAmelCase					)
												preprocessor.save_pretrained(_UpperCAmelCase					)

						SCREAMING_SNAKE_CASE_:				Optional[int]							= "convnextv2"
						if "atto" in checkpoint_url:
												model_name += "-atto"
						if "femto" in checkpoint_url:
												model_name += "-femto"
						if "pico" in checkpoint_url:
												model_name += "-pico"
						if "nano" in checkpoint_url:
												model_name += "-nano"
						elif "tiny" in checkpoint_url:
												model_name += "-tiny"
						elif "base" in checkpoint_url:
												model_name += "-base"
						elif "large" in checkpoint_url:
												model_name += "-large"
						elif "huge" in checkpoint_url:
												model_name += "-huge"
						if "22k" in checkpoint_url and "1k" not in checkpoint_url:
												model_name += "-22k"
						elif "22k" in checkpoint_url and "1k" in checkpoint_url:
												model_name += "-22k-1k"
						elif "1k" in checkpoint_url:
												model_name += "-1k"
						if "224" in checkpoint_url:
												model_name += "-224"
						elif "384" in checkpoint_url:
												model_name += "-384"
						elif "512" in checkpoint_url:
												model_name += "-512"

						if push_to_hub:
												print(f"Pushing {model_name} to the hub..."					)
												model.push_to_hub(_UpperCAmelCase					)
												preprocessor.push_to_hub(_UpperCAmelCase					)


if __name__ == "__main__":
						lowerCAmelCase							:						Tuple     			=		argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    """--checkpoint_url""",
						    default="""https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_atto_1k_224_ema.pt""",
						    type=str,
						    help="""URL of the original ConvNeXTV2 checkpoint you'd like to convert.""",
						)
						parser.add_argument(
						    """--pytorch_dump_folder_path""",
						    default="""model""",
						    type=str,
						    help="""Path to the output PyTorch model directory.""",
						)
						parser.add_argument("""--save_model""", action="""store_true""", help="""Save model to local""")
						parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image preprocessor to the hub""")

						lowerCAmelCase							:						Union[str, Any]     			=		parser.parse_args()
						convert_convnextva_checkpoint(
						    args.checkpoint_url, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub
						)






