

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

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






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

  def  __lowercase							(	self		:      List[Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Optional[int]        =       ids_tensor([self.batch_size, self.seq_length]       ,self.vocab_size     )

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

   UpperCAmelCase__       :	Dict        =       None

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

   UpperCAmelCase__       :	int        =       self.get_config()

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

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






   '''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  __lowercase							(	self		:      Any       ,A		:      Optional[Any]       ,A		:      Optional[Any]       ,A		:      Union[str, Any]       ,A		:      Union[str, Any]       ,A		:      Optional[Any]       ,A		:      Any       ,A		:      Dict     ):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       FalconModel(config=A     )
   model.to(A     )
   model.eval()
   UpperCAmelCase__       :	int        =       model(A       ,attention_mask=A     )
   UpperCAmelCase__       :	List[str]        =       model(A     )
   self.parent.assertEqual(result.last_hidden_state.shape       ,(self.batch_size, self.seq_length, self.hidden_size)     )

  def  __lowercase							(	self		:      Union[str, Any]       ,A		:      str       ,A		:      str       ,A		:      Optional[int]       ,A		:      List[str]       ,A		:      List[str]       ,A		:      Dict       ,A		:      List[str]       ,A		:      Tuple       ,A		:      List[str]       ,):






   '''simple docstring'''
   UpperCAmelCase__       :	Union[str, Any]        =       True
   UpperCAmelCase__       :	Optional[int]        =       FalconModel(A     )
   model.to(A     )
   model.eval()
   UpperCAmelCase__       :	str        =       model(
       A       ,attention_mask=A       ,encoder_hidden_states=A       ,encoder_attention_mask=A       ,)
   UpperCAmelCase__       :	List[Any]        =       model(
       A       ,attention_mask=A       ,encoder_hidden_states=A       ,)
   UpperCAmelCase__       :	int        =       model(A       ,attention_mask=A     )
   self.parent.assertEqual(result.last_hidden_state.shape       ,(self.batch_size, self.seq_length, self.hidden_size)     )

  def  __lowercase							(	self		:      Dict       ,A		:      Tuple       ,A		:      Dict       ,A		:      Union[str, Any]       ,A		:      Any       ,A		:      Union[str, Any]       ,A		:      Dict       ,A		:      int       ,A		:      Tuple       ,A		:      str       ,):






   '''simple docstring'''
   UpperCAmelCase__       :	List[str]        =       FalconForCausalLM(config=A     )
   model.to(A     )
   model.eval()
   UpperCAmelCase__       :	Tuple        =       model(A       ,attention_mask=A       ,labels=A     )
   self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.seq_length, self.vocab_size)     )

  def  __lowercase							(	self		:      str       ,A		:      Any       ,A		:      Optional[Any]       ,A		:      str       ,A		:      Any       ,A		:      List[str]       ,A		:      Any       ,A		:      Dict       ,A		:      str       ,A		:      Any       ,):






   '''simple docstring'''
   UpperCAmelCase__       :	Optional[Any]        =       True
   UpperCAmelCase__       :	int        =       True
   UpperCAmelCase__       :	List[str]        =       FalconForCausalLM(config=A     )
   model.to(A     )
   model.eval()

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

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

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

   UpperCAmelCase__       :	Dict        =       model(
       A       ,attention_mask=A       ,encoder_hidden_states=A       ,encoder_attention_mask=A       ,output_hidden_states=A       ,)["""hidden_states"""][0]
   UpperCAmelCase__       :	Any        =       model(
       A       ,attention_mask=A       ,encoder_hidden_states=A       ,encoder_attention_mask=A       ,past_key_values=A       ,output_hidden_states=A       ,)["""hidden_states"""][0]

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




  def  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Optional[Any]        =       self.prepare_config_and_inputs()
   (
       (
       UpperCAmelCase__
   ) ,   (
       UpperCAmelCase__
   ) ,   (
       UpperCAmelCase__
   ) ,   (
       UpperCAmelCase__
   ) ,   (
       UpperCAmelCase__
   ) ,   (
       UpperCAmelCase__
   ) ,   (
       UpperCAmelCase__
   ) ,   
   )       :	Tuple        =       config_and_inputs
   UpperCAmelCase__       :	Optional[Any]        =       {"""input_ids""": input_ids, """attention_mask""": input_mask}
   return config, inputs_dict







@require_torch
class   __lowercase      (     __lowerCamelCase						,      __lowerCamelCase						,      __lowerCamelCase						,      unittest.TestCase       ):
  snake_case_												=							(
      (
          FalconModel,
          FalconForCausalLM,
          FalconForSequenceClassification,
          FalconForTokenClassification,
          FalconForQuestionAnswering,
      )
      if is_torch_available()
      else ()
  )
  snake_case_												=							(FalconForCausalLM,) if is_torch_available() else ()
  snake_case_												=							(
      {
          """feature-extraction""": FalconModel,
          """text-classification""": FalconForSequenceClassification,
          """text-generation""": FalconForCausalLM,
          """question-answering""": FalconForQuestionAnswering,
          """token-classification""": FalconForTokenClassification,
          """zero-shot""": FalconForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  snake_case_												=							False
  snake_case_												=							False

  def  __lowercase							(	self		:      Any     ):






   '''simple docstring'''
   UpperCAmelCase__       :	List[str]        =       FalconModelTester(self     )
   UpperCAmelCase__       :	Optional[Any]        =       ConfigTester(self       ,config_class=A       ,hidden_size=37     )

  def  __lowercase							(	self		:      Any     ):






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

  def  __lowercase							(	self		:      Optional[Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Union[str, Any]        =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*A     )

  def  __lowercase							(	self		:      List[str]     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   *UpperCAmelCase__       :	Any        =       self.model_tester.prepare_config_and_inputs()
   for alibi in [True, False]:
    UpperCAmelCase__       :	List[Any]        =       alibi
    self.model_tester.create_and_check_model(A       ,*A     )

  def  __lowercase							(	self		:      str     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__       :	str        =       self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase__       :	Tuple        =       3
   UpperCAmelCase__       :	Dict        =       input_dict["""input_ids"""]
   UpperCAmelCase__       :	Optional[int]        =       input_ids.ne(1     ).to(A     )
   UpperCAmelCase__       :	Tuple        =       ids_tensor([self.model_tester.batch_size]       ,self.model_tester.type_sequence_label_size     )
   UpperCAmelCase__       :	str        =       FalconForSequenceClassification(A     )
   model.to(A     )
   model.eval()
   UpperCAmelCase__       :	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  __lowercase							(	self		:      Dict     ):






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

  def  __lowercase							(	self		:      int     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__       :	Dict        =       self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase__       :	Union[str, Any]        =       input_dict["""input_ids"""]
   UpperCAmelCase__       :	Optional[int]        =       FalconForCausalLM(A     )
   model.to(A     )
   model.eval()
   UpperCAmelCase__       :	Optional[Any]        =       model(A       ,use_cache=A     )
   UpperCAmelCase__       :	Any        =       input_ids.shape[0]
   UpperCAmelCase__       :	Optional[Any]        =       model._convert_to_rw_cache(result.past_key_values     )
   UpperCAmelCase__       :	int        =       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  __lowercase							(	self		:      str     ):






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




  def  __lowercase							(	self		:      Optional[Any]     ):






   '''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:
    UpperCAmelCase__ ,   UpperCAmelCase__       :	Optional[int]        =       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

    UpperCAmelCase__       :	List[Any]        =       model_class(A     ).to(A     )
    if "use_cache" not in inputs:
     UpperCAmelCase__       :	Optional[int]        =       True
    UpperCAmelCase__       :	List[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

    UpperCAmelCase__       :	int        =       (
        getattr(A       ,"""decoder_layers"""       ,A     )
        or getattr(A       ,"""num_decoder_layers"""       ,A     )
        or config.num_hidden_layers
    )
    UpperCAmelCase__       :	Optional[Any]        =       getattr(A       ,"""num_kv_heads"""       ,config.num_attention_heads     )
    UpperCAmelCase__       :	Dict        =       getattr(A       ,"""d_model"""       ,config.hidden_size     )
    UpperCAmelCase__       :	Optional[int]        =       embed_dim // num_attention_heads

    UpperCAmelCase__       :	str        =       outputs["""past_key_values"""]
    self.assertEqual(len(A     )       ,A     )

    UpperCAmelCase__ ,   UpperCAmelCase__       :	List[str]        =       inputs["""input_ids"""].shape
    for i in range(A     ):
     if config.new_decoder_architecture:
      UpperCAmelCase__       :	List[Any]        =       config.num_attention_heads
     elif config.multi_query:
      UpperCAmelCase__       :	Dict        =       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       ):

  @slow
  def  __lowercase							(	self		:      Tuple     ):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b"""     )
   UpperCAmelCase__       :	str        =       FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b"""     )
   model.eval()
   model.to(A     )
   UpperCAmelCase__       :	Optional[int]        =       tokenizer("""My favorite food is"""       ,return_tensors="""pt"""     ).to(A     )

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

   UpperCAmelCase__       :	Any        =       model.generate(**A       ,do_sample=A       ,max_new_tokens=19     )
   UpperCAmelCase__       :	Union[str, Any]        =       tokenizer.batch_decode(A     )[0]

   self.assertEqual(A       ,A     )

  @slow
  def  __lowercase							(	self		:      Optional[int]     ):






   '''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"]:
    UpperCAmelCase__       :	Any        =       AutoTokenizer.from_pretrained(A     )
    UpperCAmelCase__       :	Dict        =       FalconForCausalLM.from_pretrained(A     )
    model.eval()
    model.to(A     )
    UpperCAmelCase__       :	Dict        =       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  __lowercase							(	self		:      str     ):






   '''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",
    ]:
     UpperCAmelCase__       :	List[Any]        =       AutoTokenizer.from_pretrained(A     )
     UpperCAmelCase__       :	str        =       FalconForCausalLM.from_pretrained(A     )
     model.eval()
     model.to(device=A     )
     UpperCAmelCase__       :	Optional[Any]        =       tokenizer("""My favorite food is"""       ,return_tensors="""pt"""     ).to(A     )

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









import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


_SCREAMING_SNAKE_CASE     :					Any      =       logging.get_logger(__name__)


_SCREAMING_SNAKE_CASE     :					str      =       {"vocab_file": "vocab.json", "merges_file": "merges.txt"}

_SCREAMING_SNAKE_CASE     :					Any      =       {
    "vocab_file": {
        "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json",
        "allenai/longformer-large-4096": (
            "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json"
        ),
        "allenai/longformer-large-4096-finetuned-triviaqa": (
            "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json"
        ),
        "allenai/longformer-base-4096-extra.pos.embd.only": (
            "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json"
        ),
        "allenai/longformer-large-4096-extra.pos.embd.only": (
            "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json"
        ),
    },
    "merges_file": {
        "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt",
        "allenai/longformer-large-4096": (
            "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt"
        ),
        "allenai/longformer-large-4096-finetuned-triviaqa": (
            "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt"
        ),
        "allenai/longformer-base-4096-extra.pos.embd.only": (
            "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt"
        ),
        "allenai/longformer-large-4096-extra.pos.embd.only": (
            "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt"
        ),
    },
}

_SCREAMING_SNAKE_CASE     :					List[Any]      =       {
    "allenai/longformer-base-4096": 40_96,
    "allenai/longformer-large-4096": 40_96,
    "allenai/longformer-large-4096-finetuned-triviaqa": 40_96,
    "allenai/longformer-base-4096-extra.pos.embd.only": 40_96,
    "allenai/longformer-large-4096-extra.pos.embd.only": 40_96,
}
@lru_cache()
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
def      UpperCAmelCase__		():



     """simple docstring"""






     snake_case											=							(
         list(range(ord('''!'''							)				,ord('''~'''							) + 1							)							) + list(range(ord('''¡'''							)				,ord('''¬'''							) + 1							)							) + list(range(ord('''®'''							)				,ord('''ÿ'''							) + 1							)							)
     )
     snake_case											=							bs[:]
     snake_case											=							0
     for b in range(2**8							):
          if b not in bs:
               bs.append(UpperCamelCase_							)
               cs.append(2**8 + n							)
               n += 1
     snake_case											=							[chr(UpperCamelCase_							) for n in cs]
     return dict(zip(UpperCamelCase_				,UpperCamelCase_							)							)
def      UpperCAmelCase__		(UpperCamelCase_							):



     """simple docstring"""






     snake_case											=							set()
     snake_case											=							word[0]
     for char in word[1:]:
          pairs.add((prev_char, char)							)
          snake_case											=							char
     return pairs

class     A__   (       snake_case__      ):







    """simple docstring"""

    __magic_name__         =						VOCAB_FILES_NAMES
    __magic_name__         =						PRETRAINED_VOCAB_FILES_MAP
    __magic_name__         =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    __magic_name__         =						['input_ids', 'attention_mask']
    def __init__(			self     ,   __snake_case     ,   __snake_case     ,   __snake_case="replace"     ,   __snake_case="<s>"     ,   __snake_case="</s>"     ,   __snake_case="</s>"     ,   __snake_case="<s>"     ,   __snake_case="<unk>"     ,   __snake_case="<pad>"     ,   __snake_case="<mask>"     ,   __snake_case=False     ,   **__snake_case     ,   ):
         snake_case											=							AddedToken(__snake_case     ,   lstrip=__snake_case     ,   rstrip=__snake_case       ) if isinstance(__snake_case     ,   __snake_case       ) else bos_token
         snake_case											=							AddedToken(__snake_case     ,   lstrip=__snake_case     ,   rstrip=__snake_case       ) if isinstance(__snake_case     ,   __snake_case       ) else eos_token
         snake_case											=							AddedToken(__snake_case     ,   lstrip=__snake_case     ,   rstrip=__snake_case       ) if isinstance(__snake_case     ,   __snake_case       ) else sep_token
         snake_case											=							AddedToken(__snake_case     ,   lstrip=__snake_case     ,   rstrip=__snake_case       ) if isinstance(__snake_case     ,   __snake_case       ) else cls_token
         snake_case											=							AddedToken(__snake_case     ,   lstrip=__snake_case     ,   rstrip=__snake_case       ) if isinstance(__snake_case     ,   __snake_case       ) else unk_token
         snake_case											=							AddedToken(__snake_case     ,   lstrip=__snake_case     ,   rstrip=__snake_case       ) if isinstance(__snake_case     ,   __snake_case       ) else pad_token

         # Mask token behave like a normal word, i.e. include the space before it
         snake_case											=							AddedToken(__snake_case     ,   lstrip=__snake_case     ,   rstrip=__snake_case       ) if isinstance(__snake_case     ,   __snake_case       ) else mask_token

         super().__init__(
             errors=__snake_case     ,   bos_token=__snake_case     ,   eos_token=__snake_case     ,   unk_token=__snake_case     ,   sep_token=__snake_case     ,   cls_token=__snake_case     ,   pad_token=__snake_case     ,   mask_token=__snake_case     ,   add_prefix_space=__snake_case     ,   **__snake_case     ,   )

         with open(__snake_case     ,   encoding='''utf-8'''       ) as vocab_handle:
              snake_case											=							json.load(__snake_case       )
         snake_case											=							{v: k for k, v in self.encoder.items()}
         snake_case											=							errors  # how to handle errors in decoding
         snake_case											=							bytes_to_unicode()
         snake_case											=							{v: k for k, v in self.byte_encoder.items()}
         with open(__snake_case     ,   encoding='''utf-8'''       ) as merges_handle:
              snake_case											=							merges_handle.read().split('''\n'''       )[1:-1]
         snake_case											=							[tuple(merge.split()       ) for merge in bpe_merges]
         snake_case											=							dict(zip(__snake_case     ,   range(len(__snake_case       )       )       )       )
         snake_case											=							{}
         snake_case											=							add_prefix_space

         # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
         snake_case											=							re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'''       )
    @property
    def 						a_     (			self       ):
         return len(self.encoder       )
    def 						a_     (			self       ):
         return dict(self.encoder     ,   **self.added_tokens_encoder       )
    def 						a_     (			self     ,   __snake_case       ):
         if token in self.cache:
              return self.cache[token]
         snake_case											=							tuple(__snake_case       )
         snake_case											=							get_pairs(__snake_case       )

         if not pairs:
              return token

         while True:
              snake_case											=							min(__snake_case     ,   key=lambda __snake_case       : self.bpe_ranks.get(__snake_case     ,   float('''inf'''       )       )       )
              if bigram not in self.bpe_ranks:
                   break
              snake_case					,    snake_case											=							bigram
              snake_case											=							[]
              snake_case											=							0
              while i < len(__snake_case       ):
                   try:
                        snake_case											=							word.index(__snake_case     ,   __snake_case       )
                   except ValueError:
                        new_word.extend(word[i:]       )
                        break
                   else:
                        new_word.extend(word[i:j]       )
                        snake_case											=							j

                   if word[i] == first and i < len(__snake_case       ) - 1 and word[i + 1] == second:
                        new_word.append(first + second       )
                        i += 2
                   else:
                        new_word.append(word[i]       )
                        i += 1
              snake_case											=							tuple(__snake_case       )
              snake_case											=							new_word
              if len(__snake_case       ) == 1:
                   break
              else:
                   snake_case											=							get_pairs(__snake_case       )
         snake_case											=							''' '''.join(__snake_case       )
         snake_case											=							word
         return word
    def 						a_     (			self     ,   __snake_case       ):
         snake_case											=							[]
         for token in re.findall(self.pat     ,   __snake_case       ):
              snake_case											=							''''''.join(
                  self.byte_encoder[b] for b in token.encode('''utf-8'''       )       )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
              bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__snake_case       ).split(''' '''       )       )
         return bpe_tokens
    def 						a_     (			self     ,   __snake_case       ):
         return self.encoder.get(__snake_case     ,   self.encoder.get(self.unk_token       )       )
    def 						a_     (			self     ,   __snake_case       ):
         return self.decoder.get(__snake_case       )
    def 						a_     (			self     ,   __snake_case       ):
         snake_case											=							''''''.join(__snake_case       )
         snake_case											=							bytearray([self.byte_decoder[c] for c in text]       ).decode('''utf-8'''     ,   errors=self.errors       )
         return text
    def 						a_     (			self     ,   __snake_case     ,   __snake_case = None       ):
         if not os.path.isdir(__snake_case       ):
              logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''       )
              return
         snake_case											=							os.path.join(
             __snake_case     ,   (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']       )
         snake_case											=							os.path.join(
             __snake_case     ,   (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']       )

         with open(__snake_case     ,   '''w'''     ,   encoding='''utf-8'''       ) as f:
              f.write(json.dumps(self.encoder     ,   indent=2     ,   sort_keys=__snake_case     ,   ensure_ascii=__snake_case       ) + '''\n'''       )

         snake_case											=							0
         with open(__snake_case     ,   '''w'''     ,   encoding='''utf-8'''       ) as writer:
              writer.write('''#version: 0.2\n'''       )
              for bpe_tokens, token_index in sorted(self.bpe_ranks.items()     ,   key=lambda __snake_case       : kv[1]       ):
                   if index != token_index:
                        logger.warning(
                            F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
                            ''' Please check that the tokenizer is not corrupted!'''       )
                        snake_case											=							token_index
                   writer.write(''' '''.join(__snake_case       ) + '''\n'''       )
                   index += 1

         return vocab_file, merge_file
    def 						a_     (			self     ,   __snake_case     ,   __snake_case = None       ):
         if token_ids_a is None:
              return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
         snake_case											=							[self.cls_token_id]
         snake_case											=							[self.sep_token_id]
         return cls + token_ids_a + sep + sep + token_ids_a + sep
    def 						a_     (			self     ,   __snake_case     ,   __snake_case = None     ,   __snake_case = False       ):
         if already_has_special_tokens:
              return super().get_special_tokens_mask(
                  token_ids_a=__snake_case     ,   token_ids_a=__snake_case     ,   already_has_special_tokens=__snake_case       )

         if token_ids_a is None:
              return [1] + ([0] * len(__snake_case       )) + [1]
         return [1] + ([0] * len(__snake_case       )) + [1, 1] + ([0] * len(__snake_case       )) + [1]
    def 						a_     (			self     ,   __snake_case     ,   __snake_case = None       ):
         snake_case											=							[self.sep_token_id]
         snake_case											=							[self.cls_token_id]

         if token_ids_a is None:
              return len(cls + token_ids_a + sep       ) * [0]
         return len(cls + token_ids_a + sep + sep + token_ids_a + sep       ) * [0]




    def 						a_     (			self     ,   __snake_case     ,   __snake_case=False     ,   **__snake_case       ):
         snake_case											=							kwargs.pop('''add_prefix_space'''     ,   self.add_prefix_space       )
         if (is_split_into_words or add_prefix_space) and (len(__snake_case       ) > 0 and not text[0].isspace()):
              snake_case											=							''' ''' + text
         return (text, kwargs)




