




"""simple docstring"""


import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, 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 (
         FalconForCausalLM,
         FalconForQuestionAnswering,
         FalconForSequenceClassification,
         FalconForTokenClassification,
         FalconModel,
     )






class  lowercase:







 '''simple docstring'''





 def __init__(    self:		Optional[Any],				a_:		Dict,				a_:		List[str]=3,				a_:		Optional[Any]=7,				a_:		Any=True,				a_:		str=True,				a_:		Union[str, Any]=False,				a_:		Any=True,				a_:		List[Any]=99,				a_:		List[str]=32,				a_:		Any=5,				a_:		Optional[Any]=4,				a_:		List[str]=37,				a_:		List[str]="gelu",				a_:		Tuple=0.1,				a_:		str=0.1,				a_:		int=512,				a_:		List[str]=16,				a_:		Union[str, Any]=2,				a_:		Union[str, Any]=0.02,				a_:		List[Any]=3,				a_:		List[str]=4,				a_:		List[str]=None,				):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  parent
   _snake_case							:		int								=  batch_size
   _snake_case							:		Optional[Any]								=  seq_length
   _snake_case							:		str								=  is_training
   _snake_case							:		int								=  use_input_mask
   _snake_case							:		Union[str, Any]								=  use_token_type_ids
   _snake_case							:		Optional[Any]								=  use_labels
   _snake_case							:		List[Any]								=  vocab_size
   _snake_case							:		Tuple								=  hidden_size
   _snake_case							:		Optional[Any]								=  num_hidden_layers
   _snake_case							:		Dict								=  num_attention_heads
   _snake_case							:		int								=  intermediate_size
   _snake_case							:		Optional[int]								=  hidden_act
   _snake_case							:		Any								=  hidden_dropout_prob
   _snake_case							:		List[Any]								=  attention_probs_dropout_prob
   _snake_case							:		Optional[Any]								=  max_position_embeddings
   _snake_case							:		List[str]								=  type_vocab_size
   _snake_case							:		Tuple								=  type_sequence_label_size
   _snake_case							:		Tuple								=  initializer_range
   _snake_case							:		Any								=  num_labels
   _snake_case							:		Optional[int]								=  num_choices
   _snake_case							:		Tuple								=  scope


 def 			UpperCamelCase_       (    self:		Union[str, Any]		):




   '''simple docstring'''



   _snake_case							:		Dict								=  ids_tensor([self.batch_size, self.seq_length],				self.vocab_size		)

   _snake_case							:		List[Any]								=  None
   if self.use_input_mask:
     _snake_case							:		Tuple								=  random_attention_mask([self.batch_size, self.seq_length]		)

   _snake_case							:		Dict								=  None

   _snake_case							:		Any								=  None
   _snake_case							:		List[Any]								=  None
   _snake_case							:		Tuple								=  None
   if self.use_labels:
     _snake_case							:		Union[str, Any]								=  ids_tensor([self.batch_size],				self.type_sequence_label_size		)
     _snake_case							:		int								=  ids_tensor([self.batch_size, self.seq_length],				self.num_labels		)
     _snake_case							:		List[str]								=  ids_tensor([self.batch_size],				self.num_choices		)

   _snake_case							:		Any								=  self.get_config()

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


 def 			UpperCamelCase_       (    self:		Optional[int]		):




   '''simple docstring'''



   return FalconConfig(
       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,				pad_token_id=1,				new_decoder_architecture=a_,				)


 def 			UpperCamelCase_       (    self:		Any,				a_:		Any,				a_:		Optional[int],				a_:		str,				a_:		Union[str, Any],				a_:		Tuple,				a_:		Any,				a_:		List[Any]		):




   '''simple docstring'''



   _snake_case							:		Tuple								=  FalconModel(config=a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		List[Any]								=  model(a_,				attention_mask=a_		)
   _snake_case							:		Tuple								=  model(a_		)
   self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.hidden_size)		)


 def 			UpperCamelCase_       (    self:		List[Any],				a_:		List[str],				a_:		Union[str, Any],				a_:		Optional[Any],				a_:		Union[str, Any],				a_:		Any,				a_:		List[Any],				a_:		int,				a_:		Tuple,				a_:		int,				):




   '''simple docstring'''



   _snake_case							:		List[str]								=  True
   _snake_case							:		Any								=  FalconModel(a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		Dict								=  model(
       a_,				attention_mask=a_,				encoder_hidden_states=a_,				encoder_attention_mask=a_,				)
   _snake_case							:		Any								=  model(
       a_,				attention_mask=a_,				encoder_hidden_states=a_,				)
   _snake_case							:		Optional[int]								=  model(a_,				attention_mask=a_		)
   self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.hidden_size)		)


 def 			UpperCamelCase_       (    self:		Any,				a_:		str,				a_:		Any,				a_:		Optional[int],				a_:		Union[str, Any],				a_:		Union[str, Any],				a_:		Union[str, Any],				a_:		List[str],				a_:		List[str],				a_:		List[str],				):




   '''simple docstring'''



   _snake_case							:		Optional[int]								=  FalconForCausalLM(config=a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		Tuple								=  model(a_,				attention_mask=a_,				labels=a_		)
   self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.seq_length, self.vocab_size)		)


 def 			UpperCamelCase_       (    self:		List[Any],				a_:		Union[str, Any],				a_:		Optional[Any],				a_:		Optional[int],				a_:		Any,				a_:		List[Any],				a_:		List[str],				a_:		List[str],				a_:		Tuple,				a_:		Optional[Any],				):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  True
   _snake_case							:		List[Any]								=  True
   _snake_case							:		Tuple								=  FalconForCausalLM(config=a_		)
   model.to(a_		)
   model.eval()

   # first forward pass
   _snake_case							:		str								=  model(
       a_,				attention_mask=a_,				encoder_hidden_states=a_,				encoder_attention_mask=a_,				use_cache=a_,				)
   _snake_case							:		List[str]								=  outputs.past_key_values

   # create hypothetical multiple next token and extent to next_input_ids
   _snake_case							:		int								=  ids_tensor((self.batch_size, 3),				config.vocab_size		)
   _snake_case							:		int								=  ids_tensor((self.batch_size, 3),				vocab_size=2		)

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

   _snake_case							:		Optional[int]								=  model(
       a_,				attention_mask=a_,				encoder_hidden_states=a_,				encoder_attention_mask=a_,				output_hidden_states=a_,				)["""hidden_states"""][0]
   _snake_case							:		str								=  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
   _snake_case							:		Optional[int]								=  ids_tensor((1,),				output_from_past.shape[-1]		).item()
   _snake_case							:		int								=  output_from_no_past[:, -3:, random_slice_idx].detach()
   _snake_case							:		int								=  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 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  self.prepare_config_and_inputs()
   (
       (
       _snake_case
   )		, (
       _snake_case
   )		, (
       _snake_case
   )		, (
       _snake_case
   )		, (
       _snake_case
   )		, (
       _snake_case
   )		, (
       _snake_case
   )		, 
   )							:		Tuple								=  config_and_inputs
   _snake_case							:		Dict								=  {"""input_ids""": input_ids, """attention_mask""": input_mask}
   return config, inputs_dict







@require_torch
class  lowercase(					__a	,      __a	,      __a	,      unittest.TestCase			):







 '''simple docstring'''





 lowercase__			 = (
     (
         FalconModel,
         FalconForCausalLM,
         FalconForSequenceClassification,
         FalconForTokenClassification,
         FalconForQuestionAnswering,
     )
     if is_torch_available()
     else ()
 )
 lowercase__			 = (FalconForCausalLM,) if is_torch_available() else ()
 lowercase__			 = (
     {
         "feature-extraction": FalconModel,
         "text-classification": FalconForSequenceClassification,
         "text-generation": FalconForCausalLM,
         "question-answering": FalconForQuestionAnswering,
         "token-classification": FalconForTokenClassification,
         "zero-shot": FalconForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 lowercase__			 = False
 lowercase__			 = False


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  FalconModelTester(self		)
   _snake_case							:		Union[str, Any]								=  ConfigTester(self,				config_class=a_,				hidden_size=37		)


 def 			UpperCamelCase_       (    self:		int		):




   '''simple docstring'''



   self.config_tester.run_common_tests()


 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*a_		)


 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   _snake_case		, *_snake_case							:		Tuple								=  self.model_tester.prepare_config_and_inputs()
   for alibi in [True, False]:
     _snake_case							:		str								=  alibi
     self.model_tester.create_and_check_model(a_,				*a_		)


 def 			UpperCamelCase_       (    self:		Union[str, Any]		):




   '''simple docstring'''



   _snake_case		, _snake_case							:		Dict								=  self.model_tester.prepare_config_and_inputs_for_common()
   _snake_case							:		Optional[Any]								=  3
   _snake_case							:		List[Any]								=  input_dict["""input_ids"""]
   _snake_case							:		List[str]								=  input_ids.ne(1		).to(a_		)
   _snake_case							:		Tuple								=  ids_tensor([self.model_tester.batch_size],				self.model_tester.type_sequence_label_size		)
   _snake_case							:		Optional[int]								=  FalconForSequenceClassification(a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		Any								=  model(a_,				attention_mask=a_,				labels=a_		)
   self.assertEqual(result.logits.shape,				(self.model_tester.batch_size, self.model_tester.num_labels)		)


 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



   _snake_case		, _snake_case							:		List[str]								=  self.model_tester.prepare_config_and_inputs_for_common()
   _snake_case							:		List[Any]								=  3
   _snake_case							:		Optional[int]								=  """single_label_classification"""
   _snake_case							:		Any								=  input_dict["""input_ids"""]
   _snake_case							:		Optional[int]								=  input_ids.ne(1		).to(a_		)
   _snake_case							:		Tuple								=  ids_tensor([self.model_tester.batch_size],				self.model_tester.type_sequence_label_size		)
   _snake_case							:		Tuple								=  FalconForSequenceClassification(a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		Dict								=  model(a_,				attention_mask=a_,				labels=a_		)
   self.assertEqual(result.logits.shape,				(self.model_tester.batch_size, self.model_tester.num_labels)		)


 def 			UpperCamelCase_       (    self:		Dict		):




   '''simple docstring'''



   _snake_case		, _snake_case							:		Union[str, Any]								=  self.model_tester.prepare_config_and_inputs_for_common()
   _snake_case							:		str								=  input_dict["""input_ids"""]
   _snake_case							:		Tuple								=  FalconForCausalLM(a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		Dict								=  model(a_,				use_cache=a_		)
   _snake_case							:		Union[str, Any]								=  input_ids.shape[0]
   _snake_case							:		Tuple								=  model._convert_to_rw_cache(result.past_key_values		)
   _snake_case							:		Optional[Any]								=  model._convert_cache_to_standard_format(a_,				a_		)
   for layer in range(len(a_		)		):
     for tensor_idx in range(2		):
       self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3		)
       self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4		)
       self.assertTrue(
           torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]		)		)


 def 			UpperCamelCase_       (    self:		List[str]		):




   '''simple docstring'''



   _snake_case		, _snake_case							:		Dict								=  self.model_tester.prepare_config_and_inputs_for_common()
   _snake_case							:		Tuple								=  3
   _snake_case							:		List[Any]								=  """multi_label_classification"""
   _snake_case							:		Tuple								=  input_dict["""input_ids"""]
   _snake_case							:		str								=  input_ids.ne(1		).to(a_		)
   _snake_case							:		Any								=  ids_tensor(
       [self.model_tester.batch_size, config.num_labels],				self.model_tester.type_sequence_label_size		).to(torch.float		)
   _snake_case							:		Optional[int]								=  FalconForSequenceClassification(a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		Optional[int]								=  model(a_,				attention_mask=a_,				labels=a_		)
   self.assertEqual(result.logits.shape,				(self.model_tester.batch_size, self.model_tester.num_labels)		)


 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   for model_class in self.all_generative_model_classes:
     _snake_case		, _snake_case							:		List[str]								=  self.model_tester.prepare_config_and_inputs_for_common()

     # If it doesn't support cache, pass the test
     if not hasattr(a_,				"""use_cache"""		):
       return

     _snake_case							:		int								=  model_class(a_		).to(a_		)
     if "use_cache" not in inputs:
       _snake_case							:		List[Any]								=  True
     _snake_case							:		Optional[Any]								=  model(**a_		)

     # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
     if "past_key_values" not in outputs:
       return

     _snake_case							:		int								=  (
         getattr(a_,				"""decoder_layers""",				a_		)
         or getattr(a_,				"""num_decoder_layers""",				a_		)
         or config.num_hidden_layers
     )
     _snake_case							:		List[Any]								=  getattr(a_,				"""num_kv_heads""",				config.num_attention_heads		)
     _snake_case							:		Optional[Any]								=  getattr(a_,				"""d_model""",				config.hidden_size		)
     _snake_case							:		Union[str, Any]								=  embed_dim // num_attention_heads

     _snake_case							:		Tuple								=  outputs["""past_key_values"""]
     self.assertEqual(len(a_		),				a_		)

     _snake_case		, _snake_case							:		List[Any]								=  inputs["""input_ids"""].shape
     for i in range(a_		):
       if config.new_decoder_architecture:
         _snake_case							:		int								=  config.num_attention_heads
       elif config.multi_query:
         _snake_case							:		Any								=  1
       self.assertEqual(len(past_kv[0]		),				2		)  # K V for the decoder = 2
       self.assertEqual(
           past_kv[i][0].shape,				(batch_size, num_attention_heads, seq_length, per_head_embed_dim)		)
       self.assertEqual(
           past_kv[i][1].shape,				(batch_size, num_attention_heads, seq_length, per_head_embed_dim)		)







@require_torch
class  lowercase(					unittest.TestCase			):







 '''simple docstring'''





 @slow
 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   _snake_case							:		Tuple								=  AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b"""		)
   _snake_case							:		str								=  FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b"""		)
   model.eval()
   model.to(a_		)
   _snake_case							:		Union[str, Any]								=  tokenizer("""My favorite food is""",				return_tensors="""pt"""		).to(a_		)

   _snake_case							:		List[Any]								=  (
       """My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."""
   )

   _snake_case							:		Optional[Any]								=  model.generate(**a_,				do_sample=a_,				max_new_tokens=19		)
   _snake_case							:		List[str]								=  tokenizer.batch_decode(a_		)[0]

   self.assertEqual(a_,				a_		)


 @slow
 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



   for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
     _snake_case							:		str								=  AutoTokenizer.from_pretrained(a_		)
     _snake_case							:		List[str]								=  FalconForCausalLM.from_pretrained(a_		)
     model.eval()
     model.to(a_		)
     _snake_case							:		Any								=  tokenizer("""My favorite food is""",				return_tensors="""pt"""		).to(a_		)

     # We just test that these run without errors - the models are randomly initialized
     # and so the actual text outputs will be garbage
     model.generate(**a_,				do_sample=a_,				max_new_tokens=4		)
     model.generate(**a_,				do_sample=a_,				max_new_tokens=4		)
     model.generate(**a_,				num_beams=2,				max_new_tokens=4		)


 @slow
 def 			UpperCamelCase_       (    self:		Union[str, Any]		):




   '''simple docstring'''



   with torch.no_grad():
     for repo in [
         "Rocketknight1/falcon-rw-1b",
         "Rocketknight1/tiny-random-falcon-7b",
         "Rocketknight1/tiny-random-falcon-40b",
     ]:
       _snake_case							:		Any								=  AutoTokenizer.from_pretrained(a_		)
       _snake_case							:		int								=  FalconForCausalLM.from_pretrained(a_		)
       model.eval()
       model.to(device=a_		)
       _snake_case							:		Optional[int]								=  tokenizer("""My favorite food is""",				return_tensors="""pt"""		).to(a_		)

       # Test results are the same with and without cache
       _snake_case							:		Optional[int]								=  model.generate(**a_,				do_sample=a_,				max_new_tokens=20,				use_cache=a_		)
       _snake_case							:		List[Any]								=  model.generate(**a_,				do_sample=a_,				max_new_tokens=20,				use_cache=a_		)
       self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0		)








"""simple docstring"""


from __future__ import annotations

from math import gcd


def  UpperCAmelCase__	(snake_case__							: int		,       snake_case__							: int = 2		,       snake_case__							: int = 1		,       snake_case__							: int = 3		,       ):
  """simple docstring"""

  if num < 2:
    raise ValueError("""The input value cannot be less than 2"""   )

  # Because of the relationship between ``f(f(x))`` and ``f(x)``, this
  # algorithm struggles to find factors that are divisible by two.
  # As a workaround, we specifically check for two and even inputs.
  #   See: https://math.stackexchange.com/a/2856214/165820
  if num > 2 and num % 2 == 0:
    return 2

  # Pollard's Rho algorithm requires a function that returns pseudorandom
  # values between 0 <= X < ``num``.  It doesn't need to be random in the
  # sense that the output value is cryptographically secure or difficult
  # to calculate, it only needs to be random in the sense that all output
  # values should be equally likely to appear.
  # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num``
  # However, the success of Pollard's algorithm isn't guaranteed and is
  # determined in part by the initial seed and the chosen random function.
  # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num``
  # where ``C`` is a value that we can modify between each attempt.
  def rand_fn(snake_case__							: int		,       snake_case__							: int		,       snake_case__							: int   ) -> int:
    return (pow(snake_case__		,       2   ) + step) % modulus

  for _ in range(snake_case__   ):
    # These track the position within the cycle detection logic.
    _snake_case							:		Optional[int]								=  seed
    _snake_case							:		str								=  seed

    while True:
      # At each iteration, the tortoise moves one step and the hare moves two.
      _snake_case							:		Any								=  rand_fn(snake_case__		,       snake_case__		,       snake_case__   )
      _snake_case							:		Optional[Any]								=  rand_fn(snake_case__		,       snake_case__		,       snake_case__   )
      _snake_case							:		int								=  rand_fn(snake_case__		,       snake_case__		,       snake_case__   )

      # At some point both the tortoise and the hare will enter a cycle whose
      # length ``p`` is a divisor of ``num``.  Once in that cycle, at some point
      # the tortoise and hare will end up on the same value modulo ``p``.
      # We can detect when this happens because the position difference between
      # the tortoise and the hare will share a common divisor with ``num``.
      _snake_case							:		str								=  gcd(hare - tortoise		,       snake_case__   )

      if divisor == 1:
        # No common divisor yet, just keep searching.
        continue
      else:
        # We found a common divisor!
        if divisor == num:
          # Unfortunately, the divisor is ``num`` itself and is useless.
          break
        else:
          # The divisor is a nontrivial factor of ``num``!
          return divisor

        # If we made it here, then this attempt failed.
        # We need to pick a new starting seed for the tortoise and hare
        # in addition to a new step value for the random function.
        # To keep this example implementation deterministic, the
        # new values will be generated based on currently available
        # values instead of using something like ``random.randint``.

        # We can use the hare's position as the new seed.
        # This is actually what Richard Brent's the "optimized" variant does.
    _snake_case							:		Union[str, Any]								=  hare

    # The new step value for the random function can just be incremented.
    # At first the results will be similar to what the old function would
    # have produced, but the value will quickly diverge after a bit.
    step += 1

  # We haven't found a divisor within the requested number of attempts.
  # We were unlucky or ``num`` itself is actually prime.
  return None


if __name__ == "__main__":
     import argparse

     A_      =    argparse.ArgumentParser()
     parser.add_argument(
         '''num''',
         type=int,
         help='''The value to find a divisor of''',
     )
     parser.add_argument(
         '''--attempts''',
         type=int,
         default=3,
         help='''The number of attempts before giving up''',
     )
     A_      =    parser.parse_args()

     A_      =    pollard_rho(args.num, attempts=args.attempts)
     if divisor is None:
          print(F'''{args.num} is probably prime''')
     else:
          A_      =    args.num // divisor
          print(F'''{args.num} = {divisor} * {quotient}''')


