






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

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

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

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

require_version('''datasets>=2.0.0''', '''To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt''')

def 			__lowerCamelCase     (						snake_case__			,snake_case__			,snake_case__=0						)				->    Optional[Any]:






						"""simple docstring"""





						_SCREAMING_SNAKE_CASE       =    (size, size) if isinstance(snake_case__			,snake_case__						) else size
						_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    img.size
						_SCREAMING_SNAKE_CASE       =    size[1] - original_height if original_height < size[1] else 0
						_SCREAMING_SNAKE_CASE       =    size[0] - original_width if original_width < size[0] else 0
						_SCREAMING_SNAKE_CASE       =    functional.pad(snake_case__			,(0, 0, pad_width, pad_height)			,fill=snake_case__						)
						return img



class  __UpperCAmelCase						:







			def __init__(      self:    Dict ,      UpperCAmelCase_:    Optional[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    transforms







			def __call__(      self:    Dict ,      UpperCAmelCase_:    List[str] ,      UpperCAmelCase_:    Dict	):







									'''simple docstring'''




									for t in self.transforms:
															_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    t(UpperCAmelCase_ ,      UpperCAmelCase_	)
									return image, target



class  __UpperCAmelCase						:







			def __init__(      self:    List[Any]	):







									'''simple docstring'''




									pass







			def __call__(      self:    int ,      UpperCAmelCase_:    Tuple ,      UpperCAmelCase_:    List[str]	):







									'''simple docstring'''




									return image, target



class  __UpperCAmelCase						:







			def __init__(      self:    List[str] ,      UpperCAmelCase_:    Tuple	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    size







			def __call__(      self:    Optional[int] ,      UpperCAmelCase_:    str ,      UpperCAmelCase_:    Optional[Any]	):







									'''simple docstring'''




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



class  __UpperCAmelCase						:







			def __init__(      self:    Union[str, Any] ,      UpperCAmelCase_:    List[str] ,      UpperCAmelCase_:    Optional[Any]=None	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    min_size
									if max_size is None:
															_SCREAMING_SNAKE_CASE       =    min_size
									_SCREAMING_SNAKE_CASE       =    max_size







			def __call__(      self:    List[str] ,      UpperCAmelCase_:    Any ,      UpperCAmelCase_:    str	):







									'''simple docstring'''




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



class  __UpperCAmelCase						:







			def __init__(      self:    List[Any] ,      UpperCAmelCase_:    Union[str, Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    size if isinstance(UpperCAmelCase_ ,      UpperCAmelCase_	) else (size, size)







			def __call__(      self:    int ,      UpperCAmelCase_:    Optional[int] ,      UpperCAmelCase_:    List[str]	):







									'''simple docstring'''




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



class  __UpperCAmelCase						:







			def __init__(      self:    Optional[Any] ,      UpperCAmelCase_:    List[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    flip_prob







			def __call__(      self:    Union[str, Any] ,      UpperCAmelCase_:    List[str] ,      UpperCAmelCase_:    int	):







									'''simple docstring'''




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



class  __UpperCAmelCase						:







			def __call__(      self:    str ,      UpperCAmelCase_:    Optional[int] ,      UpperCAmelCase_:    List[Any]	):







									'''simple docstring'''




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



class  __UpperCAmelCase						:







			def __init__(      self:    str ,      UpperCAmelCase_:    Optional[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    dtype







			def __call__(      self:    str ,      UpperCAmelCase_:    Optional[Any] ,      UpperCAmelCase_:    str	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    functional.convert_image_dtype(UpperCAmelCase_ ,      self.dtype	)
									return image, target



class  __UpperCAmelCase						:







			def __init__(      self:    Optional[Any] ,      UpperCAmelCase_:    int ,      UpperCAmelCase_:    Union[str, Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    mean
									_SCREAMING_SNAKE_CASE       =    std







			def __call__(      self:    Optional[Any] ,      UpperCAmelCase_:    Optional[Any] ,      UpperCAmelCase_:    List[str]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    functional.normalize(UpperCAmelCase_ ,      mean=self.mean ,      std=self.std	)
									return image, target



class  __UpperCAmelCase						:







			def __call__(      self:    str ,      UpperCAmelCase_:    Optional[int] ,      UpperCAmelCase_:    Optional[Any]	):







									'''simple docstring'''




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

									_SCREAMING_SNAKE_CASE       =    Image.fromarray(UpperCAmelCase_	)
									return image, target



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







			def 				UpperCamelCase (      self:    Union[str, Any]	):







									'''simple docstring'''




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



@dataclass
class  __UpperCAmelCase						:
			__snake_case							: str							=				field(
			    default="nvidia/mit-b0"			,metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}			,)
			__snake_case							: Optional[str]							=				field(
			    default=_UpperCAmelCase			,metadata={"help": "Pretrained config name or path if not the same as model_name"}       )
			__snake_case							: Optional[str]							=				field(
			    default=_UpperCAmelCase			,metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}       )
			__snake_case							: str							=				field(
			    default="main"			,metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}			,)
			__snake_case							: str							=				field(default=_UpperCAmelCase			,metadata={"help": "Name or path of preprocessor config."}       )
			__snake_case							: 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 			__lowerCamelCase     (						)				->    List[str]:






						"""simple docstring"""





						_SCREAMING_SNAKE_CASE       =    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       =    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
						else:
												_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    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"""			,snake_case__			,snake_case__						)

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

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

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

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

						# Detecting last checkpoint.
						_SCREAMING_SNAKE_CASE       =    None
						if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
												_SCREAMING_SNAKE_CASE       =    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       =    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       =    dataset.rename_columns({"""pixel_values""": """image"""}						)
						if "annotation" in dataset["train"].column_names:
												_SCREAMING_SNAKE_CASE       =    dataset.rename_columns({"""annotation""": """label"""}						)

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

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

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

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

												return metrics

						_SCREAMING_SNAKE_CASE       =    AutoConfig.from_pretrained(
						    model_args.config_name or model_args.model_name_or_path			,labelaid=snake_case__			,idalabel=snake_case__			,cache_dir=model_args.cache_dir			,revision=model_args.model_revision			,use_auth_token=True if model_args.use_auth_token else None			,)
						_SCREAMING_SNAKE_CASE       =    AutoModelForSemanticSegmentation.from_pretrained(
						    model_args.model_name_or_path			,from_tf=bool(""".ckpt""" in model_args.model_name_or_path						)			,config=snake_case__			,cache_dir=model_args.cache_dir			,revision=model_args.model_revision			,use_auth_token=True if model_args.use_auth_token else None			,)
						_SCREAMING_SNAKE_CASE       =    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       =    (image_processor.size["""shortest_edge"""], image_processor.size["""shortest_edge"""])
						else:
												_SCREAMING_SNAKE_CASE       =    (image_processor.size["""height"""], image_processor.size["""width"""])
						_SCREAMING_SNAKE_CASE       =    Compose(
						    [
						        ReduceLabels() if data_args.reduce_labels else Identity(),
						        RandomCrop(size=snake_case__						),
						        RandomHorizontalFlip(flip_prob=0.5						),
						        PILToTensor(),
						        ConvertImageDtype(torch.float						),
						        Normalize(mean=image_processor.image_mean			,std=image_processor.image_std						),
						    ]						)
						# Define torchvision transform to be applied to each image.
						# jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
						_SCREAMING_SNAKE_CASE       =    Compose(
						    [
						        ReduceLabels() if data_args.reduce_labels else Identity(),
						        Resize(size=snake_case__						),
						        PILToTensor(),
						        ConvertImageDtype(torch.float						),
						        Normalize(mean=image_processor.image_mean			,std=image_processor.image_std						),
						    ]						)

						def preprocess_train(snake_case__						):
												_SCREAMING_SNAKE_CASE       =    []
												_SCREAMING_SNAKE_CASE       =    []
												for image, target in zip(example_batch["""image"""]			,example_batch["""label"""]						):
																		_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    train_transforms(image.convert("""RGB"""						)			,snake_case__						)
																		pixel_values.append(snake_case__						)
																		labels.append(snake_case__						)

												_SCREAMING_SNAKE_CASE       =    {}
												_SCREAMING_SNAKE_CASE       =    torch.stack(snake_case__						)
												_SCREAMING_SNAKE_CASE       =    torch.stack(snake_case__						)

												return encoding

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

												_SCREAMING_SNAKE_CASE       =    {}
												_SCREAMING_SNAKE_CASE       =    torch.stack(snake_case__						)
												_SCREAMING_SNAKE_CASE       =    torch.stack(snake_case__						)

												return encoding

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

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

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

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

						# Evaluation
						if training_args.do_eval:
												_SCREAMING_SNAKE_CASE       =    trainer.evaluate()
												trainer.log_metrics("""eval"""			,snake_case__						)
												trainer.save_metrics("""eval"""			,snake_case__						)

						# Write model card and (optionally) push to hub
						_SCREAMING_SNAKE_CASE       =    {
						    """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(**snake_case__						)
						else:
												trainer.create_model_card(**snake_case__						)


if __name__ == "__main__":
		main()









import inspect
import unittest

from transformers import DataaVecVisionConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import (
		    MODEL_MAPPING,
		    DataaVecVisionForImageClassification,
		    DataaVecVisionForSemanticSegmentation,
		    DataaVecVisionModel,
		)
		from transformers.models.dataavec.modeling_dataavec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import BeitImageProcessor



class  __UpperCAmelCase						:







			def __init__(      self:    str ,      UpperCAmelCase_:    List[Any] ,      UpperCAmelCase_:    Tuple=100 ,      UpperCAmelCase_:    str=13 ,      UpperCAmelCase_:    str=30 ,      UpperCAmelCase_:    Tuple=2 ,      UpperCAmelCase_:    Tuple=3 ,      UpperCAmelCase_:    List[str]=True ,      UpperCAmelCase_:    List[Any]=True ,      UpperCAmelCase_:    Optional[int]=32 ,      UpperCAmelCase_:    Optional[int]=4 ,      UpperCAmelCase_:    Tuple=4 ,      UpperCAmelCase_:    List[Any]=37 ,      UpperCAmelCase_:    Optional[Any]="gelu" ,      UpperCAmelCase_:    Optional[int]=0.1 ,      UpperCAmelCase_:    int=0.1 ,      UpperCAmelCase_:    Dict=10 ,      UpperCAmelCase_:    Dict=0.02 ,      UpperCAmelCase_:    Union[str, Any]=3 ,      UpperCAmelCase_:    List[Any]=None ,      UpperCAmelCase_:    Any=[0, 1, 2, 3] ,      ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    parent
									_SCREAMING_SNAKE_CASE       =    100
									_SCREAMING_SNAKE_CASE       =    batch_size
									_SCREAMING_SNAKE_CASE       =    image_size
									_SCREAMING_SNAKE_CASE       =    patch_size
									_SCREAMING_SNAKE_CASE       =    num_channels
									_SCREAMING_SNAKE_CASE       =    is_training
									_SCREAMING_SNAKE_CASE       =    use_labels
									_SCREAMING_SNAKE_CASE       =    hidden_size
									_SCREAMING_SNAKE_CASE       =    num_hidden_layers
									_SCREAMING_SNAKE_CASE       =    num_attention_heads
									_SCREAMING_SNAKE_CASE       =    intermediate_size
									_SCREAMING_SNAKE_CASE       =    hidden_act
									_SCREAMING_SNAKE_CASE       =    hidden_dropout_prob
									_SCREAMING_SNAKE_CASE       =    attention_probs_dropout_prob
									_SCREAMING_SNAKE_CASE       =    type_sequence_label_size
									_SCREAMING_SNAKE_CASE       =    initializer_range
									_SCREAMING_SNAKE_CASE       =    scope
									_SCREAMING_SNAKE_CASE       =    out_indices
									_SCREAMING_SNAKE_CASE       =    num_labels

									# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
									_SCREAMING_SNAKE_CASE       =    (image_size // patch_size) ** 2
									_SCREAMING_SNAKE_CASE       =    num_patches + 1







			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

									_SCREAMING_SNAKE_CASE       =    None
									_SCREAMING_SNAKE_CASE       =    None
									if self.use_labels:
															_SCREAMING_SNAKE_CASE       =    ids_tensor([self.batch_size] ,      self.type_sequence_label_size	)
															_SCREAMING_SNAKE_CASE       =    ids_tensor([self.batch_size, self.image_size, self.image_size] ,      self.num_labels	)

									_SCREAMING_SNAKE_CASE       =    self.get_config()

									return config, pixel_values, labels, pixel_labels







			def 				UpperCamelCase (      self:    Any	):







									'''simple docstring'''




									return DataaVecVisionConfig(
									    vocab_size=self.vocab_size ,      image_size=self.image_size ,      patch_size=self.patch_size ,      num_channels=self.num_channels ,      hidden_size=self.hidden_size ,      num_hidden_layers=self.num_hidden_layers ,      num_attention_heads=self.num_attention_heads ,      intermediate_size=self.intermediate_size ,      hidden_act=self.hidden_act ,      hidden_dropout_prob=self.hidden_dropout_prob ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob ,      is_decoder=UpperCAmelCase_ ,      initializer_range=self.initializer_range ,      out_indices=self.out_indices ,      )







			def 				UpperCamelCase (      self:    Optional[Any] ,      UpperCAmelCase_:    str ,      UpperCAmelCase_:    Optional[int] ,      UpperCAmelCase_:    Optional[Any] ,      UpperCAmelCase_:    List[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DataaVecVisionModel(config=UpperCAmelCase_	)
									model.to(UpperCAmelCase_	)
									model.eval()
									_SCREAMING_SNAKE_CASE       =    model(UpperCAmelCase_	)
									# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
									_SCREAMING_SNAKE_CASE       =    (self.image_size // self.patch_size) ** 2
									self.parent.assertEqual(result.last_hidden_state.shape ,      (self.batch_size, num_patches + 1, self.hidden_size)	)







			def 				UpperCamelCase (      self:    Union[str, Any] ,      UpperCAmelCase_:    Tuple ,      UpperCAmelCase_:    Optional[int] ,      UpperCAmelCase_:    Optional[int] ,      UpperCAmelCase_:    str	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.type_sequence_label_size
									_SCREAMING_SNAKE_CASE       =    DataaVecVisionForImageClassification(UpperCAmelCase_	)
									model.to(UpperCAmelCase_	)
									model.eval()
									_SCREAMING_SNAKE_CASE       =    model(UpperCAmelCase_ ,      labels=UpperCAmelCase_	)
									self.parent.assertEqual(result.logits.shape ,      (self.batch_size, self.type_sequence_label_size)	)







			def 				UpperCamelCase (      self:    List[str] ,      UpperCAmelCase_:    str ,      UpperCAmelCase_:    List[Any] ,      UpperCAmelCase_:    Tuple ,      UpperCAmelCase_:    List[str]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.num_labels
									_SCREAMING_SNAKE_CASE       =    DataaVecVisionForSemanticSegmentation(UpperCAmelCase_	)
									model.to(UpperCAmelCase_	)
									model.eval()
									_SCREAMING_SNAKE_CASE       =    model(UpperCAmelCase_	)
									self.parent.assertEqual(
									    result.logits.shape ,      (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)	)
									_SCREAMING_SNAKE_CASE       =    model(UpperCAmelCase_ ,      labels=UpperCAmelCase_	)
									self.parent.assertEqual(
									    result.logits.shape ,      (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)	)







			def 				UpperCamelCase (      self:    Optional[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.prepare_config_and_inputs()
									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    config_and_inputs
									_SCREAMING_SNAKE_CASE       =    {"""pixel_values""": pixel_values}
									return config, inputs_dict



@require_torch
class  __UpperCAmelCase						(_UpperCAmelCase			,_UpperCAmelCase			,unittest.TestCase       ):
			__snake_case							: Tuple							=				(
			    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			__snake_case							: Optional[Any]							=				(
			    {
			        "feature-extraction": DataaVecVisionModel,
			        "image-classification": DataaVecVisionForImageClassification,
			        "image-segmentation": DataaVecVisionForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			__snake_case							: Dict							=				False
			__snake_case							: List[str]							=				False
			__snake_case							: Dict							=				False







			def 				UpperCamelCase (      self:    str	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DataaVecVisionModelTester(self	)
									_SCREAMING_SNAKE_CASE       =    ConfigTester(
									    self ,      config_class=UpperCAmelCase_ ,      has_text_modality=UpperCAmelCase_ ,      hidden_size=37	)







			def 				UpperCamelCase (      self:    Optional[Any]	):







									'''simple docstring'''




									self.config_tester.run_common_tests()







			def 				UpperCamelCase (      self:    str	):







									'''simple docstring'''




									pass







			@require_torch_multi_gpu
			@unittest.skip(
			    reason="""Data2VecVision has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""	)
			def 				UpperCamelCase (      self:    List[str]	):







									'''simple docstring'''




									pass







			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE       =    model_class(UpperCAmelCase_	)
															self.assertIsInstance(model.get_input_embeddings() ,      (nn.Module)	)
															_SCREAMING_SNAKE_CASE       =    model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(UpperCAmelCase_ ,      nn.Linear	)	)







			def 				UpperCamelCase (      self:    Optional[int]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE       =    model_class(UpperCAmelCase_	)
															_SCREAMING_SNAKE_CASE       =    inspect.signature(model.forward	)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															_SCREAMING_SNAKE_CASE       =    [*signature.parameters.keys()]

															_SCREAMING_SNAKE_CASE       =    ["""pixel_values"""]
															self.assertListEqual(arg_names[:1] ,      UpperCAmelCase_	)







			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*UpperCAmelCase_	)







			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_segmentation(*UpperCAmelCase_	)







			def 				UpperCamelCase (      self:    Optional[int]	):







									'''simple docstring'''




									if not self.model_tester.is_training:
															return

									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()
									_SCREAMING_SNAKE_CASE       =    True

									for model_class in self.all_model_classes:
															if model_class in [*get_values(UpperCAmelCase_	)]:
																					continue

															_SCREAMING_SNAKE_CASE       =    model_class(UpperCAmelCase_	)
															model.to(UpperCAmelCase_	)
															model.train()
															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(UpperCAmelCase_ ,      UpperCAmelCase_ ,      return_labels=UpperCAmelCase_	)
															_SCREAMING_SNAKE_CASE       =    model(**UpperCAmelCase_	).loss
															loss.backward()







			def 				UpperCamelCase (      self:    Dict	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()
									if not self.model_tester.is_training:
															return

									_SCREAMING_SNAKE_CASE       =    False
									_SCREAMING_SNAKE_CASE       =    True

									for model_class in self.all_model_classes:
															if model_class in [*get_values(UpperCAmelCase_	)] or not model_class.supports_gradient_checkpointing:
																					continue
															# TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
															# this can then be incorporated into _prepare_for_class in test_modeling_common.py
															elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
																					_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    inputs_dict["""pixel_values"""].shape
																					_SCREAMING_SNAKE_CASE       =    torch.zeros(
																					    [self.model_tester.batch_size, height, width] ,      device=UpperCAmelCase_	).long()
															_SCREAMING_SNAKE_CASE       =    model_class(UpperCAmelCase_	)
															model.gradient_checkpointing_enable()
															model.to(UpperCAmelCase_	)
															model.train()
															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(UpperCAmelCase_ ,      UpperCAmelCase_ ,      return_labels=UpperCAmelCase_	)
															_SCREAMING_SNAKE_CASE       =    model(**UpperCAmelCase_	).loss
															loss.backward()







			def 				UpperCamelCase (      self:    str	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()

									_SCREAMING_SNAKE_CASE       =    _config_zero_init(UpperCAmelCase_	)
									for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE       =    model_class(config=UpperCAmelCase_	)
															for name, param in model.named_parameters():
																					# we skip lambda parameters as these require special initial values
																					# determined by config.layer_scale_init_value
																					if "lambda" in name:
																											continue
																					if param.requires_grad:
																											self.assertIn(
																											    ((param.data.mean() * 1E9).round() / 1E9).item() ,      [0.0, 1.0] ,      msg=F'Parameter {name} of model {model_class} seems not properly initialized' ,      )







			def 				UpperCamelCase (      self:    int ,      UpperCAmelCase_:    Optional[Any] ,      UpperCAmelCase_:    int ,      UpperCAmelCase_:    Any ,      UpperCAmelCase_:    Union[str, Any]=2E-4 ,      UpperCAmelCase_:    Tuple="outputs" ,      UpperCAmelCase_:    Union[str, Any]=None	):







									'''simple docstring'''




									super().check_pt_tf_outputs(UpperCAmelCase_ ,      UpperCAmelCase_ ,      UpperCAmelCase_ ,      UpperCAmelCase_ ,      UpperCAmelCase_ ,      UpperCAmelCase_	)







			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_	)







			@slow
			def 				UpperCamelCase (      self:    int	):







									'''simple docstring'''




									for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE       =    DataaVecVisionModel.from_pretrained(UpperCAmelCase_	)
															self.assertIsNotNone(UpperCAmelCase_	)

def 			__lowerCamelCase     (						)				->    int:






						"""simple docstring"""





						_SCREAMING_SNAKE_CASE       =    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
						return image




@require_torch
@require_vision
class  __UpperCAmelCase						(unittest.TestCase       ):







			@cached_property
			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									return (
									    BeitImageProcessor.from_pretrained("""facebook/data2vec-vision-base-ft1k"""	) if is_vision_available() else None
									)







			@slow
			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DataaVecVisionForImageClassification.from_pretrained("""facebook/data2vec-vision-base-ft1k"""	).to(
									    UpperCAmelCase_	)

									_SCREAMING_SNAKE_CASE       =    self.default_image_processor
									_SCREAMING_SNAKE_CASE       =    prepare_img()
									_SCREAMING_SNAKE_CASE       =    image_processor(images=UpperCAmelCase_ ,      return_tensors="""pt"""	).to(UpperCAmelCase_	)

									# forward pass
									with torch.no_grad():
															_SCREAMING_SNAKE_CASE       =    model(**UpperCAmelCase_	)
									_SCREAMING_SNAKE_CASE       =    outputs.logits

									# verify the logits
									_SCREAMING_SNAKE_CASE       =    torch.Size((1, 1_000)	)
									self.assertEqual(logits.shape ,      UpperCAmelCase_	)

									_SCREAMING_SNAKE_CASE       =    torch.tensor([0.32_77, -0.13_95, 0.09_11]	).to(UpperCAmelCase_	)

									self.assertTrue(torch.allclose(logits[0, :3] ,      UpperCAmelCase_ ,      atol=1E-4	)	)

									_SCREAMING_SNAKE_CASE       =    [model.config.labelaid[i] for i in ["""remote control, remote""", """tabby, tabby cat"""]]
									self.assertEqual(logits[0].topk(2	).indices.cpu().tolist() ,      UpperCAmelCase_	)

