






'''simple docstring'''



def 				lowercase_					(     __A			:							List[str]      )							->   Union[str, Any]:



 """simple docstring"""




 lowercase       : str						=[0] * len(__A      )
 lowercase       : Union[str, Any]						=[]
 lowercase       : str						=[]
 lowercase       : List[Any]						=0

 for values in graph.values():
  for i in values:
   indegree[i] += 1

 for i in range(len(__A      )      ):
  if indegree[i] == 0:
   queue.append(__A      )

 while queue:
  lowercase       : List[str]						=queue.pop(0      )
  cnt += 1
  topo.append(__A      )
  for x in graph[vertex]:
   indegree[x] -= 1
   if indegree[x] == 0:
    queue.append(__A      )

 if cnt != len(__A      ):
  print('''Cycle exists'''      )
 else:
  print(__A      )


# Adjacency List of Graph
SCREAMING_SNAKE_CASE							=						{0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}





topological_sort(graph)











"""simple docstring"""
import os
import tempfile
import unittest

from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

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 (
     FlaubertForMultipleChoice,
     FlaubertForQuestionAnswering,
     FlaubertForQuestionAnsweringSimple,
     FlaubertForSequenceClassification,
     FlaubertForTokenClassification,
     FlaubertModel,
     FlaubertWithLMHeadModel,
 )
 from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST



class        UpperCamelCase__ (				a_):







    """simple docstring"""







    def __init__(		self :	List[str]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Optional[int]=1_3				,    UpperCamelCase_ :	Dict=7				,    UpperCamelCase_ :	Dict=True				,    UpperCamelCase_ :	Optional[Any]=True				,    UpperCamelCase_ :	Union[str, Any]=True				,    UpperCamelCase_ :	Dict=True				,    UpperCamelCase_ :	Optional[int]=True				,    UpperCamelCase_ :	Tuple=False				,    UpperCamelCase_ :	Union[str, Any]=False				,    UpperCamelCase_ :	Any=False				,    UpperCamelCase_ :	Tuple=2				,    UpperCamelCase_ :	List[Any]=9_9				,    UpperCamelCase_ :	List[Any]=0				,    UpperCamelCase_ :	Tuple=3_2				,    UpperCamelCase_ :	Any=5				,    UpperCamelCase_ :	Dict=4				,    UpperCamelCase_ :	Tuple=0.1				,    UpperCamelCase_ :	Any=0.1				,    UpperCamelCase_ :	Optional[Any]=5_1_2				,    UpperCamelCase_ :	Union[str, Any]=1_2				,    UpperCamelCase_ :	List[str]=2				,    UpperCamelCase_ :	str=0.02				,    UpperCamelCase_ :	List[str]=3				,    UpperCamelCase_ :	Dict=4				,    UpperCamelCase_ :	Optional[int]="last"				,    UpperCamelCase_ :	List[str]=None				,    UpperCamelCase_ :	Tuple=None				,    ):





           '''simple docstring'''

           __magic_name__      				=    parent
           __magic_name__      				=    batch_size
           __magic_name__      				=    seq_length
           __magic_name__      				=    is_training
           __magic_name__      				=    use_input_lengths
           __magic_name__      				=    use_token_type_ids
           __magic_name__      				=    use_labels
           __magic_name__      				=    gelu_activation
           __magic_name__      				=    sinusoidal_embeddings
           __magic_name__      				=    causal
           __magic_name__      				=    asm
           __magic_name__      				=    n_langs
           __magic_name__      				=    vocab_size
           __magic_name__      				=    n_special
           __magic_name__      				=    hidden_size
           __magic_name__      				=    num_hidden_layers
           __magic_name__      				=    num_attention_heads
           __magic_name__      				=    hidden_dropout_prob
           __magic_name__      				=    attention_probs_dropout_prob
           __magic_name__      				=    max_position_embeddings
           __magic_name__      				=    type_vocab_size
           __magic_name__      				=    type_sequence_label_size
           __magic_name__      				=    initializer_range
           __magic_name__      				=    num_labels
           __magic_name__      				=    num_choices
           __magic_name__      				=    summary_type
           __magic_name__      				=    use_proj
           __magic_name__      				=    scope







    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           __magic_name__      				=    ids_tensor([self.batch_size, self.seq_length]				,    self.vocab_size )
           __magic_name__      				=    random_attention_mask([self.batch_size, self.seq_length] )

           __magic_name__      				=    None
           if self.use_input_lengths:
                  __magic_name__      				=    (
                      ids_tensor([self.batch_size]				,    vocab_size=2 ) + self.seq_length - 2
                  )  # small variation of seq_length

           __magic_name__      				=    None
           if self.use_token_type_ids:
                  __magic_name__      				=    ids_tensor([self.batch_size, self.seq_length]				,    self.n_langs )

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

           __magic_name__      				=    self.get_config()

           return (
               config,
               input_ids,
               token_type_ids,
               input_lengths,
               sequence_labels,
               token_labels,
               is_impossible_labels,
               choice_labels,
               input_mask,
           )







    def 				a__			(		self :	int ):





           '''simple docstring'''

           return FlaubertConfig(
               vocab_size=self.vocab_size				,    n_special=self.n_special				,    emb_dim=self.hidden_size				,    n_layers=self.num_hidden_layers				,    n_heads=self.num_attention_heads				,    dropout=self.hidden_dropout_prob				,    attention_dropout=self.attention_probs_dropout_prob				,    gelu_activation=self.gelu_activation				,    sinusoidal_embeddings=self.sinusoidal_embeddings				,    asm=self.asm				,    causal=self.causal				,    n_langs=self.n_langs				,    max_position_embeddings=self.max_position_embeddings				,    initializer_range=self.initializer_range				,    summary_type=self.summary_type				,    use_proj=self.use_proj				,    )







    def 				a__			(		self :	Dict				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Optional[int]				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertModel(config=UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()
           __magic_name__      				=    model(UpperCamelCase_				,    lengths=UpperCamelCase_				,    langs=UpperCamelCase_ )
           __magic_name__      				=    model(UpperCamelCase_				,    langs=UpperCamelCase_ )
           __magic_name__      				=    model(UpperCamelCase_ )
           self.parent.assertEqual(result.last_hidden_state.shape				,    (self.batch_size, self.seq_length, self.hidden_size) )







    def 				a__			(		self :	Dict				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	str				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertWithLMHeadModel(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_				,    token_type_ids=UpperCamelCase_				,    labels=UpperCamelCase_ )
           self.parent.assertEqual(result.loss.shape				,    () )
           self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.seq_length, self.vocab_size) )







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	str				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertForQuestionAnsweringSimple(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_ )

           __magic_name__      				=    model(UpperCamelCase_				,    start_positions=UpperCamelCase_				,    end_positions=UpperCamelCase_ )
           self.parent.assertEqual(result.start_logits.shape				,    (self.batch_size, self.seq_length) )
           self.parent.assertEqual(result.end_logits.shape				,    (self.batch_size, self.seq_length) )







    def 				a__			(		self :	str				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Union[str, Any]				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertForQuestionAnswering(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_ )

           __magic_name__      				=    model(
               UpperCamelCase_				,    start_positions=UpperCamelCase_				,    end_positions=UpperCamelCase_				,    cls_index=UpperCamelCase_				,    is_impossible=UpperCamelCase_				,    p_mask=UpperCamelCase_				,    )

           __magic_name__      				=    model(
               UpperCamelCase_				,    start_positions=UpperCamelCase_				,    end_positions=UpperCamelCase_				,    cls_index=UpperCamelCase_				,    is_impossible=UpperCamelCase_				,    )

           ((__magic_name__)				,  )      				=    result_with_labels.to_tuple()

           __magic_name__      				=    model(UpperCamelCase_				,    start_positions=UpperCamelCase_				,    end_positions=UpperCamelCase_ )

           ((__magic_name__)				,  )      				=    result_with_labels.to_tuple()

           self.parent.assertEqual(result_with_labels.loss.shape				,    () )
           self.parent.assertEqual(result.start_top_log_probs.shape				,    (self.batch_size, model.config.start_n_top) )
           self.parent.assertEqual(result.start_top_index.shape				,    (self.batch_size, model.config.start_n_top) )
           self.parent.assertEqual(
               result.end_top_log_probs.shape				,    (self.batch_size, model.config.start_n_top * model.config.end_n_top) )
           self.parent.assertEqual(
               result.end_top_index.shape				,    (self.batch_size, model.config.start_n_top * model.config.end_n_top) )
           self.parent.assertEqual(result.cls_logits.shape				,    (self.batch_size,) )







    def 				a__			(		self :	str				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	List[str]				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertForSequenceClassification(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_ )
           __magic_name__      				=    model(UpperCamelCase_				,    labels=UpperCamelCase_ )

           self.parent.assertEqual(result.loss.shape				,    () )
           self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.type_sequence_label_size) )







    def 				a__			(		self :	Optional[int]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Tuple				,    ):





           '''simple docstring'''

           __magic_name__      				=    self.num_labels
           __magic_name__      				=    FlaubertForTokenClassification(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_				,    attention_mask=UpperCamelCase_				,    labels=UpperCamelCase_ )
           self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.seq_length, self.num_labels) )







    def 				a__			(		self :	str				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Tuple				,    ):





           '''simple docstring'''

           __magic_name__      				=    self.num_choices
           __magic_name__      				=    FlaubertForMultipleChoice(config=UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()
           __magic_name__      				=    input_ids.unsqueeze(1 ).expand(-1				,    self.num_choices				,    -1 ).contiguous()
           __magic_name__      				=    token_type_ids.unsqueeze(1 ).expand(-1				,    self.num_choices				,    -1 ).contiguous()
           __magic_name__      				=    input_mask.unsqueeze(1 ).expand(-1				,    self.num_choices				,    -1 ).contiguous()
           __magic_name__      				=    model(
               UpperCamelCase_				,    attention_mask=UpperCamelCase_				,    token_type_ids=UpperCamelCase_				,    labels=UpperCamelCase_				,    )
           self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.num_choices) )







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





           '''simple docstring'''

           __magic_name__      				=    self.prepare_config_and_inputs()
           (
               (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  
           )      				=    config_and_inputs
           __magic_name__      				=    {
               'input_ids': input_ids,
               'token_type_ids': token_type_ids,
               'lengths': input_lengths,
               'attention_mask': input_mask,
           }
           return config, inputs_dict



@require_torch
class        UpperCamelCase__ (				a_							,	a_							,	unittest.TestCase):







    """simple docstring"""
    __UpperCAmelCase           = (
        (
            FlaubertModel,
            FlaubertWithLMHeadModel,
            FlaubertForQuestionAnswering,
            FlaubertForQuestionAnsweringSimple,
            FlaubertForSequenceClassification,
            FlaubertForTokenClassification,
            FlaubertForMultipleChoice,
        )
        if is_torch_available()
        else ()
    )
    __UpperCAmelCase           = (
        {
            """feature-extraction""": FlaubertModel,
            """fill-mask""": FlaubertWithLMHeadModel,
            """question-answering""": FlaubertForQuestionAnsweringSimple,
            """text-classification""": FlaubertForSequenceClassification,
            """token-classification""": FlaubertForTokenClassification,
            """zero-shot""": FlaubertForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           if (
               pipeline_test_casse_name == "QAPipelineTests"
               and tokenizer_name is not None
               and not tokenizer_name.endswith('Fast' )
           ):
                  # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
                  # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
                  # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
                  return True

           return False







    def 				a__			(		self :	List[Any]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Optional[Any]=False ):





           '''simple docstring'''

           __magic_name__      				=    super()._prepare_for_class(UpperCamelCase_				,    UpperCamelCase_				,    return_labels=UpperCamelCase_ )

           if return_labels:
                  if model_class.__name__ == "FlaubertForQuestionAnswering":
                         __magic_name__      				=    torch.zeros(
                             self.model_tester.batch_size				,    dtype=torch.long				,    device=UpperCamelCase_ )
                         __magic_name__      				=    torch.zeros(
                             self.model_tester.batch_size				,    dtype=torch.long				,    device=UpperCamelCase_ )

           return inputs_dict







    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertModelTester(self )
           __magic_name__      				=    ConfigTester(self				,    config_class=UpperCamelCase_				,    emb_dim=3_7 )







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

           self.config_tester.run_common_tests()







    def 				a__			(		self :	Optional[Any] ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_model(*UpperCamelCase_ )







    def 				a__			(		self :	Dict ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_lm_head(*UpperCamelCase_ )







    def 				a__			(		self :	int ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_simple_qa(*UpperCamelCase_ )







    def 				a__			(		self :	int ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_qa(*UpperCamelCase_ )







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_sequence_classif(*UpperCamelCase_ )







    def 				a__			(		self :	str ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_token_classif(*UpperCamelCase_ )







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





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_multiple_choice(*UpperCamelCase_ )







    @slow
    def 				a__			(		self :	Any ):





           '''simple docstring'''

           for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  __magic_name__      				=    FlaubertModel.from_pretrained(UpperCamelCase_ )
                  self.assertIsNotNone(UpperCamelCase_ )







    @slow
    @require_torch_gpu
    def 				a__			(		self :	str ):





           '''simple docstring'''

           __magic_name__				,  __magic_name__      				=    self.model_tester.prepare_config_and_inputs_for_common()
           for model_class in self.all_model_classes:
                  # FlauBertForMultipleChoice behaves incorrectly in JIT environments.
                  if model_class == FlaubertForMultipleChoice:
                         return

                  __magic_name__      				=    True
                  __magic_name__      				=    model_class(config=UpperCamelCase_ )

                  __magic_name__      				=    self._prepare_for_class(UpperCamelCase_				,    UpperCamelCase_ )
                  __magic_name__      				=    torch.jit.trace(
                      UpperCamelCase_				,    (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) )

                  with tempfile.TemporaryDirectory() as tmp:
                         torch.jit.save(UpperCamelCase_				,    os.path.join(UpperCamelCase_				,    'traced_model.pt' ) )
                         __magic_name__      				=    torch.jit.load(os.path.join(UpperCamelCase_				,    'traced_model.pt' )				,    map_location=UpperCamelCase_ )
                         loaded(inputs_dict['input_ids'].to(UpperCamelCase_ )				,    inputs_dict['attention_mask'].to(UpperCamelCase_ ) )



@require_torch
class        UpperCamelCase__ (				unittest.TestCase):







    """simple docstring"""







    @slow
    def 				a__			(		self :	Dict ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertModel.from_pretrained('flaubert/flaubert_base_cased' )
           __magic_name__      				=    torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] )
           with torch.no_grad():
                  __magic_name__      				=    model(UpperCamelCase_ )[0]
           __magic_name__      				=    torch.Size((1, 1_1, 7_6_8) )
           self.assertEqual(output.shape				,    UpperCamelCase_ )
           __magic_name__      				=    torch.tensor(
               [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]] )

           self.assertTrue(torch.allclose(output[:, :3, :3]				,    UpperCamelCase_				,    atol=1e-4 ) )