


'''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

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


if is_torch_available():
		import torch


def       a				(      __a			, __a			, __a=None       )  ->     Optional[int]:



					'''simple docstring'''






					if rng is None:
										UpperCamelCase__       :Any							 =			random.Random()

					UpperCamelCase__       :Optional[Any]							 =			1
					for dim in shape:
										total_dims *= dim

					UpperCamelCase__       :Union[str, Any]							 =			[]
					for _ in range(__a       ):
										values.append(rng.randint(0			, vocab_size - 1       )       )

					UpperCamelCase__       :str							 =			np.array(__a			, dtype=jnp.intaa       ).reshape(__a       )

					return output


def       a				(      __a			, __a=None       )  ->     Union[str, Any]:



					'''simple docstring'''






					UpperCamelCase__       :Optional[int]							 =			ids_tensor(__a			, vocab_size=2			, rng=__a       )
					# make sure that at least one token is attended to for each batch
					UpperCamelCase__       :Dict							 =			1
					return attn_mask
@require_flax
class        lowercase     :

		"""simple docstring"""

		_a   			=    None
		_a   			=    ()




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__       :int							 =			self.model_tester.prepare_config_and_inputs_for_common()

							# cut to half length & take max batch_size 3
							UpperCamelCase__       :Optional[int]							 =			2
							UpperCamelCase__       :Optional[Any]							 =			inputs['''input_ids'''].shape[-1] // 2
							UpperCamelCase__       :Tuple							 =			inputs['''input_ids'''][:max_batch_size, :sequence_length]

							UpperCamelCase__       :Dict							 =			jnp.ones_like(UpperCamelCase_							)
							UpperCamelCase__       :str							 =			attention_mask[:max_batch_size, :sequence_length]

							# generate max 5 tokens
							UpperCamelCase__       :Any							 =			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()`
												UpperCamelCase__       :Optional[int]							 =			config.eos_token_id
							return config, input_ids, attention_mask, max_length




		@is_pt_flax_cross_test
		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :str							 =			self._get_input_ids_and_config()
							UpperCamelCase__       :List[Any]							 =			False
							UpperCamelCase__       :Optional[Any]							 =			max_length
							UpperCamelCase__       :Any							 =			0

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :str							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :Optional[Any]							 =			model_class.__name__[4:]  # Skip the "Flax" at the beginning
												UpperCamelCase__       :Any							 =			getattr(UpperCamelCase_   ,       UpperCamelCase_							)
												UpperCamelCase__       :Optional[Any]							 =			pt_model_class(UpperCamelCase_							).eval()
												UpperCamelCase__       :Union[str, Any]							 =			load_flax_weights_in_pytorch_model(UpperCamelCase_   ,       flax_model.params							)

												UpperCamelCase__       :Dict							 =			flax_model.generate(UpperCamelCase_							).sequences
												UpperCamelCase__       :str							 =			pt_model.generate(torch.tensor(UpperCamelCase_   ,       dtype=torch.long							)							)

												if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
																	UpperCamelCase__       :List[Any]							 =			flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

												self.assertListEqual(pt_generation_outputs.numpy().tolist()   ,       flax_generation_outputs.tolist()							)




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :Optional[int]							 =			self._get_input_ids_and_config()
							UpperCamelCase__       :str							 =			False
							UpperCamelCase__       :str							 =			max_length

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :List[str]							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :Optional[Any]							 =			model.generate(UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[-1]   ,       UpperCamelCase_							)

												UpperCamelCase__       :Tuple							 =			jit(model.generate							)
												UpperCamelCase__       :Dict							 =			jit_generate(UpperCamelCase_							).sequences

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




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :Union[str, Any]							 =			self._get_input_ids_and_config()
							UpperCamelCase__       :Union[str, Any]							 =			True
							UpperCamelCase__       :Tuple							 =			max_length

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :Tuple							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :str							 =			model.generate(UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[-1]   ,       UpperCamelCase_							)

												UpperCamelCase__       :Any							 =			jit(model.generate							)
												UpperCamelCase__       :Union[str, Any]							 =			jit_generate(UpperCamelCase_							).sequences

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




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :Optional[Any]							 =			self._get_input_ids_and_config()
							UpperCamelCase__       :List[str]							 =			False
							UpperCamelCase__       :str							 =			max_length
							UpperCamelCase__       :int							 =			2

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :Any							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :Dict							 =			model.generate(UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[-1]   ,       UpperCamelCase_							)

												UpperCamelCase__       :int							 =			jit(model.generate							)
												UpperCamelCase__       :List[str]							 =			jit_generate(UpperCamelCase_							).sequences

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




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :List[Any]							 =			self._get_input_ids_and_config()
							UpperCamelCase__       :Dict							 =			False
							UpperCamelCase__       :Optional[int]							 =			max_length
							UpperCamelCase__       :int							 =			2
							UpperCamelCase__       :Optional[Any]							 =			2

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :str							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :List[str]							 =			model.generate(UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[0]   ,       input_ids.shape[0] * config.num_return_sequences							)




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :Optional[Any]							 =			self._get_input_ids_and_config()
							UpperCamelCase__       :List[Any]							 =			True
							UpperCamelCase__       :Any							 =			max_length
							UpperCamelCase__       :Union[str, Any]							 =			0.8
							UpperCamelCase__       :Optional[int]							 =			10
							UpperCamelCase__       :str							 =			0.3
							UpperCamelCase__       :Optional[Any]							 =			1
							UpperCamelCase__       :Union[str, Any]							 =			8
							UpperCamelCase__       :Optional[Any]							 =			9

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :Optional[int]							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :int							 =			model.generate(UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[-1]   ,       UpperCamelCase_							)

												UpperCamelCase__       :Optional[Any]							 =			jit(model.generate							)
												UpperCamelCase__       :Tuple							 =			jit_generate(UpperCamelCase_							).sequences

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




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :List[str]							 =			self._get_input_ids_and_config()
							UpperCamelCase__       :Optional[int]							 =			max_length
							UpperCamelCase__       :Union[str, Any]							 =			1
							UpperCamelCase__       :Any							 =			8
							UpperCamelCase__       :Union[str, Any]							 =			9

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :List[Any]							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :List[Any]							 =			model.generate(UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[-1]   ,       UpperCamelCase_							)

												UpperCamelCase__       :int							 =			jit(model.generate							)
												UpperCamelCase__       :Optional[Any]							 =			jit_generate(UpperCamelCase_							).sequences

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




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :Any							 =			self._get_input_ids_and_config()
							UpperCamelCase__       :List[str]							 =			max_length
							UpperCamelCase__       :Tuple							 =			2
							UpperCamelCase__       :Dict							 =			1
							UpperCamelCase__       :str							 =			8
							UpperCamelCase__       :Dict							 =			9

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :List[str]							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :List[str]							 =			model.generate(UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[-1]   ,       UpperCamelCase_							)

												UpperCamelCase__       :List[str]							 =			jit(model.generate							)
												UpperCamelCase__       :Optional[Any]							 =			jit_generate(UpperCamelCase_							).sequences

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




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :List[str]							 =			self._get_input_ids_and_config()

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

							UpperCamelCase__       :Any							 =			False
							UpperCamelCase__       :Union[str, Any]							 =			max_length

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :str							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :List[Any]							 =			model.generate(UpperCamelCase_   ,       attention_mask=UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[-1]   ,       UpperCamelCase_							)

												UpperCamelCase__       :List[str]							 =			jit(model.generate							)
												UpperCamelCase__       :List[Any]							 =			jit_generate(UpperCamelCase_   ,       attention_mask=UpperCamelCase_							).sequences

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




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :Optional[int]							 =			self._get_input_ids_and_config()

							# pad attention mask on the left
							UpperCamelCase__       :Optional[int]							 =			attention_mask.at[(0, 0)].set(0							)

							UpperCamelCase__       :Union[str, Any]							 =			True
							UpperCamelCase__       :Union[str, Any]							 =			max_length

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :Tuple							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :str							 =			model.generate(UpperCamelCase_   ,       attention_mask=UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[-1]   ,       UpperCamelCase_							)

												UpperCamelCase__       :Dict							 =			jit(model.generate							)
												UpperCamelCase__       :Optional[Any]							 =			jit_generate(UpperCamelCase_   ,       attention_mask=UpperCamelCase_							).sequences

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




		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :Any							 =			self._get_input_ids_and_config()

							# pad attention mask on the left
							UpperCamelCase__       :List[str]							 =			attention_mask.at[(0, 0)].set(0							)

							UpperCamelCase__       :Dict							 =			2
							UpperCamelCase__       :Tuple							 =			max_length

							for model_class in self.all_generative_model_classes:
												UpperCamelCase__       :Optional[int]							 =			model_class(UpperCamelCase_							)

												UpperCamelCase__       :Optional[Any]							 =			model.generate(UpperCamelCase_   ,       attention_mask=UpperCamelCase_							).sequences
												self.assertEqual(generation_outputs.shape[-1]   ,       UpperCamelCase_							)

												UpperCamelCase__       :str							 =			jit(model.generate							)
												UpperCamelCase__       :Any							 =			jit_generate(UpperCamelCase_   ,       attention_mask=UpperCamelCase_							).sequences

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



@require_flax
class        lowercase     (							unittest.TestCase ):

		"""simple docstring"""

		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							UpperCamelCase__       :Optional[int]							 =			AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-bert'''							)
							UpperCamelCase__       :Dict							 =			FlaxAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''							)

							UpperCamelCase__       :str							 =			'''Hello world'''
							UpperCamelCase__       :Dict							 =			tokenizer(UpperCamelCase_   ,       return_tensors='''np'''							).input_ids

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

							# arbitrary arguments that will not be used anywhere are also not accepted
							with self.assertRaisesRegex(UpperCamelCase_   ,       '''foo'''							):
												UpperCamelCase__       :List[str]							 =			{'''foo''': '''bar'''}
												model.generate(UpperCamelCase_   ,       **UpperCamelCase_							)



'''simple docstring'''
from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__snake_case											=					logging.get_logger(__name__)

__snake_case											=					{
    '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/config.json''',
    '''distilbert-base-uncased-distilled-squad''': (
        '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json'''
    ),
    '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/config.json''',
    '''distilbert-base-cased-distilled-squad''': (
        '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json'''
    ),
    '''distilbert-base-german-cased''': '''https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json''',
    '''distilbert-base-multilingual-cased''': (
        '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json'''
    ),
    '''distilbert-base-uncased-finetuned-sst-2-english''': (
        '''https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json'''
    ),
}
class        lowercase     (							A__ ):

		"""simple docstring"""

		_a   			=    'distilbert'
		_a   			=    {
		    'hidden_size': 'dim',
		    'num_attention_heads': 'n_heads',
		    'num_hidden_layers': 'n_layers',
		}




		def __init__(		self   ,       UpperCamelCase_=30522   ,       UpperCamelCase_=512   ,       UpperCamelCase_=False   ,       UpperCamelCase_=6   ,       UpperCamelCase_=12   ,       UpperCamelCase_=768   ,       UpperCamelCase_=4 * 768   ,       UpperCamelCase_=0.1   ,       UpperCamelCase_=0.1   ,       UpperCamelCase_="gelu"   ,       UpperCamelCase_=0.02   ,       UpperCamelCase_=0.1   ,       UpperCamelCase_=0.2   ,       UpperCamelCase_=0   ,       **UpperCamelCase_   ,       ):

							'''simple docstring'''


							UpperCamelCase__       :List[Any]							 =			vocab_size
							UpperCamelCase__       :Dict							 =			max_position_embeddings
							UpperCamelCase__       :str							 =			sinusoidal_pos_embds
							UpperCamelCase__       :Any							 =			n_layers
							UpperCamelCase__       :str							 =			n_heads
							UpperCamelCase__       :Tuple							 =			dim
							UpperCamelCase__       :str							 =			hidden_dim
							UpperCamelCase__       :Dict							 =			dropout
							UpperCamelCase__       :int							 =			attention_dropout
							UpperCamelCase__       :Optional[Any]							 =			activation
							UpperCamelCase__       :Optional[int]							 =			initializer_range
							UpperCamelCase__       :Union[str, Any]							 =			qa_dropout
							UpperCamelCase__       :Dict							 =			seq_classif_dropout
							super().__init__(**UpperCamelCase_   ,       pad_token_id=UpperCamelCase_							)



class        lowercase     (							A__ ):

		"""simple docstring"""

		@property
		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							if self.task == "multiple-choice":
												UpperCamelCase__       :str							 =			{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
							else:
												UpperCamelCase__       :str							 =			{0: '''batch''', 1: '''sequence'''}
							return OrderedDict(
							    [
							        ('''input_ids''', dynamic_axis),
							        ('''attention_mask''', dynamic_axis),
							    ]							)