



"""simple docstring"""
import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 torch import nn

      from transformers import RegNetForImageClassification, RegNetModel
      from transformers.models.regnet.modeling_regnet import REGNET_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   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE=3   ,  _SCREAMING_SNAKE_CASE=32   ,  _SCREAMING_SNAKE_CASE=3   ,  _SCREAMING_SNAKE_CASE=10   ,  _SCREAMING_SNAKE_CASE=[10, 20, 30, 40]   ,  _SCREAMING_SNAKE_CASE=[1, 1, 2, 1]   ,  _SCREAMING_SNAKE_CASE=True   ,  _SCREAMING_SNAKE_CASE=True   ,  _SCREAMING_SNAKE_CASE="relu"   ,  _SCREAMING_SNAKE_CASE=3   ,  _SCREAMING_SNAKE_CASE=None   ,  )						->   str:





    '''simple docstring'''




    UpperCAmelCase			:      str			=			parent
    UpperCAmelCase			:      Optional[int]			=			batch_size
    UpperCAmelCase			:      List[str]			=			image_size
    UpperCAmelCase			:      str			=			num_channels
    UpperCAmelCase			:      Dict			=			embeddings_size
    UpperCAmelCase			:      List[Any]			=			hidden_sizes
    UpperCAmelCase			:      List[Any]			=			depths
    UpperCAmelCase			:      Tuple			=			is_training
    UpperCAmelCase			:      Dict			=			use_labels
    UpperCAmelCase			:      List[str]			=			hidden_act
    UpperCAmelCase			:      str			=			num_labels
    UpperCAmelCase			:      Dict			=			scope
    UpperCAmelCase			:      str			=			len(_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   List[Any]:





    '''simple docstring'''




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

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

    UpperCAmelCase			:      Union[str, Any]			=			self.get_config()

    return config, pixel_values, labels

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Any:





    '''simple docstring'''




    return RegNetConfig(
        num_channels=self.num_channels   ,  embeddings_size=self.embeddings_size   ,  hidden_sizes=self.hidden_sizes   ,  depths=self.depths   ,  hidden_act=self.hidden_act   ,  num_labels=self.num_labels   ,  )

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   Tuple:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[int]			=			RegNetModel(config=_SCREAMING_SNAKE_CASE		)
    model.to(_SCREAMING_SNAKE_CASE		)
    model.eval()
    UpperCAmelCase			:      Any			=			model(_SCREAMING_SNAKE_CASE		)
    # 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   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   Union[str, Any]:





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			self.num_labels
    UpperCAmelCase			:      List[str]			=			RegNetForImageClassification(_SCREAMING_SNAKE_CASE		)
    model.to(_SCREAMING_SNAKE_CASE		)
    model.eval()
    UpperCAmelCase			:      Optional[Any]			=			model(_SCREAMING_SNAKE_CASE   ,  labels=_SCREAMING_SNAKE_CASE		)
    self.parent.assertEqual(result.logits.shape   ,  (self.batch_size, self.num_labels)		)




   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Any:





    '''simple docstring'''




    UpperCAmelCase			:      Any			=			self.prepare_config_and_inputs()
    UpperCAmelCase			:      List[str]			=			config_and_inputs
    UpperCAmelCase			:      Union[str, Any]			=			{"""pixel_values""": pixel_values}
    return config, inputs_dict



@require_torch
class    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__   ,    UpperCAmelCase__   ,    unittest.TestCase				):

   '''simple docstring'''





   __lowerCAmelCase						:     Any		=		(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
   __lowerCAmelCase						:     List[Any]		=		(
       {'feature-extraction': RegNetModel, 'image-classification': RegNetForImageClassification}
       if is_torch_available()
       else {}
   )

   __lowerCAmelCase						:     Tuple		=		False
   __lowerCAmelCase						:     str		=		False
   __lowerCAmelCase						:     List[Any]		=		False
   __lowerCAmelCase						:     Any		=		False

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[int]:





    '''simple docstring'''




    UpperCAmelCase			:      str			=			RegNetModelTester(self		)
    UpperCAmelCase			:      Any			=			ConfigTester(self   ,  config_class=_SCREAMING_SNAKE_CASE   ,  has_text_modality=_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




    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]:





    '''simple docstring'''




    return

   @unittest.skip(reason="""RegNet does not use inputs_embeds"""		)
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   List[Any]:





    '''simple docstring'''




    pass

   @unittest.skip(reason="""RegNet does not support input and output embeddings"""		)
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Union[str, Any]:





    '''simple docstring'''




    pass

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




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

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

     UpperCAmelCase			:      List[Any]			=			["""pixel_values"""]
     self.assertListEqual(arg_names[:1]   ,  _SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   List[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[Any]			=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




    UpperCAmelCase			:      int			=			self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     UpperCAmelCase			:      Any			=			model_class(config=_SCREAMING_SNAKE_CASE		)
     for name, module in model.named_modules():
      if isinstance(_SCREAMING_SNAKE_CASE   ,  (nn.BatchNormad, nn.GroupNorm)		):
       self.assertTrue(
           torch.all(module.weight == 1		)   ,  msg=F"Parameter {name} of model {model_class} seems not properly initialized"   ,  )
       self.assertTrue(
           torch.all(module.bias == 0		)   ,  msg=F"Parameter {name} of model {model_class} seems not properly initialized"   ,  )

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





    '''simple docstring'''




    def check_hidden_states_output(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		):
     UpperCAmelCase			:      int			=			model_class(_SCREAMING_SNAKE_CASE		)
     model.to(_SCREAMING_SNAKE_CASE		)
     model.eval()

     with torch.no_grad():
      UpperCAmelCase			:      Dict			=			model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)		)

     UpperCAmelCase			:      List[str]			=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     UpperCAmelCase			:      Any			=			self.model_tester.num_stages
     self.assertEqual(len(_SCREAMING_SNAKE_CASE		)   ,  expected_num_stages + 1		)

     # RegNet'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 // 2, self.model_tester.image_size // 2]   ,  )

    UpperCAmelCase			:      Any			=			self.model_tester.prepare_config_and_inputs_for_common()
    UpperCAmelCase			:      int			=			["""basic""", """bottleneck"""]
    for model_class in self.all_model_classes:
     for layer_type in layers_type:
      UpperCAmelCase			:      Tuple			=			layer_type
      UpperCAmelCase			:      str			=			True
      check_hidden_states_output(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)

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

      check_hidden_states_output(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   List[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[Any]			=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE		)




   @slow
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




    for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     UpperCAmelCase			:      Any			=			RegNetModel.from_pretrained(_SCREAMING_SNAKE_CASE		)
     self.assertIsNotNone(_SCREAMING_SNAKE_CASE		)

def    _snake_case		(		):
 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		)						->   str:





    '''simple docstring'''




    return (
        AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
        if is_vision_available()
        else None
    )




   @slow
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      List[str]			=			RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      str			=			self.default_image_processor
    UpperCAmelCase			:      Any			=			prepare_img()
    UpperCAmelCase			:      List[str]			=			image_processor(images=_SCREAMING_SNAKE_CASE   ,  return_tensors="""pt"""		).to(_SCREAMING_SNAKE_CASE		)

    # forward pass
    with torch.no_grad():
     UpperCAmelCase			:      List[Any]			=			model(**_SCREAMING_SNAKE_CASE		)

    # verify the logits
    UpperCAmelCase			:      int			=			torch.Size((1, 1000)		)
    self.assertEqual(outputs.logits.shape   ,  _SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      int			=			torch.tensor([-0.4180, -1.5051, -3.4836]		).to(_SCREAMING_SNAKE_CASE		)

    self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,  _SCREAMING_SNAKE_CASE   ,  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.
A:     Union[str, Any]										=	2_0_0
# 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.
A:     int										=	5_0
# 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.
A:     Tuple										=	0.4
# Just a seed to improve randomness required by the algorithm.
random.seed(random.randint(0, 1_0_0_0))

def    _snake_case		(		UpperCamelCase		:	str    ,	UpperCamelCase		:	str		):
 UpperCAmelCase			:      Tuple			=			len([g for position, g in enumerate(UpperCamelCase		) if g == main_target[position]]		)
 return (item, float(UpperCamelCase		))

def    _snake_case		(		UpperCamelCase		:	str    ,	UpperCamelCase		:	str		):
 UpperCAmelCase			:      List[str]			=			random.randint(0    ,	len(UpperCamelCase		) - 1		)
 UpperCAmelCase			:      List[str]			=			parent_a[:random_slice] + parent_a[random_slice:]
 UpperCAmelCase			:      List[str]			=			parent_a[:random_slice] + parent_a[random_slice:]
 return (child_a, child_a)

def    _snake_case		(		UpperCamelCase		:	str    ,	UpperCamelCase		:	list[str]		):
 UpperCAmelCase			:      str			=			list(UpperCamelCase		)
 if random.uniform(0    ,	1		) < MUTATION_PROBABILITY:
  UpperCAmelCase			:      int			=			random.choice(UpperCamelCase		)
 return "".join(UpperCamelCase		)

def    _snake_case		(		UpperCamelCase		:	tuple[str, float]    ,	UpperCamelCase		:	list[tuple[str, float]]    ,	UpperCamelCase		:	list[str]    ,	):
 UpperCAmelCase			:      Optional[Any]			=			[]
 # Generate more children proportionally to the fitness score.
 UpperCAmelCase			:      Optional[Any]			=			int(parent_a[1] * 100		) + 1
 UpperCAmelCase			:      List[str]			=			10 if child_n >= 10 else child_n
 for _ in range(UpperCamelCase		):
  UpperCAmelCase			:      List[str]			=			population_score[random.randint(0    ,	UpperCamelCase		)][0]

  UpperCAmelCase			,	UpperCAmelCase			:      Any			=			crossover(parent_a[0]    ,	UpperCamelCase		)
  # Append new string to the population list.
  pop.append(mutate(UpperCamelCase    ,	UpperCamelCase		)		)
  pop.append(mutate(UpperCamelCase    ,	UpperCamelCase		)		)
 return pop

def    _snake_case		(		UpperCamelCase		:	str    ,	UpperCamelCase		:	list[str]    ,	UpperCamelCase		:	bool = True		):

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

 # Generate random starting population.
 UpperCAmelCase			:      Optional[int]			=			[]
 for _ in range(UpperCamelCase		):
  population.append("""""".join([random.choice(UpperCamelCase		) for i in range(len(UpperCamelCase		)		)]		)		)

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

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

  # 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			:      str			=			[evaluate(UpperCamelCase    ,	UpperCamelCase		) for item in population]

  # Check if there is a matching evolution.
  UpperCAmelCase			:      Union[str, Any]			=			sorted(UpperCamelCase    ,	key=lambda UpperCamelCase		: x[1]    ,	reverse=UpperCamelCase		)
  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			:      Tuple			=			population[: int(N_POPULATION / 3		)]
  population.clear()
  population.extend(UpperCamelCase		)
  # Normalize population score to be between 0 and 1.
  UpperCAmelCase			:      List[str]			=			[
      (item, score / len(UpperCamelCase		)) for item, score in population_score
  ]

  # This is selection
  for i in range(UpperCamelCase		):
   population.extend(select(population_score[int(UpperCamelCase		)]    ,	UpperCamelCase    ,	UpperCamelCase		)		)
   # 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(UpperCamelCase		) > N_POPULATION:
    break


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