Spaces:
Runtime error
Runtime error
Commit
·
c7a680a
1
Parent(s):
1824728
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import BigBirdForQuestionAnswering, BigBirdTokenizerFast
|
3 |
+
import gradio as gr
|
4 |
+
|
5 |
+
FLAX_MODEL_ID = "vasudevgupta/flax-bigbird-natural-questions"
|
6 |
+
|
7 |
+
if __name__ == "__main__":
|
8 |
+
device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")
|
9 |
+
|
10 |
+
model = BigBirdForQuestionAnswering.from_pretrained(FLAX_MODEL_ID, block_size=64, num_random_blocks=3, from_flax=True)
|
11 |
+
model.to(device)
|
12 |
+
tokenizer = BigBirdTokenizerFast.from_pretrained(FLAX_MODEL_ID)
|
13 |
+
|
14 |
+
def get_answer(question, context):
|
15 |
+
encoding = tokenizer(question, context, return_tensors="pt", max_length=4096, padding="max_length", truncation=True)
|
16 |
+
input_ids = encoding.input_ids.to(device)
|
17 |
+
attention_mask = encoding.attention_mask.to(device)
|
18 |
+
|
19 |
+
with torch.no_grad():
|
20 |
+
start_scores, end_scores = model(input_ids=input_ids, attention_mask=attention_mask).to_tuple()
|
21 |
+
|
22 |
+
# Let's take the most likely token using `argmax` and retrieve the answer
|
23 |
+
all_tokens = tokenizer.convert_ids_to_tokens(encoding["input_ids"].squeeze().tolist())
|
24 |
+
|
25 |
+
answer_tokens = all_tokens[torch.argmax(start_scores): torch.argmax(end_scores)+1]
|
26 |
+
answer = tokenizer.decode(tokenizer.convert_tokens_to_ids(answer_tokens))
|
27 |
+
|
28 |
+
return answer
|
29 |
+
|
30 |
+
default_context = "BigBird Pegasus just landed! Thanks to Vasudev Gupta, BigBird Pegasus from Google AI is merged into HuggingFace Transformers. Check it out today!!!"
|
31 |
+
question = gr.inputs.TextBox(lines=2, default="Who added BigBird to HuggingFace Transformers?", label="Question")
|
32 |
+
context = gr.inputs.TextBox(lines=10, default=default_context, label="Context")
|
33 |
+
|
34 |
+
gr.Interface(fn=get_answer, inputs=[question, context], outputs="text").launch()
|
35 |
+
|