

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 			snake_case__				(   lowerCAmelCase_,    lowerCAmelCase_,    lowerCAmelCase_,    lowerCAmelCase_=None,    lowerCAmelCase_=None,    lowerCAmelCase_=None,    lowerCAmelCase_=None,    lowerCAmelCase_=None,    ):





     """simple docstring"""







     if attention_mask is None:
          SCREAMING_SNAKE_CASE      						=input_ids.ne(config.pad_token_id			)
     if decoder_attention_mask is None:
          SCREAMING_SNAKE_CASE      						=decoder_input_ids.ne(config.pad_token_id			)
     if head_mask is None:
          SCREAMING_SNAKE_CASE      						=torch.ones(config.encoder_layers,    config.encoder_attention_heads,    device=_lowerCamelCase			)
     if decoder_head_mask is None:
          SCREAMING_SNAKE_CASE      						=torch.ones(config.decoder_layers,    config.decoder_attention_heads,    device=_lowerCamelCase			)
     if cross_attn_head_mask is None:
          SCREAMING_SNAKE_CASE      						=torch.ones(config.decoder_layers,    config.decoder_attention_heads,    device=_lowerCamelCase			)
     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 		a_       :



      """simple docstring"""







      def __init__(      self     :							Union[str, Any]			,snake_case     :							Optional[Any]			,snake_case     :							int=13			,snake_case     :							str=7			,snake_case     :							Optional[int]=True			,snake_case     :							Optional[int]=False			,snake_case     :							int=99			,snake_case     :							Dict=16			,snake_case     :							Any=2			,snake_case     :							Dict=4			,snake_case     :							Union[str, Any]=4			,snake_case     :							List[str]="relu"			,snake_case     :							List[Any]=0.1			,snake_case     :							List[Any]=0.1			,snake_case     :							List[Any]=0.0			,snake_case     :							Dict=0.0			,snake_case     :							Optional[int]=20			,snake_case     :							Any=2			,snake_case     :							Any=1			,snake_case     :							Dict=0			,):
           SCREAMING_SNAKE_CASE      						=parent
           SCREAMING_SNAKE_CASE      						=batch_size
           SCREAMING_SNAKE_CASE      						=seq_length
           SCREAMING_SNAKE_CASE      						=is_training
           SCREAMING_SNAKE_CASE      						=use_labels
           SCREAMING_SNAKE_CASE      						=vocab_size
           SCREAMING_SNAKE_CASE      						=hidden_size
           SCREAMING_SNAKE_CASE      						=num_hidden_layers
           SCREAMING_SNAKE_CASE      						=num_attention_heads
           SCREAMING_SNAKE_CASE      						=intermediate_size
           SCREAMING_SNAKE_CASE      						=hidden_act
           SCREAMING_SNAKE_CASE      						=hidden_dropout_prob
           SCREAMING_SNAKE_CASE      						=attention_probs_dropout_prob
           SCREAMING_SNAKE_CASE      						=encoder_layerdrop
           SCREAMING_SNAKE_CASE      						=decoder_layerdrop
           SCREAMING_SNAKE_CASE      						=max_position_embeddings
           SCREAMING_SNAKE_CASE      						=eos_token_id
           SCREAMING_SNAKE_CASE      						=pad_token_id
           SCREAMING_SNAKE_CASE      						=bos_token_id
      def        _lowerCAmelCase     (      self     :							int				):
           SCREAMING_SNAKE_CASE      						=ids_tensor([self.batch_size, self.seq_length]			,self.vocab_size				)
           SCREAMING_SNAKE_CASE      						=self.eos_token_id  # Eos Token
           SCREAMING_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
           SCREAMING_SNAKE_CASE      						=input_ids.clamp(self.pad_token_id + 1				)
           SCREAMING_SNAKE_CASE      						=decoder_input_ids.clamp(self.pad_token_id + 1				)

           SCREAMING_SNAKE_CASE      						=self.get_config()
           SCREAMING_SNAKE_CASE      						=prepare_mam_aaa_inputs_dict(a__			,a__			,a__				)
           return config, inputs_dict
      def        _lowerCAmelCase     (      self     :							str				):
           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        _lowerCAmelCase     (      self     :							Union[str, Any]				):
           SCREAMING_SNAKE_CASE      						=self.prepare_config_and_inputs()
           return config, inputs_dict
      def        _lowerCAmelCase     (      self     :							List[Any]			,snake_case     :							int			,snake_case     :							Tuple				):
           SCREAMING_SNAKE_CASE      						=MaMaaaModel(config=a__				).get_decoder().to(a__				).eval()
           SCREAMING_SNAKE_CASE      						=inputs_dict["""input_ids"""]
           SCREAMING_SNAKE_CASE      						=inputs_dict["""attention_mask"""]
           SCREAMING_SNAKE_CASE      						=inputs_dict["""head_mask"""]

           # first forward pass
           SCREAMING_SNAKE_CASE      						=model(a__			,attention_mask=a__			,head_mask=a__			,use_cache=a__				)

           SCREAMING_SNAKE_CASE      						=outputs.to_tuple()

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

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

           SCREAMING_SNAKE_CASE      						=model(a__			,attention_mask=a__				)["""last_hidden_state"""]
           SCREAMING_SNAKE_CASE      						=model(a__			,attention_mask=a__			,past_key_values=a__				)[
               """last_hidden_state"""
           ]

           # select random slice
           SCREAMING_SNAKE_CASE      						=ids_tensor((1,)			,output_from_past.shape[-1]				).item()
           SCREAMING_SNAKE_CASE      						=output_from_no_past[:, -3:, random_slice_idx].detach()
           SCREAMING_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(a__			,a__			,atol=1e-2				)				)


      def        _lowerCAmelCase     (      self     :							Optional[Any]			,snake_case     :							Tuple			,snake_case     :							Optional[int]				):
           SCREAMING_SNAKE_CASE      						=MaMaaaModel(config=a__				).to(a__				).eval()
           SCREAMING_SNAKE_CASE      						=model(**a__				)

           SCREAMING_SNAKE_CASE      						=outputs.encoder_last_hidden_state
           SCREAMING_SNAKE_CASE      						=outputs.last_hidden_state

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

           SCREAMING_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:
                SCREAMING_SNAKE_CASE      						=model.get_decoder()
                decoder.save_pretrained(a__				)
                SCREAMING_SNAKE_CASE      						=MaMaaaDecoder.from_pretrained(a__				).to(a__				)

           SCREAMING_SNAKE_CASE      						=decoder(
               input_ids=inputs_dict['decoder_input_ids']			,attention_mask=inputs_dict['decoder_attention_mask']			,encoder_hidden_states=a__			,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 		a_       (							SCREAMING_SNAKE_CASE_ ,			SCREAMING_SNAKE_CASE_ ,			SCREAMING_SNAKE_CASE_ ,			unittest.TestCase     ):



      """simple docstring"""







      __UpperCAmelCase					=      (
          (
              MaMaaaModel,
              MaMaaaForConditionalGeneration,
          )
          if is_torch_available()
          else ()
      )
      __UpperCAmelCase					=      (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
      __UpperCAmelCase					=      (
          {
              "conversational": MaMaaaForConditionalGeneration,
              "feature-extraction": MaMaaaModel,
              "summarization": MaMaaaForConditionalGeneration,
              "text2text-generation": MaMaaaForConditionalGeneration,
              "translation": MaMaaaForConditionalGeneration,
          }
          if is_torch_available()
          else {}
      )
      __UpperCAmelCase					=      True
      __UpperCAmelCase					=      True
      __UpperCAmelCase					=      False
      __UpperCAmelCase					=      False
      def        _lowerCAmelCase     (      self     :							Optional[Any]			,snake_case     :							Dict			,snake_case     :							Union[str, Any]			,snake_case     :							Dict			,snake_case     :							Optional[int]			,snake_case     :							Tuple				):
           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        _lowerCAmelCase     (      self     :							List[Any]				):
           SCREAMING_SNAKE_CASE      						=MaMaaaModelTester(self				)
           SCREAMING_SNAKE_CASE      						=ConfigTester(self			,config_class=a__				)
      def        _lowerCAmelCase     (      self     :							List[str]				):
           self.config_tester.run_common_tests()
      def        _lowerCAmelCase     (      self     :							List[str]				):
           SCREAMING_SNAKE_CASE      						=self.model_tester.prepare_config_and_inputs()
           for model_class in self.all_model_classes:
                SCREAMING_SNAKE_CASE      						=model_class(a__				)

                with tempfile.TemporaryDirectory() as tmpdirname:
                     model.save_pretrained(a__				)
                     SCREAMING_SNAKE_CASE      						=model_class.from_pretrained(a__			,output_loading_info=a__				)
                self.assertEqual(info['missing_keys']			,[]				)
      def        _lowerCAmelCase     (      self     :							Tuple				):
           SCREAMING_SNAKE_CASE      						=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_decoder_model_past_large_inputs(*a__				)
      def        _lowerCAmelCase     (      self     :							str				):
           SCREAMING_SNAKE_CASE      						=self.model_tester.prepare_config_and_inputs_for_common()
           self.model_tester.check_encoder_decoder_model_standalone(*a__				)
      def        _lowerCAmelCase     (      self     :							Tuple				):
           SCREAMING_SNAKE_CASE      						=self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
                SCREAMING_SNAKE_CASE      						=model_class(a__				)
                model.to(a__				)
                model.eval()

                SCREAMING_SNAKE_CASE      						=copy.deepcopy(self._prepare_for_class(a__			,a__				)				)

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

                SCREAMING_SNAKE_CASE      						=model.get_input_embeddings()
                if not self.is_encoder_decoder:
                     SCREAMING_SNAKE_CASE      						=wte(a__				)
                else:
                     SCREAMING_SNAKE_CASE      						=wte(a__				)
                     SCREAMING_SNAKE_CASE      						=wte(a__				)

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


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







def 			snake_case__				(   lowerCAmelCase_			):





     """simple docstring"""







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


_lowerCamelCase							       =1e-4



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



      """simple docstring"""







      @cached_property
      def        _lowerCAmelCase     (      self     :							Optional[Any]				):
           return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'				)
      def        _lowerCAmelCase     (      self     :							Optional[Any]				):
           SCREAMING_SNAKE_CASE      						=MaMaaaModel.from_pretrained('facebook/m2m100_418M'				).to(a__				)
           SCREAMING_SNAKE_CASE      						=_long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]				)
           SCREAMING_SNAKE_CASE      						=_long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]				)
           SCREAMING_SNAKE_CASE      						=prepare_mam_aaa_inputs_dict(model.config			,a__			,a__				)
           with torch.no_grad():
                SCREAMING_SNAKE_CASE      						=model(**a__				)[0]
           SCREAMING_SNAKE_CASE      						=torch.Size((1, 11, 1024)				)
           self.assertEqual(output.shape			,a__				)
           # change to expected output here
           SCREAMING_SNAKE_CASE      						=torch.tensor(
               [[-0.7_780, -0.1_676, 0.1_038], [-6.7_556, -1.3_992, 0.0_567], [-7.5_383, -0.5_920, -0.2_779]]			,device=a__				)
           self.assertTrue(torch.allclose(output[:, :3, :3]			,a__			,atol=a__				)				)
      def        _lowerCAmelCase     (      self     :							List[str]				):
           SCREAMING_SNAKE_CASE      						=MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'				).to(a__				)

           # change to intended input
           SCREAMING_SNAKE_CASE      						=_long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]				)
           SCREAMING_SNAKE_CASE      						=_long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]				)
           SCREAMING_SNAKE_CASE      						=prepare_mam_aaa_inputs_dict(model.config			,a__			,a__				)
           with torch.no_grad():
                SCREAMING_SNAKE_CASE      						=model(**a__				)[0]
           SCREAMING_SNAKE_CASE      						=torch.Size((1, 11, model.config.vocab_size)				)
           self.assertEqual(output.shape			,a__				)
           # change to expected output here
           SCREAMING_SNAKE_CASE      						=torch.tensor(
               [[-1.0_448, -1.0_411, 3.7_992], [-3.2_191, -3.2_386, -1.3_451], [-3.6_210, -3.5_993, 0.4_925]]			,device=a__				)
           self.assertTrue(torch.allclose(output[:, :3, :3]			,a__			,atol=a__				)				)


      def        _lowerCAmelCase     (      self     :							str				):
           SCREAMING_SNAKE_CASE      						=MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'				).to(a__				)
           SCREAMING_SNAKE_CASE      						=MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'			,src_lang='fr'			,tgt_lang='en'				)

           SCREAMING_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
           SCREAMING_SNAKE_CASE      						=tokenizer(a__			,padding=a__			,return_tensors='pt'				)

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

           SCREAMING_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.""",
           ]

           SCREAMING_SNAKE_CASE      						=tokenizer.batch_decode(
               hypotheses_batch.tolist()			,clean_up_tokenization_spaces=a__			,skip_special_tokens=a__				)
           assert generated == expected_en


"""simple docstring"""




# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re

from ..models.auto import AutoProcessor
from ..models.vision_encoder_decoder import VisionEncoderDecoderModel
from ..utils import is_vision_available
from .base import PipelineTool


if is_vision_available():
     from PIL import Image
class 						__A							( SCREAMING_SNAKE_CASE_		):
     _UpperCamelCase							:			Optional[Any]							=		"naver-clova-ix/donut-base-finetuned-docvqa"
     _UpperCamelCase							:			Dict							=		(
         "This is a tool that answers a question about an document (pdf). It takes an input named `document` which "
         "should be the document containing the information, as well as a `question` that is the question about the "
         "document. It returns a text that contains the answer to the question."
     )
     _UpperCamelCase							:			Optional[int]							=		"document_qa"
     _UpperCamelCase							:			Any							=		AutoProcessor
     _UpperCamelCase							:			Union[str, Any]							=		VisionEncoderDecoderModel

     _UpperCamelCase							:			Union[str, Any]							=		["image", "text"]
     _UpperCamelCase							:			List[str]							=		["text"]






     def __init__(		self				,     *a__				,     **a__  ):
       if not is_vision_available():
         raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool."""  )

       super().__init__(*a__				,     **a__  )






     def     __A  (		self				,     a__				,     a__  ):
       _lowerCAmelCase						:       Optional[int]  			=     """<s_docvqa><s_question>{user_input}</s_question><s_answer>"""
       _lowerCAmelCase						:       Dict  			=     task_prompt.replace("""{user_input}"""				,     a__  )
       _lowerCAmelCase						:       str  			=     self.pre_processor.tokenizer(
           a__				,     add_special_tokens=a__				,     return_tensors="""pt"""  ).input_ids
       _lowerCAmelCase						:       Dict  			=     self.pre_processor(a__				,     return_tensors="""pt"""  ).pixel_values

       return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values}






     def     __A  (		self				,     a__  ):
       return self.model.generate(
           inputs["""pixel_values"""].to(self.device  )				,     decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device  )				,     max_length=self.model.decoder.config.max_position_embeddings				,     early_stopping=a__				,     pad_token_id=self.pre_processor.tokenizer.pad_token_id				,     eos_token_id=self.pre_processor.tokenizer.eos_token_id				,     use_cache=a__				,     num_beams=1				,     bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]]				,     return_dict_in_generate=a__				,     ).sequences






     def     __A  (		self				,     a__  ):
       _lowerCAmelCase						:       Tuple  			=     self.pre_processor.batch_decode(a__  )[0]
       _lowerCAmelCase						:       int  			=     sequence.replace(self.pre_processor.tokenizer.eos_token				,     """"""  )
       _lowerCAmelCase						:       List[str]  			=     sequence.replace(self.pre_processor.tokenizer.pad_token				,     """"""  )
       _lowerCAmelCase						:       List[str]  			=     re.sub(r"""<.*?>"""				,     """"""				,     a__				,     count=1  ).strip()  # remove first task start token
       _lowerCAmelCase						:       List[str]  			=     self.pre_processor.tokenajson(a__  )

       return sequence["answer"]




