rgallardo commited on
Commit
92360e8
1 Parent(s): bed8f57

Upload app

Browse files
Files changed (2) hide show
  1. app.py +44 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import LongT5ForConditionalGeneration, AutoTokenizer
2
+ import time
3
+
4
+ N = 2 # Number of previous QA pairs to use for context
5
+ MAX_NEW_TOKENS = 128 # Maximum number of tokens for each answer
6
+
7
+ tokenizer = AutoTokenizer.from_pretrained("tryolabs/long-t5-tglobal-base-blogpost-cqa")
8
+ model = LongT5ForConditionalGeneration.from_pretrained("tryolabs/long-t5-tglobal-base-blogpost-cqa")
9
+
10
+ with open("context_short.txt", "r") as f:
11
+ context = f.read()
12
+
13
+ def build_input(question, user_history=[], bot_history=[]):
14
+ model_input = f"{context} || "
15
+ previous = min(len(bot_history[1:]), N)
16
+ for i in range(previous, 0, -1):
17
+ prev_question = user_history[-i-1]
18
+ prev_answer = bot_history[-i]
19
+ model_input += f"<Q{i}> {prev_question} <A{i}> {prev_answer} "
20
+ model_input += f"<Q> {question} <A> "
21
+ return model_input
22
+
23
+ def get_model_answer(question, user_history=[], bot_history=[]):
24
+ start = time.perf_counter()
25
+ model_input = build_input(question, user_history, bot_history)
26
+ end = time.perf_counter()
27
+ print(f"Build input: {end-start}")
28
+ start = time.perf_counter()
29
+ encoded_inputs = tokenizer(model_input, max_length=3000, truncation=True, return_tensors="pt")
30
+ input_ids, attention_mask = (
31
+ encoded_inputs.input_ids,
32
+ encoded_inputs.attention_mask
33
+ )
34
+ end = time.perf_counter()
35
+ print(f"Tokenize: {end-start}")
36
+ start = time.perf_counter()
37
+ encoded_output = model.generate(input_ids=input_ids, attention_mask=attention_mask, do_sample=True, max_new_tokens=MAX_NEW_TOKENS)
38
+ answer = tokenizer.decode(encoded_output[0], skip_special_tokens=True)
39
+ end = time.perf_counter()
40
+ print(f"Generate: {end-start}")
41
+ user_history.append(question)
42
+ bot_history.append(answer)
43
+ return answer, user_history, bot_history
44
+
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ transformers
2
+ torch