






import unittest

from transformers import SpeechaTextaConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers.models.speech_to_text_a.modeling_speech_to_text_a import (
		    SpeechaTextaDecoder,
		    SpeechaTextaForCausalLM,
		)





@require_torch
class __lowerCamelCase				:





	"""simple docstring"""






	def __init__(							self ,					UpperCAmelCase ,					UpperCAmelCase=99 ,					UpperCAmelCase=13 ,					UpperCAmelCase=16 ,					UpperCAmelCase=7 ,					UpperCAmelCase=True ,					UpperCAmelCase=True ,					UpperCAmelCase=True ,					UpperCAmelCase=False ,					UpperCAmelCase=True ,					UpperCAmelCase=2 ,					UpperCAmelCase=32 ,					UpperCAmelCase=4 ,					UpperCAmelCase=4 ,					UpperCAmelCase=30 ,					UpperCAmelCase=0 ,					UpperCAmelCase=1 ,					UpperCAmelCase=2 ,					UpperCAmelCase=None ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    parent
							_UpperCAmelCase             =    batch_size
							_UpperCAmelCase             =    decoder_seq_length
							# For common tests
							_UpperCAmelCase             =    self.decoder_seq_length
							_UpperCAmelCase             =    is_training
							_UpperCAmelCase             =    use_attention_mask
							_UpperCAmelCase             =    use_labels

							_UpperCAmelCase             =    vocab_size
							_UpperCAmelCase             =    d_model
							_UpperCAmelCase             =    d_model
							_UpperCAmelCase             =    decoder_layers
							_UpperCAmelCase             =    decoder_layers
							_UpperCAmelCase             =    decoder_ffn_dim
							_UpperCAmelCase             =    decoder_attention_heads
							_UpperCAmelCase             =    decoder_attention_heads
							_UpperCAmelCase             =    eos_token_id
							_UpperCAmelCase             =    bos_token_id
							_UpperCAmelCase             =    pad_token_id
							_UpperCAmelCase             =    decoder_start_token_id
							_UpperCAmelCase             =    use_cache
							_UpperCAmelCase             =    max_position_embeddings

							_UpperCAmelCase             =    None
							_UpperCAmelCase             =    decoder_seq_length
							_UpperCAmelCase             =    2
							_UpperCAmelCase             =    1

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    ids_tensor([self.batch_size, self.decoder_seq_length] ,					self.vocab_size					)

							_UpperCAmelCase             =    None
							if self.use_attention_mask:
													_UpperCAmelCase             =    ids_tensor([self.batch_size, self.decoder_seq_length] ,					vocab_size=2					)

							_UpperCAmelCase             =    None
							if self.use_labels:
													_UpperCAmelCase             =    ids_tensor([self.batch_size, self.decoder_seq_length] ,					self.vocab_size					)

							_UpperCAmelCase             =    SpeechaTextaConfig(
							    vocab_size=self.vocab_size ,					d_model=self.d_model ,					decoder_layers=self.decoder_layers ,					decoder_ffn_dim=self.decoder_ffn_dim ,					decoder_attention_heads=self.decoder_attention_heads ,					eos_token_id=self.eos_token_id ,					bos_token_id=self.bos_token_id ,					use_cache=self.use_cache ,					pad_token_id=self.pad_token_id ,					decoder_start_token_id=self.decoder_start_token_id ,					max_position_embeddings=self.max_position_embeddings ,					)

							return (
							    config,
							    input_ids,
							    attention_mask,
							    lm_labels,
							)

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    True
							_UpperCAmelCase             =    SpeechaTextaDecoder(config=UpperCAmelCase					).to(UpperCAmelCase					).eval()
							_UpperCAmelCase             =    input_ids[:2]

							input_ids[input_ids == 0] += 1
							# first forward pass
							_UpperCAmelCase             =    model(UpperCAmelCase ,					use_cache=UpperCAmelCase					)
							_UpperCAmelCase             =    model(UpperCAmelCase					)
							_UpperCAmelCase             =    model(UpperCAmelCase ,					use_cache=UpperCAmelCase					)

							self.parent.assertTrue(len(UpperCAmelCase					) == len(UpperCAmelCase					)					)
							self.parent.assertTrue(len(UpperCAmelCase					) == len(UpperCAmelCase					) + 1					)

							_UpperCAmelCase             =    outputs['past_key_values']

							# create hypothetical next token and extent to next_input_ids
							_UpperCAmelCase             =    ids_tensor((2, 1) ,					config.vocab_size - 1					) + 1

							# append to next input_ids and
							_UpperCAmelCase             =    torch.cat([input_ids, next_tokens] ,					dim=-1					)

							print(UpperCAmelCase					)

							_UpperCAmelCase             =    model(UpperCAmelCase					)['last_hidden_state']
							_UpperCAmelCase             =    model(UpperCAmelCase ,					past_key_values=UpperCAmelCase					)['last_hidden_state']

							# select random slice
							_UpperCAmelCase             =    ids_tensor((1,) ,					output_from_past.shape[-1]					).item()
							_UpperCAmelCase             =    output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
							_UpperCAmelCase             =    output_from_past[:, 0, random_slice_idx].detach()

							# test that outputs are equal for slice
							assert torch.allclose(UpperCAmelCase ,					UpperCAmelCase ,					atol=1e-3					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.prepare_config_and_inputs()
							(
							    (
							    _UpperCAmelCase
							)      ,				(
							    _UpperCAmelCase
							)      ,				(
							    _UpperCAmelCase
							)      ,				(
							    _UpperCAmelCase
							)      ,				
							)             =    config_and_inputs

							_UpperCAmelCase             =    {
							    'input_ids': input_ids,
							    'attention_mask': attention_mask,
							}
							return config, inputs_dict





@require_torch
class __lowerCamelCase				(   snake_case__  , snake_case__  , snake_case__  , unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__			=   (SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
	UpperCamelCase__			=   (SpeechaTextaForCausalLM,) if is_torch_available() else ()
	UpperCamelCase__			=   {"text-generation": SpeechaTextaForCausalLM} if is_torch_available() else {}
	UpperCamelCase__			=   True
	UpperCamelCase__			=   False

	def  UpperCamelCase					(							self ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    SpeechaTextaStandaloneDecoderModelTester(self ,					is_training=UpperCAmelCase					)
							_UpperCAmelCase             =    ConfigTester(self ,					config_class=UpperCAmelCase					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							pass

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							pass

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							pass

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							self.config_tester.run_common_tests()

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_decoder_model_past(*UpperCAmelCase					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							return








from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


_a   			=						logging.get_logger(__name__)

_a   			=						{
    '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/config.json''',
    # See all M2M100 models at https://huggingface.co/models?filter=m2m_100
}





class __lowerCamelCase				(   snake_case__):





	"""simple docstring"""






	UpperCamelCase__			=   "m2m_100"
	UpperCamelCase__			=   ["past_key_values"]
	UpperCamelCase__			=   {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}

	def __init__(							self ,					UpperCAmelCase=12_8112 ,					UpperCAmelCase=1024 ,					UpperCAmelCase=12 ,					UpperCAmelCase=4096 ,					UpperCAmelCase=16 ,					UpperCAmelCase=12 ,					UpperCAmelCase=4096 ,					UpperCAmelCase=16 ,					UpperCAmelCase=0.05 ,					UpperCAmelCase=0.05 ,					UpperCAmelCase=True ,					UpperCAmelCase=True ,					UpperCAmelCase="relu" ,					UpperCAmelCase=1024 ,					UpperCAmelCase=0.1 ,					UpperCAmelCase=0.1 ,					UpperCAmelCase=0.0 ,					UpperCAmelCase=0.02 ,					UpperCAmelCase=2 ,					UpperCAmelCase=True ,					UpperCAmelCase=1 ,					UpperCAmelCase=0 ,					UpperCAmelCase=2 ,					**UpperCAmelCase ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    vocab_size
							_UpperCAmelCase             =    max_position_embeddings
							_UpperCAmelCase             =    d_model
							_UpperCAmelCase             =    encoder_ffn_dim
							_UpperCAmelCase             =    encoder_layers
							_UpperCAmelCase             =    encoder_attention_heads
							_UpperCAmelCase             =    decoder_ffn_dim
							_UpperCAmelCase             =    decoder_layers
							_UpperCAmelCase             =    decoder_attention_heads
							_UpperCAmelCase             =    dropout
							_UpperCAmelCase             =    attention_dropout
							_UpperCAmelCase             =    activation_dropout
							_UpperCAmelCase             =    activation_function
							_UpperCAmelCase             =    init_std
							_UpperCAmelCase             =    encoder_layerdrop
							_UpperCAmelCase             =    decoder_layerdrop
							_UpperCAmelCase             =    use_cache
							_UpperCAmelCase             =    encoder_layers
							_UpperCAmelCase             =    scale_embedding  # scale factor will be sqrt(d_model) if True

							super().__init__(
							    pad_token_id=UpperCAmelCase ,					bos_token_id=UpperCAmelCase ,					eos_token_id=UpperCAmelCase ,					is_encoder_decoder=UpperCAmelCase ,					decoder_start_token_id=UpperCAmelCase ,					**UpperCAmelCase ,					)





class __lowerCamelCase				(   snake_case__):





	"""simple docstring"""






	@property
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    OrderedDict(
							    [
							        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
							        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
							    ]					)

							if self.use_past:
													_UpperCAmelCase             =    {0: 'batch'}
													_UpperCAmelCase             =    {0: 'batch', 1: 'past_decoder_sequence + sequence'}
							else:
													_UpperCAmelCase             =    {0: 'batch', 1: 'decoder_sequence'}
													_UpperCAmelCase             =    {0: 'batch', 1: 'decoder_sequence'}

							if self.use_past:
													self.fill_with_past_key_values_(UpperCAmelCase ,					direction='inputs'					)
							return common_inputs

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase = -1 ,					UpperCAmelCase = -1 ,					UpperCAmelCase = False ,					UpperCAmelCase = None ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    compute_effective_axis_dimension(
							    UpperCAmelCase ,					fixed_dimension=OnnxConfig.default_fixed_batch ,					num_token_to_add=0					)

							# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
							_UpperCAmelCase             =    tokenizer.num_special_tokens_to_add(UpperCAmelCase					)
							_UpperCAmelCase             =    compute_effective_axis_dimension(
							    UpperCAmelCase ,					fixed_dimension=OnnxConfig.default_fixed_sequence ,					num_token_to_add=UpperCAmelCase					)

							# Generate dummy inputs according to compute batch and sequence
							_UpperCAmelCase             =    [' '.join([tokenizer.unk_token]					) * seq_length] * batch_size
							_UpperCAmelCase             =    dict(tokenizer(UpperCAmelCase ,					return_tensors=UpperCAmelCase					)					)
							return common_inputs

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase = -1 ,					UpperCAmelCase = -1 ,					UpperCAmelCase = False ,					UpperCAmelCase = None ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					)

							# Generate decoder inputs
							_UpperCAmelCase             =    seq_length if not self.use_past else 1
							_UpperCAmelCase             =    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					)
							_UpperCAmelCase             =    {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
							_UpperCAmelCase             =    dict(**UpperCAmelCase ,					**UpperCAmelCase					)

							if self.use_past:
													if not is_torch_available():
																			raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'					)
													else:
																			import torch
													_UpperCAmelCase      ,				_UpperCAmelCase             =    common_inputs['input_ids'].shape
													_UpperCAmelCase             =    common_inputs['decoder_input_ids'].shape[1]
													_UpperCAmelCase      ,				_UpperCAmelCase             =    self.num_attention_heads
													_UpperCAmelCase             =    (
													    batch,
													    num_encoder_attention_heads,
													    encoder_seq_length,
													    self._config.hidden_size // num_encoder_attention_heads,
													)
													_UpperCAmelCase             =    decoder_seq_length + 3
													_UpperCAmelCase             =    (
													    batch,
													    num_decoder_attention_heads,
													    decoder_past_length,
													    self._config.hidden_size // num_decoder_attention_heads,
													)

													_UpperCAmelCase             =    torch.cat(
													    [common_inputs['decoder_attention_mask'], torch.ones(UpperCAmelCase ,					UpperCAmelCase					)] ,					dim=1					)

													_UpperCAmelCase             =    []
													# If the number of encoder and decoder layers are present in the model configuration, both are considered
													_UpperCAmelCase      ,				_UpperCAmelCase             =    self.num_layers
													_UpperCAmelCase             =    min(UpperCAmelCase ,					UpperCAmelCase					)
													_UpperCAmelCase             =    max(UpperCAmelCase ,					UpperCAmelCase					) - min_num_layers
													_UpperCAmelCase             =    'encoder' if num_encoder_layers > num_decoder_layers else 'decoder'

													for _ in range(UpperCAmelCase					):
																			common_inputs["past_key_values"].append(
																			    (
																			        torch.zeros(UpperCAmelCase					),
																			        torch.zeros(UpperCAmelCase					),
																			        torch.zeros(UpperCAmelCase					),
																			        torch.zeros(UpperCAmelCase					),
																			    )					)
													# TODO: test this.
													_UpperCAmelCase             =    encoder_shape if remaining_side_name == 'encoder' else decoder_shape
													for _ in range(UpperCAmelCase ,					UpperCAmelCase					):
																			common_inputs["past_key_values"].append((torch.zeros(UpperCAmelCase					), torch.zeros(UpperCAmelCase					))					)
							return common_inputs

	UpperCamelCase__			=   _generate_dummy_inputs_for_default_and_seqaseq_lm
