


'''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      snake_case    :





  """simple docstring"""




  def __init__(    self			,  UpperCamelCase			,  UpperCamelCase=3			,  UpperCamelCase=7			,  UpperCamelCase=True			,  UpperCamelCase=True			,  UpperCamelCase=False			,  UpperCamelCase=True			,  UpperCamelCase=99			,  UpperCamelCase=32			,  UpperCamelCase=5			,  UpperCamelCase=4			,  UpperCamelCase=37			,  UpperCamelCase="gelu"			,  UpperCamelCase=0.1			,  UpperCamelCase=0.1			,  UpperCamelCase=512			,  UpperCamelCase=16			,  UpperCamelCase=2			,  UpperCamelCase=0.02			,  UpperCamelCase=3			,  UpperCamelCase=4			,  UpperCamelCase=None			,  ):







   """simple docstring"""
   lowerCamelCase_      =  parent
   lowerCamelCase_      =  batch_size
   lowerCamelCase_      =  seq_length
   lowerCamelCase_      =  is_training
   lowerCamelCase_      =  use_input_mask
   lowerCamelCase_      =  use_token_type_ids
   lowerCamelCase_      =  use_labels
   lowerCamelCase_      =  vocab_size
   lowerCamelCase_      =  hidden_size
   lowerCamelCase_      =  num_hidden_layers
   lowerCamelCase_      =  num_attention_heads
   lowerCamelCase_      =  intermediate_size
   lowerCamelCase_      =  hidden_act
   lowerCamelCase_      =  hidden_dropout_prob
   lowerCamelCase_      =  attention_probs_dropout_prob
   lowerCamelCase_      =  max_position_embeddings
   lowerCamelCase_      =  type_vocab_size
   lowerCamelCase_      =  type_sequence_label_size
   lowerCamelCase_      =  initializer_range
   lowerCamelCase_      =  num_labels
   lowerCamelCase_      =  num_choices
   lowerCamelCase_      =  scope






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  ids_tensor([self.batch_size, self.seq_length]			,  self.vocab_size     )

   lowerCamelCase_      =  None
   if self.use_input_mask:
    lowerCamelCase_      =  random_attention_mask([self.batch_size, self.seq_length]     )

   lowerCamelCase_      =  None

   lowerCamelCase_      =  None
   lowerCamelCase_      =  None
   lowerCamelCase_      =  None
   if self.use_labels:
    lowerCamelCase_      =  ids_tensor([self.batch_size]			,  self.type_sequence_label_size     )
    lowerCamelCase_      =  ids_tensor([self.batch_size, self.seq_length]			,  self.num_labels     )
    lowerCamelCase_      =  ids_tensor([self.batch_size]			,  self.num_choices     )

   lowerCamelCase_      =  self.get_config()

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






  def   snake_case		(    self     ):







   """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=UpperCamelCase			,  initializer_range=self.initializer_range			,  pad_token_id=1			,  new_decoder_architecture=UpperCamelCase			,  )






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  FalconModel(config=UpperCamelCase     )
   model.to(UpperCamelCase     )
   model.eval()
   lowerCamelCase_      =  model(UpperCamelCase			,  attention_mask=UpperCamelCase     )
   lowerCamelCase_      =  model(UpperCamelCase     )
   self.parent.assertEqual(result.last_hidden_state.shape			,  (self.batch_size, self.seq_length, self.hidden_size)     )






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  ):







   """simple docstring"""
   lowerCamelCase_      =  True
   lowerCamelCase_      =  FalconModel(UpperCamelCase     )
   model.to(UpperCamelCase     )
   model.eval()
   lowerCamelCase_      =  model(
       UpperCamelCase			,  attention_mask=UpperCamelCase			,  encoder_hidden_states=UpperCamelCase			,  encoder_attention_mask=UpperCamelCase			,  )
   lowerCamelCase_      =  model(
       UpperCamelCase			,  attention_mask=UpperCamelCase			,  encoder_hidden_states=UpperCamelCase			,  )
   lowerCamelCase_      =  model(UpperCamelCase			,  attention_mask=UpperCamelCase     )
   self.parent.assertEqual(result.last_hidden_state.shape			,  (self.batch_size, self.seq_length, self.hidden_size)     )






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  ):







   """simple docstring"""
   lowerCamelCase_      =  FalconForCausalLM(config=UpperCamelCase     )
   model.to(UpperCamelCase     )
   model.eval()
   lowerCamelCase_      =  model(UpperCamelCase			,  attention_mask=UpperCamelCase			,  labels=UpperCamelCase     )
   self.parent.assertEqual(result.logits.shape			,  (self.batch_size, self.seq_length, self.vocab_size)     )






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  ):







   """simple docstring"""
   lowerCamelCase_      =  True
   lowerCamelCase_      =  True
   lowerCamelCase_      =  FalconForCausalLM(config=UpperCamelCase     )
   model.to(UpperCamelCase     )
   model.eval()

   # first forward pass
   lowerCamelCase_      =  model(
       UpperCamelCase			,  attention_mask=UpperCamelCase			,  encoder_hidden_states=UpperCamelCase			,  encoder_attention_mask=UpperCamelCase			,  use_cache=UpperCamelCase			,  )
   lowerCamelCase_      =  outputs.past_key_values

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

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

   lowerCamelCase_      =  model(
       UpperCamelCase			,  attention_mask=UpperCamelCase			,  encoder_hidden_states=UpperCamelCase			,  encoder_attention_mask=UpperCamelCase			,  output_hidden_states=UpperCamelCase			,  )["hidden_states"][0]
   lowerCamelCase_      =  model(
       UpperCamelCase			,  attention_mask=UpperCamelCase			,  encoder_hidden_states=UpperCamelCase			,  encoder_attention_mask=UpperCamelCase			,  past_key_values=UpperCamelCase			,  output_hidden_states=UpperCamelCase			,  )["hidden_states"][0]

   # select random slice
   lowerCamelCase_      =  ids_tensor((1,)			,  output_from_past.shape[-1]     ).item()
   lowerCamelCase_      =  output_from_no_past[:, -3:, random_slice_idx].detach()
   lowerCamelCase_      =  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(UpperCamelCase			,  UpperCamelCase			,  atol=1e-3     )     )







  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.prepare_config_and_inputs()
   (
       (
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,
   )      =  config_and_inputs
   lowerCamelCase_      =  {"input_ids": input_ids, "attention_mask": input_mask}
   return config, inputs_dict





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





  """simple docstring"""




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






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  FalconModelTester(self     )
   lowerCamelCase_      =  ConfigTester(self			,  config_class=UpperCamelCase			,  hidden_size=37     )






  def   snake_case		(    self     ):







   """simple docstring"""
   self.config_tester.run_common_tests()






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCamelCase     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_ ,*lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs()
   for alibi in [True, False]:
    lowerCamelCase_      =  alibi
    self.model_tester.create_and_check_model(UpperCamelCase			,  *UpperCamelCase     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_ ,lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs_for_common()
   lowerCamelCase_      =  3
   lowerCamelCase_      =  input_dict["input_ids"]
   lowerCamelCase_      =  input_ids.ne(1     ).to(UpperCamelCase     )
   lowerCamelCase_      =  ids_tensor([self.model_tester.batch_size]			,  self.model_tester.type_sequence_label_size     )
   lowerCamelCase_      =  FalconForSequenceClassification(UpperCamelCase     )
   model.to(UpperCamelCase     )
   model.eval()
   lowerCamelCase_      =  model(UpperCamelCase			,  attention_mask=UpperCamelCase			,  labels=UpperCamelCase     )
   self.assertEqual(result.logits.shape			,  (self.model_tester.batch_size, self.model_tester.num_labels)     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_ ,lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs_for_common()
   lowerCamelCase_      =  3
   lowerCamelCase_      =  "single_label_classification"
   lowerCamelCase_      =  input_dict["input_ids"]
   lowerCamelCase_      =  input_ids.ne(1     ).to(UpperCamelCase     )
   lowerCamelCase_      =  ids_tensor([self.model_tester.batch_size]			,  self.model_tester.type_sequence_label_size     )
   lowerCamelCase_      =  FalconForSequenceClassification(UpperCamelCase     )
   model.to(UpperCamelCase     )
   model.eval()
   lowerCamelCase_      =  model(UpperCamelCase			,  attention_mask=UpperCamelCase			,  labels=UpperCamelCase     )
   self.assertEqual(result.logits.shape			,  (self.model_tester.batch_size, self.model_tester.num_labels)     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_ ,lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs_for_common()
   lowerCamelCase_      =  input_dict["input_ids"]
   lowerCamelCase_      =  FalconForCausalLM(UpperCamelCase     )
   model.to(UpperCamelCase     )
   model.eval()
   lowerCamelCase_      =  model(UpperCamelCase			,  use_cache=UpperCamelCase     )
   lowerCamelCase_      =  input_ids.shape[0]
   lowerCamelCase_      =  model._convert_to_rw_cache(result.past_key_values     )
   lowerCamelCase_      =  model._convert_cache_to_standard_format(UpperCamelCase			,  UpperCamelCase     )
   for layer in range(len(UpperCamelCase     )     ):
    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   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_ ,lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs_for_common()
   lowerCamelCase_      =  3
   lowerCamelCase_      =  "multi_label_classification"
   lowerCamelCase_      =  input_dict["input_ids"]
   lowerCamelCase_      =  input_ids.ne(1     ).to(UpperCamelCase     )
   lowerCamelCase_      =  ids_tensor(
       [self.model_tester.batch_size, config.num_labels]			,  self.model_tester.type_sequence_label_size     ).to(torch.float     )
   lowerCamelCase_      =  FalconForSequenceClassification(UpperCamelCase     )
   model.to(UpperCamelCase     )
   model.eval()
   lowerCamelCase_      =  model(UpperCamelCase			,  attention_mask=UpperCamelCase			,  labels=UpperCamelCase     )
   self.assertEqual(result.logits.shape			,  (self.model_tester.batch_size, self.model_tester.num_labels)     )







  def   snake_case		(    self     ):







   """simple docstring"""
   # Falcon can have different numbers of KV-heads than the number of query heads, so we need
   # to override this test to use the right head counts.
   for model_class in self.all_generative_model_classes:
    lowerCamelCase_ ,lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs_for_common()

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

    lowerCamelCase_      =  model_class(UpperCamelCase     ).to(UpperCamelCase     )
    if "use_cache" not in inputs:
     lowerCamelCase_      =  True
    lowerCamelCase_      =  model(**UpperCamelCase     )

    # 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

    lowerCamelCase_      =  (
        getattr(UpperCamelCase			,  "decoder_layers"			,  UpperCamelCase     )
        or getattr(UpperCamelCase			,  "num_decoder_layers"			,  UpperCamelCase     )
        or config.num_hidden_layers
    )
    lowerCamelCase_      =  getattr(UpperCamelCase			,  "num_kv_heads"			,  config.num_attention_heads     )
    lowerCamelCase_      =  getattr(UpperCamelCase			,  "d_model"			,  config.hidden_size     )
    lowerCamelCase_      =  embed_dim // num_attention_heads

    lowerCamelCase_      =  outputs["past_key_values"]
    self.assertEqual(len(UpperCamelCase     )			,  UpperCamelCase     )

    lowerCamelCase_ ,lowerCamelCase_      =  inputs["input_ids"].shape
    for i in range(UpperCamelCase     ):
     if config.new_decoder_architecture:
      lowerCamelCase_      =  config.num_attention_heads
     elif config.multi_query:
      lowerCamelCase_      =  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      snake_case    (    unittest.TestCase			):





  """simple docstring"""




  @slow
  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b"     )
   lowerCamelCase_      =  FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b"     )
   model.eval()
   model.to(UpperCamelCase     )
   lowerCamelCase_      =  tokenizer("My favorite food is"			,  return_tensors="pt"     ).to(UpperCamelCase     )

   lowerCamelCase_      =  (
       "My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
   )

   lowerCamelCase_      =  model.generate(**UpperCamelCase			,  do_sample=UpperCamelCase			,  max_new_tokens=19     )
   lowerCamelCase_      =  tokenizer.batch_decode(UpperCamelCase     )[0]

   self.assertEqual(UpperCamelCase			,  UpperCamelCase     )






  @slow
  def   snake_case		(    self     ):







   """simple docstring"""
   # The big models are way too big for the CI, so we use tiny random models that resemble their
   # architectures but with much smaller and fewer layers
   for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
    lowerCamelCase_      =  AutoTokenizer.from_pretrained(UpperCamelCase     )
    lowerCamelCase_      =  FalconForCausalLM.from_pretrained(UpperCamelCase     )
    model.eval()
    model.to(UpperCamelCase     )
    lowerCamelCase_      =  tokenizer("My favorite food is"			,  return_tensors="pt"     ).to(UpperCamelCase     )

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







  @slow
  def   snake_case		(    self     ):







   """simple docstring"""
   # The big models are way too big for the CI, so we use tiny random models that resemble their
   # architectures but with much smaller and fewer layers
   with torch.no_grad():
    for repo in [
        "Rocketknight1/falcon-rw-1b",
        "Rocketknight1/tiny-random-falcon-7b",
        "Rocketknight1/tiny-random-falcon-40b",
    ]:
     lowerCamelCase_      =  AutoTokenizer.from_pretrained(UpperCamelCase     )
     lowerCamelCase_      =  FalconForCausalLM.from_pretrained(UpperCamelCase     )
     model.eval()
     model.to(device=UpperCamelCase     )
     lowerCamelCase_      =  tokenizer("My favorite food is"			,  return_tensors="pt"     ).to(UpperCamelCase     )

     # Test results are the same with and without cache
     lowerCamelCase_      =  model.generate(**UpperCamelCase			,  do_sample=UpperCamelCase			,  max_new_tokens=20			,  use_cache=UpperCamelCase     )
     lowerCamelCase_      =  model.generate(**UpperCamelCase			,  do_sample=UpperCamelCase			,  max_new_tokens=20			,  use_cache=UpperCamelCase     )
     self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0     )







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


__lowerCAmelCase		       =							{
    '''configuration_encodec''': [
        '''ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''EncodecConfig''',
    ],
    '''feature_extraction_encodec''': ['''EncodecFeatureExtractor'''],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __lowerCAmelCase		       =							[
     '''ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''EncodecModel''',
     '''EncodecPreTrainedModel''',
 ]

if TYPE_CHECKING:
 from .configuration_encodec import (
     ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP,
     EncodecConfig,
 )
 from .feature_extraction_encodec import EncodecFeatureExtractor

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_encodec import (
      ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST,
      EncodecModel,
      EncodecPreTrainedModel,
  )

else:
 import sys

 __lowerCAmelCase		       =							_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


