LukeOLuck commited on
Commit
23e2f58
1 Parent(s): 2f430b3

init commit

Browse files
Files changed (6) hide show
  1. app.py +88 -0
  2. model.py +21 -0
  3. questions_texts.txt +13 -0
  4. requirements.txt +4 -0
  5. response_texts.txt +14 -0
  6. system_prompts.txt +5 -0
app.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import torch
4
+ import pickle
5
+ import gzip
6
+
7
+ from model import create_flan_T5_model
8
+ from timeit import default_timer as timer
9
+ from typing import Tuple, Dict
10
+
11
+ device = "cuda" if torch.cuda.is_available() else "cpu"
12
+
13
+ ### Load example texts ###
14
+ questions_texts = []
15
+ with open("questions_texts.txt", "r") as file:
16
+ questions_texts = [line.strip() for line in file.readlines()]
17
+
18
+ system_prompts = []
19
+ with open("system_prompts.txt", "r") as file:
20
+ system_prompts = [line.strip() for line in file.readlines()]
21
+
22
+ response_texts = []
23
+ with open("response_texts.txt", "r") as file:
24
+ response_texts = [line.strip() for line in file.readlines()]
25
+
26
+ ### Model and transforms preparation ###
27
+ # Create model and tokenizer
28
+ model, tokenizer = create_flan_T5_model()
29
+
30
+ # Load saved weights
31
+ model.load_state_dict(
32
+ torch.load(f="flan-t5-small.pth",
33
+ map_location=torch.device("cpu")) # load to CPU
34
+ )
35
+
36
+ ### Predict function ###
37
+ def predict(selection: str) -> Tuple[Dict, str, float]:
38
+ start_time = timer()
39
+
40
+ model.eval()
41
+
42
+ # Extract the question part from the selection
43
+ # Assuming the format "Prompt: {prompt} | Question: {question}"
44
+ question = selection.split("| Question: ")[1]
45
+
46
+ # Find the index of the question
47
+ idx = questions_texts.index(question)
48
+
49
+ # Now, use the index to get the system prompt and actual response
50
+ system_prompt = system_prompts[idx]
51
+ response = response_texts[idx]
52
+ #
53
+ input_text = f"context: {system_prompt} question: {question}"
54
+
55
+ model_inputs = tokenizer(input_text, return_tensors="pt", max_length=512, padding='max_length', truncation=True).to(device)
56
+
57
+ with torch.inference_mode():
58
+ predicted_token_ids = model.generate(input_ids=model_inputs['input_ids'], attention_mask=model_inputs['attention_mask'], max_length=128)
59
+
60
+ result = tokenizer.decode(predicted_token_ids[0], skip_special_tokens=True)
61
+
62
+ end_time = timer()
63
+ pred_time = round(end_time - start_time, 4)
64
+
65
+ return {"Predicted Answer": result}, {"Actual Answer": response}, pred_time
66
+
67
+ ### 4. Gradio app ###
68
+ # Create title, description and article
69
+ title = "Prompt Answering with Google's flan-t5-small"
70
+ description = "[google/flan-t5-small based model](https://huggingface.co/google/flan-t5-small) LLM model trained to take prompts and tasks on the [HuggingFace 🤗 Open-Orca/OpenOrca](https://huggingface.co/datasets/Open-Orca/OpenOrca). [Source Code Found Here](https://colab.research.google.com/drive/1sIScjt_hyNegHC15Y76JVXEOUvdD_2dh?usp=sharing)"
71
+ article = "Built with [Gradio](https://github.com/gradio-app/gradio) and [PyTorch](https://pytorch.org/). [Source Code Found Here](https://colab.research.google.com/drive/1sIScjt_hyNegHC15Y76JVXEOUvdD_2dh?usp=sharing)"
72
+
73
+ dropdown_choices = [f"Prompt: {prompt} | Question: {question}" for prompt, question in zip(system_prompts, questions_texts)]
74
+
75
+ # Create the Gradio demo
76
+ demo = gr.Interface(fn=predict,
77
+ inputs=gr.Dropdown(choices=dropdown_choices, label="Select a Question and Prompt"),
78
+ outputs=[
79
+ gr.JSON(label="Predicted Answer"),
80
+ gr.Textbox(label="Actual Answer"),
81
+ gr.Number(label="Prediction time (s)")
82
+ ],
83
+ title=title,
84
+ description=description,
85
+ article=article)
86
+
87
+ # Launch the demo
88
+ demo.launch()
model.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from transformers import AutoTokenizer, T5ForConditionalGeneration
4
+
5
+ device = "cuda" if torch.cuda.is_available() else "cpu"
6
+
7
+ def create_flan_T5_model(device=device):
8
+ """Creates a HuggingFace all-MiniLM-L6-v2 model.
9
+
10
+ Args:
11
+ device: A torch.device
12
+ Returns:
13
+ A tuple of the model and tokenizer
14
+ """
15
+ tokenizer = AutoTokenizer.from_pretrained('google/flan-t5-small')
16
+ model = T5ForConditionalGeneration.from_pretrained('google/flan-t5-small').to(device)
17
+
18
+ return model, tokenizer
19
+
20
+ # Example usage
21
+ model, tokenizer = create_flan_T5_model()
questions_texts.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You will be given a definition of a task first, then some input of the task.
2
+ This task is about using the specified sentence and converting the sentence to Resource Description Framework (RDF) triplets of the form (subject, predicate object). The RDF triplets generated must be such that the triplets accurately capture the structure and semantics of the input sentence. The input is a sentence and the output is a list of triplets of the form [subject, predicate, object] that capture the relationships present in the sentence. When a sentence has more than 1 RDF triplet possible, the output must contain all of them.
3
+
4
+ AFC Ajax (amateurs)'s ground is Sportpark De Toekomst where Ajax Youth Academy also play.
5
+ Output:
6
+ Generate an approximately fifteen-word sentence that describes all this data: Midsummer House eatType restaurant; Midsummer House food Chinese; Midsummer House priceRange moderate; Midsummer House customer rating 3 out of 5; Midsummer House near All Bar One
7
+ What happens next in this paragraph?
8
+
9
+ She then rubs a needle on a cotton ball then pushing it onto a pencil and wrapping thread around it. She then holds up a box of a product and then pouring several liquids into a bowl. she
10
+ Choose your answer from: A. adds saucepan and shakes up the product in a grinder. B. pinches the thread to style a cigarette, and then walks away. C. then dips the needle in ink and using the pencil to draw a design on her leg, rubbing it off with a rag in the end. D. begins to style her hair and cuts it several times before parting the ends of it to show the hairstyle she has created.
11
+ Please answer the following question: I want to test the ability of students to read a passage and answer questions about it. Could you please come up with a good question for the passage "In 1901, the Federation of Australia was the process by which the six separate British self-governing colonies of New South Wales, Queensland, South Australia, Tasmania, Victoria and Western Australia formed one nation. They kept the systems of government that they had developed as separate colonies but also would have a federal government that was responsible for matters concerning the whole nation. When the Constitution of Australia came into force, the colonies collectively became states of the Commonwealth of Australia."?
12
+ Answer:
13
+ James runs a TV show and there are 5 main characters and 4 minor characters. He pays the minor characters $15,000 each episode. He paid the major characters three times as much. How much does he pay per episode? Let's be accurate as possible.
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch==2.1.0
2
+ torchvision==0.16.0
3
+ gradio==3.50.2
4
+ transformers==4.35.0
response_texts.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ ["AFC Ajax (amateurs)", "has ground", "Sportpark De Toekomst"],
3
+ ["Ajax Youth Academy", "plays at", "Sportpark De Toekomst"]
4
+ ]
5
+ Midsummer House is a moderately priced Chinese restaurant with a 3/5 customer rating, located near All Bar One.
6
+ C. She then dips the needle in ink and using the pencil to draw a design on her leg, rubbing it off with a rag in the end. In this option, she is continuing the process of using the needle, pencil, and thread, which is most related to what she was doing in the previous sentence.
7
+ Based on the passage, discuss the primary motivations and outcomes of the 1901 Federation of Australia, including the roles and responsibilities of the federal government, as well as the continued governmental structures of the individual states involved.
8
+ James pays the minor characters $15,000 each episode. Since there are 4 minor characters, he pays them a total of 4 * $15,000 = $60,000 per episode.
9
+
10
+ The major characters are paid three times as much. So, each major character gets paid 3 * $15,000 = $45,000 per episode.
11
+
12
+ There are 5 main characters, so he pays them a total of 5 * $45,000 = $225,000 per episode.
13
+
14
+ In total, James pays $225,000 (major characters) + $60,000 (minor characters) = $285,000 per episode.
system_prompts.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+
2
+ You are an AI assistant. You will be given a task. You must generate a detailed and long answer.
3
+ You are a helpful assistant, who always provide explanation. Think like you are answering to a five year old.
4
+ You are an AI assistant. You will be given a task. You must generate a detailed and long answer.
5
+ You are an AI assistant that helps people find information.