KaizeShi commited on
Commit
954a751
·
1 Parent(s): 32800b9

Add application file

Browse files
Files changed (1) hide show
  1. app.py +122 -204
app.py CHANGED
@@ -1,15 +1,17 @@
1
- import os
2
- import sys
3
-
4
- import fire
5
- import gradio as gr
6
  import torch
7
- import transformers
8
  from peft import PeftModel
9
- from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer
 
10
 
11
- from utils.callbacks import Iteratorize, Stream
12
- from utils.prompter import Prompter
 
 
 
 
 
 
 
13
 
14
  if torch.cuda.is_available():
15
  device = "cuda"
@@ -19,203 +21,119 @@ else:
19
  try:
20
  if torch.backends.mps.is_available():
21
  device = "mps"
22
- except: # noqa: E722
23
  pass
24
 
25
- access_token = os.environ.get('HF_TOKEN')
26
-
27
- def main(
28
- load_8bit: bool = True,
29
- base_model: str = "meta-llama/Llama-2-7b-hf",
30
- lora_weights: str = "DSMI/LLaMA-E/7b",
31
- prompt_template: str = "", # The prompt template to use, will default to alpaca.
32
- server_name: str = "0.0.0.0", # Allows to listen on all interfaces by providing '0.
33
- share_gradio: bool = False,
34
- ):
35
- print("lora_weights: " + str(lora_weights))
36
- base_model = base_model or os.environ.get("BASE_MODEL", "")
37
- assert (
38
- base_model
39
- ), "Please specify a --base_model, e.g. --base_model='huggyllama/llama-7b'"
40
-
41
- prompter = Prompter(prompt_template)
42
- tokenizer = LlamaTokenizer.from_pretrained(base_model, token=access_token)
43
- if device == "cuda":
44
- model = LlamaForCausalLM.from_pretrained(
45
- base_model,
46
- load_in_8bit=load_8bit,
47
- torch_dtype=torch.float16,
48
- device_map="auto",
49
- )
50
- model = PeftModel.from_pretrained(
51
- model,
52
- lora_weights,
53
- torch_dtype=torch.float16,
54
- )
55
- elif device == "mps":
56
- model = LlamaForCausalLM.from_pretrained(
57
- base_model,
58
- device_map={"": device},
59
- torch_dtype=torch.float16,
60
- )
61
- model = PeftModel.from_pretrained(
62
- model,
63
- lora_weights,
64
- device_map={"": device},
65
- torch_dtype=torch.float16,
66
- )
67
  else:
68
- model = LlamaForCausalLM.from_pretrained(
69
- base_model, device_map={"": device}, low_cpu_mem_usage=True
70
- )
71
- model = PeftModel.from_pretrained(
72
- model,
73
- lora_weights,
74
- device_map={"": device},
75
- )
76
-
77
- # unwind broken decapoda-research config
78
- model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk
79
- model.config.bos_token_id = 1
80
- model.config.eos_token_id = 2
81
-
82
- if not load_8bit:
83
- model.half() # seems to fix bugs for some users.
84
-
85
- model.eval()
86
- if torch.__version__ >= "2" and sys.platform != "win32":
87
- model = torch.compile(model)
88
-
89
- def evaluate(
90
- instruction,
91
- input=None,
92
- temperature=0.1,
93
- top_p=0.75,
94
- top_k=40,
95
- num_beams=4,
96
- max_new_tokens=128,
97
- stream_output=False,
98
  **kwargs,
99
- ):
100
- prompt = prompter.generate_prompt(instruction, input)
101
- inputs = tokenizer(prompt, return_tensors="pt")
102
- input_ids = inputs["input_ids"].to(device)
103
- generation_config = GenerationConfig(
104
- temperature=temperature,
105
- top_p=top_p,
106
- top_k=top_k,
107
- num_beams=num_beams,
108
- **kwargs,
109
  )
110
-
111
- generate_params = {
112
- "input_ids": input_ids,
113
- "generation_config": generation_config,
114
- "return_dict_in_generate": True,
115
- "output_scores": True,
116
- "max_new_tokens": max_new_tokens,
117
- }
118
-
119
- if stream_output:
120
- # Stream the reply 1 token at a time.
121
- # This is based on the trick of using 'stopping_criteria' to create an iterator,
122
- # from https://github.com/oobabooga/text-generation-webui/blob/ad37f396fc8bcbab90e11ecf17c56c97bfbd4a9c/modules/text_generation.py#L216-L243.
123
-
124
- def generate_with_callback(callback=None, **kwargs):
125
- kwargs.setdefault(
126
- "stopping_criteria", transformers.StoppingCriteriaList()
127
- )
128
- kwargs["stopping_criteria"].append(
129
- Stream(callback_func=callback)
130
- )
131
- with torch.no_grad():
132
- model.generate(**kwargs)
133
-
134
- def generate_with_streaming(**kwargs):
135
- return Iteratorize(
136
- generate_with_callback, kwargs, callback=None
137
- )
138
-
139
- with generate_with_streaming(**generate_params) as generator:
140
- for output in generator:
141
- # new_tokens = len(output) - len(input_ids[0])
142
- decoded_output = tokenizer.decode(output)
143
-
144
- if output[-1] in [tokenizer.eos_token_id]:
145
- break
146
-
147
- yield prompter.get_response(decoded_output)
148
- return # early return for stream_output
149
-
150
- # Without streaming
151
- with torch.no_grad():
152
- generation_output = model.generate(
153
- input_ids=input_ids,
154
- generation_config=generation_config,
155
- return_dict_in_generate=True,
156
- output_scores=True,
157
- max_new_tokens=max_new_tokens,
158
- )
159
- s = generation_output.sequences[0]
160
- output = tokenizer.decode(s)
161
- yield prompter.get_response(output)
162
-
163
- gr.Interface(
164
- fn=evaluate,
165
- inputs=[
166
- gr.components.Textbox(
167
- lines=2,
168
- label="Instruction",
169
- placeholder="Generate an Ad for the iPhone 14.",
170
- ),
171
- gr.components.Textbox(lines=2, label="Input", placeholder="none"),
172
- gr.components.Slider(
173
- minimum=0, maximum=1, value=0.1, label="Temperature"
174
- ),
175
- gr.components.Slider(
176
- minimum=0, maximum=1, value=0.75, label="Top p"
177
- ),
178
- gr.components.Slider(
179
- minimum=0, maximum=100, step=1, value=40, label="Top k"
180
- ),
181
- gr.components.Slider(
182
- minimum=1, maximum=4, step=1, value=4, label="Beams"
183
- ),
184
- gr.components.Slider(
185
- minimum=1, maximum=2000, step=1, value=128, label="Max tokens"
186
- ),
187
- gr.components.Checkbox(label="Stream output"),
188
- ],
189
- outputs=[
190
- gr.inputs.Textbox(
191
- lines=5,
192
- label="Output",
193
- )
194
- ],
195
- title="🦙🛍️ LLaMA-E",
196
- description="LLaMA-E is a series of fine-tuned LLaMA model following the E-commerce instructions. It is developed by DSMI (http://dsmi.tech/) @ University of Technology Sydney, and trained on the 120k instruction set. This model is for academic research use only. For more details please contact: Kaize.Shi@uts.edu.au",
197
- # noqa: E501
198
- ).queue().launch(server_name="0.0.0.0", share=share_gradio)
199
- # Old testing code follows.
200
-
201
- """
202
- # testing code for readme
203
- for instruction in [
204
- "Tell me about alpacas.",
205
- "Tell me about the president of Mexico in 2019.",
206
- "Tell me about the king of France in 2019.",
207
- "List all Canadian provinces in alphabetical order.",
208
- "Write a Python program that prints the first 10 Fibonacci numbers.",
209
- "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'.", # noqa: E501
210
- "Tell me five words that rhyme with 'shock'.",
211
- "Translate the sentence 'I have no mouth but I must scream' into Spanish.",
212
- "Count up from 1 to 500.",
213
- ]:
214
- print("Instruction:", instruction)
215
- print("Response:", evaluate(instruction))
216
- print()
217
- """
218
-
219
-
220
- if __name__ == "__main__":
221
- fire.Fire(main)
 
 
 
 
 
 
1
  import torch
 
2
  from peft import PeftModel
3
+ import transformers
4
+ import gradio as gr
5
 
6
+ assert (
7
+ "LlamaTokenizer" in transformers._import_structure["models.llama"]
8
+ ), "LLaMA is now in HuggingFace's main branch.\nPlease reinstall it: pip uninstall transformers && pip install git+https://github.com/huggingface/transformers.git"
9
+ from transformers import LlamaTokenizer, LlamaForCausalLM, GenerationConfig
10
+
11
+ tokenizer = LlamaTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
12
+
13
+ BASE_MODEL = "meta-llama/Llama-2-7b-hf"
14
+ LORA_WEIGHTS = "DSMI/LLaMA-E"
15
 
16
  if torch.cuda.is_available():
17
  device = "cuda"
 
21
  try:
22
  if torch.backends.mps.is_available():
23
  device = "mps"
24
+ except:
25
  pass
26
 
27
+ if device == "cuda":
28
+ model = LlamaForCausalLM.from_pretrained(
29
+ BASE_MODEL,
30
+ load_in_8bit=False,
31
+ torch_dtype=torch.float16,
32
+ device_map="auto",
33
+ )
34
+ model = PeftModel.from_pretrained(
35
+ model, LORA_WEIGHTS, torch_dtype=torch.float16, force_download=True
36
+ )
37
+ elif device == "mps":
38
+ model = LlamaForCausalLM.from_pretrained(
39
+ BASE_MODEL,
40
+ device_map={"": device},
41
+ torch_dtype=torch.float16,
42
+ )
43
+ model = PeftModel.from_pretrained(
44
+ model,
45
+ LORA_WEIGHTS,
46
+ device_map={"": device},
47
+ torch_dtype=torch.float16,
48
+ )
49
+ else:
50
+ model = LlamaForCausalLM.from_pretrained(
51
+ BASE_MODEL, device_map={"": device}, low_cpu_mem_usage=True
52
+ )
53
+ model = PeftModel.from_pretrained(
54
+ model,
55
+ LORA_WEIGHTS,
56
+ device_map={"": device},
57
+ )
58
+
59
+
60
+ def generate_prompt(instruction, input=None):
61
+ if input:
62
+ 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.
63
+ ### Instruction:
64
+ {instruction}
65
+ ### Input:
66
+ {input}
67
+ ### Response:"""
 
68
  else:
69
+ return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
70
+ ### Instruction:
71
+ {instruction}
72
+ ### Response:"""
73
+
74
+ if device != "cpu":
75
+ model.half()
76
+ model.eval()
77
+ if torch.__version__ >= "2":
78
+ model = torch.compile(model)
79
+
80
+
81
+ def evaluate(
82
+ instruction,
83
+ input=None,
84
+ temperature=0.1,
85
+ top_p=0.75,
86
+ top_k=40,
87
+ num_beams=4,
88
+ max_new_tokens=128,
89
+ **kwargs,
90
+ ):
91
+ prompt = generate_prompt(instruction, input)
92
+ inputs = tokenizer(prompt, return_tensors="pt")
93
+ input_ids = inputs["input_ids"].to(device)
94
+ generation_config = GenerationConfig(
95
+ temperature=temperature,
96
+ top_p=top_p,
97
+ top_k=top_k,
98
+ num_beams=num_beams,
99
  **kwargs,
100
+ )
101
+ with torch.no_grad():
102
+ generation_output = model.generate(
103
+ input_ids=input_ids,
104
+ generation_config=generation_config,
105
+ return_dict_in_generate=True,
106
+ output_scores=True,
107
+ max_new_tokens=max_new_tokens,
 
 
108
  )
109
+ s = generation_output.sequences[0]
110
+ output = tokenizer.decode(s)
111
+ return output.split("### Response:")[1].strip()
112
+
113
+
114
+ g = gr.Interface(
115
+ fn=evaluate,
116
+ inputs=[
117
+ gr.components.Textbox(
118
+ lines=2, label="Instruction", placeholder="Tell me about alpacas."
119
+ ),
120
+ gr.components.Textbox(lines=2, label="Input", placeholder="none"),
121
+ gr.components.Slider(minimum=0, maximum=1, value=0.1, label="Temperature"),
122
+ gr.components.Slider(minimum=0, maximum=1, value=0.75, label="Top p"),
123
+ gr.components.Slider(minimum=0, maximum=100, step=1, value=40, label="Top k"),
124
+ gr.components.Slider(minimum=1, maximum=4, step=1, value=4, label="Beams"),
125
+ gr.components.Slider(
126
+ minimum=1, maximum=512, step=1, value=128, label="Max tokens"
127
+ ),
128
+ ],
129
+ outputs=[
130
+ gr.inputs.Textbox(
131
+ lines=5,
132
+ label="Output",
133
+ )
134
+ ],
135
+ title="🦙🛍️ LLaMA-E",
136
+ description="LLaMA-E is a series of fine-tuned LLaMA model following the E-commerce instructions. It is developed by DSMI (http://dsmi.tech/) @ University of Technology Sydney, and trained on the 120k instruction set. This model is for academic research use only. For more details please contact: Kaize.Shi@uts.edu.au",
137
+ )
138
+ g.queue(concurrency_count=1)
139
+ g.launch()