

import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

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 import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
					from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder





def    __lowerCamelCase      (					UpperCamelCase__  ,				UpperCamelCase__  ,				UpperCamelCase__  ,				UpperCamelCase__=None  ,				UpperCamelCase__=None  ,				UpperCamelCase__=None  ,				UpperCamelCase__=None  ,				UpperCamelCase__=None  ,				):







							'''simple docstring'''






							if attention_mask is None:
														snake_case_     							=       input_ids.ne(config.pad_token_id )
							if decoder_attention_mask is None:
														snake_case_     							=       decoder_input_ids.ne(config.pad_token_id )
							if head_mask is None:
														snake_case_     							=       torch.ones(config.encoder_layers  ,				config.encoder_attention_heads  ,				device=UpperCamelCase__ )
							if decoder_head_mask is None:
														snake_case_     							=       torch.ones(config.decoder_layers  ,				config.decoder_attention_heads  ,				device=UpperCamelCase__ )
							if cross_attn_head_mask is None:
														snake_case_     							=       torch.ones(config.decoder_layers  ,				config.decoder_attention_heads  ,				device=UpperCamelCase__ )
							return {
							    "input_ids": input_ids,
							    "decoder_input_ids": decoder_input_ids,
							    "attention_mask": attention_mask,
							    "decoder_attention_mask": attention_mask,
							    "head_mask": head_mask,
							    "decoder_head_mask": decoder_head_mask,
							    "cross_attn_head_mask": cross_attn_head_mask,
							}







class 					lowercase							:




				def __init__(   self ,  snake_case ,  snake_case=13 ,  snake_case=7 ,  snake_case=True ,  snake_case=False ,  snake_case=99 ,  snake_case=16 ,  snake_case=2 ,  snake_case=4 ,  snake_case=4 ,  snake_case="relu" ,  snake_case=0.1 ,  snake_case=0.1 ,  snake_case=0.0 ,  snake_case=0.0 ,  snake_case=20 ,  snake_case=2 ,  snake_case=1 ,  snake_case=0 ,  ):
											snake_case_     							=       parent
											snake_case_     							=       batch_size
											snake_case_     							=       seq_length
											snake_case_     							=       is_training
											snake_case_     							=       use_labels
											snake_case_     							=       vocab_size
											snake_case_     							=       hidden_size
											snake_case_     							=       num_hidden_layers
											snake_case_     							=       num_attention_heads
											snake_case_     							=       intermediate_size
											snake_case_     							=       hidden_act
											snake_case_     							=       hidden_dropout_prob
											snake_case_     							=       attention_probs_dropout_prob
											snake_case_     							=       encoder_layerdrop
											snake_case_     							=       decoder_layerdrop
											snake_case_     							=       max_position_embeddings
											snake_case_     							=       eos_token_id
											snake_case_     							=       pad_token_id
											snake_case_     							=       bos_token_id




				def        a				(   self			):
											snake_case_     							=       ids_tensor([self.batch_size, self.seq_length] ,  self.vocab_size			)
											snake_case_     							=       self.eos_token_id  # Eos Token
											snake_case_     							=       ids_tensor([self.batch_size, self.seq_length] ,  self.vocab_size			)

											# we need to clamp the input ids here to avoid having pad token in between
											# this is because for M2M100 the position_ids are prepared such that
											# all pad tokens have pos id = 2 and rest are between 2..seq_length
											# and the seq_length here is seq_length - num_pad_tokens
											# but when using past, there is no way of knowing if the past input ids had
											# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
											# position_ids being off by num_pad_tokens in past input
											snake_case_     							=       input_ids.clamp(self.pad_token_id + 1			)
											snake_case_     							=       decoder_input_ids.clamp(self.pad_token_id + 1			)

											snake_case_     							=       self.get_config()
											snake_case_     							=       prepare_mam_aaa_inputs_dict(snake_case ,  snake_case ,  snake_case			)
											return config, inputs_dict




				def        a				(   self			):
											return MaMaaaConfig(
											    vocab_size=self.vocab_size ,  d_model=self.hidden_size ,  encoder_layers=self.num_hidden_layers ,  decoder_layers=self.num_hidden_layers ,  encoder_attention_heads=self.num_attention_heads ,  decoder_attention_heads=self.num_attention_heads ,  encoder_ffn_dim=self.intermediate_size ,  decoder_ffn_dim=self.intermediate_size ,  dropout=self.hidden_dropout_prob ,  attention_dropout=self.attention_probs_dropout_prob ,  encoder_layerdrop=self.encoder_layerdrop ,  decoder_layerdrop=self.decoder_layerdrop ,  max_position_embeddings=self.max_position_embeddings ,  eos_token_id=self.eos_token_id ,  bos_token_id=self.bos_token_id ,  pad_token_id=self.pad_token_id ,  )




				def        a				(   self			):
											snake_case_							,       snake_case_     							=       self.prepare_config_and_inputs()
											return config, inputs_dict




				def        a				(   self ,  snake_case ,  snake_case			):
											snake_case_     							=       MaMaaaModel(config=snake_case			).get_decoder().to(snake_case			).eval()
											snake_case_     							=       inputs_dict['input_ids']
											snake_case_     							=       inputs_dict['attention_mask']
											snake_case_     							=       inputs_dict['head_mask']

											# first forward pass
											snake_case_     							=       model(snake_case ,  attention_mask=snake_case ,  head_mask=snake_case ,  use_cache=snake_case			)

											snake_case_							,       snake_case_     							=       outputs.to_tuple()

											# create hypothetical multiple next token and extent to next_input_ids
											snake_case_     							=       ids_tensor((self.batch_size, 3) ,  config.vocab_size			)
											snake_case_     							=       ids_tensor((self.batch_size, 3) ,  2			)

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

											snake_case_     							=       model(snake_case ,  attention_mask=snake_case			)['last_hidden_state']
											snake_case_     							=       model(snake_case ,  attention_mask=snake_case ,  past_key_values=snake_case			)[
											    'last_hidden_state'
											]

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

											self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]			)

											# test that outputs are equal for slice
											self.parent.assertTrue(torch.allclose(snake_case ,  snake_case ,  atol=1e-2			)			)




				def        a				(   self ,  snake_case ,  snake_case			):
											snake_case_     							=       MaMaaaModel(config=snake_case			).to(snake_case			).eval()
											snake_case_     							=       model(**snake_case			)

											snake_case_     							=       outputs.encoder_last_hidden_state
											snake_case_     							=       outputs.last_hidden_state

											with tempfile.TemporaryDirectory() as tmpdirname:
																		snake_case_     							=       model.get_encoder()
																		encoder.save_pretrained(snake_case			)
																		snake_case_     							=       MaMaaaEncoder.from_pretrained(snake_case			).to(snake_case			)

											snake_case_     							=       encoder(inputs_dict['input_ids'] ,  attention_mask=inputs_dict['attention_mask']			)[
											    0
											]

											self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3			)

											with tempfile.TemporaryDirectory() as tmpdirname:
																		snake_case_     							=       model.get_decoder()
																		decoder.save_pretrained(snake_case			)
																		snake_case_     							=       MaMaaaDecoder.from_pretrained(snake_case			).to(snake_case			)

											snake_case_     							=       decoder(
											    input_ids=inputs_dict['decoder_input_ids'] ,  attention_mask=inputs_dict['decoder_attention_mask'] ,  encoder_hidden_states=snake_case ,  encoder_attention_mask=inputs_dict['attention_mask'] ,  )[0]

											self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3			)







@require_torch
class 					lowercase							(			lowercase_      ,    lowercase_      ,    lowercase_      ,    unittest.TestCase     ):
				__SCREAMING_SNAKE_CASE   :					Tuple			     =     (
				    (
				        MaMaaaModel,
				        MaMaaaForConditionalGeneration,
				    )
				    if is_torch_available()
				    else ()
				)
				__SCREAMING_SNAKE_CASE   :					Dict			     =     (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
				__SCREAMING_SNAKE_CASE   :					Dict			     =     (
				    {
				        '''conversational''': MaMaaaForConditionalGeneration,
				        '''feature-extraction''': MaMaaaModel,
				        '''summarization''': MaMaaaForConditionalGeneration,
				        '''text2text-generation''': MaMaaaForConditionalGeneration,
				        '''translation''': MaMaaaForConditionalGeneration,
				    }
				    if is_torch_available()
				    else {}
				)
				__SCREAMING_SNAKE_CASE   :					Dict			     =     True
				__SCREAMING_SNAKE_CASE   :					int			     =     True
				__SCREAMING_SNAKE_CASE   :					Dict			     =     False
				__SCREAMING_SNAKE_CASE   :					Dict			     =     False




				def        a				(   self ,  snake_case ,  snake_case ,  snake_case ,  snake_case ,  snake_case			):
											if pipeline_test_casse_name == "TranslationPipelineTests":
																		# Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
																		# `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
																		return True

											return False




				def        a				(   self			):
											snake_case_     							=       MaMaaaModelTester(self			)
											snake_case_     							=       ConfigTester(self ,  config_class=snake_case			)




				def        a				(   self			):
											self.config_tester.run_common_tests()




				def        a				(   self			):
											snake_case_							,       snake_case_     							=       self.model_tester.prepare_config_and_inputs()
											for model_class in self.all_model_classes:
																		snake_case_     							=       model_class(snake_case			)

																		with tempfile.TemporaryDirectory() as tmpdirname:
																									model.save_pretrained(snake_case			)
																									snake_case_							,       snake_case_     							=       model_class.from_pretrained(snake_case ,  output_loading_info=snake_case			)
																		self.assertEqual(info['missing_keys'] ,  []			)




				def        a				(   self			):
											snake_case_     							=       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_decoder_model_past_large_inputs(*snake_case			)




				def        a				(   self			):
											snake_case_     							=       self.model_tester.prepare_config_and_inputs_for_common()
											self.model_tester.check_encoder_decoder_model_standalone(*snake_case			)




				def        a				(   self			):
											snake_case_							,       snake_case_     							=       self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
																		snake_case_     							=       model_class(snake_case			)
																		model.to(snake_case			)
																		model.eval()

																		snake_case_     							=       copy.deepcopy(self._prepare_for_class(snake_case ,  snake_case			)			)

																		if not self.is_encoder_decoder:
																									snake_case_     							=       inputs['input_ids']
																									del inputs["input_ids"]
																		else:
																									snake_case_     							=       inputs['input_ids']
																									snake_case_     							=       inputs.get('decoder_input_ids' ,  snake_case			)
																									del inputs["input_ids"]
																									inputs.pop('decoder_input_ids' ,  snake_case			)

																		snake_case_     							=       model.get_input_embeddings()
																		if not self.is_encoder_decoder:
																									snake_case_     							=       wte(snake_case			)
																		else:
																									snake_case_     							=       wte(snake_case			)
																									snake_case_     							=       wte(snake_case			)

																		with torch.no_grad():
																									model(**snake_case			)[0]




				def        a				(   self			):
											snake_case_							,       snake_case_     							=       self.model_tester.prepare_config_and_inputs()
											snake_case_     							=       input_dict['input_ids']
											snake_case_     							=       input_ids.ne(1			).to(snake_case			)
											snake_case_     							=       MaMaaaForConditionalGeneration(snake_case			).eval().to(snake_case			)
											if torch_device == "cuda":
																		model.half()
											model.generate(snake_case ,  attention_mask=snake_case			)
											model.generate(num_beams=4 ,  do_sample=snake_case ,  early_stopping=snake_case ,  num_return_sequences=3			)





def    __lowerCamelCase      (					UpperCamelCase__ ):







							'''simple docstring'''






							return torch.tensor(UpperCamelCase__  ,				dtype=torch.long  ,				device=UpperCamelCase__ )


_UpperCAmelCase						:  Dict									=			1e-4







@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 					lowercase							(			unittest.TestCase     ):




				@cached_property
				def        a				(   self			):
											return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'			)




				def        a				(   self			):
											snake_case_     							=       MaMaaaModel.from_pretrained('facebook/m2m100_418M'			).to(snake_case			)
											snake_case_     							=       _long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]]			)
											snake_case_     							=       _long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]]			)
											snake_case_     							=       prepare_mam_aaa_inputs_dict(model.config ,  snake_case ,  snake_case			)
											with torch.no_grad():
																		snake_case_     							=       model(**snake_case			)[0]
											snake_case_     							=       torch.Size((1, 11, 1024)			)
											self.assertEqual(output.shape ,  snake_case			)
											# change to expected output here
											snake_case_     							=       torch.tensor(
											    [[-0.77_80, -0.16_76, 0.10_38], [-6.75_56, -1.39_92, 0.05_67], [-7.53_83, -0.59_20, -0.27_79]] ,  device=snake_case			)
											self.assertTrue(torch.allclose(output[:, :3, :3] ,  snake_case ,  atol=snake_case			)			)




				def        a				(   self			):
											snake_case_     							=       MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'			).to(snake_case			)

											# change to intended input
											snake_case_     							=       _long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]]			)
											snake_case_     							=       _long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]]			)
											snake_case_     							=       prepare_mam_aaa_inputs_dict(model.config ,  snake_case ,  snake_case			)
											with torch.no_grad():
																		snake_case_     							=       model(**snake_case			)[0]
											snake_case_     							=       torch.Size((1, 11, model.config.vocab_size)			)
											self.assertEqual(output.shape ,  snake_case			)
											# change to expected output here
											snake_case_     							=       torch.tensor(
											    [[-1.04_48, -1.04_11, 3.79_92], [-3.21_91, -3.23_86, -1.34_51], [-3.62_10, -3.59_93, 0.49_25]] ,  device=snake_case			)
											self.assertTrue(torch.allclose(output[:, :3, :3] ,  snake_case ,  atol=snake_case			)			)




				def        a				(   self			):
											snake_case_     							=       MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'			).to(snake_case			)
											snake_case_     							=       MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M' ,  src_lang='fr' ,  tgt_lang='en'			)

											snake_case_     							=       [
											    'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
											    'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
											    'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'
											    ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'
											    ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.',
											]

											# The below article tests that we don't add any hypotheses outside of the top n_beams
											snake_case_     							=       tokenizer(snake_case ,  padding=snake_case ,  return_tensors='pt'			)

											snake_case_     							=       model.generate(
											    input_ids=dct['input_ids'].to(snake_case			) ,  attention_mask=dct['attention_mask'].to(snake_case			) ,  num_beams=5 ,  forced_bos_token_id=tokenizer.get_lang_id('en'			) ,  )

											snake_case_     							=       [
											    'The NSA case highlights the total absence of intelligence debate',
											    'I think there are two levels of response from the French government.',
											    'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'
											    ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'
											    ' communications in France.',
											]

											snake_case_     							=       tokenizer.batch_decode(
											    hypotheses_batch.tolist() ,  clean_up_tokenization_spaces=snake_case ,  skip_special_tokens=snake_case			)
											assert generated == expected_en







import argparse
import struct
import unittest







class 					lowercase							:




				def __init__(   self ,  snake_case			):
											snake_case_     							=       data

											# Initialize hash values
											snake_case_     							=       [
											    0x6A09E667,
											    0xBB67AE85,
											    0x3C6EF372,
											    0xA54FF53A,
											    0x510E527F,
											    0x9B05688C,
											    0x1F83D9AB,
											    0x5BE0CD19,
											]

											# Initialize round constants
											snake_case_     							=       [
											    0x428A2F98,
											    0x71374491,
											    0xB5C0FBCF,
											    0xE9B5DBA5,
											    0x3956C25B,
											    0x59F111F1,
											    0x923F82A4,
											    0xAB1C5ED5,
											    0xD807AA98,
											    0x12835B01,
											    0x243185BE,
											    0x550C7DC3,
											    0x72BE5D74,
											    0x80DEB1FE,
											    0x9BDC06A7,
											    0xC19BF174,
											    0xE49B69C1,
											    0xEFBE4786,
											    0x0FC19DC6,
											    0x240CA1CC,
											    0x2DE92C6F,
											    0x4A7484AA,
											    0x5CB0A9DC,
											    0x76F988DA,
											    0x983E5152,
											    0xA831C66D,
											    0xB00327C8,
											    0xBF597FC7,
											    0xC6E00BF3,
											    0xD5A79147,
											    0x06CA6351,
											    0x14292967,
											    0x27B70A85,
											    0x2E1B2138,
											    0x4D2C6DFC,
											    0x53380D13,
											    0x650A7354,
											    0x766A0ABB,
											    0x81C2C92E,
											    0x92722C85,
											    0xA2BFE8A1,
											    0xA81A664B,
											    0xC24B8B70,
											    0xC76C51A3,
											    0xD192E819,
											    0xD6990624,
											    0xF40E3585,
											    0x106AA070,
											    0x19A4C116,
											    0x1E376C08,
											    0x2748774C,
											    0x34B0BCB5,
											    0x391C0CB3,
											    0x4ED8AA4A,
											    0x5B9CCA4F,
											    0x682E6FF3,
											    0x748F82EE,
											    0x78A5636F,
											    0x84C87814,
											    0x8CC70208,
											    0x90BEFFFA,
											    0xA4506CEB,
											    0xBEF9A3F7,
											    0xC67178F2,
											]

											snake_case_     							=       self.preprocessing(self.data			)
											self.final_hash()




				@staticmethod
				def        a				(   snake_case			):
											snake_case_     							=       b'\x80' + (b'\x00' * (63 - (len(snake_case			) + 8) % 64))
											snake_case_     							=       struct.pack('>Q' ,  (len(snake_case			) * 8)			)
											return data + padding + big_endian_integer




				def        a				(   self			):
											# Convert into blocks of 64 bytes
											snake_case_     							=       [
											    self.preprocessed_data[x : x + 64]
											    for x in range(0 ,  len(self.preprocessed_data			) ,  64			)
											]

											for block in self.blocks:
																		# Convert the given block into a list of 4 byte integers
																		snake_case_     							=       list(struct.unpack('>16L' ,  snake_case			)			)
																		# add 48 0-ed integers
																		words += [0] * 48

																		snake_case_							,       snake_case_							,       snake_case_							,       snake_case_							,       snake_case_							,       snake_case_							,       snake_case_							,       snake_case_     							=       self.hashes

																		for index in range(0 ,  64			):
																									if index > 15:
																																# modify the zero-ed indexes at the end of the array
																																snake_case_     							=       (
																																    self.ror(words[index - 15] ,  7			)
																																    ^ self.ror(words[index - 15] ,  18			)
																																    ^ (words[index - 15] >> 3)
																																)
																																snake_case_     							=       (
																																    self.ror(words[index - 2] ,  17			)
																																    ^ self.ror(words[index - 2] ,  19			)
																																    ^ (words[index - 2] >> 10)
																																)

																																snake_case_     							=       (
																																    words[index - 16] + sa + words[index - 7] + sa
																																) % 0x100000000

																									# Compression
																									snake_case_     							=       self.ror(snake_case ,  6			) ^ self.ror(snake_case ,  11			) ^ self.ror(snake_case ,  25			)
																									snake_case_     							=       (e & f) ^ ((~e & 0xFFFFFFFF) & g)
																									snake_case_     							=       (
																									    h + sa + ch + self.round_constants[index] + words[index]
																									) % 0x100000000
																									snake_case_     							=       self.ror(snake_case ,  2			) ^ self.ror(snake_case ,  13			) ^ self.ror(snake_case ,  22			)
																									snake_case_     							=       (a & b) ^ (a & c) ^ (b & c)
																									snake_case_     							=       (sa + maj) % 0x100000000

																									snake_case_							,       snake_case_							,       snake_case_							,       snake_case_							,       snake_case_							,       snake_case_							,       snake_case_							,       snake_case_     							=       (
																									    g,
																									    f,
																									    e,
																									    ((d + tempa) % 0x100000000),
																									    c,
																									    b,
																									    a,
																									    ((tempa + tempa) % 0x100000000),
																									)

																		snake_case_     							=       [a, b, c, d, e, f, g, h]

																		# Modify final values
																		snake_case_     							=       [
																		    ((element + mutated_hash_values[index]) % 0x100000000)
																		    for index, element in enumerate(self.hashes			)
																		]

											snake_case_     							=       ''.join([hex(snake_case			)[2:].zfill(8			) for value in self.hashes]			)




				def        a				(   self ,  snake_case ,  snake_case			):
											return 0xFFFFFFFF & (value << (32 - rotations)) | (value >> rotations)







class 					lowercase							(			unittest.TestCase     ):




				def        a				(   self			):
											import hashlib

											snake_case_     							=       bytes('Test String' ,  'utf-8'			)
											self.assertEqual(SHAaaa(snake_case			).hash ,  hashlib.shaaaa(snake_case			).hexdigest()			)





def    __lowerCamelCase      (					):







							'''simple docstring'''






							import doctest

							doctest.testmod()

							snake_case_     							=       argparse.ArgumentParser()
							parser.add_argument(
							    '-s'  ,				'--string'  ,				dest='input_string'  ,				default='Hello World!! Welcome to Cryptography'  ,				help='Hash the string'  ,				)
							parser.add_argument(
							    '-f'  ,				'--file'  ,				dest='input_file'  ,				help='Hash contents of a file' )

							snake_case_     							=       parser.parse_args()

							snake_case_     							=       args.input_string

							# hash input should be a bytestring
							if args.input_file:
														with open(args.input_file  ,				'rb' ) as f:
																					snake_case_     							=       f.read()
							else:
														snake_case_     							=       bytes(UpperCamelCase__  ,				'utf-8' )

							print(SHAaaa(UpperCamelCase__ ).hash )


if __name__ == "__main__":
					main()




