






from __future__ import annotations

import os
import tempfile
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import is_tensorflow_text_available, is_tf_available
from transformers.testing_utils import require_tensorflow_text, require_tf, slow

from ..test_modeling_tf_common import floats_tensor
from .test_framework_agnostic import GenerationIntegrationTestsMixin


if is_tf_available():
     import tensorflow as tf

     from transformers import (
         AutoTokenizer,
         TFAutoModelForCausalLM,
         TFAutoModelForSeqaSeqLM,
         TFAutoModelForSpeechSeqaSeq,
         TFAutoModelForVisionaSeq,
         TFBartForConditionalGeneration,
         TFLogitsProcessorList,
         TFMinLengthLogitsProcessor,
         tf_top_k_top_p_filtering,
     )

if is_tensorflow_text_available():
     import tensorflow_text as text






@require_tf
class 						lowercase_   (      unittest.TestCase  ):






      '''simple docstring'''




      def  __lowerCAmelCase   ( self :		List[Any]    )       ->Tuple:




       """simple docstring"""


       a						    = tf.convert_to_tensor(
           [
               [
                   8.2220991,  # 3rd highest value; idx. 0
                   -0.5620044,
                   5.23229752,
                   4.0386393,
                   -6.8798378,
                   -0.54785802,
                   -3.2012153,
                   2.92777176,
                   1.88171953,
                   7.35341276,  # 5th highest value; idx. 9
                   8.43207833,  # 2nd highest value; idx. 10
                   -9.85711836,
                   -5.96209236,
                   -1.13039161,
                   -7.1115294,
                   -0.8369633,
                   -5.3186408,
                   7.06427407,
                   0.81369344,
                   -0.82023817,
                   -5.9179796,
                   0.58813443,
                   -6.99778438,
                   4.71551189,
                   -0.18771637,
                   7.44020759,  # 4th highest value; idx. 25
                   9.38450987,  # 1st highest value; idx. 26
                   2.12662941,
                   -9.32562038,
                   2.35652522,
               ],  # cummulative prob of 5 highest values <= 0.6
               [
                   0.58425518,
                   4.53139238,
                   -5.57510464,
                   -6.28030699,
                   -7.19529503,
                   -4.02122551,
                   1.39337037,
                   -6.06707057,
                   1.59480517,
                   -9.643119,
                   0.03907799,
                   0.67231762,
                   -8.88206726,
                   6.27115922,  # 4th highest value; idx. 13
                   2.28520723,
                   4.82767506,
                   4.30421368,
                   8.8275313,  # 2nd highest value; idx. 17
                   5.44029958,  # 5th highest value; idx. 18
                   -4.4735794,
                   7.38579536,  # 3rd highest value; idx. 20
                   -2.91051663,
                   2.61946077,
                   -2.5674762,
                   -9.48959302,
                   -4.02922645,
                   -1.35416918,
                   9.67702323,  # 1st highest value; idx. 27
                   -5.89478553,
                   1.85370467,
               ],  # cummulative prob of 5 highest values <= 0.6
           ]					,   dtype=tf.floataa					,   )

       a						    = tf.convert_to_tensor(
           [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]]					,   dtype=tf.intaa					,   )  # expected non filtered idx as noted above

       a						    = tf.convert_to_tensor(
           [8.222099, 7.3534126, 8.432078, 7.4402075, 9.38451, 6.271159, 8.827531, 5.4402995, 7.3857956, 9.677023]					,   dtype=tf.floataa					,   )  # expected non filtered values as noted above

       a						    = tf_top_k_top_p_filtering(__UpperCAmelCase					,   top_k=10					,   top_p=0.6					,   min_tokens_to_keep=4    )

       a						    = output[output != -float('''inf'''    )]
       a						    = tf.cast(
           tf.where(tf.not_equal(__UpperCAmelCase					,   tf.constant(-float('''inf'''    )					,   dtype=tf.floataa    )    )    )					,   dtype=tf.intaa					,   )

       tf.debugging.assert_near(__UpperCAmelCase					,   __UpperCAmelCase					,   rtol=1e-1_2    )
       tf.debugging.assert_equal(__UpperCAmelCase					,   __UpperCAmelCase    )






@require_tf
class 						lowercase_   (      unittest.TestCase					,    lowercase  ):






      '''simple docstring'''




      if is_tf_available():
            __snake_case	    =    {
                '''AutoModelForCausalLM''': TFAutoModelForCausalLM,
                '''AutoModelForSpeechSeq2Seq''': TFAutoModelForSpeechSeqaSeq,
                '''AutoModelForSeq2SeqLM''': TFAutoModelForSeqaSeqLM,
                '''AutoModelForVision2Seq''': TFAutoModelForVisionaSeq,
                '''LogitsProcessorList''': TFLogitsProcessorList,
                '''MinLengthLogitsProcessor''': TFMinLengthLogitsProcessor,
                '''create_tensor_fn''': tf.convert_to_tensor,
                '''floats_tensor''': floats_tensor,
                '''return_tensors''': '''tf''',
            }







      @slow
      def  __lowerCAmelCase   ( self :		str    )       ->Union[str, Any]:




       """simple docstring"""


       a						    = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''    )
       a						    = 2
       a						    = 2






       class 						lowercase_   (      tf.Module  ):






             '''simple docstring'''




             def __init__( self :		Dict					,   __UpperCAmelCase :		Dict    )       ->List[Any]:




              """simple docstring"""


              super(__UpperCAmelCase					,   self    ).__init__()
              a						    = model







             @tf.function(
                 input_signature=(
                     tf.TensorSpec((None, input_length)					,   tf.intaa					,   name='''input_ids'''    ),
                     tf.TensorSpec((None, input_length)					,   tf.intaa					,   name='''attention_mask'''    ),
                 )					,   jit_compile=__UpperCAmelCase					,   )
             def  __lowerCAmelCase   ( self :		Dict					,   __UpperCAmelCase :		Optional[int]					,   __UpperCAmelCase :		Optional[int]    )       ->Any:




              """simple docstring"""


              a						    = self.model.generate(
                  input_ids=__UpperCAmelCase					,   attention_mask=__UpperCAmelCase					,   max_new_tokens=__UpperCAmelCase					,   return_dict_in_generate=__UpperCAmelCase					,   )
              return {"sequences": outputs["sequences"]}
       a						    = [[2, 0], [102, 103]]
       a						    = [[1, 0], [1, 1]]
       a						    = DummyModel(model=__UpperCAmelCase    )
       with tempfile.TemporaryDirectory() as tmp_dir:
        tf.saved_model.save(__UpperCAmelCase					,   __UpperCAmelCase					,   signatures={'''serving_default''': dummy_model.serving}    )
        a						    = tf.saved_model.load(__UpperCAmelCase    ).signatures['''serving_default''']
        for batch_size in range(1					,   len(__UpperCAmelCase    ) + 1    ):
         a						    = {
             '''input_ids''': tf.constant(dummy_input_ids[:batch_size]    ),
             '''attention_mask''': tf.constant(dummy_attention_masks[:batch_size]    ),
         }
         a						    = serving_func(**__UpperCAmelCase    )['''sequences''']
         a						    = test_model.generate(**__UpperCAmelCase					,   max_new_tokens=__UpperCAmelCase    )
         tf.debugging.assert_equal(__UpperCAmelCase					,   __UpperCAmelCase    )







      @slow
      def  __lowerCAmelCase   ( self :		List[Any]    )       ->List[str]:




       """simple docstring"""


       a						    = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''    )
       a						    = 1
       a						    = 2






       class 						lowercase_   (      tf.Module  ):






             '''simple docstring'''




             def __init__( self :		int					,   __UpperCAmelCase :		str    )       ->Optional[int]:




              """simple docstring"""


              super(__UpperCAmelCase					,   self    ).__init__()
              a						    = model







             @tf.function(
                 input_signature=(
                     tf.TensorSpec((batch_size, None)					,   tf.intaa					,   name='''input_ids'''    ),
                     tf.TensorSpec((batch_size, None)					,   tf.intaa					,   name='''attention_mask'''    ),
                 )					,   jit_compile=__UpperCAmelCase					,   )
             def  __lowerCAmelCase   ( self :		int					,   __UpperCAmelCase :		Optional[Any]					,   __UpperCAmelCase :		str    )       ->List[Any]:




              """simple docstring"""


              a						    = self.model.generate(
                  input_ids=__UpperCAmelCase					,   attention_mask=__UpperCAmelCase					,   max_new_tokens=__UpperCAmelCase					,   return_dict_in_generate=__UpperCAmelCase					,   )
              return {"sequences": outputs["sequences"]}
       a						    = [[2], [102, 103]]
       a						    = [[1], [1, 1]]
       a						    = DummyModel(model=__UpperCAmelCase    )
       with tempfile.TemporaryDirectory() as tmp_dir:
        tf.saved_model.save(__UpperCAmelCase					,   __UpperCAmelCase					,   signatures={'''serving_default''': dummy_model.serving}    )
        a						    = tf.saved_model.load(__UpperCAmelCase    ).signatures['''serving_default''']
        for input_row in range(len(__UpperCAmelCase    )    ):
         a						    = {
             '''input_ids''': tf.constant([dummy_input_ids[input_row]]    ),
             '''attention_mask''': tf.constant([dummy_attention_masks[input_row]]    ),
         }
         a						    = serving_func(**__UpperCAmelCase    )['''sequences''']
         a						    = test_model.generate(**__UpperCAmelCase					,   max_new_tokens=__UpperCAmelCase    )
         tf.debugging.assert_equal(__UpperCAmelCase					,   __UpperCAmelCase    )







      @slow
      @require_tensorflow_text
      def  __lowerCAmelCase   ( self :		Union[str, Any]    )       ->Optional[Any]:




       """simple docstring"""


       with tempfile.TemporaryDirectory() as tmp_dir:
        # file needed to load the TF tokenizer
        hf_hub_download(repo_id='''google/flan-t5-small'''					,   filename='''spiece.model'''					,   local_dir=__UpperCAmelCase    )






        class 						lowercase_   (      tf.keras.layers.Layer  ):






              '''simple docstring'''




              def __init__( self :		str    )       ->List[str]:




               """simple docstring"""


               super().__init__()
               a						    = text.SentencepieceTokenizer(
                   model=tf.io.gfile.GFile(os.path.join(__UpperCAmelCase					,   '''spiece.model'''    )					,   '''rb'''    ).read()    )
               a						    = TFAutoModelForSeqaSeqLM.from_pretrained('''hf-internal-testing/tiny-random-t5'''    )







              def  __lowerCAmelCase   ( self :		Union[str, Any]					,   __UpperCAmelCase :		Union[str, Any]					,   *__UpperCAmelCase :		int					,   **__UpperCAmelCase :		List[Any]    )       ->Tuple:




               """simple docstring"""


               a						    = self.tokenizer.tokenize(__UpperCAmelCase    )
               a    ,	a						    = text.pad_model_inputs(
                   __UpperCAmelCase					,   max_seq_length=64					,   pad_value=self.model.config.pad_token_id    )
               a						    = self.model.generate(input_ids=__UpperCAmelCase					,   attention_mask=__UpperCAmelCase    )
               return self.tokenizer.detokenize(__UpperCAmelCase    )
        a						    = CompleteSentenceTransformer()
        a						    = tf.keras.layers.Input(shape=(1,)					,   dtype=tf.string					,   name='''inputs'''    )
        a						    = complete_model(__UpperCAmelCase    )
        a						    = tf.keras.Model(__UpperCAmelCase					,   __UpperCAmelCase    )
        keras_model.save(__UpperCAmelCase    )







      def  __lowerCAmelCase   ( self :		str    )       ->Any:




       """simple docstring"""


       a						    = {
           '''do_sample''': True,
           '''num_beams''': 1,
           '''top_p''': 0.7,
           '''top_k''': 10,
           '''temperature''': 0.7,
       }
       a						    = 14

       a						    = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''    )
       a						    = '''Hello, my dog is cute and'''
       a						    = tokenizer(__UpperCAmelCase					,   return_tensors='''tf'''    )
       a						    = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''    )

       a						    = 638
       # forces the generation to happen on CPU, to avoid GPU-related quirks
       with tf.device(''':/CPU:0'''    ):
        tf.random.set_seed(0    )
        a						    = model.generate(**__UpperCAmelCase					,   eos_token_id=__UpperCAmelCase					,   **__UpperCAmelCase    )
       self.assertTrue(expectation == len(generated_tokens[0]    )    )

       a						    = [638, 198]
       with tf.device(''':/CPU:0'''    ):
        tf.random.set_seed(0    )
        a						    = model.generate(**__UpperCAmelCase					,   eos_token_id=__UpperCAmelCase					,   **__UpperCAmelCase    )
       self.assertTrue(expectation == len(generated_tokens[0]    )    )







      def  __lowerCAmelCase   ( self :		List[Any]    )       ->int:




       """simple docstring"""


       a						    = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bart'''    )
       a						    = '''Hugging Face is a technology company based in New York and Paris.'''
       a						    = bart_tokenizer(__UpperCAmelCase					,   return_tensors='''tf'''    ).input_ids
       a						    = TFBartForConditionalGeneration.from_pretrained('''hf-internal-testing/tiny-random-bart'''    )
       a						    = bart_model.generate(__UpperCAmelCase    ).numpy()






       class 						lowercase_   (      lowercase  ):






             '''simple docstring'''




             def  __lowerCAmelCase   ( self :		Dict					,   __UpperCAmelCase :		Optional[int]					,   __UpperCAmelCase :		List[str]=None					,   **__UpperCAmelCase :		Dict    )       ->List[Any]:




              """simple docstring"""


              return super().call(__UpperCAmelCase					,   **__UpperCAmelCase    )
       a						    = FakeBart.from_pretrained('''hf-internal-testing/tiny-random-bart'''    )
       a						    = bart_model.generate(__UpperCAmelCase					,   foo='''bar'''    ).numpy()
       self.assertTrue(np.array_equal(__UpperCAmelCase					,   __UpperCAmelCase    )    )






       class 						lowercase_   (      bart_model.model.encoder.__class__  ):






             '''simple docstring'''




             def  __lowerCAmelCase   ( self :		List[str]					,   __UpperCAmelCase :		Optional[int]					,   **__UpperCAmelCase :		int    )       ->int:




              """simple docstring"""


              return super().call(__UpperCAmelCase					,   **__UpperCAmelCase    )
       a						    = FakeEncoder(bart_model.config					,   bart_model.model.shared    )
       a						    = fake_encoder

       # Normal generation still works (the output will be different because the encoder weights are different)
       a						    = bart_model.generate(__UpperCAmelCase    ).numpy()
       with self.assertRaises(__UpperCAmelCase    ):
        # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo"
        bart_model.generate(__UpperCAmelCase					,   foo='''bar'''    )










import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


UpperCAmelCase__							  =						logging.getLogger(__name__)






@dataclass
class 						lowercase_   :






      '''simple docstring'''




      __snake_case	    =    42
      __snake_case	    =    42
      __snake_case	    =    42






@dataclass
class 						lowercase_   :






      '''simple docstring'''




      __snake_case	    =    42
      __snake_case	    =    42
      __snake_case	    =    None
      __snake_case	    =    None






class 						lowercase_   (      lowercase  ):






      '''simple docstring'''




      __snake_case	    =    '''train'''
      __snake_case	    =    '''dev'''
      __snake_case	    =    '''test'''






class 						lowercase_   :






      '''simple docstring'''




      @staticmethod
      def  __lowerCAmelCase   ( __UpperCAmelCase :		int					,   __UpperCAmelCase :		Union[Split, str]    )       ->List[InputExample]:




       """simple docstring"""


       raise NotImplementedError







      @staticmethod
      def  __lowerCAmelCase   ( __UpperCAmelCase :		str    )       ->List[str]:




       """simple docstring"""


       raise NotImplementedError







      @staticmethod
      def  __lowerCAmelCase   ( __UpperCAmelCase :		List[InputExample]					,   __UpperCAmelCase :		List[str]					,   __UpperCAmelCase :		int					,   __UpperCAmelCase :		PreTrainedTokenizer					,   __UpperCAmelCase :		Tuple=False					,   __UpperCAmelCase :		str="[CLS]"					,   __UpperCAmelCase :		str=1					,   __UpperCAmelCase :		List[str]="[SEP]"					,   __UpperCAmelCase :		Union[str, Any]=False					,   __UpperCAmelCase :		Tuple=False					,   __UpperCAmelCase :		List[str]=0					,   __UpperCAmelCase :		int=0					,   __UpperCAmelCase :		Tuple=-100					,   __UpperCAmelCase :		Optional[int]=0					,   __UpperCAmelCase :		Any=True					,   )       ->List[InputFeatures]:




       """simple docstring"""


       a						    = {label: i for i, label in enumerate(__UpperCAmelCase    )}

       a						    = []
       for ex_index, example in enumerate(__UpperCAmelCase    ):
        if ex_index % 10_000 == 0:
         logger.info('''Writing example %d of %d'''					,   __UpperCAmelCase					,   len(__UpperCAmelCase    )    )

        a						    = []
        a						    = []
        for word, label in zip(example.words					,   example.labels    ):
         a						    = tokenizer.tokenize(__UpperCAmelCase    )

         # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
         if len(__UpperCAmelCase    ) > 0:
          tokens.extend(__UpperCAmelCase    )
          # Use the real label id for the first token of the word, and padding ids for the remaining tokens
          label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__UpperCAmelCase    ) - 1)    )

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
        a						    = tokenizer.num_special_tokens_to_add()
        if len(__UpperCAmelCase    ) > max_seq_length - special_tokens_count:
         a						    = tokens[: (max_seq_length - special_tokens_count)]
         a						    = label_ids[: (max_seq_length - special_tokens_count)]

        # The convention in BERT is:
        # (a) For sequence pairs:
        #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
        #  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
        # (b) For single sequences:
        #  tokens:   [CLS] the dog is hairy . [SEP]
        #  type_ids:   0   0   0   0  0     0   0
        #
        # Where "type_ids" are used to indicate whether this is the first
        # sequence or the second sequence. The embedding vectors for `type=0` and
        # `type=1` were learned during pre-training and are added to the wordpiece
        # embedding vector (and position vector). This is not *strictly* necessary
        # since the [SEP] token unambiguously separates the sequences, but it makes
        # it easier for the model to learn the concept of sequences.
        #
        # For classification tasks, the first vector (corresponding to [CLS]) is
        # used as the "sentence vector". Note that this only makes sense because
        # the entire model is fine-tuned.
        tokens += [sep_token]
        label_ids += [pad_token_label_id]
        if sep_token_extra:
         # roberta uses an extra separator b/w pairs of sentences
         tokens += [sep_token]
         label_ids += [pad_token_label_id]
        a						    = [sequence_a_segment_id] * len(__UpperCAmelCase    )

        if cls_token_at_end:
         tokens += [cls_token]
         label_ids += [pad_token_label_id]
         segment_ids += [cls_token_segment_id]
        else:
         a						    = [cls_token] + tokens
         a						    = [pad_token_label_id] + label_ids
         a						    = [cls_token_segment_id] + segment_ids

        a						    = tokenizer.convert_tokens_to_ids(__UpperCAmelCase    )

        # The mask has 1 for real tokens and 0 for padding tokens. Only real
        # tokens are attended to.
        a						    = [1 if mask_padding_with_zero else 0] * len(__UpperCAmelCase    )

        # Zero-pad up to the sequence length.
        a						    = max_seq_length - len(__UpperCAmelCase    )
        if pad_on_left:
         a						    = ([pad_token] * padding_length) + input_ids
         a						    = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
         a						    = ([pad_token_segment_id] * padding_length) + segment_ids
         a						    = ([pad_token_label_id] * padding_length) + label_ids
        else:
         input_ids += [pad_token] * padding_length
         input_mask += [0 if mask_padding_with_zero else 1] * padding_length
         segment_ids += [pad_token_segment_id] * padding_length
         label_ids += [pad_token_label_id] * padding_length

        assert len(__UpperCAmelCase    ) == max_seq_length
        assert len(__UpperCAmelCase    ) == max_seq_length
        assert len(__UpperCAmelCase    ) == max_seq_length
        assert len(__UpperCAmelCase    ) == max_seq_length

        if ex_index < 5:
         logger.info('''*** Example ***'''    )
         logger.info('''guid: %s'''					,   example.guid    )
         logger.info('''tokens: %s'''					,   ''' '''.join([str(__UpperCAmelCase    ) for x in tokens]    )    )
         logger.info('''input_ids: %s'''					,   ''' '''.join([str(__UpperCAmelCase    ) for x in input_ids]    )    )
         logger.info('''input_mask: %s'''					,   ''' '''.join([str(__UpperCAmelCase    ) for x in input_mask]    )    )
         logger.info('''segment_ids: %s'''					,   ''' '''.join([str(__UpperCAmelCase    ) for x in segment_ids]    )    )
         logger.info('''label_ids: %s'''					,   ''' '''.join([str(__UpperCAmelCase    ) for x in label_ids]    )    )

        if "token_type_ids" not in tokenizer.model_input_names:
         a						    = None

        features.append(
            InputFeatures(
                input_ids=__UpperCAmelCase					,   attention_mask=__UpperCAmelCase					,   token_type_ids=__UpperCAmelCase					,   label_ids=__UpperCAmelCase    )    )
       return features


if is_torch_available():
     import torch
     from torch import nn
     from torch.utils.data import Dataset






     class 						lowercase_   (      lowercase  ):






           '''simple docstring'''




           __snake_case	    =    42
           __snake_case	    =    nn.CrossEntropyLoss().ignore_index







           def __init__( self :		str					,   __UpperCAmelCase :		TokenClassificationTask					,   __UpperCAmelCase :		str					,   __UpperCAmelCase :		PreTrainedTokenizer					,   __UpperCAmelCase :		List[str]					,   __UpperCAmelCase :		str					,   __UpperCAmelCase :		Optional[int] = None					,   __UpperCAmelCase :		Any=False					,   __UpperCAmelCase :		Split = Split.train					,   )       ->List[str]:




            """simple docstring"""


            a						    = os.path.join(
                __UpperCAmelCase					,   '''cached_{}_{}_{}'''.format(mode.value					,   tokenizer.__class__.__name__					,   str(__UpperCAmelCase    )    )					,   )

            # Make sure only the first process in distributed training processes the dataset,
            # and the others will use the cache.
            a						    = cached_features_file + '''.lock'''
            with FileLock(__UpperCAmelCase    ):
             if os.path.exists(__UpperCAmelCase    ) and not overwrite_cache:
              logger.info(F"""Loading features from cached file {cached_features_file}"""    )
              a						    = torch.load(__UpperCAmelCase    )
             else:
              logger.info(F"""Creating features from dataset file at {data_dir}"""    )
              a						    = token_classification_task.read_examples_from_file(__UpperCAmelCase					,   __UpperCAmelCase    )
              # TODO clean up all this to leverage built-in features of tokenizers
              a						    = token_classification_task.convert_examples_to_features(
                  __UpperCAmelCase					,   __UpperCAmelCase					,   __UpperCAmelCase					,   __UpperCAmelCase					,   cls_token_at_end=bool(model_type in ['''xlnet''']    )					,   cls_token=tokenizer.cls_token					,   cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0					,   sep_token=tokenizer.sep_token					,   sep_token_extra=__UpperCAmelCase					,   pad_on_left=bool(tokenizer.padding_side == '''left'''    )					,   pad_token=tokenizer.pad_token_id					,   pad_token_segment_id=tokenizer.pad_token_type_id					,   pad_token_label_id=self.pad_token_label_id					,   )
              logger.info(F"""Saving features into cached file {cached_features_file}"""    )
              torch.save(self.features					,   __UpperCAmelCase    )







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




            """simple docstring"""


            return len(self.features    )







           def __getitem__( self :		List[Any]					,   __UpperCAmelCase :		Dict    )       ->InputFeatures:




            """simple docstring"""


            return self.features[i]


if is_tf_available():
     import tensorflow as tf






     class 						lowercase_   :






           '''simple docstring'''




           __snake_case	    =    42
           __snake_case	    =    -1_00







           def __init__( self :		Any					,   __UpperCAmelCase :		TokenClassificationTask					,   __UpperCAmelCase :		str					,   __UpperCAmelCase :		PreTrainedTokenizer					,   __UpperCAmelCase :		List[str]					,   __UpperCAmelCase :		str					,   __UpperCAmelCase :		Optional[int] = None					,   __UpperCAmelCase :		List[Any]=False					,   __UpperCAmelCase :		Split = Split.train					,   )       ->Optional[int]:




            """simple docstring"""


            a						    = token_classification_task.read_examples_from_file(__UpperCAmelCase					,   __UpperCAmelCase    )
            # TODO clean up all this to leverage built-in features of tokenizers
            a						    = token_classification_task.convert_examples_to_features(
                __UpperCAmelCase					,   __UpperCAmelCase					,   __UpperCAmelCase					,   __UpperCAmelCase					,   cls_token_at_end=bool(model_type in ['''xlnet''']    )					,   cls_token=tokenizer.cls_token					,   cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0					,   sep_token=tokenizer.sep_token					,   sep_token_extra=__UpperCAmelCase					,   pad_on_left=bool(tokenizer.padding_side == '''left'''    )					,   pad_token=tokenizer.pad_token_id					,   pad_token_segment_id=tokenizer.pad_token_type_id					,   pad_token_label_id=self.pad_token_label_id					,   )

            def gen():
             for ex in self.features:
              if ex.token_type_ids is None:
               yield (
                   {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
                   ex.label_ids,
               )
              else:
               yield (
                   {
                       "input_ids": ex.input_ids,
                       "attention_mask": ex.attention_mask,
                       "token_type_ids": ex.token_type_ids,
                   },
                   ex.label_ids,
               )

            if "token_type_ids" not in tokenizer.model_input_names:
             a						    = tf.data.Dataset.from_generator(
                 __UpperCAmelCase					,   ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa)					,   (
                     {'''input_ids''': tf.TensorShape([None]    ), '''attention_mask''': tf.TensorShape([None]    )},
                     tf.TensorShape([None]    ),
                 )					,   )
            else:
             a						    = tf.data.Dataset.from_generator(
                 __UpperCAmelCase					,   ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa)					,   (
                     {
                         '''input_ids''': tf.TensorShape([None]    ),
                         '''attention_mask''': tf.TensorShape([None]    ),
                         '''token_type_ids''': tf.TensorShape([None]    ),
                     },
                     tf.TensorShape([None]    ),
                 )					,   )







           def  __lowerCAmelCase   ( self :		str    )       ->Optional[int]:




            """simple docstring"""


            a						    = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features    )    )    )

            return self.dataset







           def __len__( self :		List[str]    )       ->Dict:




            """simple docstring"""


            return len(self.features    )







           def __getitem__( self :		Tuple					,   __UpperCAmelCase :		List[Any]    )       ->InputFeatures:




            """simple docstring"""


            return self.features[i]


