





'''simple docstring'''







import inspect
import unittest

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

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


if is_torch_available():
   import torch
   from torch import nn

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


if is_vision_available():
   from PIL import Image

   from transformers import BeitImageProcessor


class 				__lowerCamelCase				:
    """simple docstring"""


    def __init__(						self    :							Any   ,							SCREAMING_SNAKE_CASE    :							Tuple   ,							SCREAMING_SNAKE_CASE    :							List[str]=100   ,							SCREAMING_SNAKE_CASE    :							Optional[int]=13   ,							SCREAMING_SNAKE_CASE    :							Dict=30   ,							SCREAMING_SNAKE_CASE    :							List[Any]=2   ,							SCREAMING_SNAKE_CASE    :							List[str]=3   ,							SCREAMING_SNAKE_CASE    :							Dict=True   ,							SCREAMING_SNAKE_CASE    :							List[Any]=True   ,							SCREAMING_SNAKE_CASE    :							Optional[int]=32   ,							SCREAMING_SNAKE_CASE    :							Dict=4   ,							SCREAMING_SNAKE_CASE    :							Tuple=4   ,							SCREAMING_SNAKE_CASE    :							str=37   ,							SCREAMING_SNAKE_CASE    :							Union[str, Any]="gelu"   ,							SCREAMING_SNAKE_CASE    :							List[Any]=0.1   ,							SCREAMING_SNAKE_CASE    :							str=0.1   ,							SCREAMING_SNAKE_CASE    :							int=10   ,							SCREAMING_SNAKE_CASE    :							Union[str, Any]=0.02   ,							SCREAMING_SNAKE_CASE    :							Union[str, Any]=3   ,							SCREAMING_SNAKE_CASE    :							List[str]=None   ,							SCREAMING_SNAKE_CASE    :							List[str]=[0, 1, 2, 3]   ,							):
           _A  :			str											=      parent
           _A  :			Optional[Any]											=      100
           _A  :			Optional[int]											=      batch_size
           _A  :			Dict											=      image_size
           _A  :			Optional[int]											=      patch_size
           _A  :			Dict											=      num_channels
           _A  :			Union[str, Any]											=      is_training
           _A  :			List[Any]											=      use_labels
           _A  :			Optional[Any]											=      hidden_size
           _A  :			Union[str, Any]											=      num_hidden_layers
           _A  :			Dict											=      num_attention_heads
           _A  :			List[Any]											=      intermediate_size
           _A  :			str											=      hidden_act
           _A  :			Union[str, Any]											=      hidden_dropout_prob
           _A  :			Optional[int]											=      attention_probs_dropout_prob
           _A  :			Optional[int]											=      type_sequence_label_size
           _A  :			str											=      initializer_range
           _A  :			List[str]											=      scope
           _A  :			Optional[int]											=      out_indices
           _A  :			Union[str, Any]											=      num_labels

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


    def      A					(						self    :							Union[str, Any]):
           _A  :			Optional[int]											=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

           _A  :			int											=      None
           _A  :			str											=      None
           if self.use_labels:
                  _A  :			Tuple											=      ids_tensor([self.batch_size]   ,							self.type_sequence_label_size)
                  _A  :			Tuple											=      ids_tensor([self.batch_size, self.image_size, self.image_size]   ,							self.num_labels)

           _A  :			Any											=      self.get_config()

           return config, pixel_values, labels, pixel_labels


    def      A					(						self    :							Tuple):
           return DataaVecVisionConfig(
               vocab_size=self.vocab_size   ,							image_size=self.image_size   ,							patch_size=self.patch_size   ,							num_channels=self.num_channels   ,							hidden_size=self.hidden_size   ,							num_hidden_layers=self.num_hidden_layers   ,							num_attention_heads=self.num_attention_heads   ,							intermediate_size=self.intermediate_size   ,							hidden_act=self.hidden_act   ,							hidden_dropout_prob=self.hidden_dropout_prob   ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,							is_decoder=SCREAMING_SNAKE_CASE   ,							initializer_range=self.initializer_range   ,							out_indices=self.out_indices   ,							)


    def      A					(						self    :							str   ,							SCREAMING_SNAKE_CASE    :							Optional[int]   ,							SCREAMING_SNAKE_CASE    :							Any   ,							SCREAMING_SNAKE_CASE    :							Optional[Any]   ,							SCREAMING_SNAKE_CASE    :							Any):
           _A  :			Dict											=      DataaVecVisionModel(config=SCREAMING_SNAKE_CASE)
           model.to(SCREAMING_SNAKE_CASE)
           model.eval()
           _A  :			int											=      model(SCREAMING_SNAKE_CASE)
           # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
           _A  :			List[str]											=      (self.image_size // self.patch_size) ** 2
           self.parent.assertEqual(result.last_hidden_state.shape   ,							(self.batch_size, num_patches + 1, self.hidden_size))


    def      A					(						self    :							List[str]   ,							SCREAMING_SNAKE_CASE    :							Optional[Any]   ,							SCREAMING_SNAKE_CASE    :							Dict   ,							SCREAMING_SNAKE_CASE    :							Any   ,							SCREAMING_SNAKE_CASE    :							Tuple):
           _A  :			Dict											=      self.type_sequence_label_size
           _A  :			Optional[Any]											=      DataaVecVisionForImageClassification(SCREAMING_SNAKE_CASE)
           model.to(SCREAMING_SNAKE_CASE)
           model.eval()
           _A  :			Tuple											=      model(SCREAMING_SNAKE_CASE   ,							labels=SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(result.logits.shape   ,							(self.batch_size, self.type_sequence_label_size))


    def      A					(						self    :							str   ,							SCREAMING_SNAKE_CASE    :							str   ,							SCREAMING_SNAKE_CASE    :							Optional[Any]   ,							SCREAMING_SNAKE_CASE    :							Dict   ,							SCREAMING_SNAKE_CASE    :							Tuple):
           _A  :			Any											=      self.num_labels
           _A  :			Optional[Any]											=      DataaVecVisionForSemanticSegmentation(SCREAMING_SNAKE_CASE)
           model.to(SCREAMING_SNAKE_CASE)
           model.eval()
           _A  :			List[Any]											=      model(SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(
               result.logits.shape   ,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2))
           _A  :			Optional[int]											=      model(SCREAMING_SNAKE_CASE   ,							labels=SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(
               result.logits.shape   ,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2))


    def      A					(						self    :							Optional[int]):
           _A  :			str											=      self.prepare_config_and_inputs()
           _A  :			Tuple											=      config_and_inputs
           _A  :			Any											=      {'pixel_values': pixel_values}
           return config, inputs_dict




@require_torch
class 				__lowerCamelCase				( a_       ,      a_       ,      unittest.TestCase ):
    """simple docstring"""
    a									=					(
        (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
        if is_torch_available()
        else ()
    )
    a									=					(
        {
            "feature-extraction": DataaVecVisionModel,
            "image-classification": DataaVecVisionForImageClassification,
            "image-segmentation": DataaVecVisionForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    a									=					False
    a									=					False
    a									=					False


    def      A					(						self    :							int):
           _A  :			Dict											=      DataaVecVisionModelTester(self)
           _A  :			int											=      ConfigTester(
               self   ,							config_class=SCREAMING_SNAKE_CASE   ,							has_text_modality=SCREAMING_SNAKE_CASE   ,							hidden_size=37)


    def      A					(						self    :							Dict):
           self.config_tester.run_common_tests()


    def      A					(						self    :							Optional[Any]):
           # Data2VecVision does not use inputs_embeds
           pass


    @require_torch_multi_gpu
    @unittest.skip(
        reason='Data2VecVision has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`')
    def      A					(						self    :							Any):
           pass


    def      A					(						self    :							Union[str, Any]):
           _A  :			Tuple											=      self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  _A  :			int											=      model_class(SCREAMING_SNAKE_CASE)
                  self.assertIsInstance(model.get_input_embeddings()   ,							(nn.Module))
                  _A  :			List[Any]											=      model.get_output_embeddings()
                  self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE   ,							nn.Linear))


    def      A					(						self    :							int):
           _A  :			Optional[int]											=      self.model_tester.prepare_config_and_inputs_for_common()

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

                  _A  :			Any											=      ['pixel_values']
                  self.assertListEqual(arg_names[:1]   ,							SCREAMING_SNAKE_CASE)


    def      A					(						self    :							Dict):
           _A  :			str											=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE)


    def      A					(						self    :							Optional[int]):
           _A  :			int											=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_segmentation(*SCREAMING_SNAKE_CASE)


    def      A					(						self    :							str):
           if not self.model_tester.is_training:
                  return

           _A  :			Optional[int]											=      self.model_tester.prepare_config_and_inputs_for_common()
           _A  :			str											=      True

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

                  _A  :			Tuple											=      model_class(SCREAMING_SNAKE_CASE)
                  model.to(SCREAMING_SNAKE_CASE)
                  model.train()
                  _A  :			Dict											=      self._prepare_for_class(SCREAMING_SNAKE_CASE   ,							SCREAMING_SNAKE_CASE   ,							return_labels=SCREAMING_SNAKE_CASE)
                  _A  :			Any											=      model(**SCREAMING_SNAKE_CASE).loss
                  loss.backward()


    def      A					(						self    :							List[str]):
           _A  :			Dict											=      self.model_tester.prepare_config_and_inputs_for_common()
           if not self.model_tester.is_training:
                  return

           _A  :			Optional[Any]											=      False
           _A  :			Optional[int]											=      True

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


    def      A					(						self    :							Optional[int]):
           _A  :			List[str]											=      self.model_tester.prepare_config_and_inputs_for_common()

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


    def      A					(						self    :							Optional[int]   ,							SCREAMING_SNAKE_CASE    :							int   ,							SCREAMING_SNAKE_CASE    :							Optional[Any]   ,							SCREAMING_SNAKE_CASE    :							int   ,							SCREAMING_SNAKE_CASE    :							int=2e-4   ,							SCREAMING_SNAKE_CASE    :							Tuple="outputs"   ,							SCREAMING_SNAKE_CASE    :							int=None):
           # We override with a slightly higher tol value, as semseg models tend to diverge a bit more
           super().check_pt_tf_outputs(SCREAMING_SNAKE_CASE   ,							SCREAMING_SNAKE_CASE   ,							SCREAMING_SNAKE_CASE   ,							SCREAMING_SNAKE_CASE   ,							SCREAMING_SNAKE_CASE   ,							SCREAMING_SNAKE_CASE)


    def      A					(						self    :							Tuple):
           _A  :			Optional[int]											=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE)


    @slow
    def      A					(						self    :							str):
           for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  _A  :			Union[str, Any]											=      DataaVecVisionModel.from_pretrained(SCREAMING_SNAKE_CASE)
                  self.assertIsNotNone(SCREAMING_SNAKE_CASE)






def    lowerCAmelCase__ (       ):
       _A  :			Any											=      Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
       return image


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


    @cached_property
    def      A					(						self    :							str):
           return (
               BeitImageProcessor.from_pretrained('facebook/data2vec-vision-base-ft1k') if is_vision_available() else None
           )


    @slow
    def      A					(						self    :							List[Any]):
           _A  :			int											=      DataaVecVisionForImageClassification.from_pretrained('facebook/data2vec-vision-base-ft1k').to(
               SCREAMING_SNAKE_CASE)

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

           # forward pass
           with torch.no_grad():
                  _A  :			str											=      model(**SCREAMING_SNAKE_CASE)
           _A  :			int											=      outputs.logits

           # verify the logits
           _A  :			Union[str, Any]											=      torch.Size((1, 1000))
           self.assertEqual(logits.shape   ,							SCREAMING_SNAKE_CASE)

           _A  :			List[str]											=      torch.tensor([0.3277, -0.1395, 0.0911]).to(SCREAMING_SNAKE_CASE)

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

           _A  :			int											=      [model.config.labelaid[i] for i in ['remote control, remote', 'tabby, tabby cat']]
           self.assertEqual(logits[0].topk(2).indices.cpu().tolist()   ,							SCREAMING_SNAKE_CASE)










'''simple docstring'''







import math






def    lowerCAmelCase__ (       lowerCamelCase  :    int     ):

       if 1 < number < 4:
              # 2 and 3 are primes
              return True
       elif number < 2 or number % 2 == 0 or number % 3 == 0:
              # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
              return False

       # All primes number are in format of 6k +/- 1
       for i in range(5						,int(math.sqrt(lowerCamelCase     ) + 1     )						,6     ):
              if number % i == 0 or number % (i + 2) == 0:
                     return False
       return True






def    lowerCAmelCase__ (       lowerCamelCase  :    int = 1000						,lowerCamelCase  :    int = 1000     ):
       _A  :			int											=      [0, 0, 0]  # length, a, b
       for a in range((a_limit * -1) + 1						,lowerCamelCase     ):
              for b in range(2						,lowerCamelCase     ):
                     if is_prime(lowerCamelCase     ):
                            _A  :			Dict											=      0
                            _A  :			Tuple											=      0
                            while is_prime((n**2) + (a * n) + b     ):
                                   count += 1
                                   n += 1
                            if count > longest[0]:
                                   _A  :			List[str]											=      [count, a, b]
       _A  :			str											=      longest[1] * longest[2]
       return ans


if __name__ == "__main__":
   print(solution(1000, 1000))






