






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

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


__A      =				logging.get_logger(__name__)

__A      =				{
    'Helsinki-NLP/opus-mt-en-de': 'https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json',
    # See all Marian models at https://huggingface.co/models?filter=marian
}





class 						SCREAMING_SNAKE_CASE				( snake_case					):





							"""simple docstring"""

							A_						  =					"marian"
							A_						  =					["past_key_values"]
							A_						  =					{"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}

							def __init__(  self:   Union[str, Any]		,     __A:   Any=5_81_01		,     __A:   Optional[Any]=None		,     __A:   List[str]=10_24		,     __A:   Any=12		,     __A:   Tuple=40_96		,     __A:   Union[str, Any]=16		,     __A:   Tuple=12		,     __A:   Optional[int]=40_96		,     __A:   List[Any]=16		,     __A:   Optional[Any]=0.0		,     __A:   Optional[Any]=0.0		,     __A:   Optional[int]=True		,     __A:   str=True		,     __A:   Tuple="gelu"		,     __A:   str=10_24		,     __A:   str=0.1		,     __A:   Dict=0.0		,     __A:   List[str]=0.0		,     __A:   List[Any]=0.02		,     __A:   int=5_81_00		,     __A:   Tuple=False		,     __A:   Optional[int]=5_81_00		,     __A:   int=0		,     __A:   Optional[int]=0		,     __A:   Optional[int]=True		,     **__A:   Dict		,     )    ->				Dict:
												_A								= vocab_size
												_A								= decoder_vocab_size or vocab_size
												_A								= max_position_embeddings
												_A								= d_model
												_A								= encoder_ffn_dim
												_A								= encoder_layers
												_A								= encoder_attention_heads
												_A								= decoder_ffn_dim
												_A								= decoder_layers
												_A								= decoder_attention_heads
												_A								= dropout
												_A								= attention_dropout
												_A								= activation_dropout
												_A								= activation_function
												_A								= init_std
												_A								= encoder_layerdrop
												_A								= decoder_layerdrop
												_A								= use_cache
												_A								= encoder_layers
												_A								= scale_embedding  # scale factor will be sqrt(d_model) if True
												_A								= share_encoder_decoder_embeddings
												super().__init__(
												    pad_token_id=__A		,     eos_token_id=__A		,     is_encoder_decoder=__A		,     decoder_start_token_id=__A		,     forced_eos_token_id=__A		,     **__A		,     )





class 						SCREAMING_SNAKE_CASE				( snake_case					):





							"""simple docstring"""

							@property
							# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
							def       __A (  self:   Any   )    ->				Mapping[str, Mapping[int, str]]:
												if self.task in ["default", "seq2seq-lm"]:
																	_A								= OrderedDict(
																	    [
																	        ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
																	        ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
																	    ]   )

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

																	if self.use_past:
																						self.fill_with_past_key_values_(__A		,     direction='''inputs'''   )
												elif self.task == "causal-lm":
																	# TODO: figure this case out.
																	_A								= OrderedDict(
																	    [
																	        ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
																	        ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
																	    ]   )
																	if self.use_past:
																						_A							,_A								= self.num_layers
																						for i in range(__A   ):
																											_A								= {0: '''batch''', 2: '''past_sequence + sequence'''}
																											_A								= {0: '''batch''', 2: '''past_sequence + sequence'''}
												else:
																	_A								= OrderedDict(
																	    [
																	        ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
																	        ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
																	        ('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}),
																	        ('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}),
																	    ]   )

												return common_inputs

							@property
							# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
							def       __A (  self:   int   )    ->				Mapping[str, Mapping[int, str]]:
												if self.task in ["default", "seq2seq-lm"]:
																	_A								= super().outputs
												else:
																	_A								= super(__A		,     self   ).outputs
																	if self.use_past:
																						_A							,_A								= self.num_layers
																						for i in range(__A   ):
																											_A								= {0: '''batch''', 2: '''past_sequence + sequence'''}
																											_A								= {0: '''batch''', 2: '''past_sequence + sequence'''}
												return common_outputs

							def       __A (  self:   Optional[Any]		,     __A:   PreTrainedTokenizer		,     __A:   int = -1		,     __A:   int = -1		,     __A:   bool = False		,     __A:   Optional[TensorType] = None		,     )    ->				Mapping[str, Any]:
												_A								= self._generate_dummy_inputs_for_encoder_and_decoder(
												    __A		,     __A		,     __A		,     __A		,     __A   )

												# Generate decoder inputs
												_A								= seq_length if not self.use_past else 1
												_A								= self._generate_dummy_inputs_for_encoder_and_decoder(
												    __A		,     __A		,     __A		,     __A		,     __A   )
												_A								= {f"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
												_A								= dict(**__A		,     **__A   )

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

																	_A								= torch.cat(
																	    [common_inputs['''decoder_attention_mask'''], torch.ones(__A		,     __A   )]		,     dim=1   )

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

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

							def       __A (  self:   List[str]		,     __A:   PreTrainedTokenizer		,     __A:   int = -1		,     __A:   int = -1		,     __A:   bool = False		,     __A:   Optional[TensorType] = None		,     )    ->				Mapping[str, Any]:
												_A								= self._generate_dummy_inputs_for_encoder_and_decoder(
												    __A		,     __A		,     __A		,     __A		,     __A   )

												if self.use_past:
																	if not is_torch_available():
																						raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.'''   )
																	else:
																						import torch
																	_A							,_A								= common_inputs['''input_ids'''].shape
																	# Not using the same length for past_key_values
																	_A								= seqlen + 2
																	_A							,_A								= self.num_layers
																	_A							,_A								= self.num_attention_heads
																	_A								= (
																	    batch,
																	    num_encoder_attention_heads,
																	    past_key_values_length,
																	    self._config.hidden_size // num_encoder_attention_heads,
																	)

																	_A								= common_inputs['''attention_mask'''].dtype
																	_A								= torch.cat(
																	    [common_inputs['''attention_mask'''], torch.ones(__A		,     __A		,     dtype=__A   )]		,     dim=1   )
																	_A								= [
																	    (torch.zeros(__A   ), torch.zeros(__A   )) for _ in range(__A   )
																	]
												return common_inputs

							def       __A (  self:   int		,     __A:   PreTrainedTokenizer		,     __A:   int = -1		,     __A:   int = -1		,     __A:   bool = False		,     __A:   Optional[TensorType] = None		,     )    ->				Mapping[str, Any]:
												# Copied from OnnxConfig.generate_dummy_inputs
												# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
												# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
												_A								= compute_effective_axis_dimension(
												    __A		,     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
												_A								= tokenizer.num_special_tokens_to_add(__A   )
												_A								= compute_effective_axis_dimension(
												    __A		,     fixed_dimension=OnnxConfig.default_fixed_sequence		,     num_token_to_add=__A   )

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

							def       __A (  self:   Union[str, Any]		,     __A:   PreTrainedTokenizer		,     __A:   int = -1		,     __A:   int = -1		,     __A:   bool = False		,     __A:   Optional[TensorType] = None		,     )    ->				Mapping[str, Any]:
												if self.task in ["default", "seq2seq-lm"]:
																	_A								= self._generate_dummy_inputs_for_default_and_seqaseq_lm(
																	    __A		,     batch_size=__A		,     seq_length=__A		,     is_pair=__A		,     framework=__A   )

												else:
																	_A								= self._generate_dummy_inputs_for_causal_lm(
																	    __A		,     batch_size=__A		,     seq_length=__A		,     is_pair=__A		,     framework=__A   )

												return common_inputs

							def       __A (  self:   Dict		,     __A:   Any		,     __A:   Any		,     __A:   Tuple		,     __A:   Dict   )    ->				Union[str, Any]:
												if self.task in ["default", "seq2seq-lm"]:
																	_A								= super()._flatten_past_key_values_(__A		,     __A		,     __A		,     __A   )
												else:
																	_A								= super(__A		,     self   )._flatten_past_key_values_(
																	    __A		,     __A		,     __A		,     __A   )



							@property
							def       __A (  self:   Any   )    ->				float:
												return 1e-4











import gc
import unittest

from transformers import CTRLConfig, 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 (
				    CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
				    CTRLForSequenceClassification,
				    CTRLLMHeadModel,
				    CTRLModel,
				)





class 						SCREAMING_SNAKE_CASE				:





							"""simple docstring"""

							def __init__(  self:   Tuple		,     __A:   Any		,     __A:   List[Any]=14		,     __A:   Dict=7		,     __A:   List[str]=True		,     __A:   Tuple=True		,     __A:   Union[str, Any]=True		,     __A:   List[Any]=True		,     __A:   Optional[int]=True		,     __A:   Tuple=99		,     __A:   Optional[Any]=32		,     __A:   List[str]=5		,     __A:   Dict=4		,     __A:   str=37		,     __A:   Dict="gelu"		,     __A:   List[str]=0.1		,     __A:   str=0.1		,     __A:   Any=5_12		,     __A:   Union[str, Any]=16		,     __A:   List[Any]=2		,     __A:   Tuple=0.02		,     __A:   Tuple=3		,     __A:   Union[str, Any]=4		,     __A:   Any=None		,     )    ->				Optional[Any]:
												_A								= parent
												_A								= batch_size
												_A								= seq_length
												_A								= is_training
												_A								= use_token_type_ids
												_A								= use_input_mask
												_A								= use_labels
												_A								= use_mc_token_ids
												_A								= vocab_size
												_A								= hidden_size
												_A								= num_hidden_layers
												_A								= num_attention_heads
												_A								= intermediate_size
												_A								= hidden_act
												_A								= hidden_dropout_prob
												_A								= attention_probs_dropout_prob
												_A								= max_position_embeddings
												_A								= type_vocab_size
												_A								= type_sequence_label_size
												_A								= initializer_range
												_A								= num_labels
												_A								= num_choices
												_A								= scope
												_A								= self.vocab_size - 1

							def       __A (  self:   Optional[int]   )    ->				Union[str, Any]:
												_A								= ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size   )

												_A								= None
												if self.use_input_mask:
																	_A								= random_attention_mask([self.batch_size, self.seq_length]   )

												_A								= None
												if self.use_token_type_ids:
																	_A								= ids_tensor([self.batch_size, self.seq_length]		,     self.type_vocab_size   )

												_A								= None
												if self.use_mc_token_ids:
																	_A								= ids_tensor([self.batch_size, self.num_choices]		,     self.seq_length   )

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

												_A								= self.get_config()

												_A								= ids_tensor([self.num_hidden_layers, self.num_attention_heads]		,     2   )

												return (
												    config,
												    input_ids,
												    input_mask,
												    head_mask,
												    token_type_ids,
												    mc_token_ids,
												    sequence_labels,
												    token_labels,
												    choice_labels,
												)

							def       __A (  self:   Optional[int]   )    ->				List[Any]:
												return CTRLConfig(
												    vocab_size=self.vocab_size		,     n_embd=self.hidden_size		,     n_layer=self.num_hidden_layers		,     n_head=self.num_attention_heads		,     n_positions=self.max_position_embeddings		,     pad_token_id=self.pad_token_id		,     )

							def       __A (  self:   Union[str, Any]		,     __A:   Union[str, Any]		,     __A:   Dict		,     __A:   Optional[int]		,     __A:   List[str]		,     __A:   List[str]		,     *__A:   Optional[int]   )    ->				Optional[Any]:
												_A								= CTRLModel(config=__A   )
												model.to(__A   )
												model.eval()

												model(__A		,     token_type_ids=__A		,     head_mask=__A   )
												model(__A		,     token_type_ids=__A   )
												_A								= model(__A   )
												self.parent.assertEqual(result.last_hidden_state.shape		,     (self.batch_size, self.seq_length, self.hidden_size)   )
												self.parent.assertEqual(len(result.past_key_values   )		,     config.n_layer   )

							def       __A (  self:   Optional[Any]		,     __A:   List[str]		,     __A:   Dict		,     __A:   List[Any]		,     __A:   List[Any]		,     __A:   Any		,     *__A:   Any   )    ->				str:
												_A								= CTRLLMHeadModel(__A   )
												model.to(__A   )
												model.eval()

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

							def       __A (  self:   Optional[int]   )    ->				Dict:
												_A								= self.prepare_config_and_inputs()

												(
												    (
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,
												)								= config_and_inputs

												_A								= {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}

												return config, inputs_dict



							def       __A (  self:   List[str]		,     __A:   Dict		,     __A:   Dict		,     __A:   Tuple		,     __A:   List[Any]		,     *__A:   Optional[int]   )    ->				Any:
												_A								= self.num_labels
												_A								= CTRLForSequenceClassification(__A   )
												model.to(__A   )
												model.eval()
												_A								= ids_tensor([self.batch_size]		,     self.type_sequence_label_size   )
												_A								= model(__A		,     token_type_ids=__A		,     labels=__A   )
												self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_labels)   )





@require_torch
class 						SCREAMING_SNAKE_CASE				( snake_case  ,	snake_case  ,	snake_case  ,	unittest.TestCase					):





							"""simple docstring"""

							A_						  =					(CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
							A_						  =					(CTRLLMHeadModel,) if is_torch_available() else ()
							A_						  =					(
							    {
							        "feature-extraction": CTRLModel,
							        "text-classification": CTRLForSequenceClassification,
							        "text-generation": CTRLLMHeadModel,
							        "zero-shot": CTRLForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							A_						  =					True
							A_						  =					False
							A_						  =					False

							def       __A (  self:   Any		,     __A:   List[Any]		,     __A:   int		,     __A:   Optional[Any]		,     __A:   Optional[int]		,     __A:   List[Any]   )    ->				List[str]:
												if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
																	# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
																	# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
																	# config could not be created.
																	return True

												return False

							def       __A (  self:   Any   )    ->				Union[str, Any]:
												_A								= CTRLModelTester(self   )
												_A								= ConfigTester(self		,     config_class=__A		,     n_embd=37   )

							def       __A (  self:   Optional[int]   )    ->				List[Any]:
												super().tearDown()
												# clean-up as much as possible GPU memory occupied by PyTorch
												gc.collect()
												torch.cuda.empty_cache()

							def       __A (  self:   Dict   )    ->				Any:
												self.config_tester.run_common_tests()

							def       __A (  self:   str   )    ->				Optional[Any]:
												_A								= self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_ctrl_model(*__A   )

							def       __A (  self:   List[str]   )    ->				Any:
												_A								= self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_lm_head_model(*__A   )

							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
							def       __A (  self:   Optional[Any]   )    ->				int:
												pass

							@slow
							def       __A (  self:   Tuple   )    ->				Dict:
												for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_A								= CTRLModel.from_pretrained(__A   )
																	self.assertIsNotNone(__A   )



							@unittest.skip('''The model doesn\'t support left padding'''   )  # and it's not used enough to be worth fixing :)
							def       __A (  self:   Any   )    ->				Union[str, Any]:
												pass





@require_torch
class 						SCREAMING_SNAKE_CASE				( unittest.TestCase					):





							"""simple docstring"""

							def       __A (  self:   int   )    ->				Union[str, Any]:
												super().tearDown()
												# clean-up as much as possible GPU memory occupied by PyTorch
												gc.collect()
												torch.cuda.empty_cache()



							@slow
							def       __A (  self:   Any   )    ->				Any:
												_A								= CTRLLMHeadModel.from_pretrained('''ctrl'''   )
												model.to(__A   )
												_A								= torch.tensor(
												    [[1_18_59, 0, 16_11, 8]]		,     dtype=torch.long		,     device=__A   )  # Legal the president is
												_A								= [
												    1_18_59,
												    0,
												    16_11,
												    8,
												    5,
												    1_50,
												    2_64_49,
												    2,
												    19,
												    3_48,
												    4_69,
												    3,
												    25_95,
												    48,
												    2_07_40,
												    24_65_33,
												    24_65_33,
												    19,
												    30,
												    5,
												]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

												_A								= model.generate(__A		,     do_sample=__A   )
												self.assertListEqual(output_ids[0].tolist()		,     __A   )



