code: 
  
  
  
  
  
  
  import json
  import logging
  import os
  import random
  import sys
  from dataclasses import dataclass, field
  from typing import Optional
  
  import evaluate
  import numpy as np
  import torch
  from datasets import load_dataset
  from huggingface_hub import hf_hub_download
  from PIL import Image
  from torch import nn
  from torchvision import transforms
  from torchvision.transforms import functional
  
  import transformers
  from transformers import (
      AutoConfig,
      AutoImageProcessor,
      AutoModelForSemanticSegmentation,
      HfArgumentParser,
      Trainer,
      TrainingArguments,
      default_data_collator,
  )
  from transformers.trainer_utils import get_last_checkpoint
  from transformers.utils import check_min_version, send_example_telemetry
  from transformers.utils.versions import require_version
  __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 			lowercase__  (				A_:	List[str]     ,			A_:	List[Any]     ,			A_:	str=0		)  ->							Dict:
  
  
  
  
  
  
  
         """simple docstring"""
  
  
  
  
  
  
         __UpperCAmelCase    							=(size, size) if isinstance(lowerCAmelCase__     ,			lowerCAmelCase__		) else size
         __UpperCAmelCase    							=img.size
         __UpperCAmelCase    							=size[1] - original_height if original_height < size[1] else 0
         __UpperCAmelCase    							=size[0] - original_width if original_width < size[0] else 0
         __UpperCAmelCase    							=functional.pad(lowerCAmelCase__     ,			(0, 0, pad_width, pad_height)     ,			fill=lowerCAmelCase__		)
         return img
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __init__(							self			:    str   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]			)			->       Union[str, Any]:
             __UpperCAmelCase    							=transforms
  
  
  
      def __call__(							self			:    Any   ,    __SCREAMING_SNAKE_CASE			:    Optional[Any]   ,    __SCREAMING_SNAKE_CASE			:    Union[str, Any]			)			->       List[str]:
             for t in self.transforms:
                    __UpperCAmelCase    							=t(__SCREAMING_SNAKE_CASE   ,    __SCREAMING_SNAKE_CASE			)
             return image, target
  
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __init__(							self			:    Optional[Any]			)			->       str:
             pass
  
  
  
      def __call__(							self			:    Tuple   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]   ,    __SCREAMING_SNAKE_CASE			:    int			)			->       List[str]:
             return image, target
  
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __init__(							self			:    List[Any]   ,    __SCREAMING_SNAKE_CASE			:    Dict			)			->       Any:
             __UpperCAmelCase    							=size
  
  
  
      def __call__(							self			:    Union[str, Any]   ,    __SCREAMING_SNAKE_CASE			:    Tuple   ,    __SCREAMING_SNAKE_CASE			:    int			)			->       List[str]:
             __UpperCAmelCase    							=functional.resize(__SCREAMING_SNAKE_CASE   ,    self.size			)
             __UpperCAmelCase    							=functional.resize(__SCREAMING_SNAKE_CASE   ,    self.size   ,    interpolation=transforms.InterpolationMode.NEAREST			)
             return image, target
  
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __init__(							self			:    List[Any]   ,    __SCREAMING_SNAKE_CASE			:    List[str]   ,    __SCREAMING_SNAKE_CASE			:    Union[str, Any]=None			)			->       Optional[int]:
             __UpperCAmelCase    							=min_size
             if max_size is None:
                    __UpperCAmelCase    							=min_size
             __UpperCAmelCase    							=max_size
  
  
  
      def __call__(							self			:    Optional[int]   ,    __SCREAMING_SNAKE_CASE			:    Optional[Any]   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]			)			->       List[str]:
             __UpperCAmelCase    							=random.randint(self.min_size   ,    self.max_size			)
             __UpperCAmelCase    							=functional.resize(__SCREAMING_SNAKE_CASE   ,    __SCREAMING_SNAKE_CASE			)
             __UpperCAmelCase    							=functional.resize(__SCREAMING_SNAKE_CASE   ,    __SCREAMING_SNAKE_CASE   ,    interpolation=transforms.InterpolationMode.NEAREST			)
             return image, target
  
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __init__(							self			:    Any   ,    __SCREAMING_SNAKE_CASE			:    Union[str, Any]			)			->       Optional[int]:
             __UpperCAmelCase    							=size if isinstance(__SCREAMING_SNAKE_CASE   ,    __SCREAMING_SNAKE_CASE			) else (size, size)
  
  
  
      def __call__(							self			:    Tuple   ,    __SCREAMING_SNAKE_CASE			:    Dict   ,    __SCREAMING_SNAKE_CASE			:    Any			)			->       Optional[int]:
             __UpperCAmelCase    							=pad_if_smaller(__SCREAMING_SNAKE_CASE   ,    self.size			)
             __UpperCAmelCase    							=pad_if_smaller(__SCREAMING_SNAKE_CASE   ,    self.size   ,    fill=255			)
             __UpperCAmelCase    							=transforms.RandomCrop.get_params(__SCREAMING_SNAKE_CASE   ,    self.size			)
             __UpperCAmelCase    							=functional.crop(__SCREAMING_SNAKE_CASE   ,    *__SCREAMING_SNAKE_CASE			)
             __UpperCAmelCase    							=functional.crop(__SCREAMING_SNAKE_CASE   ,    *__SCREAMING_SNAKE_CASE			)
             return image, target
  
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __init__(							self			:    Optional[Any]   ,    __SCREAMING_SNAKE_CASE			:    int			)			->       List[Any]:
             __UpperCAmelCase    							=flip_prob
  
  
  
      def __call__(							self			:    int   ,    __SCREAMING_SNAKE_CASE			:    int   ,    __SCREAMING_SNAKE_CASE			:    List[str]			)			->       List[str]:
             if random.random() < self.flip_prob:
                    __UpperCAmelCase    							=functional.hflip(__SCREAMING_SNAKE_CASE			)
                    __UpperCAmelCase    							=functional.hflip(__SCREAMING_SNAKE_CASE			)
             return image, target
  
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __call__(							self			:    str   ,    __SCREAMING_SNAKE_CASE			:    int   ,    __SCREAMING_SNAKE_CASE			:    Dict			)			->       List[Any]:
             __UpperCAmelCase    							=functional.pil_to_tensor(__SCREAMING_SNAKE_CASE			)
             __UpperCAmelCase    							=torch.as_tensor(np.array(__SCREAMING_SNAKE_CASE			)   ,    dtype=torch.intaa			)
             return image, target
  
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __init__(							self			:    int   ,    __SCREAMING_SNAKE_CASE			:    Optional[Any]			)			->       Tuple:
             __UpperCAmelCase    							=dtype
  
  
  
      def __call__(							self			:    Optional[Any]   ,    __SCREAMING_SNAKE_CASE			:    int   ,    __SCREAMING_SNAKE_CASE			:    Any			)			->       List[Any]:
             __UpperCAmelCase    							=functional.convert_image_dtype(__SCREAMING_SNAKE_CASE   ,    self.dtype			)
             return image, target
  
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __init__(							self			:    Optional[Any]   ,    __SCREAMING_SNAKE_CASE			:    int   ,    __SCREAMING_SNAKE_CASE			:    str			)			->       Dict:
             __UpperCAmelCase    							=mean
             __UpperCAmelCase    							=std
  
  
  
      def __call__(							self			:    str   ,    __SCREAMING_SNAKE_CASE			:    Dict   ,    __SCREAMING_SNAKE_CASE			:    Optional[Any]			)			->       Tuple:
             __UpperCAmelCase    							=functional.normalize(__SCREAMING_SNAKE_CASE   ,    mean=self.mean   ,    std=self.std			)
             return image, target
  
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __call__(							self			:    List[Any]   ,    __SCREAMING_SNAKE_CASE			:    Any   ,    __SCREAMING_SNAKE_CASE			:    List[Any]			)			->       Optional[Any]:
             if not isinstance(__SCREAMING_SNAKE_CASE   ,    np.ndarray			):
                    __UpperCAmelCase    							=np.array(__SCREAMING_SNAKE_CASE			).astype(np.uinta			)
             # avoid using underflow conversion
             __UpperCAmelCase    							=255
             __UpperCAmelCase    							=target - 1
             __UpperCAmelCase    							=255
  
             __UpperCAmelCase    							=Image.fromarray(__SCREAMING_SNAKE_CASE			)
             return image, target
  
  
  
  
  @dataclass
  class 							_A :
      """simple docstring"""
  
      lowerCamelCase  :       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).'
          }				,				)
      lowerCamelCase  :       Optional[str]   =   field(
          default=snake_case__				,				metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}							)
      lowerCamelCase  :       Optional[float]   =   field(
          default=0.1_5				,				metadata={'help': 'Percent to split off of train for validation.'}							)
      lowerCamelCase  :       Optional[int]   =   field(
          default=snake_case__				,				metadata={
              'help': (
                  'For debugging purposes or quicker training, truncate the number of training examples to this '
                  'value if set.'
              )
          }				,				)
      lowerCamelCase  :       Optional[int]   =   field(
          default=snake_case__				,				metadata={
              'help': (
                  'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
                  'value if set.'
              )
          }				,				)
      lowerCamelCase  :       Optional[bool]   =   field(
          default=snake_case__				,				metadata={'help': 'Whether or not to reduce all labels by 1 and replace background by 255.'}				,				)
  
  
  
      def _a       (							self			:    Union[str, Any]			)			->       List[Any]:
             if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
                    raise ValueError(
                        """You must specify either a dataset name from the hub or a train and/or validation directory."""			)
  
  
  
  
  @dataclass
  class 							_A :
      """simple docstring"""
  
      lowerCamelCase  :       str   =   field(
          default='nvidia/mit-b0'				,				metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}				,				)
      lowerCamelCase  :       Optional[str]   =   field(
          default=snake_case__				,				metadata={'help': 'Pretrained config name or path if not the same as model_name'}							)
      lowerCamelCase  :       Optional[str]   =   field(
          default=snake_case__				,				metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'}							)
      lowerCamelCase  :       str   =   field(
          default='main'				,				metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}				,				)
      lowerCamelCase  :       str   =   field(default=snake_case__				,				metadata={'help': 'Name or path of preprocessor config.'}							)
      lowerCamelCase  :       bool   =   field(
          default=snake_case__				,				metadata={
              'help': (
                  'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
                  'with private models).'
              )
          }				,				)
  
  
  
  
  
  
  
  def 			lowercase__  (				)  ->							str:
  
  
  
  
  
  
  
         """simple docstring"""
  
  
  
  
  
  
         __UpperCAmelCase    							=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.
                __UpperCAmelCase    							=parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]		)		)
         else:
                __UpperCAmelCase    							=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()
  
         __UpperCAmelCase    							=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.
         __UpperCAmelCase    							=None
         if os.path.isdir(training_args.output_dir		) and training_args.do_train and not training_args.overwrite_output_dir:
                __UpperCAmelCase    							=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
         __UpperCAmelCase    							=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:
                __UpperCAmelCase    							=dataset.rename_columns({"""pixel_values""": """image"""}		)
         if "annotation" in dataset["train"].column_names:
                __UpperCAmelCase    							=dataset.rename_columns({"""annotation""": """label"""}		)
  
         # If we don't have a validation split, split off a percentage of train as validation.
         __UpperCAmelCase    							=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:
                __UpperCAmelCase    							=dataset['train'].train_test_split(data_args.train_val_split		)
                __UpperCAmelCase    							=split['train']
                __UpperCAmelCase    							=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":
                __UpperCAmelCase    							='huggingface/label-files'
                __UpperCAmelCase    							='ade20k-id2label.json'
         else:
                __UpperCAmelCase    							=data_args.dataset_name
                __UpperCAmelCase    							='id2label.json'
         __UpperCAmelCase    							=json.load(open(hf_hub_download(lowerCAmelCase__     ,			lowerCAmelCase__     ,			repo_type="""dataset"""		)     ,			"""r"""		)		)
         __UpperCAmelCase    							={int(lowerCAmelCase__		): v for k, v in idalabel.items()}
         __UpperCAmelCase    							={v: str(lowerCAmelCase__		) for k, v in idalabel.items()}
  
         # Load the mean IoU metric from the datasets package
         __UpperCAmelCase    							=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(A_:	Dict		):
                __UpperCAmelCase    							=eval_pred
                __UpperCAmelCase    							=torch.from_numpy(lowerCAmelCase__		)
                # scale the logits to the size of the label
                __UpperCAmelCase    							=nn.functional.interpolate(
                    lowerCAmelCase__     ,			size=labels.shape[-2:]     ,			mode="""bilinear"""     ,			align_corners=lowerCAmelCase__     ,			).argmax(dim=1		)
  
                __UpperCAmelCase    							=logits_tensor.detach().cpu().numpy()
                __UpperCAmelCase    							=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
                __UpperCAmelCase    							=metrics.pop("""per_category_accuracy"""		).tolist()
                __UpperCAmelCase    							=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
  
         __UpperCAmelCase    							=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     ,			)
         __UpperCAmelCase    							=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     ,			)
         __UpperCAmelCase    							=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.
                __UpperCAmelCase    							=(image_processor.size['shortest_edge'], image_processor.size['shortest_edge'])
         else:
                __UpperCAmelCase    							=(image_processor.size['height'], image_processor.size['width'])
         __UpperCAmelCase    							=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)
         __UpperCAmelCase    							=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(A_:	Union[str, Any]		):
                __UpperCAmelCase    							=[]
                __UpperCAmelCase    							=[]
                for image, target in zip(example_batch["""image"""]     ,			example_batch["""label"""]		):
                       __UpperCAmelCase    							=train_transforms(image.convert("""RGB"""		)     ,			lowerCAmelCase__		)
                       pixel_values.append(lowerCAmelCase__		)
                       labels.append(lowerCAmelCase__		)
  
                __UpperCAmelCase    							={}
                __UpperCAmelCase    							=torch.stack(lowerCAmelCase__		)
                __UpperCAmelCase    							=torch.stack(lowerCAmelCase__		)
  
                return encoding
  
         def preprocess_val(A_:	List[Any]		):
                __UpperCAmelCase    							=[]
                __UpperCAmelCase    							=[]
                for image, target in zip(example_batch["""image"""]     ,			example_batch["""label"""]		):
                       __UpperCAmelCase    							=val_transforms(image.convert("""RGB"""		)     ,			lowerCAmelCase__		)
                       pixel_values.append(lowerCAmelCase__		)
                       labels.append(lowerCAmelCase__		)
  
                __UpperCAmelCase    							={}
                __UpperCAmelCase    							=torch.stack(lowerCAmelCase__		)
                __UpperCAmelCase    							=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:
                       __UpperCAmelCase    							=(
                           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:
                       __UpperCAmelCase    							=(
                           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
         __UpperCAmelCase    							=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:
                __UpperCAmelCase    							=None
                if training_args.resume_from_checkpoint is not None:
                       __UpperCAmelCase    							=training_args.resume_from_checkpoint
                elif last_checkpoint is not None:
                       __UpperCAmelCase    							=last_checkpoint
                __UpperCAmelCase    							=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:
                __UpperCAmelCase    							=trainer.evaluate()
                trainer.log_metrics("""eval"""     ,			lowerCAmelCase__		)
                trainer.save_metrics("""eval"""     ,			lowerCAmelCase__		)
  
         # Write model card and (optionally) push to hub
         __UpperCAmelCase    							={
             'finetuned_from': model_args.model_name_or_path,
             'dataset': data_args.dataset_name,
             'tags': ['image-segmentation', 'vision'],
         }
         if training_args.push_to_hub:
                trainer.push_to_hub(**lowerCAmelCase__		)
         else:
                trainer.create_model_card(**lowerCAmelCase__		)
  
  
  if __name__ == "__main__":
     main()
  
  
  
  
  
style_context: 
  
  
  
  
  
  
  import unittest
  
  from transformers import ErnieMConfig, is_torch_available
  from transformers.testing_utils import require_torch, slow, torch_device
  
  from ...test_configuration_common import ConfigTester
  from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
  from ...test_pipeline_mixin import PipelineTesterMixin
  
  
  if is_torch_available():
     import torch
  
     from transformers import (
         ErnieMForInformationExtraction,
         ErnieMForMultipleChoice,
         ErnieMForQuestionAnswering,
         ErnieMForSequenceClassification,
         ErnieMForTokenClassification,
         ErnieMModel,
     )
     from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST
  
  
  
  class 							_A :
      """simple docstring"""
  
      def __init__(							self			:    Any   ,    __SCREAMING_SNAKE_CASE			:    str   ,    __SCREAMING_SNAKE_CASE			:    List[str]=13   ,    __SCREAMING_SNAKE_CASE			:    Union[str, Any]=7   ,    __SCREAMING_SNAKE_CASE			:    List[Any]=True   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]=True   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]=True   ,    __SCREAMING_SNAKE_CASE			:    str=99   ,    __SCREAMING_SNAKE_CASE			:    int=32   ,    __SCREAMING_SNAKE_CASE			:    str=5   ,    __SCREAMING_SNAKE_CASE			:    int=4   ,    __SCREAMING_SNAKE_CASE			:    List[str]=37   ,    __SCREAMING_SNAKE_CASE			:    int="gelu"   ,    __SCREAMING_SNAKE_CASE			:    Tuple=0.1   ,    __SCREAMING_SNAKE_CASE			:    List[str]=0.1   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]=512   ,    __SCREAMING_SNAKE_CASE			:    int=16   ,    __SCREAMING_SNAKE_CASE			:    int=2   ,    __SCREAMING_SNAKE_CASE			:    Any=0.02   ,    __SCREAMING_SNAKE_CASE			:    Dict=3   ,    __SCREAMING_SNAKE_CASE			:    Dict=4   ,    __SCREAMING_SNAKE_CASE			:    str=None   ,    )			->       Optional[Any]:
             __UpperCAmelCase    							=parent
             __UpperCAmelCase    							=batch_size
             __UpperCAmelCase    							=seq_length
             __UpperCAmelCase    							=is_training
             __UpperCAmelCase    							=use_input_mask
             __UpperCAmelCase    							=use_labels
             __UpperCAmelCase    							=vocab_size
             __UpperCAmelCase    							=hidden_size
             __UpperCAmelCase    							=num_hidden_layers
             __UpperCAmelCase    							=num_attention_heads
             __UpperCAmelCase    							=intermediate_size
             __UpperCAmelCase    							=hidden_act
             __UpperCAmelCase    							=hidden_dropout_prob
             __UpperCAmelCase    							=attention_probs_dropout_prob
             __UpperCAmelCase    							=max_position_embeddings
             __UpperCAmelCase    							=type_vocab_size
             __UpperCAmelCase    							=type_sequence_label_size
             __UpperCAmelCase    							=initializer_range
             __UpperCAmelCase    							=num_labels
             __UpperCAmelCase    							=num_choices
             __UpperCAmelCase    							=scope
  
  
  
      def _a       (							self			:    str			)			->       Optional[Any]:
             __UpperCAmelCase    							=ids_tensor([self.batch_size, self.seq_length]   ,    self.vocab_size			)
  
             __UpperCAmelCase    							=None
             if self.use_input_mask:
                    __UpperCAmelCase    							=random_attention_mask([self.batch_size, self.seq_length]			)
  
             __UpperCAmelCase    							=None
             __UpperCAmelCase    							=None
             __UpperCAmelCase    							=None
             if self.use_labels:
                    __UpperCAmelCase    							=ids_tensor([self.batch_size]   ,    self.type_sequence_label_size			)
                    __UpperCAmelCase    							=ids_tensor([self.batch_size, self.seq_length]   ,    self.num_labels			)
                    __UpperCAmelCase    							=ids_tensor([self.batch_size]   ,    self.num_choices			)
  
             __UpperCAmelCase    							=self.get_config()
  
             return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
  
  
  
      def _a       (							self			:    Optional[Any]			)			->       Any:
             __UpperCAmelCase    							=ids_tensor([self.batch_size, self.seq_length]   ,    self.vocab_size			)
  
             __UpperCAmelCase    							=None
             if self.use_input_mask:
                    __UpperCAmelCase    							=random_attention_mask([self.batch_size, self.seq_length]			)
             __UpperCAmelCase    							=self.get_config()
  
             return config, input_ids, input_mask
  
  
  
      def _a       (							self			:    List[str]			)			->       List[str]:
             return ErnieMConfig(
                 vocab_size=self.vocab_size   ,    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   ,    max_position_embeddings=self.max_position_embeddings   ,    type_vocab_size=self.type_vocab_size   ,    initializer_range=self.initializer_range   ,    )
  
  
  
      def _a       (							self			:    str   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]   ,    __SCREAMING_SNAKE_CASE			:    List[str]   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]   ,    __SCREAMING_SNAKE_CASE			:    Union[str, Any]   ,    __SCREAMING_SNAKE_CASE			:    str   ,    __SCREAMING_SNAKE_CASE			:    Dict			)			->       Optional[int]:
             __UpperCAmelCase    							=ErnieMModel(config=__SCREAMING_SNAKE_CASE			)
             model.to(__SCREAMING_SNAKE_CASE			)
             model.eval()
             __UpperCAmelCase    							=model(__SCREAMING_SNAKE_CASE   ,    return_dict=__SCREAMING_SNAKE_CASE			)
             self.parent.assertEqual(result.last_hidden_state.shape   ,    (self.batch_size, self.seq_length, self.hidden_size)			)
  
  
  
      def _a       (							self			:    Tuple   ,    __SCREAMING_SNAKE_CASE			:    List[str]   ,    __SCREAMING_SNAKE_CASE			:    Optional[Any]   ,    __SCREAMING_SNAKE_CASE			:    List[Any]   ,    __SCREAMING_SNAKE_CASE			:    Tuple   ,    __SCREAMING_SNAKE_CASE			:    Any   ,    __SCREAMING_SNAKE_CASE			:    Dict			)			->       int:
             __UpperCAmelCase    							=ErnieMForQuestionAnswering(config=__SCREAMING_SNAKE_CASE			)
             model.to(__SCREAMING_SNAKE_CASE			)
             model.eval()
             __UpperCAmelCase    							=model(
                 __SCREAMING_SNAKE_CASE   ,    attention_mask=__SCREAMING_SNAKE_CASE   ,    start_positions=__SCREAMING_SNAKE_CASE   ,    end_positions=__SCREAMING_SNAKE_CASE   ,    )
             self.parent.assertEqual(result.start_logits.shape   ,    (self.batch_size, self.seq_length)			)
             self.parent.assertEqual(result.end_logits.shape   ,    (self.batch_size, self.seq_length)			)
  
  
  
      def _a       (							self			:    Optional[Any]   ,    __SCREAMING_SNAKE_CASE			:    List[str]   ,    __SCREAMING_SNAKE_CASE			:    List[Any]   ,    __SCREAMING_SNAKE_CASE			:    List[str]   ,    __SCREAMING_SNAKE_CASE			:    Tuple   ,    __SCREAMING_SNAKE_CASE			:    Dict   ,    __SCREAMING_SNAKE_CASE			:    Optional[Any]			)			->       Any:
             __UpperCAmelCase    							=ErnieMForInformationExtraction(config=__SCREAMING_SNAKE_CASE			)
             model.to(__SCREAMING_SNAKE_CASE			)
             model.eval()
             __UpperCAmelCase    							=torch.ones_like(__SCREAMING_SNAKE_CASE   ,    dtype=torch.floataa			)
             __UpperCAmelCase    							=model(
                 __SCREAMING_SNAKE_CASE   ,    attention_mask=__SCREAMING_SNAKE_CASE   ,    start_positions=__SCREAMING_SNAKE_CASE   ,    end_positions=__SCREAMING_SNAKE_CASE   ,    )
             self.parent.assertEqual(result.start_logits.shape   ,    (self.batch_size, self.seq_length)			)
             self.parent.assertEqual(result.end_logits.shape   ,    (self.batch_size, self.seq_length)			)
  
  
  
      def _a       (							self			:    Union[str, Any]   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]   ,    __SCREAMING_SNAKE_CASE			:    Any   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]   ,    __SCREAMING_SNAKE_CASE			:    List[Any]   ,    __SCREAMING_SNAKE_CASE			:    Optional[Any]			)			->       str:
             __UpperCAmelCase    							=self.num_labels
             __UpperCAmelCase    							=ErnieMForSequenceClassification(__SCREAMING_SNAKE_CASE			)
             model.to(__SCREAMING_SNAKE_CASE			)
             model.eval()
             __UpperCAmelCase    							=model(__SCREAMING_SNAKE_CASE   ,    attention_mask=__SCREAMING_SNAKE_CASE   ,    labels=__SCREAMING_SNAKE_CASE			)
             self.parent.assertEqual(result.logits.shape   ,    (self.batch_size, self.num_labels)			)
  
  
  
      def _a       (							self			:    Dict   ,    __SCREAMING_SNAKE_CASE			:    Optional[Any]   ,    __SCREAMING_SNAKE_CASE			:    List[Any]   ,    __SCREAMING_SNAKE_CASE			:    Union[str, Any]   ,    __SCREAMING_SNAKE_CASE			:    Dict   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]   ,    __SCREAMING_SNAKE_CASE			:    Dict			)			->       Dict:
             __UpperCAmelCase    							=self.num_labels
             __UpperCAmelCase    							=ErnieMForTokenClassification(config=__SCREAMING_SNAKE_CASE			)
             model.to(__SCREAMING_SNAKE_CASE			)
             model.eval()
             input_ids.to(__SCREAMING_SNAKE_CASE			)
             input_mask.to(__SCREAMING_SNAKE_CASE			)
             token_labels.to(__SCREAMING_SNAKE_CASE			)
  
             __UpperCAmelCase    							=model(__SCREAMING_SNAKE_CASE   ,    attention_mask=__SCREAMING_SNAKE_CASE   ,    labels=__SCREAMING_SNAKE_CASE			)
  
             self.parent.assertEqual(result.logits.shape   ,    (self.batch_size, self.seq_length, self.num_labels)			)
  
  
  
      def _a       (							self			:    Optional[Any]   ,    __SCREAMING_SNAKE_CASE			:    Union[str, Any]   ,    __SCREAMING_SNAKE_CASE			:    Optional[int]   ,    __SCREAMING_SNAKE_CASE			:    Tuple   ,    __SCREAMING_SNAKE_CASE			:    int   ,    __SCREAMING_SNAKE_CASE			:    Tuple   ,    __SCREAMING_SNAKE_CASE			:    Optional[Any]			)			->       List[Any]:
             __UpperCAmelCase    							=self.num_choices
             __UpperCAmelCase    							=ErnieMForMultipleChoice(config=__SCREAMING_SNAKE_CASE			)
             model.to(__SCREAMING_SNAKE_CASE			)
             model.eval()
             __UpperCAmelCase    							=input_ids.unsqueeze(1			).expand(-1   ,    self.num_choices   ,    -1			).contiguous()
             __UpperCAmelCase    							=input_mask.unsqueeze(1			).expand(-1   ,    self.num_choices   ,    -1			).contiguous()
             __UpperCAmelCase    							=model(
                 __SCREAMING_SNAKE_CASE   ,    attention_mask=__SCREAMING_SNAKE_CASE   ,    labels=__SCREAMING_SNAKE_CASE   ,    )
             self.parent.assertEqual(result.logits.shape   ,    (self.batch_size, self.num_choices)			)
  
  
  
      def _a       (							self			:    Any			)			->       List[str]:
             __UpperCAmelCase    							=self.prepare_config_and_inputs()
             (
                 (
                 __UpperCAmelCase
             )							,   (
                 __UpperCAmelCase
             )							,   (
                 __UpperCAmelCase
             )							,   (
                 __UpperCAmelCase
             )							,   (
                 __UpperCAmelCase
             )							,   (
                 __UpperCAmelCase
             )							,   
             )    							=config_and_inputs
             __UpperCAmelCase    							={"""input_ids""": input_ids, """attention_mask""": input_mask}
             return config, inputs_dict
  
  
  
  
  @require_torch
  class 							_A (    UpperCamelCase				,				UpperCamelCase				,				unittest.TestCase							):
      """simple docstring"""
  
      lowerCamelCase  :       Union[str, Any]   =   (
          (
              ErnieMModel,
              ErnieMForMultipleChoice,
              ErnieMForQuestionAnswering,
              ErnieMForSequenceClassification,
              ErnieMForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      lowerCamelCase  :       Optional[Any]   =   ()
      lowerCamelCase  :       str   =   (
          {
              'feature-extraction': ErnieMModel,
              'question-answering': ErnieMForQuestionAnswering,
              'text-classification': ErnieMForSequenceClassification,
              'token-classification': ErnieMForTokenClassification,
              'zero-shot': ErnieMForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      lowerCamelCase  :       Optional[int]   =   False
  
  
  
      def _a       (							self			:    Dict   ,    __SCREAMING_SNAKE_CASE			:    Dict   ,    __SCREAMING_SNAKE_CASE			:    Union[str, Any]   ,    __SCREAMING_SNAKE_CASE			:    List[Any]   ,    __SCREAMING_SNAKE_CASE			:    int   ,    __SCREAMING_SNAKE_CASE			:    int			)			->       Optional[int]:
             if pipeline_test_casse_name == "QAPipelineTests":
                    return True
  
             return False
  
  
  
      def _a       (							self			:    Optional[int]			)			->       List[Any]:
             __UpperCAmelCase    							=ErnieMModelTester(self			)
             __UpperCAmelCase    							=ConfigTester(self   ,    config_class=__SCREAMING_SNAKE_CASE   ,    hidden_size=37			)
  
  
  
      def _a       (							self			:    int			)			->       List[str]:
             self.config_tester.run_common_tests()
  
  
  
      def _a       (							self			:    str			)			->       str:
             __UpperCAmelCase    							=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE			)
  
  
  
      def _a       (							self			:    Optional[int]			)			->       List[str]:
             __UpperCAmelCase    							=self.model_tester.prepare_config_and_inputs()
             for type in ["absolute", "relative_key", "relative_key_query"]:
                    __UpperCAmelCase    							=type
                    self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE			)
  
  
  
      def _a       (							self			:    Optional[int]			)			->       str:
             __UpperCAmelCase    							=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_multiple_choice(*__SCREAMING_SNAKE_CASE			)
  
  
  
      def _a       (							self			:    List[str]			)			->       Union[str, Any]:
             __UpperCAmelCase    							=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE			)
  
  
  
      def _a       (							self			:    Any			)			->       str:
             __UpperCAmelCase    							=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE			)
  
  
  
      def _a       (							self			:    str			)			->       List[Any]:
             __UpperCAmelCase    							=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_information_extraction(*__SCREAMING_SNAKE_CASE			)
  
  
  
      def _a       (							self			:    List[Any]			)			->       List[str]:
             __UpperCAmelCase    							=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE			)
  
  
  
      @slow
      def _a       (							self			:    List[str]			)			->       Optional[Any]:
             for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    __UpperCAmelCase    							=ErnieMModel.from_pretrained(__SCREAMING_SNAKE_CASE			)
                    self.assertIsNotNone(__SCREAMING_SNAKE_CASE			)
  
  
  
  
  @require_torch
  class 							_A (    unittest.TestCase							):
      """simple docstring"""
  
      @slow
      def _a       (							self			:    Tuple			)			->       Optional[Any]:
             __UpperCAmelCase    							=ErnieMModel.from_pretrained("""susnato/ernie-m-base_pytorch"""			)
             model.eval()
             __UpperCAmelCase    							=torch.tensor([[0, 1, 2, 3, 4, 5]]			)
             __UpperCAmelCase    							=model(__SCREAMING_SNAKE_CASE			)[0]
  
             # TODO Replace vocab size
             __UpperCAmelCase    							=768
  
             __UpperCAmelCase    							=torch.Size((1, 6, hidden_size)			)
             self.assertEqual(output.shape   ,    __SCREAMING_SNAKE_CASE			)
  
             __UpperCAmelCase    							=torch.tensor(
                 [[[-0.0_012, 0.1_245, -0.0_214], [-0.0_742, 0.0_244, -0.0_771], [-0.0_333, 0.1_164, -0.1_554]]]			)
  
             self.assertTrue(torch.allclose(output[:, :3, :3]   ,    __SCREAMING_SNAKE_CASE   ,    atol=1e-3			)			)
  
  
  
  
  