





"""simple docstring"""


import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel



class      __SCREAMING_SNAKE_CASE    :







  '''simple docstring'''


  def __init__(		self   :       Union[str, Any]					,   __a   :       Union[str, Any]					,   __a   :       Tuple=13					,   __a   :       str=7					,   __a   :       Tuple=True					,   __a   :       Tuple=True					,   __a   :       int=False					,   __a   :       Optional[Any]=True					,   __a   :       Union[str, Any]=99					,   __a   :       Tuple=32					,   __a   :       List[Any]=5					,   __a   :       Dict=4					,   __a   :       Tuple=37					,   __a   :       Tuple="gelu"					,   __a   :       Union[str, Any]=0.1					,   __a   :       Dict=0.1					,   __a   :       Optional[Any]=512					,   __a   :       Tuple=16					,   __a   :       Tuple=2					,   __a   :       str=0.02					,   __a   :       Optional[Any]=3					,   __a   :       Optional[Any]=4					,   __a   :       Tuple=None					,   )		->				List[str]:
        _UpperCamelCase      :	Optional[Any]						=       parent
        _UpperCamelCase      :	str						=       batch_size
        _UpperCamelCase      :	Any						=       seq_length
        _UpperCamelCase      :	str						=       is_training
        _UpperCamelCase      :	Optional[Any]						=       use_input_mask
        _UpperCamelCase      :	Optional[int]						=       use_token_type_ids
        _UpperCamelCase      :	Optional[Any]						=       use_labels
        _UpperCamelCase      :	Tuple						=       vocab_size
        _UpperCamelCase      :	str						=       hidden_size
        _UpperCamelCase      :	int						=       num_hidden_layers
        _UpperCamelCase      :	str						=       num_attention_heads
        _UpperCamelCase      :	Tuple						=       intermediate_size
        _UpperCamelCase      :	Dict						=       hidden_act
        _UpperCamelCase      :	str						=       hidden_dropout_prob
        _UpperCamelCase      :	List[str]						=       attention_probs_dropout_prob
        _UpperCamelCase      :	Optional[int]						=       max_position_embeddings
        _UpperCamelCase      :	List[Any]						=       type_vocab_size
        _UpperCamelCase      :	Any						=       type_sequence_label_size
        _UpperCamelCase      :	Union[str, Any]						=       initializer_range
        _UpperCamelCase      :	List[Any]						=       num_labels
        _UpperCamelCase      :	List[str]						=       num_choices
        _UpperCamelCase      :	Any						=       scope

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				int:
        _UpperCamelCase      :	int						=       ids_tensor([self.batch_size, self.seq_length]					,   self.vocab_size	)

        _UpperCamelCase      :	Union[str, Any]						=       None
        if self.use_input_mask:
              _UpperCamelCase      :	int						=       random_attention_mask([self.batch_size, self.seq_length]	)

        _UpperCamelCase      :	int						=       None
        if self.use_token_type_ids:
              _UpperCamelCase      :	int						=       ids_tensor([self.batch_size, self.seq_length]					,   self.type_vocab_size	)

        _UpperCamelCase      :	Optional[int]						=       None
        _UpperCamelCase      :	Optional[int]						=       None
        _UpperCamelCase      :	Tuple						=       None
        if self.use_labels:
              _UpperCamelCase      :	Dict						=       ids_tensor([self.batch_size]					,   self.type_sequence_label_size	)
              _UpperCamelCase      :	Optional[int]						=       ids_tensor([self.batch_size, self.seq_length]					,   self.num_labels	)
              _UpperCamelCase      :	Dict						=       ids_tensor([self.batch_size]					,   self.num_choices	)

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

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				Union[str, Any]:
        return OpenLlamaConfig(
            vocab_size=self.vocab_size					,   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					,   max_position_embeddings=self.max_position_embeddings					,   type_vocab_size=self.type_vocab_size					,   is_decoder=__a					,   initializer_range=self.initializer_range					,   use_stable_embedding=__a					,   )

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any					,   __a   :       Tuple					,   __a   :       List[str]					,   __a   :       List[str]					,   __a   :       str					,   __a   :       Union[str, Any]					,   __a   :       Optional[Any]					,   __a   :       Any	)		->				List[str]:
        _UpperCamelCase      :	List[Any]						=       OpenLlamaModel(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Dict						=       model(__a					,   attention_mask=__a	)
        _UpperCamelCase      :	Tuple						=       model(__a	)
        self.parent.assertEqual(result.last_hidden_state.shape					,   (self.batch_size, self.seq_length, self.hidden_size)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any					,   __a   :       Union[str, Any]					,   __a   :       Union[str, Any]					,   __a   :       List[str]					,   __a   :       int					,   __a   :       Optional[int]					,   __a   :       Any					,   __a   :       str					,   __a   :       Optional[Any]					,   __a   :       str					,   )		->				List[Any]:
        _UpperCamelCase      :	Optional[Any]						=       True
        _UpperCamelCase      :	Dict						=       OpenLlamaModel(__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Dict						=       model(
            __a					,   attention_mask=__a					,   encoder_hidden_states=__a					,   encoder_attention_mask=__a					,   )
        _UpperCamelCase      :	List[Any]						=       model(
            __a					,   attention_mask=__a					,   encoder_hidden_states=__a					,   )
        _UpperCamelCase      :	List[Any]						=       model(__a					,   attention_mask=__a	)
        self.parent.assertEqual(result.last_hidden_state.shape					,   (self.batch_size, self.seq_length, self.hidden_size)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       int					,   __a   :       List[Any]					,   __a   :       List[str]					,   __a   :       Union[str, Any]					,   __a   :       str					,   __a   :       Dict					,   __a   :       str					,   __a   :       List[Any]					,   __a   :       Optional[int]					,   )		->				List[str]:
        _UpperCamelCase      :	List[str]						=       OpenLlamaForCausalLM(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Any						=       model(__a					,   attention_mask=__a					,   labels=__a	)
        self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.seq_length, self.vocab_size)	)

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

        # first forward pass
        _UpperCamelCase      :	Dict						=       model(
            __a					,   attention_mask=__a					,   encoder_hidden_states=__a					,   encoder_attention_mask=__a					,   use_cache=__a					,   )
        _UpperCamelCase      :	List[Any]						=       outputs.past_key_values

        # create hypothetical multiple next token and extent to next_input_ids
        _UpperCamelCase      :	List[Any]						=       ids_tensor((self.batch_size, 3)					,   config.vocab_size	)
        _UpperCamelCase      :	Any						=       ids_tensor((self.batch_size, 3)					,   vocab_size=2	)

        # append to next input_ids and
        _UpperCamelCase      :	Optional[int]						=       torch.cat([input_ids, next_tokens]					,   dim=-1	)
        _UpperCamelCase      :	str						=       torch.cat([input_mask, next_mask]					,   dim=-1	)

        _UpperCamelCase      :	Tuple						=       model(
            __a					,   attention_mask=__a					,   encoder_hidden_states=__a					,   encoder_attention_mask=__a					,   output_hidden_states=__a					,   )["hidden_states"][0]
        _UpperCamelCase      :	List[Any]						=       model(
            __a					,   attention_mask=__a					,   encoder_hidden_states=__a					,   encoder_attention_mask=__a					,   past_key_values=__a					,   output_hidden_states=__a					,   )["hidden_states"][0]

        # select random slice
        _UpperCamelCase      :	Dict						=       ids_tensor((1,)					,   output_from_past.shape[-1]	).item()
        _UpperCamelCase      :	List[str]						=       output_from_no_past[:, -3:, random_slice_idx].detach()
        _UpperCamelCase      :	Union[str, Any]						=       output_from_past[:, :, random_slice_idx].detach()

        self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]	)

        # test that outputs are equal for slice
        self.parent.assertTrue(torch.allclose(__a					,   __a					,   atol=1e-3	)	)


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





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







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:List[str]	     =					(
      (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
  )
  SCREAMING_SNAKE_CASE__							:Dict	     =					(OpenLlamaForCausalLM,) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE__							:int	     =					(
      {
          "feature-extraction": OpenLlamaModel,
          "text-classification": OpenLlamaForSequenceClassification,
          "text-generation": OpenLlamaForCausalLM,
          "zero-shot": OpenLlamaForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  SCREAMING_SNAKE_CASE__							:Dict	     =					False
  SCREAMING_SNAKE_CASE__							:List[str]	     =					False

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Any:
        _UpperCamelCase      :	List[Any]						=       OpenLlamaModelTester(self	)
        _UpperCamelCase      :	Optional[Any]						=       ConfigTester(self					,   config_class=__a					,   hidden_size=37	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Any:
        self.config_tester.run_common_tests()

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Dict:
        _UpperCamelCase      :	List[str]						=       self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
              _UpperCamelCase      :	Any						=       type
              self.model_tester.create_and_check_model(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				Optional[Any]:
        _UpperCamelCase,  _UpperCamelCase      :	List[str]						=       self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCamelCase      :	Optional[int]						=       3
        _UpperCamelCase      :	Any						=       input_dict["input_ids"]
        _UpperCamelCase      :	Dict						=       input_ids.ne(1	).to(__a	)
        _UpperCamelCase      :	Tuple						=       ids_tensor([self.model_tester.batch_size]					,   self.model_tester.type_sequence_label_size	)
        _UpperCamelCase      :	List[str]						=       OpenLlamaForSequenceClassification(__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	List[str]						=       model(__a					,   attention_mask=__a					,   labels=__a	)
        self.assertEqual(result.logits.shape					,   (self.model_tester.batch_size, self.model_tester.num_labels)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				int:
        _UpperCamelCase,  _UpperCamelCase      :	str						=       self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCamelCase      :	Optional[Any]						=       3
        _UpperCamelCase      :	Optional[Any]						=       "single_label_classification"
        _UpperCamelCase      :	Any						=       input_dict["input_ids"]
        _UpperCamelCase      :	List[str]						=       input_ids.ne(1	).to(__a	)
        _UpperCamelCase      :	Any						=       ids_tensor([self.model_tester.batch_size]					,   self.model_tester.type_sequence_label_size	)
        _UpperCamelCase      :	Dict						=       OpenLlamaForSequenceClassification(__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	int						=       model(__a					,   attention_mask=__a					,   labels=__a	)
        self.assertEqual(result.logits.shape					,   (self.model_tester.batch_size, self.model_tester.num_labels)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Tuple:
        _UpperCamelCase,  _UpperCamelCase      :	int						=       self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCamelCase      :	Tuple						=       3
        _UpperCamelCase      :	Tuple						=       "multi_label_classification"
        _UpperCamelCase      :	List[Any]						=       input_dict["input_ids"]
        _UpperCamelCase      :	Tuple						=       input_ids.ne(1	).to(__a	)
        _UpperCamelCase      :	Dict						=       ids_tensor(
            [self.model_tester.batch_size, config.num_labels]					,   self.model_tester.type_sequence_label_size	).to(torch.float	)
        _UpperCamelCase      :	int						=       OpenLlamaForSequenceClassification(__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Any						=       model(__a					,   attention_mask=__a					,   labels=__a	)
        self.assertEqual(result.logits.shape					,   (self.model_tester.batch_size, self.model_tester.num_labels)	)

  @unittest.skip("Open-Llama buffers include complex numbers, which breaks this test"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				Union[str, Any]:
        pass


  @parameterized.expand([("linear",), ("dynamic",)]	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple					,   __a   :       List[Any]	)		->				str:
        _UpperCamelCase,  _UpperCamelCase      :	List[str]						=       self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCamelCase      :	Optional[int]						=       ids_tensor([1, 10]					,   config.vocab_size	)
        _UpperCamelCase      :	Tuple						=       ids_tensor([1, int(config.max_position_embeddings * 1.5	)]					,   config.vocab_size	)

        set_seed(42	)  # Fixed seed at init time so the two models get the same random weights
        _UpperCamelCase      :	List[Any]						=       OpenLlamaModel(__a	)
        original_model.to(__a	)
        original_model.eval()
        _UpperCamelCase      :	List[Any]						=       original_model(__a	).last_hidden_state
        _UpperCamelCase      :	Dict						=       original_model(__a	).last_hidden_state

        set_seed(42	)  # Fixed seed at init time so the two models get the same random weights
        _UpperCamelCase      :	Optional[int]						=       {"type": scaling_type, "factor": 10.0}
        _UpperCamelCase      :	Optional[Any]						=       OpenLlamaModel(__a	)
        scaled_model.to(__a	)
        scaled_model.eval()
        _UpperCamelCase      :	Union[str, Any]						=       scaled_model(__a	).last_hidden_state
        _UpperCamelCase      :	str						=       scaled_model(__a	).last_hidden_state

        # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
        # maximum sequence length, so the outputs for the short input should match.
        if scaling_type == "dynamic":
              self.assertTrue(torch.allclose(__a					,   __a					,   atol=1e-5	)	)
        else:
              self.assertFalse(torch.allclose(__a					,   __a					,   atol=1e-5	)	)

        # The output should be different for long inputs
        self.assertFalse(torch.allclose(__a					,   __a					,   atol=1e-5	)	)







"""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}"""
  )
