darpan-jain commited on
Commit
7218e93
1 Parent(s): 8936ba0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -31
app.py CHANGED
@@ -1,44 +1,104 @@
1
- from transformers import AutoTokenizer, AutoModelForCausalLM
2
- import gradio as gr
3
  import torch
4
- import random
5
- import time
6
-
7
- # tokenizer = AutoTokenizer.from_pretrained("chavinlo/gpt4-x-alpaca")
8
- # model = AutoModelForCausalLM.from_pretrained("chavinlo/gpt4-x-alpaca")
9
 
10
- tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
11
- model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
 
 
12
 
 
 
 
13
 
14
- with gr.Blocks() as demo:
15
- chatbot = gr.Chatbot()
16
- msg = gr.Textbox()
17
- clear = gr.Button("Clear")
18
 
19
- def user(user_message, history):
20
- return "", history + [[user_message, None]]
 
 
 
 
 
 
 
 
21
 
22
- def bot(history):
23
- user_message = history[-1][0]
24
- new_user_input_ids = tokenizer.encode(user_message + tokenizer.eos_token, return_tensors='pt')
 
 
 
 
25
 
26
- # append the new user input tokens to the chat history
27
- bot_input_ids = torch.cat([torch.LongTensor(history), new_user_input_ids], dim=-1)
 
 
 
 
 
 
 
28
 
29
- # generate a response
30
- history = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id).tolist()
 
 
 
 
 
 
 
 
31
 
32
- # convert the tokens to text, and then split the responses into lines
33
- response = tokenizer.decode(history[0]).split("<|endoftext|>")
34
- response = [(response[i], response[i+1]) for i in range(0, len(response)-1, 2)] # convert to tuples of list
 
 
 
 
 
 
 
 
35
 
36
- return history
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
40
- bot, chatbot, chatbot
41
- )
42
- clear.click(lambda: None, None, chatbot, queue=False)
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- demo.launch()
 
 
1
+ from transformers import LlamaTokenizer, LlamaForCausalLM, GenerationConfig
2
+ from peft import PeftModel
3
  import torch
4
+ import transformers
5
+ import gradio as gr
 
 
 
6
 
7
+ MODEL = "decapoda-research/llama-7b-hf"
8
+ LORA_WEIGHTS = "tloen/alpaca-lora-7b"
9
+ device = "cpu"
10
+ print(f"Model device = {device}", flush=True)
11
 
12
+ tokenizer = LlamaTokenizer.from_pretrained(MODEL)
13
+ model = LlamaForCausalLM.from_pretrained(MODEL, device_map={"": device}, low_cpu_mem_usage=True)
14
+ model = PeftModel.from_pretrained(model, LORA_WEIGHTS, device_map={"": device},)
15
 
16
+ model.eval()
 
 
 
17
 
18
+ def generate_prompt(instruction, input=None):
19
+ if input:
20
+ return f""" Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
21
+
22
+ ### Instruction: {instruction}
23
+
24
+ ### Input: {input}
25
+
26
+ ### Response:
27
+ """
28
 
29
+ else:
30
+ return f""" Below is an instruction that describes a task. Write a response that appropriately completes the request.
31
+
32
+ ### Instruction: {instruction}
33
+
34
+ ### Response:
35
+ """
36
 
37
+ def eval_prompt(
38
+ instruction: str,
39
+ input = None,
40
+ temparature = 0.7,
41
+ top_p = 0.75,
42
+ top_k = 40,
43
+ num_beams = 3,
44
+ max_new_tokens = 128,
45
+ **kwargs):
46
 
47
+ prompt = generate_prompt(instruction, input)
48
+ inputs = tokenizer(prompt, return_tensor = 'pt')
49
+ input_ids = inputs['input_ids']
50
+ generation_config = GenerationConfig(
51
+ temparatue = temparature,
52
+ top_p = top_p,
53
+ top_k = top_k,
54
+ num_beams = num_beams,
55
+ repetition_penalty = 1.17,
56
+ ** kwargs,)
57
 
58
+ with torch.no_grad():
59
+ generation_output = model.generate(
60
+ input_ids = input_ids,
61
+ generation_config = generation_config,
62
+ return_dict_in_generate = True,
63
+ output_scores = True,
64
+ max_new_tokens = max_new_tokens,
65
+ )
66
+ s = generation_output.sequence[0]
67
+ response = tokenizer.decode(s)
68
+ return response.split("### Response: ")[1].strip()
69
 
 
70
 
71
+ # def run_app():
72
+ # g = gr.Interface(
73
+ # fn = eval_prompt,
74
+ # inputs = [
75
+ # gr.components.Textbox(
76
+ # lines = 2, label = 'Instruction', placeholder= "Enter an instruction here."),
77
+ # gr.components.Textbox(lines = 2, label = 'Input', placeholder = "Add an input here.")
78
+ # ],
79
+ # outputs = [ gr.inputs.Textbox(lines = 5, label = 'Output') ],
80
+ # title = 'Alpaca Demo'
81
+ # )
82
+ #
83
+ # g.queue(concurrency_count=1)
84
+ # g.launch(share=True, debug=True)
85
 
86
+ if __name__ == "__main__":
87
+ # testing code for readme
88
+ for instruction in [
89
+ # "Tell me about alpacas.",
90
+ # "Tell me about the president of Mexico in 2019.",
91
+ # "Tell me about the king of France in 2019.",
92
+ # "List all Canadian provinces in alphabetical order.",
93
+ # "Write a Python program that prints the first 10 Fibonacci numbers.",
94
+ # "Write a program that prints the numbers from 1 to 100. But for multiples of three print 'Fizz' instead of the number and for the multiples of five print 'Buzz'. For numbers which are multiples of both three and five print 'FizzBuzz'.",
95
+ "Tell me five words that rhyme with 'shock'.",
96
+ "Translate the sentence 'I have no mouth but I must scream' into Spanish.",
97
+ # "Count up from 1 to 500.",
98
+ ]:
99
+ print("Instruction:", instruction)
100
+ print("Response:", eval_prompt(instruction))
101
+ print()
102
 
103
+ ## Run the actual gradio app
104
+ # run_app()