

import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from ....modeling_outputs import BaseModelOutputWithPooling, SequenceClassifierOutput
from ....modeling_utils import ModuleUtilsMixin
from ....utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings


lowerCamelCase									= logging.get_logger(__name__)

lowerCamelCase									= """MMBTConfig"""







class 						__magic_name__      (							nn.Module							):

   '''simple docstring'''




   def __init__(    self,   lowercase_,   lowercase_,   lowercase_	)							->   int:






     """simple docstring"""






     super().__init__()
     a__  =config
     a__  =encoder
     a__  =nn.Linear(config.modal_hidden_size,   config.hidden_size	)
     a__  =embeddings.position_embeddings
     a__  =embeddings.token_type_embeddings
     a__  =embeddings.word_embeddings
     a__  =embeddings.LayerNorm
     a__  =nn.Dropout(p=config.hidden_dropout_prob	)



   def 			_UpperCAmelCase			(    self,   lowercase_,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None	)							->   Optional[int]:






     """simple docstring"""






     a__  =self.proj_embeddings(self.encoder(lowerCAmelCase__	)	)
     a__  =token_embeddings.size(1	)

     if start_token is not None:
       a__  =self.word_embeddings(lowerCAmelCase__	)
       seq_length += 1
       a__  =torch.cat([start_token_embeds.unsqueeze(1	), token_embeddings],   dim=1	)

     if end_token is not None:
       a__  =self.word_embeddings(lowerCAmelCase__	)
       seq_length += 1
       a__  =torch.cat([token_embeddings, end_token_embeds.unsqueeze(1	)],   dim=1	)

     if position_ids is None:
       a__  =torch.arange(lowerCAmelCase__,   dtype=torch.long,   device=input_modal.device	)
       a__  =position_ids.unsqueeze(0	).expand(input_modal.size(0	),   lowerCAmelCase__	)

     if token_type_ids is None:
       a__  =torch.zeros(
           (input_modal.size(0	), seq_length),   dtype=torch.long,   device=input_modal.device	)

     a__  =self.position_embeddings(lowerCAmelCase__	)
     a__  =self.token_type_embeddings(lowerCAmelCase__	)
     a__  =token_embeddings + position_embeddings + token_type_embeddings
     a__  =self.LayerNorm(lowerCAmelCase__	)
     a__  =self.dropout(lowerCAmelCase__	)
     return embeddings





lowerCamelCase									= r"""
    MMBT model was proposed in [Supervised Multimodal Bitransformers for Classifying Images and
    Text](https://github.com/facebookresearch/mmbt) by Douwe Kiela, Suvrat Bhooshan, Hamed Firooz, Davide Testuggine.
    It's a supervised multimodal bitransformer model that fuses information from text and other image encoders, and
    obtain state-of-the-art performance on various multimodal classification benchmark tasks.

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`MMBTConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration.
        transformer (`nn.Module`): A text transformer that is used by MMBT.
            It should have embeddings, encoder, and pooler attributes.
        encoder (`nn.Module`): Encoder for the second modality.
            It should take in a batch of modal inputs and return k, n dimension embeddings.
"""

lowerCamelCase									= r"""
    Args:
        input_modal (`torch.FloatTensor` of shape `(batch_size, ***)`):
            The other modality data. It will be the shape that the encoder for that type expects. e.g. With an Image
            Encoder, the shape would be (batch_size, channels, height, width)
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. It does not expect [CLS] token to be added as it's
            appended to the end of other modality embeddings. Indices can be obtained using [`AutoTokenizer`]. See
            [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        modal_start_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Optional start token to be added to Other Modality Embedding. [CLS] Most commonly used for classification
            tasks.
        modal_end_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Optional end token to be added to Other Modality Embedding. [SEP] Most commonly used.
        attention_mask (*optional*) `torch.FloatTensor` of shape `(batch_size, sequence_length)`:
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, sequence_length)`:
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        modal_token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, modal_sequence_length)`:
            Segment token indices to indicate different portions of the non-text modality. The embeddings from these
            tokens will be summed with the respective token embeddings for the non-text modality.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        modal_position_ids (`torch.LongTensor` of shape `(batch_size, modal_sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings for the non-text modality.
            Selected in the range `[0, config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, embedding_dim)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""







@add_start_docstrings(
    'The bare MMBT Model outputting raw hidden-states without any specific head on top.'		,	_UpperCAmelCase		,	)
class 						__magic_name__      (							nn.Module		,	_UpperCAmelCase							):

   '''simple docstring'''




   def __init__(    self,   lowercase_,   lowercase_,   lowercase_	)							->   Optional[int]:






     """simple docstring"""






     super().__init__()
     a__  =config
     a__  =transformer
     a__  =ModalEmbeddings(lowerCAmelCase__,   lowerCAmelCase__,   transformer.embeddings	)



   @add_start_docstrings_to_model_forward(lowerCAmelCase__	)
   @replace_return_docstrings(output_type=lowerCAmelCase__,   config_class=_CONFIG_FOR_DOC	)
   def 			_UpperCAmelCase			(    self,   lowercase_,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   )							->   Optional[Any]:






     """simple docstring"""






     a__  =output_attentions if output_attentions is not None else self.config.output_attentions
     a__  =(
         output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
     )
     a__  =return_dict if return_dict is not None else self.config.use_return_dict

     if input_ids is not None and inputs_embeds is not None:
       raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time'''	)
     elif input_ids is not None:
       a__  =input_ids.size()
     elif inputs_embeds is not None:
       a__  =inputs_embeds.size()[:-1]
     else:
       raise ValueError('''You have to specify either input_ids or inputs_embeds'''	)

     a__  =input_ids.device if input_ids is not None else inputs_embeds.device

     a__  =self.modal_encoder(
         lowerCAmelCase__,   start_token=lowerCAmelCase__,   end_token=lowerCAmelCase__,   position_ids=lowerCAmelCase__,   token_type_ids=lowerCAmelCase__,   )

     a__  =modal_embeddings.size()[:-1]

     if token_type_ids is None:
       a__  =torch.ones(lowerCAmelCase__,   dtype=torch.long,   device=lowerCAmelCase__	)

     a__  =self.transformer.embeddings(
         input_ids=lowerCAmelCase__,   position_ids=lowerCAmelCase__,   token_type_ids=lowerCAmelCase__,   inputs_embeds=lowerCAmelCase__	)

     a__  =torch.cat([modal_embeddings, txt_embeddings],   1	)

     a__  =embedding_output.size()[:-1]

     if attention_mask is None:
       a__  =torch.ones(lowerCAmelCase__,   device=lowerCAmelCase__	)
     else:
       a__  =torch.cat(
           [torch.ones(lowerCAmelCase__,   device=lowerCAmelCase__,   dtype=torch.long	), attention_mask],   dim=1	)
     if encoder_attention_mask is None:
       a__  =torch.ones(lowerCAmelCase__,   device=lowerCAmelCase__	)
     else:
       a__  =torch.cat(
           [torch.ones(lowerCAmelCase__,   device=lowerCAmelCase__	), encoder_attention_mask],   dim=1	)

     a__  =self.get_extended_attention_mask(lowerCAmelCase__,   lowerCAmelCase__	)
     a__  =self.invert_attention_mask(lowerCAmelCase__	)
     a__  =self.get_head_mask(lowerCAmelCase__,   self.config.num_hidden_layers	)

     a__  =self.transformer.encoder(
         lowerCAmelCase__,   attention_mask=lowerCAmelCase__,   head_mask=lowerCAmelCase__,   encoder_hidden_states=lowerCAmelCase__,   encoder_attention_mask=lowerCAmelCase__,   output_attentions=lowerCAmelCase__,   output_hidden_states=lowerCAmelCase__,   return_dict=lowerCAmelCase__,   )

     a__  =encoder_outputs[0]
     a__  =self.transformer.pooler(lowerCAmelCase__	)

     if not return_dict:
       return (sequence_output, pooled_output) + encoder_outputs[1:]

     return BaseModelOutputWithPooling(
         last_hidden_state=lowerCAmelCase__,   pooler_output=lowerCAmelCase__,   hidden_states=encoder_outputs.hidden_states,   attentions=encoder_outputs.attentions,   )



   def 			_UpperCAmelCase			(    self	)							->   Any:






     """simple docstring"""






     return self.embeddings.word_embeddings



   def 			_UpperCAmelCase			(    self,   lowercase_	)							->   Optional[Any]:






     """simple docstring"""






     a__  =value







@add_start_docstrings(
    '\n    MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n    '		,	_UpperCAmelCase		,	_UpperCAmelCase		,	)
class 						__magic_name__      (							nn.Module							):

   '''simple docstring'''




   def __init__(    self,   lowercase_,   lowercase_,   lowercase_	)							->   Union[str, Any]:






     """simple docstring"""






     super().__init__()
     a__  =config.num_labels

     a__  =MMBTModel(lowerCAmelCase__,   lowerCAmelCase__,   lowerCAmelCase__	)
     a__  =nn.Dropout(config.hidden_dropout_prob	)
     a__  =nn.Linear(config.hidden_size,   config.num_labels	)



   def 			_UpperCAmelCase			(    self,   lowercase_,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   lowercase_=None,   )							->   Optional[Any]:






     """simple docstring"""






     a__  =return_dict if return_dict is not None else self.config.use_return_dict

     a__  =self.mmbt(
         input_modal=lowerCAmelCase__,   input_ids=lowerCAmelCase__,   modal_start_tokens=lowerCAmelCase__,   modal_end_tokens=lowerCAmelCase__,   attention_mask=lowerCAmelCase__,   token_type_ids=lowerCAmelCase__,   modal_token_type_ids=lowerCAmelCase__,   position_ids=lowerCAmelCase__,   modal_position_ids=lowerCAmelCase__,   head_mask=lowerCAmelCase__,   inputs_embeds=lowerCAmelCase__,   return_dict=lowerCAmelCase__,   )

     a__  =outputs[1]

     a__  =self.dropout(lowerCAmelCase__	)
     a__  =self.classifier(lowerCAmelCase__	)

     a__  =None
     if labels is not None:
       if self.num_labels == 1:
         #  We are doing regression
         a__  =MSELoss()
         a__  =loss_fct(logits.view(-1	),   labels.view(-1	)	)
       else:
         a__  =CrossEntropyLoss()
         a__  =loss_fct(logits.view(-1,   self.num_labels	),   labels.view(-1	)	)

     if not return_dict:
       a__  =(logits,) + outputs[2:]
       return ((loss,) + output) if loss is not None else output

     return SequenceClassifierOutput(
         loss=lowerCAmelCase__,   logits=lowerCAmelCase__,   hidden_states=outputs.hidden_states,   attentions=outputs.attentions,   )



import unittest

import numpy as np

from transformers import (
    GPTSanJapaneseConfig,
    GPTSanJapaneseForConditionalGeneration,
    GPTSanJapaneseModel,
    GPTSanJapaneseTokenizer,
    is_torch_available,
)
from transformers.generation import GenerationConfig
from transformers.testing_utils import require_torch, slow, tooslow, 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







class 						__magic_name__      :

   '''simple docstring'''




   def __init__(    self,   lowercase_,   lowercase_=36000,   lowercase_=13,   lowercase_=7,   lowercase_=True,   lowercase_=32,   lowercase_=42,   lowercase_=5,   lowercase_=2,   lowercase_=4,   lowercase_=2,   lowercase_=32,   lowercase_=80,   lowercase_=33,   lowercase_=0.0,   lowercase_=1E-6,   lowercase_=100,   lowercase_=0.0,   )							->   Optional[int]:






     """simple docstring"""






     a__  =vocab_size
     a__  =parent
     a__  =batch_size
     a__  =num_contexts
     # For common tests
     a__  =self.num_contexts
     a__  =is_training
     a__  =hidden_size
     a__  =num_ext_layers
     a__  =ext_size
     a__  =num_hidden_layers
     a__  =num_attention_heads
     a__  =num_experts
     a__  =d_ff
     a__  =d_ext
     a__  =d_spout
     a__  =dropout_rate
     a__  =layer_norm_epsilon
     a__  =expert_capacity
     a__  =router_jitter_noise



   def 			_UpperCAmelCase			(    self	)							->   Any:






     """simple docstring"""






     return GPTSanJapaneseConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''	)



   def 			_UpperCAmelCase			(    self	)							->   Any:






     """simple docstring"""






     a__  =ids_tensor([self.batch_size, self.seq_length],   self.vocab_size	)

     a__  =self.get_config()

     return (config, input_ids)



   def 			_UpperCAmelCase			(    self	)							->   Optional[Any]:






     """simple docstring"""






     a__  =ids_tensor([self.batch_size, self.seq_length],   self.vocab_size	)

     a__  =self.get_config()

     return (config, {"input_ids": input_ids})



   def 			_UpperCAmelCase			(    self	)							->   str:






     """simple docstring"""






     return GPTSanJapaneseConfig(
         vocab_size=self.vocab_size,   num_contexts=self.seq_length,   d_model=self.hidden_size,   d_ff=self.d_ff,   d_ext=self.d_ext,   d_spout=self.d_spout,   num_switch_layers=self.num_hidden_layers - self.num_ext_layers,   num_ext_layers=self.num_ext_layers,   num_heads=self.num_attention_heads,   num_experts=self.num_experts,   expert_capacity=self.expert_capacity,   dropout_rate=self.dropout_rate,   layer_norm_epsilon=self.layer_norm_epsilon,   router_jitter_noise=self.router_jitter_noise,   )



   def 			_UpperCAmelCase			(    self,   lowercase_,   lowercase_,   )							->   Tuple:






     """simple docstring"""






     a__  =GPTSanJapaneseForConditionalGeneration(config=lowercase_	)
     model.to(lowercase_	)
     model.eval()
     a__  =model(
         input_ids=lowercase_,   )
     self.parent.assertIsNotNone(lowercase_	)







@require_torch
class 						__magic_name__      (							lowerCamelCase__		,	lowerCamelCase__		,	unittest.TestCase							):

   '''simple docstring'''




   lowerCamelCase__			:     Union[str, Any]    =       (GPTSanJapaneseModel,) if is_torch_available() else ()
   lowerCamelCase__			:     Optional[int]    =       (
       {
           'conversational': GPTSanJapaneseForConditionalGeneration,
           'feature-extraction': GPTSanJapaneseForConditionalGeneration,
           'summarization': GPTSanJapaneseForConditionalGeneration,
           'text2text-generation': GPTSanJapaneseForConditionalGeneration,
           'translation': GPTSanJapaneseForConditionalGeneration,
       }
       if is_torch_available()
       else {}
   )
   lowerCamelCase__			:     Dict    =       False
   lowerCamelCase__			:     Tuple    =       False
   lowerCamelCase__			:     Optional[int]    =       False
   lowerCamelCase__			:     Dict    =       False
   lowerCamelCase__			:     str    =       False
   lowerCamelCase__			:     List[Any]    =       False
   lowerCamelCase__			:     Tuple    =       False
   lowerCamelCase__			:     Optional[int]    =       False
   # The small GPTSAN_JAPANESE model needs higher percentages for CPU/MP tests
   lowerCamelCase__			:     Any    =       [0.8, 0.9]



   def 			_UpperCAmelCase			(    self,   lowercase_,   lowercase_,   lowercase_,   lowercase_,   lowercase_	)							->   Tuple:






     """simple docstring"""






     if pipeline_test_casse_name == "SummarizationPipelineTests":
       # TODO: fix `_reorder_cache` is not implemented for this model
       return True
     elif pipeline_test_casse_name == "Text2TextGenerationPipelineTests":
       # TODO: check this.
       return True

     return False



   def 			_UpperCAmelCase			(    self	)							->   Union[str, Any]:






     """simple docstring"""






     a__  =GPTSanJapaneseTester(self	)
     a__  =ConfigTester(self,   config_class=lowercase_,   d_model=37	)



   def 			_UpperCAmelCase			(    self	)							->   Any:






     """simple docstring"""






     GPTSanJapaneseConfig()



   def 			_UpperCAmelCase			(    self	)							->   str:






     """simple docstring"""






     a__  =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_	)



   @unittest.skip(
       reason='''skip for now as the computed `max_memory` by `model_split_percents` in the test method will be changed inside `from_pretrained`'''	)
   def 			_UpperCAmelCase			(    self	)							->   int:






     """simple docstring"""






     super().test_model_parallelism()



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






     """simple docstring"""






     pass







@require_torch
class 						__magic_name__      (							lowerCamelCase__		,	lowerCamelCase__		,	unittest.TestCase							):

   '''simple docstring'''




   lowerCamelCase__			:     Optional[int]    =       (GPTSanJapaneseForConditionalGeneration,) if is_torch_available() else ()
   lowerCamelCase__			:     List[Any]    =       False
   lowerCamelCase__			:     str    =       False
   lowerCamelCase__			:     Union[str, Any]    =       False
   lowerCamelCase__			:     Tuple    =       False
   lowerCamelCase__			:     Union[str, Any]    =       False
   lowerCamelCase__			:     int    =       False
   # The small GPTSAN_JAPANESE model needs higher percentages for CPU/MP tests
   lowerCamelCase__			:     List[str]    =       [0.8, 0.9]



   def 			_UpperCAmelCase			(    self	)							->   int:






     """simple docstring"""






     a__  =GPTSanJapaneseTester(self	)
     a__  =ConfigTester(self,   config_class=lowercase_,   d_model=37	)



   def 			_UpperCAmelCase			(    self	)							->   Dict:






     """simple docstring"""






     GPTSanJapaneseConfig()



   def 			_UpperCAmelCase			(    self	)							->   Any:






     """simple docstring"""






     a__  =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_	)



   @unittest.skip(
       reason='''skip for now as the computed `max_memory` by `model_split_percents` in the test method will be changed inside `from_pretrained`'''	)
   def 			_UpperCAmelCase			(    self	)							->   Dict:






     """simple docstring"""






     super().test_model_parallelism()



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






     """simple docstring"""






     pass



   @slow
   def 			_UpperCAmelCase			(    self	)							->   Optional[Any]:






     """simple docstring"""






     a__  =GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     a__  =GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     a__  =tokenizer.encode('''武田信玄は''',   return_tensors='''pt'''	)
     a__  =model(lowercase_	)
     a__  =outputs.logits.detach().cpu().numpy()
     # Output of original model created with mesh-tensoflow
     a__  =[
         # fmt: off
         [-12.037839889526367, -12.433061599731445, -14.333840370178223, -12.450345993041992, -11.1661376953125,
         -11.930137634277344, -10.659740447998047, -12.909574508666992, -13.241043090820312, -13.398579597473145,
         -11.107524871826172, -12.3685941696167, -22.97943115234375, -10.481067657470703, -12.484030723571777,
         -12.807360649108887, -14.769700050354004, -12.233579635620117, -13.428145408630371, -22.624177932739258],
         [-7.511149883270264, -8.281851768493652, -7.943127155303955, -7.55021333694458, -6.49869966506958,
         -7.586796283721924, -6.978085994720459, -7.839145183563232, -8.21964168548584, -8.695091247558594,
         -6.706910610198975, -6.6585798263549805, -19.565698623657227, -5.353842735290527, -8.350686073303223,
         -8.039388656616211, -10.856569290161133, -7.75154447555542, -8.819022178649902, -19.51532745361328],
         [-9.73066234588623, -10.223922729492188, -9.932981491088867, -11.857836723327637, -7.662626266479492,
         -11.13529109954834, -7.765097618103027, -11.472923278808594, -9.543149948120117, -11.905633926391602,
         -9.366164207458496, -11.5734281539917, -23.699003219604492, -9.429590225219727, -10.42839241027832,
         -10.585240364074707, -10.94771957397461, -11.095416069030762, -10.390240669250488, -23.769372940063477],
         [-9.728265762329102, -9.859712600708008, -10.09729290008545, -9.678522109985352, -6.879519939422607,
         -9.68487548828125, -4.2803425788879395, -10.018914222717285, -9.308445930480957, -10.63394546508789,
         -8.083646774291992, -9.06301498413086, -21.904266357421875, -8.90160846710205, -8.841876029968262,
         -11.856719970703125, -12.079398155212402, -11.233753204345703, -10.177338600158691, -21.87256622314453],
         [-9.669764518737793, -9.614198684692383, -9.814510345458984, -9.996501922607422, -11.375690460205078,
         -10.113405227661133, -10.546867370605469, -10.04369068145752, -10.907809257507324, -10.504216194152832,
         -11.129199028015137, -10.151124000549316, -21.96586799621582, -9.086349487304688, -11.730339050292969,
         -10.460667610168457, -10.298049926757812, -10.784148216247559, -10.840693473815918, -22.03152847290039],
         # fmt: on
     ]
     a__  =np.array(lowercase_	).flatten()
     a__  =output_logits[0, :, :20].flatten()

     def check(lowercase_,   lowercase_,   lowercase_=5E-4	):
       return abs(a - b	) < epsilon * max(abs(lowercase_	),   abs(lowercase_	)	)

     self.assertTrue(np.all([check(target[i],   predict[i]	) for i in range(len(lowercase_	)	)]	)	)



   @slow
   def 			_UpperCAmelCase			(    self	)							->   Optional[int]:






     """simple docstring"""






     a__  =GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     a__  =GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     model.to(lowercase_	)

     # set deterministically
     a__  =GenerationConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     a__  =1

     # use different length sentences to test batching
     a__  =[
         '''甲斐なら武田と言うほど''',
         '''織田信長は、''',
     ]

     a__  ='''left'''
     a__  =tokenizer(lowercase_,   return_tensors='''pt''',   padding=lowercase_	)
     a__  =inputs['''input_ids'''].to(lowercase_	)

     self.assertNotEqual(inputs['''attention_mask'''][0].numpy().tolist(),   inputs['''attention_mask'''][1].numpy().tolist()	)

     a__  =model.generate(
         input_ids=lowercase_,   attention_mask=inputs['''attention_mask'''].to(lowercase_	),   max_new_tokens=3,   generation_config=lowercase_,   )

     a__  =tokenizer(sentences[0],   return_tensors='''pt'''	).input_ids.to(lowercase_	)
     a__  =model.generate(
         input_ids=lowercase_,   max_new_tokens=3,   generation_config=lowercase_	)

     a__  =tokenizer(sentences[1],   return_tensors='''pt'''	).input_ids.to(lowercase_	)
     a__  =model.generate(input_ids=lowercase_,   max_new_tokens=3,   generation_config=lowercase_	)

     self.assertNotEqual(inputs_non_padded.shape,   inputs_padded.shape	)

     a__  =tokenizer.batch_decode(lowercase_,   skip_special_tokens=lowercase_	)
     a__  =tokenizer.decode(output_non_padded[0],   skip_special_tokens=lowercase_	)
     a__  =tokenizer.decode(output_padded[0],   skip_special_tokens=lowercase_	)

     a__  =[
         '''甲斐なら武田と言うほど甲斐の武田''',
         '''織田信長は、このような''',
     ]
     self.assertListEqual(lowercase_,   lowercase_	)
     self.assertListEqual(lowercase_,   [non_padded_sentence, padded_sentence]	)



   @tooslow
   def 			_UpperCAmelCase			(    self	)							->   List[Any]:






     """simple docstring"""






     a__  =GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     a__  =GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     # Output of original model created with mesh-tensoflow
     a__  =[
         ('''武田信玄は''', 35675),
         ('''武田信玄は、''', 45),
         ('''武田信玄は、この''', 29),
         ('''武田信玄は、このよう''', 30642),
         ('''武田信玄は、このような''', 35680),
         ('''武田信玄は、このような「''', 8640),
         ('''武田信玄は、このような「武田''', 31617),
         ('''武田信玄は、このような「武田家''', 30646),
         ('''武田信玄は、このような「武田家の''', 31617),
         ('''武田信玄は、このような「武田家の家''', 31381),
     ]
     for input, output in target:
       a__  =tokenizer.encode(lowercase_,   return_tensors='''pt'''	)
       a__  =model(lowercase_	)
       a__  =outputs.logits.detach().cpu().numpy()[0]
       a__  =np.argmax(output_logits[-1]	)
       self.assertEqual(lowercase_,   lowercase_	)



   @slow
   def 			_UpperCAmelCase			(    self	)							->   Optional[Any]:






     """simple docstring"""






     a__  =GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     a__  =GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     model.to(lowercase_	)

     # set deterministically
     a__  =GenerationConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     a__  =1

     a__  ='''武田信玄は、'''
     a__  =tokenizer(lowercase_,   return_tensors='''pt'''	).input_ids.to(lowercase_	)
     a__  =tokenizer([input_text, input_text],   return_tensors='''pt'''	).input_ids.to(lowercase_	)

     # spout from uniform and one-hot
     a__  =[
         # fmt: off
         [0.87882208, 0.38426396, 0.33220248, 0.43890406, 0.16562252,
         0.04803985, 0.211572  , 0.23188473, 0.37153068, 0.7836377 ,
         0.02160172, 0.38761719, 0.75290772, 0.90198857, 0.34365777,
         0.64168169, 0.44318471, 0.14575746, 0.92562881, 0.40812148,
         0.29019122, 0.88861599, 0.65524846, 0.43563456, 0.38177187,
         0.70832965, 0.81527892, 0.68832812, 0.38833192, 0.4561522 ,
         0.14828817, 0.47248213, 0.54357335, 0.82009566, 0.1338884 ,
         0.02755417, 0.19764677, 0.2422084 , 0.04757674, 0.65409606,
         0.0824589 , 0.03304383, 0.94387689, 0.98764509, 0.82433901,
         0.27646741, 0.64907493, 0.76009406, 0.30087915, 0.17904689,
         0.41601714, 0.67046398, 0.10422822, 0.08447374, 0.07354344,
         0.61423565, 0.70284866, 0.7532333 , 0.1972038 , 0.29575659,
         0.90583886, 0.29265307, 0.50000175, 0.70407655, 0.889363  ,
         0.81904418, 0.66829128, 0.64468815, 0.56563723, 0.85601875,
         0.94924672, 0.00166762, 0.25220643, 0.74540219, 0.67993247,
         0.1549675 , 0.39385352, 0.92153607, 0.63745931, 0.27759043,
         0.84702295, 0.65904271, 0.58676614, 0.8666936 , 0.39607438,
         0.79954983, 0.42220697, 0.39650381, 0.7849864 , 0.56150201,
         0.15678925, 0.14746032, 0.34542114, 0.47026783, 0.11956489,
         0.25421435, 0.33788901, 0.68934842, 0.36424685, 0.71737898,
         0.38983449, 0.94393779, 0.39575588, 0.36616553, 0.87104665,
         0.64630203, 0.22516905, 0.88270804, 0.15031338, 0.75144345,
         0.46459025, 0.85396454, 0.86355643, 0.65139851, 0.70266061,
         0.30241389, 0.81056497, 0.88865969, 0.38773807, 0.70635849,
         0.90718459, 0.43245789, 0.28000654, 0.45935562, 0.08773519,
         0.9552151 , 0.93901511, 0.22489288], # uniform
         [1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
          0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
          0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
          0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
          0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
          0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
          0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
          0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
          0., 0., 0., 0., 0., 0., 0., 0.],
         # fmt: on
     ]

     a__  =model.generate(
         input_ids=lowercase_,   spout=spouts[0],   max_new_tokens=20,   generation_config=lowercase_,   )

     a__  =model.generate(
         input_ids=lowercase_,   spout=spouts[1],   max_new_tokens=20,   generation_config=lowercase_,   )

     a__  =model.generate(
         input_ids=lowercase_,   spout=lowercase_,   max_new_tokens=20,   generation_config=lowercase_,   )

     a__  =tokenizer.decode(outputa[0]	)
     a__  =tokenizer.decode(outputa[0]	)
     a__  =tokenizer.batch_decode(lowercase_	)

     a__  =[
         '''武田信玄は、武田氏の滅亡後、武田氏の居城であった甲斐武田氏の居城である''',
         '''武田信玄は、武田家の滅亡を防ぐため、武田家の家臣である武田信虎を討''',
     ]
     self.assertListEqual(lowercase_,   lowercase_	)
     self.assertListEqual(lowercase_,   [outa_sentence, outa_sentence]	)



   @slow
   def 			_UpperCAmelCase			(    self	)							->   str:






     """simple docstring"""






     a__  =GPTSanJapaneseForConditionalGeneration.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     a__  =GPTSanJapaneseTokenizer.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     model.to(lowercase_	)

     # set deterministically
     a__  =GenerationConfig.from_pretrained('''Tanrei/GPTSAN-japanese'''	)
     a__  =1

     a__  ='''武田信玄'''
     a__  ='''織田信長'''
     a__  ='''は、'''
     a__  ='''が、'''
     a__  =tokenizer(lowercase_,   prefix_text=lowercase_,   return_tensors='''pt'''	)
     a__  =tokenizer(lowercase_,   prefix_text=lowercase_,   return_tensors='''pt'''	)
     a__  =tokenizer([[prefix_text_a, input_text_a], [prefix_text_a, input_text_a]],   return_tensors='''pt'''	)

     a__  =model.generate(
         input_ids=input_tok_a.input_ids.to(lowercase_	),   token_type_ids=input_tok_a.token_type_ids.to(lowercase_	),   max_new_tokens=20,   generation_config=lowercase_,   )

     a__  =model.generate(
         input_ids=input_tok_a.input_ids.to(lowercase_	),   token_type_ids=input_tok_a.token_type_ids.to(lowercase_	),   max_new_tokens=20,   generation_config=lowercase_,   )

     a__  =model.generate(
         input_ids=input_tok_a.input_ids.to(lowercase_	),   token_type_ids=input_tok_a.token_type_ids.to(lowercase_	),   attention_mask=input_tok_a.attention_mask.to(lowercase_	),   max_new_tokens=20,   generation_config=lowercase_,   )

     a__  =tokenizer.decode(outputa[0]	)
     a__  =tokenizer.decode(outputa[0]	)
     a__  =tokenizer.batch_decode(lowercase_	)

     a__  =[
         '''武田信玄は、武田氏の祖である武田信虎を、その子・武田信友を擁して''',
         '''織田信長が、織田信長の妻・お市の方を妻として迎えたという逸話が残''',
     ]
     self.assertListEqual(lowercase_,   lowercase_	)
     self.assertListEqual(lowercase_,   [outa_sentence, outa_sentence]	)
