


'''simple docstring'''







import argparse
import logging
import os
import time
import timeit

import datasets
import numpy as np
import pycuda.autoinit  # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions

import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate


lowerCAmelCase    :     Tuple					=						trt.Logger(trt.Logger.WARNING)
lowerCAmelCase    :     Optional[int]					=						absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)

lowerCAmelCase    :     Union[str, Any]					=						logging.getLogger(__name__)

lowerCAmelCase    :     Union[str, Any]					=						argparse.ArgumentParser()

# Required parameters
parser.add_argument(
    """--onnx_model_path""",
    default=None,
    type=str,
    required=True,
    help="""Path to ONNX model: """,
)

parser.add_argument(
    """--output_dir""",
    default=None,
    type=str,
    required=True,
    help="""The output directory where the model checkpoints and predictions will be written.""",
)

# Other parameters

parser.add_argument(
    """--tokenizer_name""",
    default="""""",
    type=str,
    required=True,
    help="""Pretrained tokenizer name or path if not the same as model_name""",
)

parser.add_argument(
    """--version_2_with_negative""",
    action="""store_true""",
    help="""If true, the SQuAD examples contain some that do not have an answer.""",
)
parser.add_argument(
    """--null_score_diff_threshold""",
    type=float,
    default=0.0,
    help="""If null_score - best_non_null is greater than the threshold predict null.""",
)

parser.add_argument(
    """--max_seq_length""",
    default=3_84,
    type=int,
    help=(
        """The maximum total input sequence length after WordPiece tokenization. Sequences """
        """longer than this will be truncated, and sequences shorter than this will be padded."""
    ),
)
parser.add_argument(
    """--doc_stride""",
    default=1_28,
    type=int,
    help="""When splitting up a long document into chunks, how much stride to take between chunks.""",
)

parser.add_argument("""--per_device_eval_batch_size""", default=8, type=int, help="""Batch size per GPU/CPU for evaluation.""")

parser.add_argument(
    """--n_best_size""",
    default=20,
    type=int,
    help="""The total number of n-best predictions to generate in the nbest_predictions.json output file.""",
)
parser.add_argument(
    """--max_answer_length""",
    default=30,
    type=int,
    help=(
        """The maximum length of an answer that can be generated. This is needed because the start """
        """and end predictions are not conditioned on one another."""
    ),
)

parser.add_argument("""--seed""", type=int, default=42, help="""random seed for initialization""")

parser.add_argument(
    """--dataset_name""",
    type=str,
    default=None,
    required=True,
    help="""The name of the dataset to use (via the datasets library).""",
)
parser.add_argument(
    """--dataset_config_name""",
    type=str,
    default=None,
    help="""The configuration name of the dataset to use (via the datasets library).""",
)
parser.add_argument(
    """--preprocessing_num_workers""", type=int, default=4, help="""A csv or a json file containing the training data."""
)
parser.add_argument("""--overwrite_cache""", action="""store_true""", help="""Overwrite the cached training and evaluation sets""")
parser.add_argument(
    """--fp16""",
    action="""store_true""",
    help="""Whether to use 16-bit (mixed) precision instead of 32-bit""",
)
parser.add_argument(
    """--int8""",
    action="""store_true""",
    help="""Whether to use INT8""",
)

lowerCAmelCase    :     Tuple					=						parser.parse_args()

if args.tokenizer_name:
       lowerCAmelCase    :     Tuple					=						AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
       raise ValueError(
           """You are instantiating a new tokenizer from scratch. This is not supported by this script."""
           """You can do it from another script, save it, and load it from here, using --tokenizer_name."""
       )

logger.info("""Training/evaluation parameters %s""", args)

lowerCAmelCase    :     Optional[Any]					=						args.per_device_eval_batch_size

lowerCAmelCase    :     Dict					=						(args.eval_batch_size, args.max_seq_length)

# TRT Engine properties
lowerCAmelCase    :     str					=						True

lowerCAmelCase    :     str					=						"""temp_engine/bert-fp32.engine"""
if args.fpaa:
       lowerCAmelCase    :     Optional[Any]					=						"""temp_engine/bert-fp16.engine"""
if args.inta:
       lowerCAmelCase    :     Dict					=						"""temp_engine/bert-int8.engine"""

# import ONNX file
if not os.path.exists("""temp_engine"""):
       os.makedirs("""temp_engine""")

lowerCAmelCase    :     Any					=						1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
    network, TRT_LOGGER
) as parser:
       with open(args.onnx_model_path, """rb""") as model:
              if not parser.parse(model.read()):
                     for error in range(parser.num_errors):
                            print(parser.get_error(error))

    # Query input names and shapes from parsed TensorRT network
       lowerCAmelCase    :     Any					=						[network.get_input(i) for i in range(network.num_inputs)]
       lowerCAmelCase    :     Any					=						[_input.name for _input in network_inputs]  # ex: ["actual_input1"]

       with builder.create_builder_config() as config:
              lowerCAmelCase    :     List[Any]					=						1 << 50
              if STRICT_TYPES:
                     config.set_flag(trt.BuilderFlag.STRICT_TYPES)
              if args.fpaa:
                     config.set_flag(trt.BuilderFlag.FPaa)
              if args.inta:
                     config.set_flag(trt.BuilderFlag.INTa)
              lowerCAmelCase    :     Optional[Any]					=						builder.create_optimization_profile()
              config.add_optimization_profile(profile)
              for i in range(len(input_names)):
                     profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
              lowerCAmelCase    :     Optional[int]					=						builder.build_engine(network, config)

              # serialize_engine and store in file (can be directly loaded and deserialized):
              with open(engine_name, """wb""") as f:
                     f.write(engine.serialize())






def 			lowercase				(_A   ,						_A   ,						_A   ,						_A   ,						_A   ,						_A   ,						_A   ,						_A					):







       """simple docstring"""







       _lowerCAmelCase    :							List[Any]   			=       np.asarray(inputs['input_ids']   ,						dtype=np.intaa					)
       _lowerCAmelCase    :							int   			=       np.asarray(inputs['attention_mask']   ,						dtype=np.intaa					)
       _lowerCAmelCase    :							Any   			=       np.asarray(inputs['token_type_ids']   ,						dtype=np.intaa					)

       # Copy inputs
       cuda.memcpy_htod_async(d_inputs[0]   ,						input_ids.ravel()   ,						_A					)
       cuda.memcpy_htod_async(d_inputs[1]   ,						attention_mask.ravel()   ,						_A					)
       cuda.memcpy_htod_async(d_inputs[2]   ,						token_type_ids.ravel()   ,						_A					)
       # start time
       _lowerCAmelCase    :							int   			=       time.time()
       # Run inference
       context.execute_async(
           bindings=[int(_A					) for d_inp in d_inputs] + [int(_A					), int(_A					)]   ,						stream_handle=stream.handle					)
       # Transfer predictions back from GPU
       cuda.memcpy_dtoh_async(_A   ,						_A   ,						_A					)
       cuda.memcpy_dtoh_async(_A   ,						_A   ,						_A					)
       # Synchronize the stream and take time
       stream.synchronize()
       # end time
       _lowerCAmelCase    :							List[str]   			=       time.time()
       _lowerCAmelCase    :							str   			=       end_time - start_time
       _lowerCAmelCase    :							List[str]   			=       (h_outputa, h_outputa)
       # print(outputs)
       return outputs, infer_time


# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
lowerCAmelCase    :     int					=						Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""",
    datefmt="""%m/%d/%Y %H:%M:%S""",
    level=logging.INFO,
)

# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
       datasets.utils.logging.set_verbosity_warning()
       transformers.utils.logging.set_verbosity_info()
else:
       datasets.utils.logging.set_verbosity_error()
       transformers.utils.logging.set_verbosity_error()

# If passed along, set the training seed now.
if args.seed is not None:
       set_seed(args.seed)

# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
       # Downloading and loading a dataset from the hub.
       lowerCAmelCase    :     Optional[Any]					=						load_dataset(args.dataset_name, args.dataset_config_name)
else:
       raise ValueError("""Evaluation requires a dataset name""")
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.

# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.

lowerCAmelCase    :     Optional[Any]					=						raw_datasets["""validation"""].column_names

lowerCAmelCase    :     Optional[int]					=						"""question""" if """question""" in column_names else column_names[0]
lowerCAmelCase    :     List[str]					=						"""context""" if """context""" in column_names else column_names[1]
lowerCAmelCase    :     int					=						"""answers""" if """answers""" in column_names else column_names[2]

# Padding side determines if we do (question|context) or (context|question).
lowerCAmelCase    :     Dict					=						tokenizer.padding_side == """right"""

if args.max_seq_length > tokenizer.model_max_length:
       logger.warning(
           F'''The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the'''
           F'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'''
       )

lowerCAmelCase    :     Any					=						min(args.max_seq_length, tokenizer.model_max_length)






def 			lowercase				(_A					):







       """simple docstring"""







       _lowerCAmelCase    :							Tuple   			=       [q.lstrip() for q in examples[question_column_name]]

       # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
       # in one example possible giving several features when a context is long, each of those features having a
       # context that overlaps a bit the context of the previous feature.
       _lowerCAmelCase    :							List[str]   			=       tokenizer(
           examples[question_column_name if pad_on_right else context_column_name]   ,						examples[context_column_name if pad_on_right else question_column_name]   ,						truncation='only_second' if pad_on_right else 'only_first'   ,						max_length=_A   ,						stride=args.doc_stride   ,						return_overflowing_tokens=_A   ,						return_offsets_mapping=_A   ,						padding='max_length'   ,						)

       # Since one example might give us several features if it has a long context, we need a map from a feature to
       # its corresponding example. This key gives us just that.
       _lowerCAmelCase    :							Tuple   			=       tokenized_examples.pop('overflow_to_sample_mapping'					)

       # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
       # corresponding example_id and we will store the offset mappings.
       _lowerCAmelCase    :							Any   			=       []

       for i in range(len(tokenized_examples['input_ids']					)					):
              # Grab the sequence corresponding to that example (to know what is the context and what is the question).
              _lowerCAmelCase    :							Optional[Any]   			=       tokenized_examples.sequence_ids(_A					)
              _lowerCAmelCase    :							Any   			=       1 if pad_on_right else 0

              # One example can give several spans, this is the index of the example containing this span of text.
              _lowerCAmelCase    :							str   			=       sample_mapping[i]
              tokenized_examples["example_id"].append(examples['id'][sample_index]					)

              # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
              # position is part of the context or not.
              _lowerCAmelCase    :							Union[str, Any]   			=       [
                  (o if sequence_ids[k] == context_index else None)
                  for k, o in enumerate(tokenized_examples['offset_mapping'][i]					)
              ]

       return tokenized_examples


lowerCAmelCase    :     str					=						raw_datasets["""validation"""]
# Validation Feature Creation
lowerCAmelCase    :     Dict					=						eval_examples.map(
    prepare_validation_features,
    batched=True,
    num_proc=args.preprocessing_num_workers,
    remove_columns=column_names,
    load_from_cache_file=not args.overwrite_cache,
    desc="""Running tokenizer on validation dataset""",
)

lowerCAmelCase    :     Any					=						default_data_collator

lowerCAmelCase    :     Union[str, Any]					=						eval_dataset.remove_columns(["""example_id""", """offset_mapping"""])
lowerCAmelCase    :     List[Any]					=						DataLoader(
    eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)






def 			lowercase				(_A   ,						_A   ,						_A   ,						_A="eval"					):







       """simple docstring"""







       _lowerCAmelCase    :							Any   			=       postprocess_qa_predictions(
           examples=_A   ,						features=_A   ,						predictions=_A   ,						version_2_with_negative=args.version_2_with_negative   ,						n_best_size=args.n_best_size   ,						max_answer_length=args.max_answer_length   ,						null_score_diff_threshold=args.null_score_diff_threshold   ,						output_dir=args.output_dir   ,						prefix=_A   ,						)
       # Format the result to the format the metric expects.
       if args.version_2_with_negative:
              _lowerCAmelCase    :							List[str]   			=       [
                  {'id': k, 'prediction_text': v, 'no_answer_probability': 0.0} for k, v in predictions.items()
              ]
       else:
              _lowerCAmelCase    :							int   			=       [{'id': k, 'prediction_text': v} for k, v in predictions.items()]

       _lowerCAmelCase    :							Tuple   			=       [{'id': ex['id'], 'answers': ex[answer_column_name]} for ex in examples]
       return EvalPrediction(predictions=_A   ,						label_ids=_A					)


lowerCAmelCase    :     str					=						load_metric("""squad_v2""" if args.version_2_with_negative else """squad""")

# Evaluation!
logger.info("""Loading ONNX model %s for evaluation""", args.onnx_model_path)
with open(engine_name, """rb""") as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
    f.read()
) as engine, engine.create_execution_context() as context:
       # setup for TRT inferrence
       for i in range(len(input_names)):
              context.set_binding_shape(i, INPUT_SHAPE)
       assert context.all_binding_shapes_specified






       def 			lowercase				(_A					):







              """simple docstring"""







              return trt.volume(engine.get_binding_shape(_A					)					) * engine.get_binding_dtype(_A					).itemsize

       # Allocate device memory for inputs and outputs.
       lowerCAmelCase    :     str					=						[cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]

       # Allocate output buffer
       lowerCAmelCase    :     Tuple					=						cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
       lowerCAmelCase    :     Optional[Any]					=						cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
       lowerCAmelCase    :     int					=						cuda.mem_alloc(h_outputa.nbytes)
       lowerCAmelCase    :     Dict					=						cuda.mem_alloc(h_outputa.nbytes)

       # Create a stream in which to copy inputs/outputs and run inference.
       lowerCAmelCase    :     Tuple					=						cuda.Stream()

       # Evaluation
       logger.info("""***** Running Evaluation *****""")
       logger.info(F'''  Num examples = {len(eval_dataset)}''')
       logger.info(F'''  Batch size = {args.per_device_eval_batch_size}''')

       lowerCAmelCase    :     List[Any]					=						0.0
       lowerCAmelCase    :     Optional[int]					=						0
       lowerCAmelCase    :     Optional[int]					=						timeit.default_timer()

       lowerCAmelCase    :     List[Any]					=						None
       for step, batch in enumerate(eval_dataloader):
              lowerCAmelCase	,						lowerCAmelCase    :     Optional[Any]					=						model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
              total_time += infer_time
              niter += 1

              lowerCAmelCase	,						lowerCAmelCase    :     Optional[int]					=						outputs
              lowerCAmelCase    :     Tuple					=						torch.tensor(start_logits)
              lowerCAmelCase    :     Any					=						torch.tensor(end_logits)

              # necessary to pad predictions and labels for being gathered
              lowerCAmelCase    :     Tuple					=						accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00)
              lowerCAmelCase    :     Tuple					=						accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00)

              lowerCAmelCase    :     str					=						(accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
              lowerCAmelCase    :     Any					=						logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00)

       if all_preds is not None:
              lowerCAmelCase    :     Union[str, Any]					=						nested_truncate(all_preds, len(eval_dataset))

       lowerCAmelCase    :     int					=						timeit.default_timer() - start_time
       logger.info("""  Evaluation done in total %f secs (%f sec per example)""", evalTime, evalTime / len(eval_dataset))
       # Inference time from TRT
       logger.info("""Average Inference Time = {:.3f} ms""".format(total_time * 10_00 / niter))
       logger.info("""Total Inference Time =  {:.3f} ms""".format(total_time * 10_00))
       logger.info("""Total Number of Inference =  %d""", niter)

lowerCAmelCase    :     Union[str, Any]					=						post_processing_function(eval_examples, eval_dataset, all_preds)
lowerCAmelCase    :     Dict					=						metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(F'''Evaluation metrics: {eval_metric}''')





'''simple docstring'''







import inspect
import unittest

from transformers import MobileViTVaConfig
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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
       from transformers.models.mobilevitva.modeling_mobilevitva import (
           MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
           make_divisible,
       )


if is_vision_available():
       from PIL import Image

       from transformers import MobileViTImageProcessor
class 	UpperCamelCase__					( SCREAMING_SNAKE_CASE_	):



     """simple docstring"""






     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							int   			=       self.config_class(**self.inputs_dict   )
            self.parent.assertTrue(hasattr(snake_case__      ,	'width_multiplier'   )   )
class 	UpperCamelCase__					:



     """simple docstring"""






     def __init__( self      ,	snake_case__      ,	snake_case__=13      ,	snake_case__=64      ,	snake_case__=2      ,	snake_case__=3      ,	snake_case__="swish"      ,	snake_case__=3      ,	snake_case__=32      ,	snake_case__=0.1      ,	snake_case__=0.02      ,	snake_case__=True      ,	snake_case__=True      ,	snake_case__=10      ,	snake_case__=None      ,	snake_case__=0.25      ,	snake_case__=0.0      ,	snake_case__=0.0      ,	):

            '''simple docstring'''

            _lowerCAmelCase    :							Tuple   			=       parent
            _lowerCAmelCase    :							Optional[int]   			=       batch_size
            _lowerCAmelCase    :							List[Any]   			=       image_size
            _lowerCAmelCase    :							List[Any]   			=       patch_size
            _lowerCAmelCase    :							List[str]   			=       num_channels
            _lowerCAmelCase    :							Optional[Any]   			=       make_divisible(512 * width_multiplier      ,	divisor=8   )
            _lowerCAmelCase    :							Optional[Any]   			=       hidden_act
            _lowerCAmelCase    :							List[Any]   			=       conv_kernel_size
            _lowerCAmelCase    :							Optional[Any]   			=       output_stride
            _lowerCAmelCase    :							List[Any]   			=       classifier_dropout_prob
            _lowerCAmelCase    :							str   			=       use_labels
            _lowerCAmelCase    :							List[str]   			=       is_training
            _lowerCAmelCase    :							Optional[int]   			=       num_labels
            _lowerCAmelCase    :							List[str]   			=       initializer_range
            _lowerCAmelCase    :							str   			=       scope
            _lowerCAmelCase    :							Any   			=       width_multiplier
            _lowerCAmelCase    :							Union[str, Any]   			=       ffn_dropout
            _lowerCAmelCase    :							Optional[int]   			=       attn_dropout







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[Any]   			=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

            _lowerCAmelCase    :							Optional[Any]   			=       None
            _lowerCAmelCase    :							Dict   			=       None
            if self.use_labels:
                   _lowerCAmelCase    :							Optional[Any]   			=       ids_tensor([self.batch_size]      ,	self.num_labels   )
                   _lowerCAmelCase    :							Optional[Any]   			=       ids_tensor([self.batch_size, self.image_size, self.image_size]      ,	self.num_labels   )

            _lowerCAmelCase    :							Optional[int]   			=       self.get_config()

            return config, pixel_values, labels, pixel_labels







     def a	( self   ):

            '''simple docstring'''

            return MobileViTVaConfig(
                image_size=self.image_size      ,	patch_size=self.patch_size      ,	num_channels=self.num_channels      ,	hidden_act=self.hidden_act      ,	conv_kernel_size=self.conv_kernel_size      ,	output_stride=self.output_stride      ,	classifier_dropout_prob=self.classifier_dropout_prob      ,	initializer_range=self.initializer_range      ,	width_multiplier=self.width_multiplier      ,	ffn_dropout=self.ffn_dropout_prob      ,	attn_dropout=self.attn_dropout_prob      ,	)







     def a	( self      ,	snake_case__      ,	snake_case__      ,	snake_case__      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       MobileViTVaModel(config=snake_case__   )
            model.to(snake_case__   )
            model.eval()
            _lowerCAmelCase    :							str   			=       model(snake_case__   )
            self.parent.assertEqual(
                result.last_hidden_state.shape      ,	(
                    self.batch_size,
                    self.last_hidden_size,
                    self.image_size // self.output_stride,
                    self.image_size // self.output_stride,
                )      ,	)







     def a	( self      ,	snake_case__      ,	snake_case__      ,	snake_case__      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[int]   			=       self.num_labels
            _lowerCAmelCase    :							List[Any]   			=       MobileViTVaForImageClassification(snake_case__   )
            model.to(snake_case__   )
            model.eval()
            _lowerCAmelCase    :							int   			=       model(snake_case__      ,	labels=snake_case__   )
            self.parent.assertEqual(result.logits.shape      ,	(self.batch_size, self.num_labels)   )







     def a	( self      ,	snake_case__      ,	snake_case__      ,	snake_case__      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							List[Any]   			=       self.num_labels
            _lowerCAmelCase    :							Optional[int]   			=       MobileViTVaForSemanticSegmentation(snake_case__   )
            model.to(snake_case__   )
            model.eval()
            _lowerCAmelCase    :							Dict   			=       model(snake_case__   )
            self.parent.assertEqual(
                result.logits.shape      ,	(
                    self.batch_size,
                    self.num_labels,
                    self.image_size // self.output_stride,
                    self.image_size // self.output_stride,
                )      ,	)
            _lowerCAmelCase    :							Any   			=       model(snake_case__      ,	labels=snake_case__   )
            self.parent.assertEqual(
                result.logits.shape      ,	(
                    self.batch_size,
                    self.num_labels,
                    self.image_size // self.output_stride,
                    self.image_size // self.output_stride,
                )      ,	)







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							int   			=       self.prepare_config_and_inputs()
            _lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase    :							Optional[int]   			=       config_and_inputs
            _lowerCAmelCase    :							Tuple   			=       {'pixel_values': pixel_values}
            return config, inputs_dict
@require_torch
class 	UpperCamelCase__					( SCREAMING_SNAKE_CASE_    ,					SCREAMING_SNAKE_CASE_    ,					unittest.TestCase	):



     """simple docstring"""






     __magic_name__    			=    (
         (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )

     __magic_name__    			=    (
         {
             "feature-extraction": MobileViTVaModel,
             "image-classification": MobileViTVaForImageClassification,
             "image-segmentation": MobileViTVaForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     __magic_name__    			=    False
     __magic_name__    			=    False
     __magic_name__    			=    False
     __magic_name__    			=    False







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							int   			=       MobileViTVaModelTester(self   )
            _lowerCAmelCase    :							Dict   			=       MobileViTVaConfigTester(self      ,	config_class=snake_case__      ,	has_text_modality=snake_case__   )







     def a	( self   ):

            '''simple docstring'''

            self.config_tester.run_common_tests()







     @unittest.skip(reason='MobileViTV2 does not use inputs_embeds'   )
     def a	( self   ):

            '''simple docstring'''

            pass







     @unittest.skip(reason='MobileViTV2 does not support input and output embeddings'   )
     def a	( self   ):

            '''simple docstring'''

            pass







     @unittest.skip(reason='MobileViTV2 does not output attentions'   )
     def a	( self   ):

            '''simple docstring'''

            pass







     @require_torch_multi_gpu
     @unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.'   )
     def a	( self   ):

            '''simple docstring'''

            pass







     @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'   )
     def a	( self   ):

            '''simple docstring'''

            pass







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase			,     _lowerCAmelCase    :							Optional[int]   			=       self.model_tester.prepare_config_and_inputs_for_common()

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

                   _lowerCAmelCase    :							Any   			=       ['pixel_values']
                   self.assertListEqual(arg_names[:1]      ,	snake_case__   )







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[int]   			=       self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*snake_case__   )







     def a	( self   ):

            '''simple docstring'''

            def check_hidden_states_output(snake_case__      ,	snake_case__      ,	snake_case__   ):
                   _lowerCAmelCase    :							Dict   			=       model_class(snake_case__   )
                   model.to(snake_case__   )
                   model.eval()

                   with torch.no_grad():
                          _lowerCAmelCase    :							Optional[Any]   			=       model(**self._prepare_for_class(snake_case__      ,	snake_case__   )   )

                   _lowerCAmelCase    :							List[str]   			=       outputs.hidden_states

                   _lowerCAmelCase    :							List[str]   			=       5
                   self.assertEqual(len(snake_case__   )      ,	snake_case__   )

                   # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
                   # with the width and height being successively divided by 2.
                   _lowerCAmelCase    :							List[Any]   			=       2
                   for i in range(len(snake_case__   )   ):
                          self.assertListEqual(
                              list(hidden_states[i].shape[-2:]   )      ,	[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]      ,	)
                          divisor *= 2

                   self.assertEqual(self.model_tester.output_stride      ,	divisor // 2   )

            _lowerCAmelCase			,     _lowerCAmelCase    :							Optional[int]   			=       self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                   _lowerCAmelCase    :							Optional[int]   			=       True
                   check_hidden_states_output(snake_case__      ,	snake_case__      ,	snake_case__   )

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   _lowerCAmelCase    :							Any   			=       True

                   check_hidden_states_output(snake_case__      ,	snake_case__      ,	snake_case__   )







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Dict   			=       self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*snake_case__   )







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__   )







     @slow
     def a	( self   ):

            '''simple docstring'''

            for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   _lowerCAmelCase    :							Dict   			=       MobileViTVaModel.from_pretrained(snake_case__   )
                   self.assertIsNotNone(snake_case__   )






def 			lowercase				():







       """simple docstring"""







       _lowerCAmelCase    :							Any   			=       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
       return image
@require_torch
@require_vision
class 	UpperCamelCase__					( unittest.TestCase	):



     """simple docstring"""






     @cached_property
     def a	( self   ):

            '''simple docstring'''

            return (
                MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'   )
                if is_vision_available()
                else None
            )







     @slow
     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Union[str, Any]   			=       MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'   ).to(
                snake_case__   )

            _lowerCAmelCase    :							str   			=       self.default_image_processor
            _lowerCAmelCase    :							Any   			=       prepare_img()
            _lowerCAmelCase    :							Optional[int]   			=       image_processor(images=snake_case__      ,	return_tensors='pt'   ).to(snake_case__   )

            # forward pass
            with torch.no_grad():
                   _lowerCAmelCase    :							Tuple   			=       model(**snake_case__   )

            # verify the logits
            _lowerCAmelCase    :							Optional[Any]   			=       torch.Size((1, 1000)   )
            self.assertEqual(outputs.logits.shape      ,	snake_case__   )

            _lowerCAmelCase    :							Tuple   			=       torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01]   ).to(snake_case__   )

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







     @slow
     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							List[str]   			=       MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'   )
            _lowerCAmelCase    :							Any   			=       model.to(snake_case__   )

            _lowerCAmelCase    :							int   			=       MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'   )

            _lowerCAmelCase    :							Optional[int]   			=       prepare_img()
            _lowerCAmelCase    :							Dict   			=       image_processor(images=snake_case__      ,	return_tensors='pt'   ).to(snake_case__   )

            # forward pass
            with torch.no_grad():
                   _lowerCAmelCase    :							int   			=       model(**snake_case__   )
            _lowerCAmelCase    :							Dict   			=       outputs.logits

            # verify the logits
            _lowerCAmelCase    :							str   			=       torch.Size((1, 21, 32, 32)   )
            self.assertEqual(logits.shape      ,	snake_case__   )

            _lowerCAmelCase    :							Any   			=       torch.tensor(
                [
                    [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
                    [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
                    [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
                ]      ,	device=snake_case__      ,	)

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







     @slow
     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'   )
            _lowerCAmelCase    :							List[Any]   			=       model.to(snake_case__   )

            _lowerCAmelCase    :							str   			=       MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'   )

            _lowerCAmelCase    :							Tuple   			=       prepare_img()
            _lowerCAmelCase    :							List[str]   			=       image_processor(images=snake_case__      ,	return_tensors='pt'   ).to(snake_case__   )

            # forward pass
            with torch.no_grad():
                   _lowerCAmelCase    :							Any   			=       model(**snake_case__   )

            _lowerCAmelCase    :							Optional[Any]   			=       outputs.logits.detach().cpu()

            _lowerCAmelCase    :							Any   			=       image_processor.post_process_semantic_segmentation(outputs=snake_case__      ,	target_sizes=[(50, 60)]   )
            _lowerCAmelCase    :							List[Any]   			=       torch.Size((50, 60)   )
            self.assertEqual(segmentation[0].shape      ,	snake_case__   )

            _lowerCAmelCase    :							List[str]   			=       image_processor.post_process_semantic_segmentation(outputs=snake_case__   )
            _lowerCAmelCase    :							Tuple   			=       torch.Size((32, 32)   )
            self.assertEqual(segmentation[0].shape      ,	snake_case__   )

