lifeofcoding commited on
Commit
f738540
β€’
1 Parent(s): 2a98166
Files changed (2) hide show
  1. app.py +3 -2
  2. app2.py +277 -0
app.py CHANGED
@@ -11,7 +11,8 @@ from transformers import LlamaTokenizer, LlamaForCausalLM, GenerationConfig
11
  tokenizer = LlamaTokenizer.from_pretrained("decapoda-research/llama-7b-hf")
12
 
13
  BASE_MODEL = "decapoda-research/llama-7b-hf"
14
- LORA_WEIGHTS = "tloen/alpaca-lora-7b"
 
15
 
16
  if torch.cuda.is_available():
17
  device = "cuda"
@@ -137,7 +138,7 @@ g = gr.Interface(
137
  label="Output",
138
  )
139
  ],
140
- title="πŸ¦™πŸŒ² Alpaca-LoRA",
141
  description="Alpaca-LoRA is a 7B-parameter LLaMA model finetuned to follow instructions. It is trained on the [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca) dataset and makes use of the Huggingface LLaMA implementation. For more information, please visit [the project's website](https://github.com/tloen/alpaca-lora).",
142
  )
143
  g.queue(concurrency_count=1)
 
11
  tokenizer = LlamaTokenizer.from_pretrained("decapoda-research/llama-7b-hf")
12
 
13
  BASE_MODEL = "decapoda-research/llama-7b-hf"
14
+ LORA_WEIGHTS = "lifeofcoding/alpaca-lora-movie-review-sentiment"
15
+
16
 
17
  if torch.cuda.is_available():
18
  device = "cuda"
 
138
  label="Output",
139
  )
140
  ],
141
+ title="πŸ¦™πŸŒ² Alpaca-LoRA (Fined tuned by LifeOfCoding)",
142
  description="Alpaca-LoRA is a 7B-parameter LLaMA model finetuned to follow instructions. It is trained on the [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca) dataset and makes use of the Huggingface LLaMA implementation. For more information, please visit [the project's website](https://github.com/tloen/alpaca-lora).",
143
  )
144
  g.queue(concurrency_count=1)
app2.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from peft import PeftModel
3
+ import transformers
4
+ import gradio as gr
5
+ from gradio.themes.base import Base
6
+ from gradio.themes.utils import colors, fonts, sizes
7
+ from typing import Iterable
8
+
9
+ assert (
10
+ "LlamaTokenizer" in transformers._import_structure["models.llama"]
11
+ ), "LLaMA is now in HuggingFace's main branch.\nPlease reinstall it: pip uninstall transformers && pip install git+https://github.com/huggingface/transformers.git"
12
+ from transformers import LlamaTokenizer, LlamaForCausalLM, GenerationConfig
13
+
14
+ tokenizer = LlamaTokenizer.from_pretrained("decapoda-research/llama-7b-hf")
15
+
16
+ BASE_MODEL = "decapoda-research/llama-7b-hf"
17
+ LORA_WEIGHTS = "lifeofcoding/alpaca-lora-movie-review-sentiment"
18
+
19
+ theme = gr.themes.Monochrome(
20
+ primary_hue="indigo",
21
+ secondary_hue="blue",
22
+ neutral_hue="slate",
23
+ radius_size=gr.themes.sizes.radius_sm,
24
+ font=[gr.themes.GoogleFont("Open Sans"), "ui-sans-serif", "system-ui", "sans-serif"],
25
+ )
26
+
27
+
28
+ if torch.cuda.is_available():
29
+ device = "cuda"
30
+ else:
31
+ device = "cpu"
32
+
33
+ try:
34
+ if torch.backends.mps.is_available():
35
+ device = "mps"
36
+ except:
37
+ pass
38
+
39
+ if device == "cuda":
40
+ model = LlamaForCausalLM.from_pretrained(
41
+ BASE_MODEL,
42
+ load_in_8bit=False,
43
+ torch_dtype=torch.float16,
44
+ device_map="auto",
45
+ )
46
+ model = PeftModel.from_pretrained(
47
+ model, LORA_WEIGHTS, torch_dtype=torch.float16, force_download=True
48
+ )
49
+ elif device == "mps":
50
+ model = LlamaForCausalLM.from_pretrained(
51
+ BASE_MODEL,
52
+ device_map={"": device},
53
+ torch_dtype=torch.float16,
54
+ )
55
+ model = PeftModel.from_pretrained(
56
+ model,
57
+ LORA_WEIGHTS,
58
+ device_map={"": device},
59
+ torch_dtype=torch.float16,
60
+ )
61
+ else:
62
+ model = LlamaForCausalLM.from_pretrained(
63
+ BASE_MODEL, device_map={"": device}, low_cpu_mem_usage=True
64
+ )
65
+ model = PeftModel.from_pretrained(
66
+ model,
67
+ LORA_WEIGHTS,
68
+ device_map={"": device},
69
+ )
70
+
71
+
72
+ def generate_prompt(instruction, input=None):
73
+ if input:
74
+ 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.
75
+
76
+ ### Instruction:
77
+ {instruction}
78
+
79
+ ### Input:
80
+ {input}
81
+
82
+ ### Response:"""
83
+ else:
84
+ return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
85
+
86
+ ### Instruction:
87
+ {instruction}
88
+
89
+ ### Response:"""
90
+
91
+ if device != "cpu":
92
+ model.half()
93
+ model.eval()
94
+ if torch.__version__ >= "2":
95
+ model = torch.compile(model)
96
+
97
+
98
+ def evaluate(
99
+ instruction,
100
+ input=None,
101
+ temperature=0.1,
102
+ top_p=0.75,
103
+ top_k=40,
104
+ num_beams=4,
105
+ max_new_tokens=128,
106
+ **kwargs,
107
+ ):
108
+ prompt = generate_prompt(instruction, input)
109
+ inputs = tokenizer(prompt, return_tensors="pt")
110
+ input_ids = inputs["input_ids"].to(device)
111
+ generation_config = GenerationConfig(
112
+ temperature=temperature,
113
+ top_p=top_p,
114
+ top_k=top_k,
115
+ num_beams=num_beams,
116
+ **kwargs,
117
+ )
118
+ with torch.no_grad():
119
+ generation_output = model.generate(
120
+ input_ids=input_ids,
121
+ generation_config=generation_config,
122
+ return_dict_in_generate=True,
123
+ output_scores=True,
124
+ max_new_tokens=max_new_tokens,
125
+ )
126
+ s = generation_output.sequences[0]
127
+ output = tokenizer.decode(s)
128
+ return output.split("### Response:")[1].strip()
129
+
130
+
131
+ examples = [
132
+ "Instead of making a peanut butter and jelly sandwich, what else could I combine peanut butter with in a sandwich? Give five ideas",
133
+ "How do I make a campfire?",
134
+ "Explain to me the difference between nuclear fission and fusion.",
135
+ "Write an ad for sale Nikon D750."
136
+ ]
137
+
138
+ def process_example(args):
139
+ for x in evaluate(args):
140
+ pass
141
+ return x
142
+
143
+ css = ".generating {visibility: hidden}"
144
+
145
+ # Based on the gradio theming guide and borrowed from https://huggingface.co/spaces/shivi/dolly-v2-demo
146
+ class SeafoamCustom(Base):
147
+ def __init__(
148
+ self,
149
+ *,
150
+ primary_hue: colors.Color | str = colors.emerald,
151
+ secondary_hue: colors.Color | str = colors.blue,
152
+ neutral_hue: colors.Color | str = colors.blue,
153
+ spacing_size: sizes.Size | str = sizes.spacing_md,
154
+ radius_size: sizes.Size | str = sizes.radius_md,
155
+ font: fonts.Font
156
+ | str
157
+ | Iterable[fonts.Font | str] = (
158
+ fonts.GoogleFont("Quicksand"),
159
+ "ui-sans-serif",
160
+ "sans-serif",
161
+ ),
162
+ font_mono: fonts.Font
163
+ | str
164
+ | Iterable[fonts.Font | str] = (
165
+ fonts.GoogleFont("IBM Plex Mono"),
166
+ "ui-monospace",
167
+ "monospace",
168
+ ),
169
+ ):
170
+ super().__init__(
171
+ primary_hue=primary_hue,
172
+ secondary_hue=secondary_hue,
173
+ neutral_hue=neutral_hue,
174
+ spacing_size=spacing_size,
175
+ radius_size=radius_size,
176
+ font=font,
177
+ font_mono=font_mono,
178
+ )
179
+ super().set(
180
+ button_primary_background_fill="linear-gradient(90deg, *primary_300, *secondary_400)",
181
+ button_primary_background_fill_hover="linear-gradient(90deg, *primary_200, *secondary_300)",
182
+ button_primary_text_color="white",
183
+ button_primary_background_fill_dark="linear-gradient(90deg, *primary_600, *secondary_800)",
184
+ block_shadow="*shadow_drop_lg",
185
+ button_shadow="*shadow_drop_lg",
186
+ input_background_fill="zinc",
187
+ input_border_color="*secondary_300",
188
+ input_shadow="*shadow_drop",
189
+ input_shadow_focus="*shadow_drop_lg",
190
+ )
191
+
192
+
193
+ seafoam = SeafoamCustom()
194
+
195
+
196
+ with gr.Blocks(theme=seafoam, analytics_enabled=False, css=css) as demo:
197
+ with gr.Column():
198
+ gr.Markdown(
199
+ """ ## Alpaca-LoRa
200
+ 13b quantized 4bit (q4_1)
201
+
202
+ Type in the box below and click the button to generate answers to your most pressing questions!
203
+
204
+ """
205
+ )
206
+
207
+ with gr.Row():
208
+ with gr.Column(scale=3):
209
+ instruction = gr.Textbox(placeholder="Enter your question here", label="Question", elem_id="q-input")
210
+
211
+ with gr.Box():
212
+ gr.Markdown("**Answer**")
213
+ output = gr.Markdown(elem_id="q-output")
214
+ submit = gr.Button("Generate", variant="primary")
215
+ gr.Examples(
216
+ examples=examples,
217
+ inputs=[instruction],
218
+ cache_examples=False,
219
+ fn=process_example,
220
+ outputs=[output],
221
+ )
222
+
223
+
224
+
225
+ submit.click(evaluate, inputs=[instruction], outputs=[output])
226
+ instruction.submit(evaluate, inputs=[instruction], outputs=[output])
227
+
228
+ demo.queue(concurrency_count=1).launch(debug=True)
229
+
230
+ """
231
+ g = gr.Interface(
232
+ fn=evaluate,
233
+ inputs=[
234
+ gr.components.Textbox(
235
+ lines=2, label="Instruction", placeholder="Tell me about alpacas."
236
+ ),
237
+ gr.components.Textbox(lines=2, label="Input", placeholder="none"),
238
+ gr.components.Slider(minimum=0, maximum=1, value=0.1, label="Temperature"),
239
+ gr.components.Slider(minimum=0, maximum=1, value=0.75, label="Top p"),
240
+ gr.components.Slider(minimum=0, maximum=100, step=1, value=40, label="Top k"),
241
+ gr.components.Slider(minimum=1, maximum=4, step=1, value=4, label="Beams"),
242
+ gr.components.Slider(
243
+ minimum=1, maximum=512, step=1, value=128, label="Max tokens"
244
+ ),
245
+ ],
246
+ outputs=[
247
+ gr.inputs.Textbox(
248
+ lines=5,
249
+ label="Output",
250
+ )
251
+ ],
252
+ title="πŸ¦™πŸŒ² Alpaca-LoRA",
253
+ description="Alpaca-LoRA is a 7B-parameter LLaMA model finetuned to follow instructions. It is trained on the [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca) dataset and makes use of the Huggingface LLaMA implementation. For more information, please visit [the project's website](https://github.com/tloen/alpaca-lora).",
254
+ )
255
+ g.queue(concurrency_count=1)
256
+ g.launch()
257
+ """
258
+ # Old testing code follows.
259
+
260
+ """
261
+ if __name__ == "__main__":
262
+ # testing code for readme
263
+ for instruction in [
264
+ "Tell me about alpacas.",
265
+ "Tell me about the president of Mexico in 2019.",
266
+ "Tell me about the king of France in 2019.",
267
+ "List all Canadian provinces in alphabetical order.",
268
+ "Write a Python program that prints the first 10 Fibonacci numbers.",
269
+ "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'.",
270
+ "Tell me five words that rhyme with 'shock'.",
271
+ "Translate the sentence 'I have no mouth but I must scream' into Spanish.",
272
+ "Count up from 1 to 500.",
273
+ ]:
274
+ print("Instruction:", instruction)
275
+ print("Response:", evaluate(instruction))
276
+ print()
277
+ """