

"""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		:			Optional[int]					,A		:			str					,A		:			List[Any]=3					,A		:			Dict=7					,A		:			str=True					,A		:			int=True					,A		:			List[Any]=False					,A		:			Optional[Any]=True					,A		:			str=99					,A		:			str=32					,A		:			str=5					,A		:			Tuple=4					,A		:			Optional[int]=37					,A		:			Dict="gelu"					,A		:			List[Any]=0.1					,A		:			Optional[Any]=0.1					,A		:			Union[str, Any]=512					,A		:			List[Any]=16					,A		:			str=2					,A		:			Optional[Any]=0.0_2					,A		:			Optional[Any]=3					,A		:			Any=4					,A		:			Optional[Any]=None					,):






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

  def    __lowercase       (  self		:			Optional[Any]    ):






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

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

   UpperCAmelCase__					:  List[str]					   =					None

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

   UpperCAmelCase__					:  Optional[Any]					   =					self.get_config()

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

  def    __lowercase       (  self		:			List[str]    ):






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






   '''simple docstring'''
   UpperCAmelCase__					:  Dict					   =					FalconModel(config=A    )
   model.to(A    )
   model.eval()
   UpperCAmelCase__					:  Tuple					   =					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		:			Optional[Any]					,A		:			Dict					,A		:			str					,A		:			str					,A		:			Union[str, Any]					,A		:			str					,A		:			Any					,A		:			Dict					,A		:			Dict					,A		:			Dict					,):






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

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






   '''simple docstring'''
   UpperCAmelCase__					:  Optional[int]					   =					FalconForCausalLM(config=A    )
   model.to(A    )
   model.eval()
   UpperCAmelCase__					:  Dict					   =					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		:			List[Any]					,A		:			str					,A		:			Union[str, Any]					,A		:			Dict					,A		:			List[str]					,A		:			int					,A		:			List[str]					,A		:			Union[str, Any]					,A		:			int					,A		:			Optional[Any]					,):






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

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

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

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

   UpperCAmelCase__					:  List[str]					   =					model(
       A					,attention_mask=A					,encoder_hidden_states=A					,encoder_attention_mask=A					,output_hidden_states=A					,)['hidden_states'][0]
   UpperCAmelCase__					:  int					   =					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__					:  Dict					   =					ids_tensor((1,)					,output_from_past.shape[-1]    ).item()
   UpperCAmelCase__					:  List[str]					   =					output_from_no_past[:, -3:, random_slice_idx].detach()
   UpperCAmelCase__					:  Dict					   =					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		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__					:  List[Any]					   =					self.prepare_config_and_inputs()
   (
       UpperCAmelCase__       
   )					:  List[Any]					   =					config_and_inputs
   UpperCAmelCase__					:  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		:			Optional[Any]    ):






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

  def    __lowercase       (  self		:			Tuple    ):






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

  def    __lowercase       (  self		:			Union[str, 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		:			Optional[int]    ):






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

  def    __lowercase       (  self		:			List[Any]    ):






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






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






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






   '''simple docstring'''
   UpperCAmelCase__					:  List[Any]					   =					self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase__					:  Any					   =					3
   UpperCAmelCase__					:  Optional[Any]					   =					'multi_label_classification'
   UpperCAmelCase__					:  Union[str, Any]					   =					input_dict['input_ids']
   UpperCAmelCase__					:  Any					   =					input_ids.ne(1    ).to(A    )
   UpperCAmelCase__					:  Dict					   =					ids_tensor(
       [self.model_tester.batch_size, config.num_labels]					,self.model_tester.type_sequence_label_size    ).to(torch.float    )
   UpperCAmelCase__					:  Optional[Any]					   =					FalconForSequenceClassification(A    )
   model.to(A    )
   model.eval()
   UpperCAmelCase__					:  Dict					   =					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		:			List[str]    ):






   '''simple docstring'''







   for model_class in self.all_generative_model_classes:
    UpperCAmelCase__					:  Dict					   =					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__					:  Any					   =					model_class(A    ).to(A    )
    if "use_cache" not in inputs:
     UpperCAmelCase__					:  Dict					   =					True
    UpperCAmelCase__					:  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__					:  str					   =					(
        getattr(A					,"""decoder_layers"""					,A    )
        or getattr(A					,"""num_decoder_layers"""					,A    )
        or config.num_hidden_layers
    )
    UpperCAmelCase__					:  List[str]					   =					getattr(A					,"""num_kv_heads"""					,config.num_attention_heads    )
    UpperCAmelCase__					:  str					   =					getattr(A					,"""d_model"""					,config.hidden_size    )
    UpperCAmelCase__					:  Optional[Any]					   =					embed_dim // num_attention_heads

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

    UpperCAmelCase__					:  Optional[Any]					   =					inputs['input_ids'].shape
    for i in range(A    ):
     if config.new_decoder_architecture:
      UpperCAmelCase__					:  Optional[Any]					   =					config.num_attention_heads
     elif config.multi_query:
      UpperCAmelCase__					:  Union[str, Any]					   =					1
     self.assertEqual(len(past_kv[0]    )					,2    )  # K V for the decoder = 2
     self.assertEqual(
         past_kv[i][0].shape					,(batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )
     self.assertEqual(
         past_kv[i][1].shape					,(batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )







@require_torch
class      __lowercase			(    unittest.TestCase					):

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






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

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

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

   self.assertEqual(A					,A    )

  @slow
  def    __lowercase       (  self		:			List[str]    ):






   '''simple docstring'''







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

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




  @slow
  def    __lowercase       (  self		:			int    ):






   '''simple docstring'''







   with torch.no_grad():
    for repo in [
        "Rocketknight1/falcon-rw-1b",
        "Rocketknight1/tiny-random-falcon-7b",
        "Rocketknight1/tiny-random-falcon-40b",
    ]:
     UpperCAmelCase__					:  Optional[int]					   =					AutoTokenizer.from_pretrained(A    )
     UpperCAmelCase__					:  Optional[Any]					   =					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[int]					   =					model.generate(**A					,do_sample=A					,max_new_tokens=20					,use_cache=A    )
     UpperCAmelCase__					:  int					   =					model.generate(**A					,do_sample=A					,max_new_tokens=20					,use_cache=A    )
     self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0    )








"""simple docstring"""




import argparse
import os
import re

import packaging.version


__UpperCAmelCase =				'examples/'
__UpperCAmelCase =				{
    'examples': (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),
    'init': (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
    'setup': (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'),
    'doc': (re.compile(r'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'),
}
__UpperCAmelCase =				{
    'init': 'src/transformers/__init__.py',
    'setup': 'setup.py',
}
__UpperCAmelCase =				'README.md'
def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase      ):
 '''simple docstring'''





 with open(__UpperCamelCase							,    """r"""							,    encoding="""utf-8"""							,    newline="""\n"""      ) as f:
  UpperCAmelCase__					:  Dict					   =					f.read()
 UpperCAmelCase__   ,      UpperCAmelCase__					:  Any					   =					REPLACE_PATTERNS[pattern]
 UpperCAmelCase__					:  List[str]					   =					replace.replace("""VERSION"""							,    __UpperCamelCase      )
 UpperCAmelCase__					:  Tuple					   =					re_pattern.sub(__UpperCamelCase							,    __UpperCamelCase      )
 with open(__UpperCamelCase							,    """w"""							,    encoding="""utf-8"""							,    newline="""\n"""      ) as f:
  f.write(__UpperCamelCase      )
def   lowerCAmelCase						(					__UpperCamelCase      ):
 '''simple docstring'''





 for folder, directories, fnames in os.walk(__UpperCamelCase      ):
  # Removing some of the folders with non-actively maintained examples from the walk
  if "research_projects" in directories:
   directories.remove("""research_projects"""      )
  if "legacy" in directories:
   directories.remove("""legacy"""      )
  for fname in fnames:
   if fname.endswith(""".py"""      ):
    update_version_in_file(os.path.join(__UpperCamelCase							,    __UpperCamelCase      )							,    __UpperCamelCase							,    pattern="""examples"""      )
def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase=False      ):
 '''simple docstring'''





 for pattern, fname in REPLACE_FILES.items():
  update_version_in_file(__UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase      )
 if not patch:
  update_version_in_examples(__UpperCamelCase      )
def   lowerCAmelCase						(					):
 '''simple docstring'''





 UpperCAmelCase__					:  Dict					   =					"""🤗 Transformers currently provides the following architectures"""
 UpperCAmelCase__					:  Union[str, Any]					   =					"""1. Want to contribute a new model?"""
 with open(__UpperCamelCase							,    """r"""							,    encoding="""utf-8"""							,    newline="""\n"""      ) as f:
  UpperCAmelCase__					:  str					   =					f.readlines()

 # Find the start of the list.
 UpperCAmelCase__					:  List[Any]					   =					0
 while not lines[start_index].startswith(_start_prompt      ):
  start_index += 1
 start_index += 1

 UpperCAmelCase__					:  int					   =					start_index
 # Update the lines in the model list.
 while not lines[index].startswith(_end_prompt      ):
  if lines[index].startswith("""1."""      ):
   UpperCAmelCase__					:  List[Any]					   =					lines[index].replace(
       """https://huggingface.co/docs/transformers/main/model_doc"""							,    """https://huggingface.co/docs/transformers/model_doc"""							,    )
  index += 1

 with open(__UpperCamelCase							,    """w"""							,    encoding="""utf-8"""							,    newline="""\n"""      ) as f:
  f.writelines(__UpperCamelCase      )
def   lowerCAmelCase						(					):
 '''simple docstring'''





 with open(REPLACE_FILES["""init"""]							,    """r"""      ) as f:
  UpperCAmelCase__					:  Optional[Any]					   =					f.read()
 UpperCAmelCase__					:  int					   =					REPLACE_PATTERNS["""init"""][0].search(__UpperCamelCase      ).groups()[0]
 return packaging.version.parse(__UpperCamelCase      )
def   lowerCAmelCase						(					__UpperCamelCase=False      ):
 '''simple docstring'''





 UpperCAmelCase__					:  List[str]					   =					get_version()
 if patch and default_version.is_devrelease:
  raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!"""      )
 if default_version.is_devrelease:
  UpperCAmelCase__					:  List[str]					   =					default_version.base_version
 elif patch:
  UpperCAmelCase__					:  Any					   =					F"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
 else:
  UpperCAmelCase__					:  Optional[Any]					   =					F"{default_version.major}.{default_version.minor + 1}.0"

 # Now let's ask nicely if that's the right one.
 UpperCAmelCase__					:  Optional[int]					   =					input(F"Which version are you releasing? [{default_version}]"      )
 if len(__UpperCamelCase      ) == 0:
  UpperCAmelCase__					:  Union[str, Any]					   =					default_version

 print(F"Updating version to {version}."      )
 global_version_update(__UpperCamelCase							,    patch=__UpperCamelCase      )
 if not patch:
  print("""Cleaning main README, don't forget to run `make fix-copies`."""      )
  clean_main_ref_in_model_list()
def   lowerCAmelCase						(					):
 '''simple docstring'''





 UpperCAmelCase__					:  Optional[Any]					   =					get_version()
 UpperCAmelCase__					:  Any					   =					F"{current_version.major}.{current_version.minor + 1}.0.dev0"
 UpperCAmelCase__					:  List[Any]					   =					current_version.base_version

 # Check with the user we got that right.
 UpperCAmelCase__					:  Dict					   =					input(F"Which version are we developing now? [{dev_version}]"      )
 if len(__UpperCamelCase      ) == 0:
  UpperCAmelCase__					:  List[Any]					   =					dev_version

 print(F"Updating version to {version}."      )
 global_version_update(__UpperCamelCase      )
 print("""Cleaning main README, don't forget to run `make fix-copies`."""      )
 clean_main_ref_in_model_list()


if __name__ == "__main__":
      __UpperCAmelCase =				argparse.ArgumentParser()
      parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.')
      parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.')
      __UpperCAmelCase =				parser.parse_args()
      if not args.post_release:
            pre_release_work(patch=args.patch)
      elif args.patch:
            print('Nothing to do after a patch :-)')
      else:
            post_release_work()





