
"""simple docstring"""


import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
    embed_questions_for_retrieval,
    make_qa_sas_model,
    qa_sas_generate,
    query_es_index,
    query_qa_dense_index,
)

import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer


SCREAMING_SNAKE_CASE			  =  """bart"""
SCREAMING_SNAKE_CASE			  =  True



@st.cache(allow_output_mutation=UpperCAmelCase_					)
def 						lowerCamelCase__      (				)->				Union[str, Any]:







       """simple docstring"""
       if LOAD_DENSE_INDEX:
              UpperCamelCase       			=		AutoTokenizer.from_pretrained("yjernite/retribert-base-uncased"					)
              UpperCamelCase       			=		AutoModel.from_pretrained("yjernite/retribert-base-uncased"					).to("cuda:0"					)
              UpperCamelCase       			=		qar_model.eval()
       else:
              UpperCamelCase			,							UpperCamelCase       			=		(None, None)
       if MODEL_TYPE == "bart":
              UpperCamelCase       			=		AutoTokenizer.from_pretrained("yjernite/bart_eli5"					)
              UpperCamelCase       			=		AutoModelForSeqaSeqLM.from_pretrained("yjernite/bart_eli5"					).to("cuda:0"					)
              UpperCamelCase       			=		torch.load("seq2seq_models/eli5_bart_model_blm_2.pth"					)
              sas_model.load_state_dict(save_dict["model"]					)
              UpperCamelCase       			=		sas_model.eval()
       else:
              UpperCamelCase			,							UpperCamelCase       			=		make_qa_sas_model(
                  model_name="t5-small"		,   from_file="seq2seq_models/eli5_t5_model_1024_4.pth"		,   device="cuda:0"					)
       return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)



@st.cache(allow_output_mutation=UpperCAmelCase_					)
def 						lowerCamelCase__      (				)->				List[Any]:







       """simple docstring"""
       if LOAD_DENSE_INDEX:
              UpperCamelCase       			=		faiss.StandardGpuResources()
              UpperCamelCase       			=		datasets.load_dataset(path="wiki_snippets"		,   name="wiki40b_en_100_0"					)["train"]
              UpperCamelCase       			=		np.memmap(
                  "wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat"		,   dtype="float32"		,   mode="r"		,   shape=(wikiaab_passages.num_rows, 1_28)		,   )
              UpperCamelCase       			=		faiss.IndexFlatIP(1_28					)
              UpperCamelCase       			=		faiss.index_cpu_to_gpu(UpperCAmelCase_		,   1		,   UpperCAmelCase_					)
              wikiaab_gpu_index_flat.add(UpperCAmelCase_					)  # TODO fix for larger GPU
       else:
              UpperCamelCase			,							UpperCamelCase       			=		(None, None)
       UpperCamelCase       			=		Elasticsearch([{"host": "localhost", "port": "9200"}]					)
       return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)



@st.cache(allow_output_mutation=UpperCAmelCase_					)
def 						lowerCamelCase__      (				)->				int:







       """simple docstring"""
       UpperCamelCase       			=		datasets.load_dataset("eli5"		,   name="LFQA_reddit"					)
       UpperCamelCase       			=		elia["train_eli5"]
       UpperCamelCase       			=		np.memmap(
           "eli5_questions_reps.dat"		,   dtype="float32"		,   mode="r"		,   shape=(elia_train.num_rows, 1_28)					)
       UpperCamelCase       			=		faiss.IndexFlatIP(1_28					)
       eli5_train_q_index.add(UpperCAmelCase_					)
       return (elia_train, eli5_train_q_index)


SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE			  =  load_indexes()
SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE			  =  load_models()
SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE			  =  load_train_data()



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_=10					)->				Optional[int]:







       """simple docstring"""
       UpperCamelCase       			=		embed_questions_for_retrieval([question]		,   UpperCAmelCase_		,   UpperCAmelCase_					)
       UpperCamelCase			,							UpperCamelCase       			=		eli5_train_q_index.search(UpperCAmelCase_		,   UpperCAmelCase_					)
       UpperCamelCase       			=		[elia_train[int(UpperCAmelCase_					)] for i in I[0]]
       return nn_examples



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_="wiki40b"		,   UpperCAmelCase_="dense"		,   UpperCAmelCase_=10					)->				str:







       """simple docstring"""
       if source == "none":
              UpperCamelCase			,							UpperCamelCase       			=		(" <P> ".join(["" for _ in range(11					)]					).strip(), [])
       else:
              if method == "dense":
                     UpperCamelCase			,							UpperCamelCase       			=		query_qa_dense_index(
                         UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_					)
              else:
                     UpperCamelCase			,							UpperCamelCase       			=		query_es_index(
                         UpperCAmelCase_		,   UpperCAmelCase_		,   index_name="english_wiki40b_snippets_100w"		,   n_results=UpperCAmelCase_		,   )
       UpperCamelCase       			=		[
           (res["article_title"], res["section_title"].strip(), res["score"], res["passage_text"]) for res in hit_lst
       ]
       UpperCamelCase       			=		"question: {} context: {}".format(UpperCAmelCase_		,   UpperCAmelCase_					)
       return question_doc, support_list



@st.cache(
    hash_funcs={
        torch.Tensor: (lambda UpperCAmelCase_					: None),
        transformers.models.bart.tokenization_bart.BartTokenizer: (lambda UpperCAmelCase_					: None),
    }					)
def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_=64		,   UpperCAmelCase_=2_56		,   UpperCAmelCase_=False		,   UpperCAmelCase_=2		,   UpperCAmelCase_=0.95		,   UpperCAmelCase_=0.8					)->				Tuple:







       """simple docstring"""
       with torch.no_grad():
              UpperCamelCase       			=		qa_sas_generate(
                  UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_		,   num_answers=1		,   num_beams=UpperCAmelCase_		,   min_len=UpperCAmelCase_		,   max_len=UpperCAmelCase_		,   do_sample=UpperCAmelCase_		,   temp=UpperCAmelCase_		,   top_p=UpperCAmelCase_		,   top_k=UpperCAmelCase_		,   max_input_length=10_24		,   device="cuda:0"		,   )[0]
       return (answer, support_list)


st.title("""Long Form Question Answering with ELI5""")

# Start sidebar
SCREAMING_SNAKE_CASE			  =  """<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>"""
SCREAMING_SNAKE_CASE			  =  """
<html>
  <head>
    <style>
      .img-container {
        padding-left: 90px;
        padding-right: 90px;
        padding-top: 50px;
        padding-bottom: 50px;
        background-color: #f0f3f9;
      }
    </style>
  </head>
  <body>
    <span class=\"img-container\"> <!-- Inline parent element -->
      %s
    </span>
  </body>
</html>
""" % (
    header_html,
)
st.sidebar.markdown(
    header_full,
    unsafe_allow_html=True,
)

# Long Form QA with ELI5 and Wikipedia
SCREAMING_SNAKE_CASE			  =  """
This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).
First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,
a pre-processed fixed snapshot of Wikipedia.
"""
st.sidebar.markdown(description, unsafe_allow_html=True)

SCREAMING_SNAKE_CASE			  =  [
    """Answer the question""",
    """View the retrieved document only""",
    """View the most similar ELI5 question and answer""",
    """Show me everything, please!""",
]
SCREAMING_SNAKE_CASE			  =  st.sidebar.checkbox("""Demo options""")
if demo_options:
      SCREAMING_SNAKE_CASE			  =  st.sidebar.selectbox(
          """""",
          action_list,
          index=3,
      )
      SCREAMING_SNAKE_CASE			  =  action_list.index(action_st)
      SCREAMING_SNAKE_CASE			  =  st.sidebar.selectbox(
          """""",
          ["""Show full text of passages""", """Show passage section titles"""],
          index=0,
      )
      SCREAMING_SNAKE_CASE			  =  show_type == """Show full text of passages"""
else:
      SCREAMING_SNAKE_CASE			  =  3
      SCREAMING_SNAKE_CASE			  =  True

SCREAMING_SNAKE_CASE			  =  st.sidebar.checkbox("""Retrieval options""")
if retrieval_options:
      SCREAMING_SNAKE_CASE			  =  """
    ### Information retriever options

    The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding
    trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.
    The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.
    """
      st.sidebar.markdown(retriever_info)
      SCREAMING_SNAKE_CASE			  =  st.sidebar.selectbox("""Which Wikipedia format should the model use?""", ["""wiki40b""", """none"""])
      SCREAMING_SNAKE_CASE			  =  st.sidebar.selectbox("""Which Wikipedia indexer should the model use?""", ["""dense""", """sparse""", """mixed"""])
else:
      SCREAMING_SNAKE_CASE			  =  """wiki40b"""
      SCREAMING_SNAKE_CASE			  =  """dense"""

SCREAMING_SNAKE_CASE			  =  """beam"""
SCREAMING_SNAKE_CASE			  =  2
SCREAMING_SNAKE_CASE			  =  64
SCREAMING_SNAKE_CASE			  =  256
SCREAMING_SNAKE_CASE			  =  None
SCREAMING_SNAKE_CASE			  =  None
SCREAMING_SNAKE_CASE			  =  st.sidebar.checkbox("""Generation options""")
if generate_options:
      SCREAMING_SNAKE_CASE			  =  """
    ### Answer generation options

    The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)
    weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with
    **beam** search, or **sample** from the decoder's output probabilities.
    """
      st.sidebar.markdown(generate_info)
      SCREAMING_SNAKE_CASE			  =  st.sidebar.selectbox("""Would you like to use beam search or sample an answer?""", ["""beam""", """sampled"""])
      SCREAMING_SNAKE_CASE			  =  st.sidebar.slider(
          """Minimum generation length""", min_value=8, max_value=256, value=64, step=8, format=None, key=None
      )
      SCREAMING_SNAKE_CASE			  =  st.sidebar.slider(
          """Maximum generation length""", min_value=64, max_value=512, value=256, step=16, format=None, key=None
      )
      if sampled == "beam":
            SCREAMING_SNAKE_CASE			  =  st.sidebar.slider("""Beam size""", min_value=1, max_value=8, value=2, step=None, format=None, key=None)
      else:
            SCREAMING_SNAKE_CASE			  =  st.sidebar.slider(
                """Nucleus sampling p""", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
            )
            SCREAMING_SNAKE_CASE			  =  st.sidebar.slider(
                """Temperature""", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
            )
            SCREAMING_SNAKE_CASE			  =  None

# start main text
SCREAMING_SNAKE_CASE			  =  [
    """<MY QUESTION>""",
    """How do people make chocolate?""",
    """Why do we get a fever when we are sick?""",
    """How can different animals perceive different colors?""",
    """What is natural language processing?""",
    """What's the best way to treat a sunburn?""",
    """What exactly are vitamins ?""",
    """How does nuclear energy provide electricity?""",
    """What's the difference between viruses and bacteria?""",
    """Why are flutes classified as woodwinds when most of them are made out of metal ?""",
    """Why do people like drinking coffee even though it tastes so bad?""",
    """What happens when wine ages? How does it make the wine taste better?""",
    """If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?""",
    """How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?""",
    """How does New Zealand have so many large bird predators?""",
]
SCREAMING_SNAKE_CASE			  =  st.selectbox(
    """What would you like to ask? ---- select <MY QUESTION> to enter a new query""",
    questions_list,
    index=1,
)
if question_s == "<MY QUESTION>":
      SCREAMING_SNAKE_CASE			  =  st.text_input("""Enter your question here:""", """""")
else:
      SCREAMING_SNAKE_CASE			  =  question_s

if st.button("""Show me!"""):
      if action in [0, 1, 3]:
            if index_type == "mixed":
                  SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE			  =  make_support(question, source=wiki_source, method="""dense""", n_results=10)
                  SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE			  =  make_support(question, source=wiki_source, method="""sparse""", n_results=10)
                  SCREAMING_SNAKE_CASE			  =  []
                  for res_d, res_s in zip(support_list_dense, support_list_sparse):
                        if tuple(res_d) not in support_list:
                              support_list += [tuple(res_d)]
                        if tuple(res_s) not in support_list:
                              support_list += [tuple(res_s)]
                  SCREAMING_SNAKE_CASE			  =  support_list[:10]
                  SCREAMING_SNAKE_CASE			  =  """<P> """ + """ <P> """.join([res[-1] for res in support_list])
            else:
                  SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE			  =  make_support(question, source=wiki_source, method=index_type, n_results=10)
      if action in [0, 3]:
            SCREAMING_SNAKE_CASE  ,   SCREAMING_SNAKE_CASE			  =  answer_question(
                question_doc,
                sas_model,
                sas_tokenizer,
                min_len=min_len,
                max_len=int(max_len),
                sampling=(sampled == """sampled"""),
                n_beams=n_beams,
                top_p=top_p,
                temp=temp,
            )
            st.markdown("""### The model generated answer is:""")
            st.write(answer)
      if action in [0, 1, 3] and wiki_source != "none":
            st.markdown("""--- \n ### The model is drawing information from the following Wikipedia passages:""")
            for i, res in enumerate(support_list):
                  SCREAMING_SNAKE_CASE			  =  """https://en.wikipedia.org/wiki/{}""".format(res[0].replace(""" """, """_"""))
                  SCREAMING_SNAKE_CASE			  =  res[1].strip()
                  if sec_titles == "":
                        SCREAMING_SNAKE_CASE			  =  """[{}]({})""".format(res[0], wiki_url)
                  else:
                        SCREAMING_SNAKE_CASE			  =  sec_titles.split(""" & """)
                        SCREAMING_SNAKE_CASE			  =  """ & """.join(
                            ["""[{}]({}#{})""".format(sec.strip(), wiki_url, sec.strip().replace(""" """, """_""")) for sec in sec_list]
                        )
                  st.markdown(
                      """{0:02d} - **Article**: {1:<18} <br>  _Section_: {2}""".format(i + 1, res[0], sections),
                      unsafe_allow_html=True,
                  )
                  if show_passages:
                        st.write(
                            """> <span style=\"font-family:arial; font-size:10pt;\">""" + res[-1] + """</span>""", unsafe_allow_html=True
                        )
      if action in [2, 3]:
            SCREAMING_SNAKE_CASE			  =  find_nearest_training(question)
            SCREAMING_SNAKE_CASE			  =  nn_train_list[0]
            st.markdown(
                """--- \n ### The most similar question in the ELI5 training set was: \n\n {}""".format(train_exple["""title"""])
            )
            SCREAMING_SNAKE_CASE			  =  [
                """{}. {}""".format(i + 1, """  \n""".join([line.strip() for line in ans.split("""\n""") if line.strip() != """"""]))
                for i, (ans, sc) in enumerate(zip(train_exple["""answers"""]["""text"""], train_exple["""answers"""]["""score"""]))
                if i == 0 or sc > 2
            ]
            st.markdown("""##### Its answers were: \n\n {}""".format("""\n""".join(answers_st)))


SCREAMING_SNAKE_CASE			  =  """
---

**Disclaimer**

*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.
Evaluating biases of such a model and ensuring factual generations are still very much open research problems.
Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*
"""

st.sidebar.markdown(disclaimer, unsafe_allow_html=True)







"""simple docstring"""


import unittest

from transformers import GPTNeoXJapaneseConfig, is_torch_available
from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
from transformers.testing_utils import require_torch, slow, torch_device

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 GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel



class 	__a	:






       def __init__(	self			:				Optional[int]							,   UpperCAmelCase_			:				Any							,   UpperCAmelCase_			:				str=13							,   UpperCAmelCase_			:				Optional[int]=7							,   UpperCAmelCase_			:				Optional[int]=True							,   UpperCAmelCase_			:				Optional[Any]=True							,   UpperCAmelCase_			:				Optional[int]=True							,   UpperCAmelCase_			:				int=True							,   UpperCAmelCase_			:				Dict=99							,   UpperCAmelCase_			:				str=32							,   UpperCAmelCase_			:				List[Any]=5							,   UpperCAmelCase_			:				str=4							,   UpperCAmelCase_			:				Union[str, Any]=4							,   UpperCAmelCase_			:				Optional[int]="gelu"							,   UpperCAmelCase_			:				Tuple=0.0							,   UpperCAmelCase_			:				Any=0.1							,   UpperCAmelCase_			:				int=True							,   UpperCAmelCase_			:				Union[str, Any]=512							,   UpperCAmelCase_			:				int=16							,   UpperCAmelCase_			:				Optional[Any]=2							,   UpperCAmelCase_			:				str=0.02							,   UpperCAmelCase_			:				Any=3							,   UpperCAmelCase_			:				Any=4							,   UpperCAmelCase_			:				Optional[Any]=None							,   )->	Tuple:







              """simple docstring"""
              UpperCamelCase       			=		parent
              UpperCamelCase       			=		batch_size
              UpperCamelCase       			=		seq_length
              UpperCamelCase       			=		is_training
              UpperCamelCase       			=		use_input_mask
              UpperCamelCase       			=		use_token_type_ids
              UpperCamelCase       			=		use_labels
              UpperCamelCase       			=		vocab_size
              UpperCamelCase       			=		hidden_size
              UpperCamelCase       			=		num_hidden_layers
              UpperCamelCase       			=		num_attention_heads
              UpperCamelCase       			=		intermediate_multiple_size
              UpperCamelCase       			=		hidden_act
              UpperCamelCase       			=		hidden_dropout
              UpperCamelCase       			=		attention_dropout
              UpperCamelCase       			=		weight_tying
              UpperCamelCase       			=		max_position_embeddings
              UpperCamelCase       			=		type_vocab_size
              UpperCamelCase       			=		type_sequence_label_size
              UpperCamelCase       			=		initializer_range
              UpperCamelCase       			=		num_labels
              UpperCamelCase       			=		num_choices
              UpperCamelCase       			=		scope






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]      )->	Union[str, Any]:







              """simple docstring"""
              UpperCamelCase       			=		ids_tensor([self.batch_size, self.seq_length]							,   self.vocab_size      )

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

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

              UpperCamelCase       			=		self.get_config()

              return config, input_ids, input_mask, token_labels






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict      )->	Dict:







              """simple docstring"""
              return GPTNeoXJapaneseConfig(
                  vocab_size=self.vocab_size							,   hidden_size=self.hidden_size							,   num_hidden_layers=self.num_hidden_layers							,   num_attention_heads=self.num_attention_heads							,   intermediate_multiple_size=self.intermediate_multiple_size							,   hidden_act=self.hidden_act							,   hidden_dropout=self.hidden_dropout							,   attention_dropout=self.attention_dropout							,   weight_tying=self.weight_tying							,   max_position_embeddings=self.max_position_embeddings							,   type_vocab_size=self.type_vocab_size							,   is_decoder=UpperCAmelCase_							,   initializer_range=self.initializer_range							,   )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	List[Any]:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.prepare_config_and_inputs()

              UpperCamelCase       			=		True

              return config, input_ids, input_mask, token_labels






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Union[str, Any]							,   UpperCAmelCase_			:				List[Any]							,   UpperCAmelCase_			:				Union[str, Any]							,   UpperCAmelCase_			:				List[Any]      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		GPTNeoXJapaneseModel(config=UpperCAmelCase_      )
              model.to(UpperCAmelCase_      )
              model.eval()
              UpperCamelCase       			=		model(UpperCAmelCase_							,   attention_mask=UpperCAmelCase_      )
              UpperCamelCase       			=		model(UpperCAmelCase_      )
              self.parent.assertEqual(result.last_hidden_state.shape							,   (self.batch_size, self.seq_length, self.hidden_size)      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any							,   UpperCAmelCase_			:				List[str]							,   UpperCAmelCase_			:				List[Any]							,   UpperCAmelCase_			:				List[str]      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		True
              UpperCamelCase       			=		GPTNeoXJapaneseModel(UpperCAmelCase_      )
              model.to(UpperCAmelCase_      )
              model.eval()
              UpperCamelCase       			=		model(UpperCAmelCase_							,   attention_mask=UpperCAmelCase_      )
              self.parent.assertEqual(result.last_hidden_state.shape							,   (self.batch_size, self.seq_length, self.hidden_size)      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[str]							,   UpperCAmelCase_			:				Tuple							,   UpperCAmelCase_			:				Dict							,   UpperCAmelCase_			:				List[Any]							,   UpperCAmelCase_			:				Optional[Any]      )->	Any:







              """simple docstring"""
              UpperCamelCase       			=		GPTNeoXJapaneseForCausalLM(config=UpperCAmelCase_      )
              model.to(UpperCAmelCase_      )
              model.eval()
              UpperCamelCase       			=		model(UpperCAmelCase_							,   attention_mask=UpperCAmelCase_							,   labels=UpperCAmelCase_      )
              self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.seq_length, self.vocab_size)      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict							,   UpperCAmelCase_			:				int							,   UpperCAmelCase_			:				Optional[int]							,   UpperCAmelCase_			:				Optional[Any]      )->	Any:







              """simple docstring"""
              UpperCamelCase       			=		True
              UpperCamelCase       			=		GPTNeoXJapaneseForCausalLM(config=UpperCAmelCase_      )
              model.to(UpperCAmelCase_      )
              model.eval()

              # first forward pass
              UpperCamelCase       			=		model(UpperCAmelCase_							,   attention_mask=UpperCAmelCase_							,   use_cache=UpperCAmelCase_      )
              UpperCamelCase       			=		outputs.past_key_values

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

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

              UpperCamelCase       			=		model(UpperCAmelCase_							,   attention_mask=UpperCAmelCase_							,   output_hidden_states=UpperCAmelCase_      )
              UpperCamelCase       			=		output_from_no_past["hidden_states"][0]
              UpperCamelCase       			=		model(
                  UpperCAmelCase_							,   attention_mask=UpperCAmelCase_							,   past_key_values=UpperCAmelCase_							,   output_hidden_states=UpperCAmelCase_							,   )["hidden_states"][0]

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






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







              """simple docstring"""
              UpperCamelCase       			=		self.prepare_config_and_inputs()
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		config_and_inputs
              UpperCamelCase       			=		{"input_ids": input_ids, "attention_mask": input_mask}
              return config, inputs_dict





@require_torch
class 	__a	(   _lowerCAmelCase     ,  _lowerCAmelCase     ,  unittest.TestCase						):
       UpperCamelCase_		:       Union[str, Any]				=      (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
       UpperCamelCase_		:       Optional[int]				=      (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else ()
       UpperCamelCase_		:       List[str]				=      (
           {'''feature-extraction''': GPTNeoXJapaneseModel, '''text-generation''': GPTNeoXJapaneseForCausalLM}
           if is_torch_available()
           else {}
       )
       UpperCamelCase_		:       Optional[Any]				=      False
       UpperCamelCase_		:       Tuple				=      False
       UpperCamelCase_		:       Optional[int]				=      False
       UpperCamelCase_		:       List[Any]				=      False






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[str]      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		GPTNeoXJapaneseModelTester(self      )
              UpperCamelCase       			=		ConfigTester(self							,   config_class=UpperCAmelCase_							,   hidden_size=37      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				str      )->	Any:







              """simple docstring"""
              self.config_tester.run_common_tests()






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]      )->	Dict:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(UpperCAmelCase_							,   UpperCAmelCase_							,   UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[Any]      )->	Optional[Any]:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs_for_decoder()
              self.model_tester.create_and_check_model_as_decoder(UpperCAmelCase_							,   UpperCAmelCase_							,   UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict      )->	List[Any]:







              """simple docstring"""
              # This regression test was failing with PyTorch < 1.3
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs_for_decoder()

              UpperCamelCase       			=		None

              self.model_tester.create_and_check_model_as_decoder(UpperCAmelCase_							,   UpperCAmelCase_							,   UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[Any]      )->	List[Any]:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_decoder_model_past_large_inputs(UpperCAmelCase_							,   UpperCAmelCase_							,   UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[Any]      )->	Optional[int]:







              """simple docstring"""
              UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase_      )






       @slow
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict      )->	str:







              """simple docstring"""
              UpperCamelCase       			=		"abeja/gpt-neox-japanese-2.7b"

              UpperCamelCase       			=		["データサイエンティストとは、", "100年後に必要とされる会社は、", "フルリモートの環境で働くために必要なことは、", "国境の長いトンネルを抜けると", "美味しい日本食といえば、"]

              UpperCamelCase       			=		[
                  "データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。",
                  "100年後に必要とされる会社は、「人」が中心の会社です。",
                  "フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。",
                  "国境の長いトンネルを抜けると、そこは雪国だった。",
                  "美味しい日本食といえば、やっぱりお寿司ですよね。",
              ]

              UpperCamelCase       			=		GPTNeoXJapaneseTokenizer.from_pretrained(UpperCAmelCase_      )
              UpperCamelCase       			=		GPTNeoXJapaneseForCausalLM.from_pretrained(UpperCAmelCase_      )

              UpperCamelCase       			=		[]
              for prompt in prompts:
                     UpperCamelCase       			=		tokenizer(UpperCAmelCase_							,   return_tensors="pt"      ).input_ids
                     UpperCamelCase       			=		model.generate(UpperCAmelCase_							,   max_length=50      )
                     UpperCamelCase       			=		tokenizer.batch_decode(UpperCAmelCase_							,   skip_special_tokens=UpperCAmelCase_      )
                     predicted_outputs += generated_string
              self.assertListEqual(UpperCAmelCase_							,   UpperCAmelCase_      )





