



'''simple docstring'''





import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, 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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
   from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import MobileNetVaImageProcessor






class 					lowerCamelCase_    (				SCREAMING_SNAKE_CASE_     ):
  """simple docstring"""




  def 						_lowercase     ( self      :	List[str]   )					->					Optional[int]:
    __lowerCamelCase       :       str           = self.config_class(**self.inputs_dict   )
    self.parent.assertTrue(hasattr(_a			,	'tf_padding'   )   )
    self.parent.assertTrue(hasattr(_a			,	'depth_multiplier'   )   )






class 					lowerCamelCase_    :
  """simple docstring"""




  def __init__( self      :	Any			,	_a      :	List[str]			,	_a      :	Optional[int]=13			,	_a      :	List[Any]=3			,	_a      :	Dict=32			,	_a      :	str=0.25			,	_a      :	str=8			,	_a      :	Any=8			,	_a      :	Tuple=6			,	_a      :	Any=32			,	_a      :	Any=True			,	_a      :	List[Any]=True			,	_a      :	Union[str, Any]=True			,	_a      :	int="relu6"			,	_a      :	Optional[Any]=1280			,	_a      :	Union[str, Any]=0.1			,	_a      :	Optional[int]=0.02			,	_a      :	int=True			,	_a      :	Dict=True			,	_a      :	List[str]=10			,	_a      :	Union[str, Any]=None			,	)					->					Any:
    __lowerCamelCase       :       str           = parent
    __lowerCamelCase       :       Any           = batch_size
    __lowerCamelCase       :       Optional[int]           = num_channels
    __lowerCamelCase       :       str           = image_size
    __lowerCamelCase       :       Union[str, Any]           = depth_multiplier
    __lowerCamelCase       :       Optional[int]           = depth_divisible_by
    __lowerCamelCase       :       Any           = min_depth
    __lowerCamelCase       :       Optional[Any]           = expand_ratio
    __lowerCamelCase       :       List[Any]           = tf_padding
    __lowerCamelCase       :       Optional[int]           = output_stride
    __lowerCamelCase       :       Union[str, Any]           = first_layer_is_expansion
    __lowerCamelCase       :       Union[str, Any]           = finegrained_output
    __lowerCamelCase       :       int           = hidden_act
    __lowerCamelCase       :       Optional[int]           = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier   )
    __lowerCamelCase       :       Union[str, Any]           = classifier_dropout_prob
    __lowerCamelCase       :       Optional[Any]           = use_labels
    __lowerCamelCase       :       Dict           = is_training
    __lowerCamelCase       :       List[str]           = num_labels
    __lowerCamelCase       :       str           = initializer_range
    __lowerCamelCase       :       str           = scope




  def 						_lowercase     ( self      :	Optional[int]   )					->					Union[str, Any]:
    __lowerCamelCase       :       Dict           = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

    __lowerCamelCase       :       List[str]           = self.get_config()

    return config, pixel_values, labels, pixel_labels




  def 						_lowercase     ( self      :	Tuple   )					->					int:
    return MobileNetVaConfig(
        num_channels=self.num_channels			,	image_size=self.image_size			,	depth_multiplier=self.depth_multiplier			,	depth_divisible_by=self.depth_divisible_by			,	min_depth=self.min_depth			,	expand_ratio=self.expand_ratio			,	output_stride=self.output_stride			,	first_layer_is_expansion=self.first_layer_is_expansion			,	finegrained_output=self.finegrained_output			,	hidden_act=self.hidden_act			,	tf_padding=self.tf_padding			,	classifier_dropout_prob=self.classifier_dropout_prob			,	initializer_range=self.initializer_range			,	)




  def 						_lowercase     ( self      :	Dict			,	_a      :	Optional[int]			,	_a      :	Tuple			,	_a      :	Dict			,	_a      :	List[str]   )					->					Any:
    __lowerCamelCase       :       Tuple           = MobileNetVaModel(config=_a   )
    model.to(_a   )
    model.eval()
    __lowerCamelCase       :       Dict           = model(_a   )
    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,
        )			,	)
    self.parent.assertEqual(
        result.pooler_output.shape			,	(self.batch_size, self.last_hidden_size)			,	)




  def 						_lowercase     ( self      :	Optional[Any]			,	_a      :	Tuple			,	_a      :	Optional[int]			,	_a      :	Optional[int]			,	_a      :	Tuple   )					->					Dict:
    __lowerCamelCase       :       Dict           = self.num_labels
    __lowerCamelCase       :       List[str]           = MobileNetVaForImageClassification(_a   )
    model.to(_a   )
    model.eval()
    __lowerCamelCase       :       int           = model(_a			,	labels=_a   )
    self.parent.assertEqual(result.logits.shape			,	(self.batch_size, self.num_labels)   )




  def 						_lowercase     ( self      :	str			,	_a      :	Optional[int]			,	_a      :	Dict			,	_a      :	List[Any]			,	_a      :	List[str]   )					->					Union[str, Any]:
    __lowerCamelCase       :       Tuple           = self.num_labels
    __lowerCamelCase       :       Union[str, Any]           = MobileNetVaForSemanticSegmentation(_a   )
    model.to(_a   )
    model.eval()
    __lowerCamelCase       :       Any           = model(_a   )
    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       :       List[str]           = model(_a			,	labels=_a   )
    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 						_lowercase     ( self      :	Optional[int]   )					->					Optional[int]:
    __lowerCamelCase       :       Optional[int]           = self.prepare_config_and_inputs()
    __lowerCamelCase       ,__lowerCamelCase       ,__lowerCamelCase       ,__lowerCamelCase       :       Optional[Any]           = config_and_inputs
    __lowerCamelCase       :       Any           = {'pixel_values': pixel_values}
    return config, inputs_dict






@require_torch
class 					lowerCamelCase_    (				SCREAMING_SNAKE_CASE_   ,   SCREAMING_SNAKE_CASE_   ,   unittest.TestCase     ):
  """simple docstring"""




  a_												=(
      (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
      if is_torch_available()
      else ()
  )
  a_												=(
      {
          """feature-extraction""": MobileNetVaModel,
          """image-classification""": MobileNetVaForImageClassification,
          """image-segmentation""": MobileNetVaForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  a_												=False
  a_												=False
  a_												=False
  a_												=False




  def 						_lowercase     ( self      :	Dict   )					->					Dict:
    __lowerCamelCase       :       str           = MobileNetVaModelTester(self   )
    __lowerCamelCase       :       Optional[int]           = MobileNetVaConfigTester(self			,	config_class=_a			,	has_text_modality=_a   )




  def 						_lowercase     ( self      :	Tuple   )					->					str:
    self.config_tester.run_common_tests()




  @unittest.skip(reason='MobileNetV2 does not use inputs_embeds'   )
  def 						_lowercase     ( self      :	Any   )					->					int:
    pass




  @unittest.skip(reason='MobileNetV2 does not support input and output embeddings'   )
  def 						_lowercase     ( self      :	List[str]   )					->					Any:
    pass




  @unittest.skip(reason='MobileNetV2 does not output attentions'   )
  def 						_lowercase     ( self      :	str   )					->					Dict:
    pass




  def 						_lowercase     ( self      :	Dict   )					->					Tuple:
    __lowerCamelCase       ,__lowerCamelCase       :       Optional[Any]           = self.model_tester.prepare_config_and_inputs_for_common()

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

      __lowerCamelCase       :       str           = ['pixel_values']
      self.assertListEqual(arg_names[:1]			,	_a   )




  def 						_lowercase     ( self      :	List[Any]   )					->					Optional[Any]:
    __lowerCamelCase       :       Any           = self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*_a   )




  def 						_lowercase     ( self      :	Any   )					->					Optional[int]:
    def check_hidden_states_output(_a      :	Optional[Any]			,	_a      :	List[Any]			,	_a      :	Union[str, Any]   ):
      __lowerCamelCase       :       List[Any]           = model_class(_a   )
      model.to(_a   )
      model.eval()

      with torch.no_grad():
        __lowerCamelCase       :       int           = model(**self._prepare_for_class(_a			,	_a   )   )

      __lowerCamelCase       :       int           = outputs.hidden_states

      __lowerCamelCase       :       Optional[Any]           = 16
      self.assertEqual(len(_a   )			,	_a   )

    __lowerCamelCase       ,__lowerCamelCase       :       List[str]           = self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      __lowerCamelCase       :       int           = True
      check_hidden_states_output(_a			,	_a			,	_a   )

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

      check_hidden_states_output(_a			,	_a			,	_a   )




  def 						_lowercase     ( self      :	List[str]   )					->					Tuple:
    __lowerCamelCase       :       Tuple           = self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*_a   )




  def 						_lowercase     ( self      :	Any   )					->					List[Any]:
    __lowerCamelCase       :       Tuple           = self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_semantic_segmentation(*_a   )




  @slow
  def 						_lowercase     ( self      :	Optional[int]   )					->					Union[str, Any]:
    for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __lowerCamelCase       :       int           = MobileNetVaModel.from_pretrained(_a   )
      self.assertIsNotNone(_a   )




def        a_     (							)      ->      Optional[Any]:
  __lowerCamelCase       :       str           = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
  return image






@require_torch
@require_vision
class 					lowerCamelCase_    (				unittest.TestCase     ):
  """simple docstring"""




  @cached_property
  def 						_lowercase     ( self      :	Dict   )					->					Optional[int]:
    return (
        MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224'   ) if is_vision_available() else None
    )




  @slow
  def 						_lowercase     ( self      :	Any   )					->					str:
    __lowerCamelCase       :       int           = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224'   ).to(_a   )

    __lowerCamelCase       :       Optional[Any]           = self.default_image_processor
    __lowerCamelCase       :       Any           = prepare_img()
    __lowerCamelCase       :       List[str]           = image_processor(images=_a			,	return_tensors='pt'   ).to(_a   )

    # forward pass
    with torch.no_grad():
      __lowerCamelCase       :       Dict           = model(**_a   )

    # verify the logits
    __lowerCamelCase       :       List[str]           = torch.Size((1, 1001)   )
    self.assertEqual(outputs.logits.shape			,	_a   )

    __lowerCamelCase       :       Union[str, Any]           = torch.tensor([0.2445, -1.1993, 0.1905]   ).to(_a   )

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




  @slow
  def 						_lowercase     ( self      :	Dict   )					->					str:
    __lowerCamelCase       :       Tuple           = MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'   )
    __lowerCamelCase       :       Any           = model.to(_a   )

    __lowerCamelCase       :       str           = MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'   )

    __lowerCamelCase       :       Optional[Any]           = prepare_img()
    __lowerCamelCase       :       Union[str, Any]           = image_processor(images=_a			,	return_tensors='pt'   ).to(_a   )

    # forward pass
    with torch.no_grad():
      __lowerCamelCase       :       Union[str, Any]           = model(**_a   )
    __lowerCamelCase       :       List[Any]           = outputs.logits

    # verify the logits
    __lowerCamelCase       :       Union[str, Any]           = torch.Size((1, 21, 65, 65)   )
    self.assertEqual(logits.shape			,	_a   )

    __lowerCamelCase       :       Optional[Any]           = torch.tensor(
        [
            [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
            [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
            [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
        ]			,	device=_a			,	)

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











'''simple docstring'''





from collections.abc import Sequence

def        a_     (							_lowerCAmelCase       ,_lowerCAmelCase       )      ->      float:
  return sum(c * (x**i) for i, c in enumerate(_lowerCAmelCase       )       )

def        a_     (							_lowerCAmelCase       ,_lowerCAmelCase       )      ->      float:
  __lowerCamelCase       :       Any           = 0.0
  for coeff in reversed(_lowerCAmelCase       ):
    __lowerCamelCase       :       Tuple           = result * x + coeff
  return result


if __name__ == "__main__":
   _UpperCamelCase											=						(0.0, 0.0, 5.0, 9.3, 7.0)
   _UpperCamelCase											=						1_0.0
   print(evaluate_poly(poly, x))
   print(horner(poly, x))






