





"""simple docstring"""


import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
  from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor



class      __SCREAMING_SNAKE_CASE    :







  '''simple docstring'''


  def __init__(		self   :       Union[str, Any]					,   __a   :       str					,   __a   :       Union[str, Any]=13					,   __a   :       str=32					,   __a   :       Any=3					,   __a   :       List[str]=4					,   __a   :       int=[10, 20, 30, 40]					,   __a   :       int=[2, 2, 3, 2]					,   __a   :       Union[str, Any]=True					,   __a   :       str=True					,   __a   :       Dict=37					,   __a   :       Tuple="gelu"					,   __a   :       List[str]=10					,   __a   :       List[str]=0.02					,   __a   :       List[str]=["stage2", "stage3", "stage4"]					,   __a   :       Any=[2, 3, 4]					,   __a   :       List[Any]=None					,   )		->				Dict:
        _UpperCamelCase      :	str						=       parent
        _UpperCamelCase      :	Union[str, Any]						=       batch_size
        _UpperCamelCase      :	Tuple						=       image_size
        _UpperCamelCase      :	Any						=       num_channels
        _UpperCamelCase      :	List[Any]						=       num_stages
        _UpperCamelCase      :	str						=       hidden_sizes
        _UpperCamelCase      :	Union[str, Any]						=       depths
        _UpperCamelCase      :	Union[str, Any]						=       is_training
        _UpperCamelCase      :	Any						=       use_labels
        _UpperCamelCase      :	Optional[int]						=       intermediate_size
        _UpperCamelCase      :	Optional[Any]						=       hidden_act
        _UpperCamelCase      :	List[str]						=       num_labels
        _UpperCamelCase      :	List[str]						=       initializer_range
        _UpperCamelCase      :	List[Any]						=       out_features
        _UpperCamelCase      :	Any						=       out_indices
        _UpperCamelCase      :	Any						=       scope

  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				Any:
        _UpperCamelCase      :	int						=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

        _UpperCamelCase      :	str						=       None
        if self.use_labels:
              _UpperCamelCase      :	Optional[int]						=       ids_tensor([self.batch_size]					,   self.num_labels	)

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

        return config, pixel_values, labels

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				int:
        return ConvNextVaConfig(
            num_channels=self.num_channels					,   hidden_sizes=self.hidden_sizes					,   depths=self.depths					,   num_stages=self.num_stages					,   hidden_act=self.hidden_act					,   is_decoder=__a					,   initializer_range=self.initializer_range					,   out_features=self.out_features					,   out_indices=self.out_indices					,   num_labels=self.num_labels					,   )

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]					,   __a   :       List[Any]					,   __a   :       Union[str, Any]					,   __a   :       Any	)		->				Union[str, Any]:
        _UpperCamelCase      :	Union[str, Any]						=       ConvNextVaModel(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Union[str, Any]						=       model(__a	)
        # expected last hidden states: B, C, H // 32, W // 32
        self.parent.assertEqual(
            result.last_hidden_state.shape					,   (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)					,   )

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple					,   __a   :       List[Any]					,   __a   :       Tuple					,   __a   :       str	)		->				Optional[int]:
        _UpperCamelCase      :	Tuple						=       ConvNextVaForImageClassification(__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Optional[int]						=       model(__a					,   labels=__a	)
        self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.num_labels)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       List[str]					,   __a   :       List[Any]					,   __a   :       Tuple	)		->				Tuple:
        _UpperCamelCase      :	Union[str, Any]						=       ConvNextVaBackbone(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	List[str]						=       model(__a	)

        # verify hidden states
        self.parent.assertEqual(len(result.feature_maps	)					,   len(config.out_features	)	)
        self.parent.assertListEqual(list(result.feature_maps[0].shape	)					,   [self.batch_size, self.hidden_sizes[1], 4, 4]	)

        # verify channels
        self.parent.assertEqual(len(model.channels	)					,   len(config.out_features	)	)
        self.parent.assertListEqual(model.channels					,   config.hidden_sizes[1:]	)

        # verify backbone works with out_features=None
        _UpperCamelCase      :	Dict						=       None
        _UpperCamelCase      :	str						=       ConvNextVaBackbone(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Union[str, Any]						=       model(__a	)

        # verify feature maps
        self.parent.assertEqual(len(result.feature_maps	)					,   1	)
        self.parent.assertListEqual(list(result.feature_maps[0].shape	)					,   [self.batch_size, self.hidden_sizes[-1], 1, 1]	)

        # verify channels
        self.parent.assertEqual(len(model.channels	)					,   1	)
        self.parent.assertListEqual(model.channels					,   [config.hidden_sizes[-1]]	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Optional[Any]:
        _UpperCamelCase      :	int						=       self.prepare_config_and_inputs()
        _UpperCamelCase      :	int						=       config_and_inputs
        _UpperCamelCase      :	str						=       {"pixel_values": pixel_values}
        return config, inputs_dict


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				List[Any]:
        _UpperCamelCase      :	List[Any]						=       self.prepare_config_and_inputs()
        _UpperCamelCase      :	int						=       config_and_inputs
        _UpperCamelCase      :	Optional[int]						=       {"pixel_values": pixel_values, "labels": labels}
        return config, inputs_dict





@require_torch
class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase		,  _UpperCamelCase		,  unittest.TestCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:Tuple	     =					(
      (
          ConvNextVaModel,
          ConvNextVaForImageClassification,
          ConvNextVaBackbone,
      )
      if is_torch_available()
      else ()
  )
  SCREAMING_SNAKE_CASE__							:List[Any]	     =					(
      {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE__							:Dict	     =					False
  SCREAMING_SNAKE_CASE__							:List[Any]	     =					False
  SCREAMING_SNAKE_CASE__							:Dict	     =					False
  SCREAMING_SNAKE_CASE__							:Union[str, Any]	     =					False
  SCREAMING_SNAKE_CASE__							:Union[str, Any]	     =					False

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				List[Any]:
        _UpperCamelCase      :	List[Any]						=       ConvNextVaModelTester(self	)
        _UpperCamelCase      :	Dict						=       ConfigTester(self					,   config_class=__a					,   has_text_modality=__a					,   hidden_size=37	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				int:
        self.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				str:
        return

  @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Tuple:
        pass

  @unittest.skip(reason="ConvNextV2 does not support input and output embeddings"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Tuple:
        pass

  @unittest.skip(reason="ConvNextV2 does not use feedforward chunking"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				Tuple:
        pass

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Tuple:
        if not self.model_tester.is_training:
              return

        for model_class in self.all_model_classes:
              _UpperCamelCase      :	Tuple						=       self.model_tester.prepare_config_and_inputs_with_labels()
              _UpperCamelCase      :	Any						=       True

              if model_class.__name__ in [
                  *get_values(__a	),
                  *get_values(__a	),
              ]:
                    continue

              _UpperCamelCase      :	Tuple						=       model_class(__a	)
              model.to(__a	)
              model.train()
              _UpperCamelCase      :	List[str]						=       self._prepare_for_class(__a					,   __a					,   return_labels=__a	)
              _UpperCamelCase      :	Optional[Any]						=       model(**__a	).loss
              loss.backward()

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Optional[int]:
        if not self.model_tester.is_training:
              return

        for model_class in self.all_model_classes:
              _UpperCamelCase      :	Tuple						=       self.model_tester.prepare_config_and_inputs_with_labels()
              _UpperCamelCase      :	Dict						=       False
              _UpperCamelCase      :	Optional[int]						=       True

              if (
                  model_class.__name__
                  in [*get_values(__a	), *get_values(__a	)]
                  or not model_class.supports_gradient_checkpointing
              ):
                    continue

              _UpperCamelCase      :	List[Any]						=       model_class(__a	)
              model.to(__a	)
              model.gradient_checkpointing_enable()
              model.train()
              _UpperCamelCase      :	Optional[int]						=       self._prepare_for_class(__a					,   __a					,   return_labels=__a	)
              _UpperCamelCase      :	Optional[int]						=       model(**__a	).loss
              loss.backward()

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				List[Any]:
        _UpperCamelCase      :	int						=       self.model_tester.prepare_config_and_inputs_for_common()

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

              _UpperCamelCase      :	Tuple						=       ["pixel_values"]
              self.assertListEqual(arg_names[:1]					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				int:
        _UpperCamelCase      :	int						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				Tuple:
        def check_hidden_states_output(__a   :       Optional[Any]					,   __a   :       Optional[Any]					,   __a   :       List[Any]	):
              _UpperCamelCase      :	int						=       model_class(__a	)
              model.to(__a	)
              model.eval()

              with torch.no_grad():
                    _UpperCamelCase      :	List[Any]						=       model(**self._prepare_for_class(__a					,   __a	)	)

              _UpperCamelCase      :	List[Any]						=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              _UpperCamelCase      :	Optional[Any]						=       self.model_tester.num_stages
              self.assertEqual(len(__a	)					,   expected_num_stages + 1	)

              # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width)
              self.assertListEqual(
                  list(hidden_states[0].shape[-2:]	)					,   [self.model_tester.image_size // 4, self.model_tester.image_size // 4]					,   )

        _UpperCamelCase      :	Dict						=       self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _UpperCamelCase      :	Dict						=       True
              check_hidden_states_output(__a					,   __a					,   __a	)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              _UpperCamelCase      :	Optional[int]						=       True

              check_hidden_states_output(__a					,   __a					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				Optional[Any]:
        _UpperCamelCase      :	int						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__a	)


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Any:
        for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _UpperCamelCase      :	Any						=       ConvNextVaModel.from_pretrained(__a	)
              self.assertIsNotNone(__a	)





def 					lowercase__    (					)					->		Dict:




      """simple docstring"""

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



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







  '''simple docstring'''


  @cached_property
  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				List[str]:
        return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"	) if is_vision_available() else None


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Union[str, Any]:
        _UpperCamelCase      :	Tuple						=       ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"	).to(__a	)

        _UpperCamelCase      :	List[Any]						=       self.default_image_processor
        _UpperCamelCase      :	Optional[Any]						=       prepare_img()
        _UpperCamelCase      :	List[Any]						=       preprocessor(images=__a					,   return_tensors="pt"	).to(__a	)

        # forward pass
        with torch.no_grad():
              _UpperCamelCase      :	List[str]						=       model(**__a	)

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

        _UpperCamelCase      :	Union[str, Any]						=       torch.tensor([0.99_96, 0.19_66, -0.43_86]	).to(__a	)
        self.assertTrue(torch.allclose(outputs.logits[0, :3]					,   __a					,   atol=1e-4	)	)







"""simple docstring"""


from __future__ import annotations

import random

# Maximum size of the population.  Bigger could be faster but is more memory expensive.
lowerCamelCase__				  =   200
# Number of elements selected in every generation of evolution. The selection takes
# place from best to worst of that generation and must be smaller than N_POPULATION.
lowerCamelCase__				  =   50
# Probability that an element of a generation can mutate, changing one of its genes.
# This will guarantee that all genes will be used during evolution.
lowerCamelCase__				  =   0.4
# Just a seed to improve randomness required by the algorithm.
random.seed(random.randint(0, 1000))




def 					lowercase__    (					lowercase_		,lowercase_			)					->		tuple[str, float]:




      """simple docstring"""

      _UpperCamelCase      :	str						=       len([g for position, g in enumerate(lowercase_			) if g == main_target[position]]			)
      return (item, float(lowercase_			))




def 					lowercase__    (					lowercase_		,lowercase_			)					->		tuple[str, str]:




      """simple docstring"""

      _UpperCamelCase      :	Tuple						=       random.randint(0		,len(lowercase_			) - 1			)
      _UpperCamelCase      :	Dict						=       parent_a[:random_slice] + parent_a[random_slice:]
      _UpperCamelCase      :	Tuple						=       parent_a[:random_slice] + parent_a[random_slice:]
      return (child_a, child_a)




def 					lowercase__    (					lowercase_		,lowercase_			)					->		str:




      """simple docstring"""

      _UpperCamelCase      :	int						=       list(lowercase_			)
      if random.uniform(0		,1			) < MUTATION_PROBABILITY:
            _UpperCamelCase      :	int						=       random.choice(lowercase_			)
      return "".join(lowercase_			)




def 					lowercase__    (					lowercase_		,lowercase_		,lowercase_		,)					->		list[str]:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       []
      # Generate more children proportionally to the fitness score.
      _UpperCamelCase      :	List[str]						=       int(parent_a[1] * 100			) + 1
      _UpperCamelCase      :	Union[str, Any]						=       10 if child_n >= 10 else child_n
      for _ in range(lowercase_			):
            _UpperCamelCase      :	Dict						=       population_score[random.randint(0		,lowercase_			)][0]

            _UpperCamelCase,  _UpperCamelCase      :	Dict						=       crossover(parent_a[0]		,lowercase_			)
            # Append new string to the population list.
            pop.append(mutate(lowercase_		,lowercase_			)			)
            pop.append(mutate(lowercase_		,lowercase_			)			)
      return pop




def 					lowercase__    (					lowercase_		,lowercase_		,lowercase_ = True			)					->		tuple[int, int, str]:




      """simple docstring"""

      if N_POPULATION < N_SELECTED:
            _UpperCamelCase      :	List[str]						=       F'''{N_POPULATION} must be bigger than {N_SELECTED}'''
            raise ValueError(lowercase_			)
      # Verify that the target contains no genes besides the ones inside genes variable.
      _UpperCamelCase      :	int						=       sorted({c for c in target if c not in genes}			)
      if not_in_genes_list:
            _UpperCamelCase      :	int						=       F'''{not_in_genes_list} is not in genes list, evolution cannot converge'''
            raise ValueError(lowercase_			)

      # Generate random starting population.
      _UpperCamelCase      :	Union[str, Any]						=       []
      for _ in range(lowercase_			):
            population.append("".join([random.choice(lowercase_			) for i in range(len(lowercase_			)			)]			)			)

      # Just some logs to know what the algorithms is doing.
      _UpperCamelCase,  _UpperCamelCase      :	str						=       0, 0

      # This loop will end when we find a perfect match for our target.
      while True:
            generation += 1
            total_population += len(lowercase_			)

            # Random population created. Now it's time to evaluate.

            # Adding a bit of concurrency can make everything faster,
            #
            # import concurrent.futures
            # population_score: list[tuple[str, float]] = []
            # with concurrent.futures.ThreadPoolExecutor(
            #                                   max_workers=NUM_WORKERS) as executor:
            #     futures = {executor.submit(evaluate, item) for item in population}
            #     concurrent.futures.wait(futures)
            #     population_score = [item.result() for item in futures]
            #
            # but with a simple algorithm like this, it will probably be slower.
            # We just need to call evaluate for every item inside the population.
            _UpperCamelCase      :	int						=       [evaluate(lowercase_		,lowercase_			) for item in population]

            # Check if there is a matching evolution.
            _UpperCamelCase      :	Optional[Any]						=       sorted(lowercase_		,key=lambda lowercase_			: x[1]		,reverse=lowercase_			)
            if population_score[0][0] == target:
                  return (generation, total_population, population_score[0][0])

            # Print the best result every 10 generation.
            # Just to know that the algorithm is working.
            if debug and generation % 10 == 0:
                  print(
                      F'''\nGeneration: {generation}'''
                      F'''\nTotal Population:{total_population}'''
                      F'''\nBest score: {population_score[0][1]}'''
                      F'''\nBest string: {population_score[0][0]}'''			)

            # Flush the old population, keeping some of the best evolutions.
            # Keeping this avoid regression of evolution.
            _UpperCamelCase      :	str						=       population[: int(N_POPULATION / 3			)]
            population.clear()
            population.extend(lowercase_			)
            # Normalize population score to be between 0 and 1.
            _UpperCamelCase      :	str						=       [
                (item, score / len(lowercase_			)) for item, score in population_score
            ]

            # This is selection
            for i in range(lowercase_			):
                  population.extend(select(population_score[int(lowercase_			)]		,lowercase_		,lowercase_			)			)
                  # Check if the population has already reached the maximum value and if so,
                  # break the cycle.  If this check is disabled, the algorithm will take
                  # forever to compute large strings, but will also calculate small strings in
                  # a far fewer generations.
                  if len(lowercase_			) > N_POPULATION:
                        break


if __name__ == "__main__":
  lowerCamelCase__				  =   (
      "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!"
  )
  lowerCamelCase__				  =   list(
      " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm"
      "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\"
  )
  lowerCamelCase__  ,    lowerCamelCase__  ,    lowerCamelCase__				  =   basic(target_str, genes_list)
  print(
      f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}"""
  )
