





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






    """simple docstring"""





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





    def 							a__				(				self  )			->		List[Any]:
         UpperCAmelCase_      :							str       =      ids_tensor([self.batch_size, self.seq_length]       ,self.vocab_size  )

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

         UpperCAmelCase_      :							List[Any]       =      None

         UpperCAmelCase_      :							Optional[Any]       =      None
         UpperCAmelCase_      :							int       =      None
         UpperCAmelCase_      :							Any       =      None
         if self.use_labels:
              UpperCAmelCase_      :							List[str]       =      ids_tensor([self.batch_size]       ,self.type_sequence_label_size  )
              UpperCAmelCase_      :							List[str]       =      ids_tensor([self.batch_size, self.seq_length]       ,self.num_labels  )
              UpperCAmelCase_      :							int       =      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 							a__				(				self  )			->		Tuple:
         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=_SCREAMING_SNAKE_CASE       ,initializer_range=self.initializer_range       ,pad_token_id=1       ,new_decoder_architecture=_SCREAMING_SNAKE_CASE       ,)





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		int:
         UpperCAmelCase_      :							Any       =      FalconModel(config=_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Any       =      model(_SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Any       =      model(_SCREAMING_SNAKE_CASE  )
         self.parent.assertEqual(result.last_hidden_state.shape       ,(self.batch_size, self.seq_length, self.hidden_size)  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,)			->		Dict:
         UpperCAmelCase_      :							List[Any]       =      True
         UpperCAmelCase_      :							Any       =      FalconModel(_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Optional[int]       =      model(
             _SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE       ,encoder_hidden_states=_SCREAMING_SNAKE_CASE       ,encoder_attention_mask=_SCREAMING_SNAKE_CASE       ,)
         UpperCAmelCase_      :							Optional[int]       =      model(
             _SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE       ,encoder_hidden_states=_SCREAMING_SNAKE_CASE       ,)
         UpperCAmelCase_      :							Optional[Any]       =      model(_SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE  )
         self.parent.assertEqual(result.last_hidden_state.shape       ,(self.batch_size, self.seq_length, self.hidden_size)  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,)			->		Union[str, Any]:
         UpperCAmelCase_      :							List[str]       =      FalconForCausalLM(config=_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Tuple       =      model(_SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE       ,labels=_SCREAMING_SNAKE_CASE  )
         self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.seq_length, self.vocab_size)  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,)			->		Tuple:
         UpperCAmelCase_      :							List[Any]       =      True
         UpperCAmelCase_      :							Optional[int]       =      True
         UpperCAmelCase_      :							int       =      FalconForCausalLM(config=_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()

         # first forward pass
         UpperCAmelCase_      :							Optional[int]       =      model(
             _SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE       ,encoder_hidden_states=_SCREAMING_SNAKE_CASE       ,encoder_attention_mask=_SCREAMING_SNAKE_CASE       ,use_cache=_SCREAMING_SNAKE_CASE       ,)
         UpperCAmelCase_      :							List[Any]       =      outputs.past_key_values

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

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

         UpperCAmelCase_      :							Dict       =      model(
             _SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE       ,encoder_hidden_states=_SCREAMING_SNAKE_CASE       ,encoder_attention_mask=_SCREAMING_SNAKE_CASE       ,output_hidden_states=_SCREAMING_SNAKE_CASE       ,)['''hidden_states'''][0]
         UpperCAmelCase_      :							int       =      model(
             _SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE       ,encoder_hidden_states=_SCREAMING_SNAKE_CASE       ,encoder_attention_mask=_SCREAMING_SNAKE_CASE       ,past_key_values=_SCREAMING_SNAKE_CASE       ,output_hidden_states=_SCREAMING_SNAKE_CASE       ,)['''hidden_states'''][0]

         # select random slice
         UpperCAmelCase_      :							List[str]       =      ids_tensor((1,)       ,output_from_past.shape[-1]  ).item()
         UpperCAmelCase_      :							Union[str, Any]       =      output_from_no_past[:, -3:, random_slice_idx].detach()
         UpperCAmelCase_      :							str       =      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(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,atol=1e-3  )  )





    def 							a__				(				self  )			->		Any:
         UpperCAmelCase_      :							List[str]       =      self.prepare_config_and_inputs()
         (
             UpperCAmelCase_   
         )      :							List[Any]       =      config_and_inputs
         UpperCAmelCase_      :							str       =      {'''input_ids''': input_ids, '''attention_mask''': input_mask}
         return config, inputs_dict


@require_torch
class   __a(					_a    ,						_a    ,						_a    ,						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 							a__				(				self  )			->		Dict:
         UpperCAmelCase_      :							List[Any]       =      FalconModelTester(self  )
         UpperCAmelCase_      :							Optional[int]       =      ConfigTester(self       ,config_class=_SCREAMING_SNAKE_CASE       ,hidden_size=37  )





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





    def 							a__				(				self  )			->		Tuple:
         UpperCAmelCase_      :							int       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		List[Any]:
         UpperCAmelCase_      :							int       =      self.model_tester.prepare_config_and_inputs()
         for alibi in [True, False]:
              UpperCAmelCase_      :							str       =      alibi
              self.model_tester.create_and_check_model(_SCREAMING_SNAKE_CASE       ,*_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Union[str, Any]:
         UpperCAmelCase_      :							Tuple       =      self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase_      :							str       =      3
         UpperCAmelCase_      :							int       =      input_dict['''input_ids''']
         UpperCAmelCase_      :							Any       =      input_ids.ne(1  ).to(_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							str       =      ids_tensor([self.model_tester.batch_size]       ,self.model_tester.type_sequence_label_size  )
         UpperCAmelCase_      :							Union[str, Any]       =      FalconForSequenceClassification(_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Optional[int]       =      model(_SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE       ,labels=_SCREAMING_SNAKE_CASE  )
         self.assertEqual(result.logits.shape       ,(self.model_tester.batch_size, self.model_tester.num_labels)  )





    def 							a__				(				self  )			->		Dict:
         UpperCAmelCase_      :							Dict       =      self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase_      :							Any       =      3
         UpperCAmelCase_      :							Union[str, Any]       =      '''single_label_classification'''
         UpperCAmelCase_      :							int       =      input_dict['''input_ids''']
         UpperCAmelCase_      :							int       =      input_ids.ne(1  ).to(_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Union[str, Any]       =      ids_tensor([self.model_tester.batch_size]       ,self.model_tester.type_sequence_label_size  )
         UpperCAmelCase_      :							Dict       =      FalconForSequenceClassification(_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Any       =      model(_SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE       ,labels=_SCREAMING_SNAKE_CASE  )
         self.assertEqual(result.logits.shape       ,(self.model_tester.batch_size, self.model_tester.num_labels)  )





    def 							a__				(				self  )			->		Dict:
         UpperCAmelCase_      :							Any       =      self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase_      :							Any       =      input_dict['''input_ids''']
         UpperCAmelCase_      :							int       =      FalconForCausalLM(_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Any       =      model(_SCREAMING_SNAKE_CASE       ,use_cache=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							List[Any]       =      input_ids.shape[0]
         UpperCAmelCase_      :							List[Any]       =      model._convert_to_rw_cache(result.past_key_values  )
         UpperCAmelCase_      :							str       =      model._convert_cache_to_standard_format(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )
         for layer in range(len(_SCREAMING_SNAKE_CASE  )  ):
              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 							a__				(				self  )			->		Any:
         UpperCAmelCase_      :							Any       =      self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase_      :							Any       =      3
         UpperCAmelCase_      :							str       =      '''multi_label_classification'''
         UpperCAmelCase_      :							List[str]       =      input_dict['''input_ids''']
         UpperCAmelCase_      :							str       =      input_ids.ne(1  ).to(_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Optional[Any]       =      ids_tensor(
             [self.model_tester.batch_size, config.num_labels]       ,self.model_tester.type_sequence_label_size  ).to(torch.float  )
         UpperCAmelCase_      :							Optional[int]       =      FalconForSequenceClassification(_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Any       =      model(_SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE       ,labels=_SCREAMING_SNAKE_CASE  )
         self.assertEqual(result.logits.shape       ,(self.model_tester.batch_size, self.model_tester.num_labels)  )





    def 							a__				(				self  )			->		Optional[int]:
         # 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:
              UpperCAmelCase_      :							Union[str, Any]       =      self.model_tester.prepare_config_and_inputs_for_common()

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

              UpperCAmelCase_      :							Any       =      model_class(_SCREAMING_SNAKE_CASE  ).to(_SCREAMING_SNAKE_CASE  )
              if "use_cache" not in inputs:
                   UpperCAmelCase_      :							Dict       =      True
              UpperCAmelCase_      :							Tuple       =      model(**_SCREAMING_SNAKE_CASE  )

              # 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

              UpperCAmelCase_      :							Union[str, Any]       =      (
                  getattr(_SCREAMING_SNAKE_CASE       ,'''decoder_layers'''       ,_SCREAMING_SNAKE_CASE  )
                  or getattr(_SCREAMING_SNAKE_CASE       ,'''num_decoder_layers'''       ,_SCREAMING_SNAKE_CASE  )
                  or config.num_hidden_layers
              )
              UpperCAmelCase_      :							Tuple       =      getattr(_SCREAMING_SNAKE_CASE       ,'''num_kv_heads'''       ,config.num_attention_heads  )
              UpperCAmelCase_      :							Optional[int]       =      getattr(_SCREAMING_SNAKE_CASE       ,'''d_model'''       ,config.hidden_size  )
              UpperCAmelCase_      :							Tuple       =      embed_dim // num_attention_heads

              UpperCAmelCase_      :							Optional[int]       =      outputs['''past_key_values''']
              self.assertEqual(len(_SCREAMING_SNAKE_CASE  )       ,_SCREAMING_SNAKE_CASE  )

              UpperCAmelCase_      :							Tuple       =      inputs['''input_ids'''].shape
              for i in range(_SCREAMING_SNAKE_CASE  ):
                   if config.new_decoder_architecture:
                        UpperCAmelCase_      :							int       =      config.num_attention_heads
                   elif config.multi_query:
                        UpperCAmelCase_      :							Optional[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   __a(					unittest.TestCase       ):






    """simple docstring"""





    @slow
    def 							a__				(				self  )			->		str:
         UpperCAmelCase_      :							Optional[int]       =      AutoTokenizer.from_pretrained('''Rocketknight1/falcon-rw-1b'''  )
         UpperCAmelCase_      :							Tuple       =      FalconForCausalLM.from_pretrained('''Rocketknight1/falcon-rw-1b'''  )
         model.eval()
         model.to(_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Union[str, Any]       =      tokenizer('''My favorite food is'''       ,return_tensors='''pt'''  ).to(_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Any       =      (
             '''My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.'''
         )

         UpperCAmelCase_      :							Optional[int]       =      model.generate(**_SCREAMING_SNAKE_CASE       ,do_sample=_SCREAMING_SNAKE_CASE       ,max_new_tokens=19  )
         UpperCAmelCase_      :							Union[str, Any]       =      tokenizer.batch_decode(_SCREAMING_SNAKE_CASE  )[0]

         self.assertEqual(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )





    @slow
    def 							a__				(				self  )			->		str:
         # 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"]:
              UpperCAmelCase_      :							List[Any]       =      AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  )
              UpperCAmelCase_      :							Any       =      FalconForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE  )
              model.eval()
              model.to(_SCREAMING_SNAKE_CASE  )
              UpperCAmelCase_      :							Any       =      tokenizer('''My favorite food is'''       ,return_tensors='''pt'''  ).to(_SCREAMING_SNAKE_CASE  )

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





    @slow
    def 							a__				(				self  )			->		List[str]:
         # 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",
              ]:
                   UpperCAmelCase_      :							List[Any]       =      AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  )
                   UpperCAmelCase_      :							Optional[Any]       =      FalconForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE  )
                   model.eval()
                   model.to(device=_SCREAMING_SNAKE_CASE  )
                   UpperCAmelCase_      :							Optional[Any]       =      tokenizer('''My favorite food is'''       ,return_tensors='''pt'''  ).to(_SCREAMING_SNAKE_CASE  )

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





import os
import sys
import warnings
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union

import numpy as np
import pyarrow as pa

from .. import config
from ..download.streaming_download_manager import xopen
from ..table import array_cast
from ..utils.file_utils import is_local_path
from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict


if TYPE_CHECKING:
     import PIL.Image

     from .features import FeatureType


__a          =			None
__a          =			'<' if sys.byteorder == 'little' else '>'
# Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image
__a          =			[
    np.dtype('|b1'),
    np.dtype('|u1'),
    np.dtype('<u2'),
    np.dtype('>u2'),
    np.dtype('<i2'),
    np.dtype('>i2'),
    np.dtype('<u4'),
    np.dtype('>u4'),
    np.dtype('<i4'),
    np.dtype('>i4'),
    np.dtype('<f4'),
    np.dtype('>f4'),
    np.dtype('<f8'),
    np.dtype('>f8'),
]

@dataclass
class   __a:






    """simple docstring"""





    lowerCAmelCase        =				True
    lowerCAmelCase        =				None
    # Automatically constructed
    lowerCAmelCase        =				"PIL.Image.Image"
    lowerCAmelCase        =				pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()}       )
    lowerCAmelCase        =				field(default='''Image'''    ,						init=_a    ,						repr=_a       )





    def __call__(				self  )			->		Optional[Any]:
         return self.pa_type





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE  )			->		dict:
         if config.PIL_AVAILABLE:
              import PIL.Image
         else:
              raise ImportError('''To support encoding images, please install \'Pillow\'.'''  )

         if isinstance(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
              UpperCAmelCase_      :							Optional[int]       =      np.array(_SCREAMING_SNAKE_CASE  )

         if isinstance(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
              return {"path": value, "bytes": None}
         elif isinstance(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
              return {"path": None, "bytes": value}
         elif isinstance(_SCREAMING_SNAKE_CASE       ,np.ndarray  ):
              # convert the image array to PNG/TIFF bytes
              return encode_np_array(_SCREAMING_SNAKE_CASE  )
         elif isinstance(_SCREAMING_SNAKE_CASE       ,PIL.Image.Image  ):
              # convert the PIL image to bytes (default format is PNG/TIFF)
              return encode_pil_image(_SCREAMING_SNAKE_CASE  )
         elif value.get('''path'''  ) is not None and os.path.isfile(value['''path''']  ):
              # we set "bytes": None to not duplicate the data if they're already available locally
              return {"bytes": None, "path": value.get('''path'''  )}
         elif value.get('''bytes'''  ) is not None or value.get('''path'''  ) is not None:
              # store the image bytes, and path is used to infer the image format using the file extension
              return {"bytes": value.get('''bytes'''  ), "path": value.get('''path'''  )}
         else:
              raise ValueError(
                  f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.'''  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE=None  )			->		"PIL.Image.Image":
         if not self.decode:
              raise RuntimeError('''Decoding is disabled for this feature. Please use Image(decode=True) instead.'''  )

         if config.PIL_AVAILABLE:
              import PIL.Image
         else:
              raise ImportError('''To support decoding images, please install \'Pillow\'.'''  )

         if token_per_repo_id is None:
              UpperCAmelCase_      :							str       =      {}

         UpperCAmelCase_,   UpperCAmelCase_      :							List[str]       =      value['''path'''], value['''bytes''']
         if bytes_ is None:
              if path is None:
                   raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.'''  )
              else:
                   if is_local_path(_SCREAMING_SNAKE_CASE  ):
                        UpperCAmelCase_      :							int       =      PIL.Image.open(_SCREAMING_SNAKE_CASE  )
                   else:
                        UpperCAmelCase_      :							int       =      path.split('''::'''  )[-1]
                        try:
                             UpperCAmelCase_      :							str       =      string_to_dict(_SCREAMING_SNAKE_CASE       ,config.HUB_DATASETS_URL  )['''repo_id''']
                             UpperCAmelCase_      :							Optional[Any]       =      token_per_repo_id.get(_SCREAMING_SNAKE_CASE  )
                        except ValueError:
                             UpperCAmelCase_      :							Any       =      None
                        with xopen(_SCREAMING_SNAKE_CASE       ,'''rb'''       ,use_auth_token=_SCREAMING_SNAKE_CASE  ) as f:
                             UpperCAmelCase_      :							List[str]       =      BytesIO(f.read()  )
                        UpperCAmelCase_      :							Optional[int]       =      PIL.Image.open(bytes_  )
         else:
              UpperCAmelCase_      :							Dict       =      PIL.Image.open(BytesIO(bytes_  )  )
         image.load()  # to avoid "Too many open files" errors
         return image





    def 							a__				(				self  )			->		Union["FeatureType", Dict[str, "FeatureType"]]:
         from .features import Value

         return (
             self
             if self.decode
             else {
                 "bytes": Value('''binary'''  ),
                 "path": Value('''string'''  ),
             }
         )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE  )			->		pa.StructArray:
         if pa.types.is_string(storage.type  ):
              UpperCAmelCase_      :							Union[str, Any]       =      pa.array([None] * len(_SCREAMING_SNAKE_CASE  )       ,type=pa.binary()  )
              UpperCAmelCase_      :							int       =      pa.StructArray.from_arrays([bytes_array, storage]       ,['''bytes''', '''path''']       ,mask=storage.is_null()  )
         elif pa.types.is_binary(storage.type  ):
              UpperCAmelCase_      :							Tuple       =      pa.array([None] * len(_SCREAMING_SNAKE_CASE  )       ,type=pa.string()  )
              UpperCAmelCase_      :							int       =      pa.StructArray.from_arrays([storage, path_array]       ,['''bytes''', '''path''']       ,mask=storage.is_null()  )
         elif pa.types.is_struct(storage.type  ):
              if storage.type.get_field_index('''bytes'''  ) >= 0:
                   UpperCAmelCase_      :							str       =      storage.field('''bytes'''  )
              else:
                   UpperCAmelCase_      :							Union[str, Any]       =      pa.array([None] * len(_SCREAMING_SNAKE_CASE  )       ,type=pa.binary()  )
              if storage.type.get_field_index('''path'''  ) >= 0:
                   UpperCAmelCase_      :							List[str]       =      storage.field('''path'''  )
              else:
                   UpperCAmelCase_      :							List[Any]       =      pa.array([None] * len(_SCREAMING_SNAKE_CASE  )       ,type=pa.string()  )
              UpperCAmelCase_      :							Any       =      pa.StructArray.from_arrays([bytes_array, path_array]       ,['''bytes''', '''path''']       ,mask=storage.is_null()  )
         elif pa.types.is_list(storage.type  ):
              UpperCAmelCase_      :							Optional[Any]       =      pa.array(
                  [encode_np_array(np.array(_SCREAMING_SNAKE_CASE  )  )['''bytes'''] if arr is not None else None for arr in storage.to_pylist()]       ,type=pa.binary()       ,)
              UpperCAmelCase_      :							Any       =      pa.array([None] * len(_SCREAMING_SNAKE_CASE  )       ,type=pa.string()  )
              UpperCAmelCase_      :							Any       =      pa.StructArray.from_arrays(
                  [bytes_array, path_array]       ,['''bytes''', '''path''']       ,mask=bytes_array.is_null()  )
         return array_cast(_SCREAMING_SNAKE_CASE       ,self.pa_type  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE  )			->		pa.StructArray:

         @no_op_if_value_is_null
         def path_to_bytes(_SCREAMING_SNAKE_CASE  ):
              with xopen(_SCREAMING_SNAKE_CASE       ,'''rb'''  ) as f:
                   UpperCAmelCase_      :							List[Any]       =      f.read()
              return bytes_

         UpperCAmelCase_      :							Dict       =      pa.array(
             [
                 (path_to_bytes(x['''path''']  ) if x['''bytes'''] is None else x['''bytes''']) if x is not None else None
                 for x in storage.to_pylist()
             ]       ,type=pa.binary()       ,)
         UpperCAmelCase_      :							Union[str, Any]       =      pa.array(
             [os.path.basename(_SCREAMING_SNAKE_CASE  ) if path is not None else None for path in storage.field('''path'''  ).to_pylist()]       ,type=pa.string()       ,)
         UpperCAmelCase_      :							Tuple       =      pa.StructArray.from_arrays([bytes_array, path_array]       ,['''bytes''', '''path''']       ,mask=bytes_array.is_null()  )
         return array_cast(_SCREAMING_SNAKE_CASE       ,self.pa_type  )







def lowerCamelCase__       (      ):

     '''simple docstring'''


     if config.PIL_AVAILABLE:
          import PIL.Image
     else:
          raise ImportError('''To support encoding images, please install \'Pillow\'.'''				)

     global _IMAGE_COMPRESSION_FORMATS
     if _IMAGE_COMPRESSION_FORMATS is None:
          PIL.Image.init()
          UpperCAmelCase_      :							Optional[Any]       =      list(set(PIL.Image.OPEN.keys()				) & set(PIL.Image.SAVE.keys()				)				)
     return _IMAGE_COMPRESSION_FORMATS







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							Optional[int]       =      BytesIO()
     if image.format in list_image_compression_formats():
          UpperCAmelCase_      :							List[str]       =      image.format
     else:
          UpperCAmelCase_      :							int       =      '''PNG''' if image.mode in ['''1''', '''L''', '''LA''', '''RGB''', '''RGBA'''] else '''TIFF'''
     image.save(_lowercase			,						format=_lowercase				)
     return buffer.getvalue()







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     if hasattr(_lowercase			,						'''filename'''				) and image.filename != "":
          return {"path": image.filename, "bytes": None}
     else:
          return {"path": None, "bytes": image_to_bytes(_lowercase				)}







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     if config.PIL_AVAILABLE:
          import PIL.Image
     else:
          raise ImportError('''To support encoding images, please install \'Pillow\'.'''				)

     UpperCAmelCase_      :							int       =      array.dtype
     UpperCAmelCase_      :							Optional[Any]       =      dtype.byteorder if dtype.byteorder != '''=''' else _NATIVE_BYTEORDER
     UpperCAmelCase_      :							str       =      dtype.kind
     UpperCAmelCase_      :							int       =      dtype.itemsize

     UpperCAmelCase_      :							Optional[int]       =      None

     # Multi-channel array case (only np.dtype("|u1") is allowed)
     if array.shape[2:]:
          UpperCAmelCase_      :							str       =      np.dtype('''|u1'''				)
          if dtype_kind not in ["u", "i"]:
               raise TypeError(
                   f'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.'''				)
          if dtype is not dest_dtype:
               warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\''''				)
    # Exact match
     elif dtype in _VALID_IMAGE_ARRAY_DTPYES:
          UpperCAmelCase_      :							Dict       =      dtype
     else:  # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually)
          while dtype_itemsize >= 1:
               UpperCAmelCase_      :							Optional[int]       =      dtype_byteorder + dtype_kind + str(_lowercase				)
               UpperCAmelCase_      :							Dict       =      np.dtype(_lowercase				)
               if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES:
                    warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\''''				)
                    break
               else:
                    dtype_itemsize //= 2

     if dest_dtype is None:
          raise TypeError(
              f'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}'''				)
     UpperCAmelCase_      :							Dict       =      PIL.Image.fromarray(array.astype(_lowercase				)				)
     return {"path": None, "bytes": image_to_bytes(_lowercase				)}







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     if config.PIL_AVAILABLE:
          import PIL.Image
     else:
          raise ImportError('''To support encoding images, please install \'Pillow\'.'''				)

     if objs:
          UpperCAmelCase_,   UpperCAmelCase_      :							List[Any]       =      first_non_null_value(_lowercase				)
          if isinstance(_lowercase			,						_lowercase				):
               return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs]
          if isinstance(_lowercase			,						np.ndarray				):
               UpperCAmelCase_      :							List[str]       =      no_op_if_value_is_null(_lowercase				)
               return [obj_to_image_dict_func(_lowercase				) for obj in objs]
          elif isinstance(_lowercase			,						PIL.Image.Image				):
               UpperCAmelCase_      :							Union[str, Any]       =      no_op_if_value_is_null(_lowercase				)
               return [obj_to_image_dict_func(_lowercase				) for obj in objs]
          else:
               return objs
     else:
          return objs