





"""simple docstring"""

import random
import unittest

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
       import os

       import jax.numpy as jnp
       from jax import jit

       from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
       from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

       UpperCAmelCase__  							='''0.12'''  # assumed parallelism: 8


if is_torch_available():
       import torch


def lowerCAmelCase_      (				UpperCamelCase__	: Dict				,   UpperCamelCase__	: str				,   UpperCamelCase__	: Any=None ):






 """simple docstring"""







 if rng is None:
  __lowercase									=	random.Random()

 __lowercase									=	1
 for dim in shape:
  total_dims *= dim

 __lowercase									=	[]
 for _ in range(UpperCAmelCase__ ):
  values.append(rng.randint(0				,   vocab_size - 1 ) )

 __lowercase									=	np.array(UpperCAmelCase__				,   dtype=jnp.intaa ).reshape(UpperCAmelCase__ )

 return output


def lowerCAmelCase_      (				UpperCamelCase__	: int				,   UpperCamelCase__	: Dict=None ):






 """simple docstring"""







 __lowercase									=	ids_tensor(UpperCAmelCase__				,   vocab_size=2				,   rng=UpperCAmelCase__ )
 # make sure that at least one token is attended to for each batch
 __lowercase									=	1
 return attn_mask





@require_flax
class    lowerCamelCase__						:
      a :     Optional[Any]											=		None
      a :     Optional[int]											=		()
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]							):






       '''simple docstring'''


       __lowercase							,		__lowercase									=	self.model_tester.prepare_config_and_inputs_for_common()

       # cut to half length & take max batch_size 3
       __lowercase									=	2
       __lowercase									=	inputs["""input_ids"""].shape[-1] // 2
       __lowercase									=	inputs["""input_ids"""][:max_batch_size, :sequence_length]

       __lowercase									=	jnp.ones_like(__lowerCAmelCase							)
       __lowercase									=	attention_mask[:max_batch_size, :sequence_length]

       # generate max 5 tokens
       __lowercase									=	input_ids.shape[-1] + 5
       if config.eos_token_id is not None and config.pad_token_id is None:
        # hack to allow generate for models such as GPT2 as is done in `generate()`
        __lowercase									=	config.eos_token_id
       return config, input_ids, attention_mask, max_length
      @is_pt_flax_cross_test
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()
       __lowercase									=	False
       __lowercase									=	max_length
       __lowercase									=	0

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model_class.__name__[4:]  # Skip the "Flax" at the beginning
        __lowercase									=	getattr(__lowerCAmelCase      ,       __lowerCAmelCase							)
        __lowercase									=	pt_model_class(__lowerCAmelCase							).eval()
        __lowercase									=	load_flax_weights_in_pytorch_model(__lowerCAmelCase      ,       flax_model.params							)

        __lowercase									=	flax_model.generate(__lowerCAmelCase							).sequences
        __lowercase									=	pt_model.generate(torch.tensor(__lowerCAmelCase      ,       dtype=torch.long							)							)

        if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
         __lowercase									=	flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

        self.assertListEqual(pt_generation_outputs.numpy().tolist()      ,       flax_generation_outputs.tolist()							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[Any]							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()
       __lowercase									=	False
       __lowercase									=	max_length

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[-1]      ,       __lowerCAmelCase							)

        __lowercase									=	jit(model.generate							)
        __lowercase									=	jit_generate(__lowerCAmelCase							).sequences

        self.assertListEqual(generation_outputs.tolist()      ,       jit_generation_outputs.tolist()							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Union[str, Any]							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()
       __lowercase									=	True
       __lowercase									=	max_length

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[-1]      ,       __lowerCAmelCase							)

        __lowercase									=	jit(model.generate							)
        __lowercase									=	jit_generate(__lowerCAmelCase							).sequences

        self.assertListEqual(generation_outputs.tolist()      ,       jit_generation_outputs.tolist()							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()
       __lowercase									=	False
       __lowercase									=	max_length
       __lowercase									=	2

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[-1]      ,       __lowerCAmelCase							)

        __lowercase									=	jit(model.generate							)
        __lowercase									=	jit_generate(__lowerCAmelCase							).sequences

        self.assertListEqual(generation_outputs.tolist()      ,       jit_generation_outputs.tolist()							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()
       __lowercase									=	False
       __lowercase									=	max_length
       __lowercase									=	2
       __lowercase									=	2

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[0]      ,       input_ids.shape[0] * config.num_return_sequences							)
      def SCREAMING_SNAKE_CASE_	(		self	:	str							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()
       __lowercase									=	True
       __lowercase									=	max_length
       __lowercase									=	0.8
       __lowercase									=	1_0
       __lowercase									=	0.3
       __lowercase									=	1
       __lowercase									=	8
       __lowercase									=	9

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[-1]      ,       __lowerCAmelCase							)

        __lowercase									=	jit(model.generate							)
        __lowercase									=	jit_generate(__lowerCAmelCase							).sequences

        self.assertListEqual(generation_outputs.tolist()      ,       jit_generation_outputs.tolist()							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[int]							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()
       __lowercase									=	max_length
       __lowercase									=	1
       __lowercase									=	8
       __lowercase									=	9

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[-1]      ,       __lowerCAmelCase							)

        __lowercase									=	jit(model.generate							)
        __lowercase									=	jit_generate(__lowerCAmelCase							).sequences

        self.assertListEqual(generation_outputs.tolist()      ,       jit_generation_outputs.tolist()							)
      def SCREAMING_SNAKE_CASE_	(		self	:	str							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()
       __lowercase									=	max_length
       __lowercase									=	2
       __lowercase									=	1
       __lowercase									=	8
       __lowercase									=	9

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[-1]      ,       __lowerCAmelCase							)

        __lowercase									=	jit(model.generate							)
        __lowercase									=	jit_generate(__lowerCAmelCase							).sequences

        self.assertListEqual(generation_outputs.tolist()      ,       jit_generation_outputs.tolist()							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[int]							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()

       # pad attention mask on the left
       __lowercase									=	attention_mask.at[(0, 0)].set(0							)

       __lowercase									=	False
       __lowercase									=	max_length

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase      ,       attention_mask=__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[-1]      ,       __lowerCAmelCase							)

        __lowercase									=	jit(model.generate							)
        __lowercase									=	jit_generate(__lowerCAmelCase      ,       attention_mask=__lowerCAmelCase							).sequences

        self.assertListEqual(generation_outputs.tolist()      ,       jit_generation_outputs.tolist()							)
      def SCREAMING_SNAKE_CASE_	(		self	:	int							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()

       # pad attention mask on the left
       __lowercase									=	attention_mask.at[(0, 0)].set(0							)

       __lowercase									=	True
       __lowercase									=	max_length

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase      ,       attention_mask=__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[-1]      ,       __lowerCAmelCase							)

        __lowercase									=	jit(model.generate							)
        __lowercase									=	jit_generate(__lowerCAmelCase      ,       attention_mask=__lowerCAmelCase							).sequences

        self.assertListEqual(generation_outputs.tolist()      ,       jit_generation_outputs.tolist()							)






      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase							,		__lowercase							,		__lowercase							,		__lowercase									=	self._get_input_ids_and_config()

       # pad attention mask on the left
       __lowercase									=	attention_mask.at[(0, 0)].set(0							)

       __lowercase									=	2
       __lowercase									=	max_length

       for model_class in self.all_generative_model_classes:
        __lowercase									=	model_class(__lowerCAmelCase							)

        __lowercase									=	model.generate(__lowerCAmelCase      ,       attention_mask=__lowerCAmelCase							).sequences
        self.assertEqual(generation_outputs.shape[-1]      ,       __lowerCAmelCase							)

        __lowercase									=	jit(model.generate							)
        __lowercase									=	jit_generate(__lowerCAmelCase      ,       attention_mask=__lowerCAmelCase							).sequences

        self.assertListEqual(generation_outputs.tolist()      ,       jit_generation_outputs.tolist()							)






@require_flax
class    lowerCamelCase__						(		unittest.TestCase    ):
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase									=	AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert"""							)
       __lowercase									=	FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only"""							)

       __lowercase									=	"""Hello world"""
       __lowercase									=	tokenizer(__lowerCAmelCase      ,       return_tensors="""np"""							).input_ids

       # typos are quickly detected (the correct argument is `do_sample`)
       with self.assertRaisesRegex(__lowerCAmelCase      ,       """do_samples"""							):
        model.generate(__lowerCAmelCase      ,       do_samples=__lowerCAmelCase							)

       # arbitrary arguments that will not be used anywhere are also not accepted
       with self.assertRaisesRegex(__lowerCAmelCase      ,       """foo"""							):
        __lowercase									=	{"""foo""": """bar"""}
        model.generate(__lowerCAmelCase      ,       **__lowerCAmelCase							)




"""simple docstring"""

import random


def lowerCAmelCase_      (				UpperCamelCase__	: int				,   UpperCamelCase__	: float				,   UpperCamelCase__	: bool = False ):






 """simple docstring"""







 __lowercase									=	{i: [] for i in range(UpperCamelCase__ )}

 # if probability is greater or equal than 1, then generate a complete graph
 if probability >= 1:
  return complete_graph(UpperCamelCase__ )
 # if probability is lower or equal than 0, then return a graph without edges
 if probability <= 0:
  return graph

 # for each couple of nodes, add an edge from u to v
 # if the number randomly generated is greater than probability probability
 for i in range(UpperCamelCase__ ):
  for j in range(i + 1				,   UpperCamelCase__ ):
   if random.random() < probability:
    graph[i].append(UpperCamelCase__ )
    if not directed:
     # if the graph is undirected, add an edge in from j to i, either
     graph[j].append(UpperCamelCase__ )
 return graph


def lowerCAmelCase_      (				UpperCamelCase__	: int ):






 """simple docstring"""







 return {
     i: [j for j in range(UpperCamelCase__ ) if i != j] for i in range(UpperCamelCase__ )
 }


if __name__ == "__main__":
       import doctest

       doctest.testmod()
