hoaiht commited on
Commit
1986514
1 Parent(s): f50146d

Upload generate_gpt-j-vi.py

Browse files
Files changed (1) hide show
  1. generate_gpt-j-vi.py +183 -0
generate_gpt-j-vi.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import torch
3
+ from peft import PeftModel
4
+ import transformers
5
+ import gradio as gr
6
+
7
+ # assert (
8
+ # "LlamaTokenizer" in transformers._import_structure["models.llama"]
9
+ # ), "LLaMA is now in HuggingFace's main branch.\nPlease reinstall it: pip uninstall transformers && pip install git+https://github.com/huggingface/transformers.git"
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
11
+
12
+ tokenizer = AutoTokenizer.from_pretrained("VietAI/gpt-j-6B-vietnamese-news")
13
+
14
+ LOAD_8BIT = True
15
+ BASE_MODEL = "VietAI/gpt-j-6B-vietnamese-news"
16
+ # LORA_WEIGHTS = "tloen/alpaca-lora-7b"
17
+ # LORA_WEIGHTS = "hoaiht/alpaca-lora-7b-vi"
18
+ LORA_WEIGHTS = "hoaiht/vietnamese-alpaca-lora-gpt-j"
19
+
20
+ if torch.cuda.is_available():
21
+ device = "cuda"
22
+ else:
23
+ device = "cpu"
24
+
25
+ try:
26
+ if torch.backends.mps.is_available():
27
+ device = "mps"
28
+ except:
29
+ pass
30
+
31
+ if device == "cuda":
32
+ model = AutoModelForCausalLM.from_pretrained(
33
+ BASE_MODEL,
34
+ load_in_8bit=LOAD_8BIT,
35
+ torch_dtype=torch.float16,
36
+ device_map="auto",
37
+ )
38
+ model = PeftModel.from_pretrained(
39
+ model,
40
+ LORA_WEIGHTS,
41
+ torch_dtype=torch.float16,
42
+ )
43
+ elif device == "mps":
44
+ model = transformers.AutoModelForCausalLM.from_pretrained(
45
+ BASE_MODEL,
46
+ device_map={"": device},
47
+ torch_dtype=torch.float16,
48
+ )
49
+ model = PeftModel.from_pretrained(
50
+ model,
51
+ LORA_WEIGHTS,
52
+ device_map={"": device},
53
+ torch_dtype=torch.float16,
54
+ )
55
+ else:
56
+ model = transformers.AutoModelForCausalLM.from_pretrained(
57
+ BASE_MODEL, device_map={"": device}, low_cpu_mem_usage=True
58
+ )
59
+ model = PeftModel.from_pretrained(
60
+ model,
61
+ LORA_WEIGHTS,
62
+ device_map={"": device},
63
+ )
64
+
65
+
66
+ def generate_prompt(instruction, input=None):
67
+ if input:
68
+ # 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.
69
+ return f"""Dưới đây là một hướng dẫn mô tả một tác vụ, kèm theo một đầu vào cung cấp thêm ngữ cảnh. Viết một phản hồi hoàn thành yêu cầu một cách thích hợp.
70
+
71
+
72
+ ### Instruction:
73
+ {instruction}
74
+
75
+ ### Input:
76
+ {input}
77
+
78
+ ### Response:"""
79
+ else:
80
+ # return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
81
+ return f"""Dưới đây là một hướng dẫn mô tả một tác vụ. Viết một phản hồi hoàn thành yêu cầu một cách thích hợp.
82
+
83
+
84
+ ### Instruction:
85
+ {instruction}
86
+
87
+ ### Response:"""
88
+
89
+ if not LOAD_8BIT:
90
+ model.half() # seems to fix bugs for some users.
91
+
92
+ model.eval()
93
+ if torch.__version__ >= "2" and sys.platform != "win32":
94
+ model = torch.compile(model)
95
+
96
+
97
+ def evaluate(
98
+ instruction,
99
+ input=None,
100
+ temperature=0.1,
101
+ top_p=0.75,
102
+ top_k=40,
103
+ num_beams=4,
104
+ max_new_tokens=128,
105
+ **kwargs,
106
+ ):
107
+ prompt = generate_prompt(instruction, input)
108
+ inputs = tokenizer(prompt, return_tensors="pt")
109
+ input_ids = inputs["input_ids"].to(device)
110
+ generation_config = GenerationConfig(
111
+ temperature=temperature,
112
+ top_p=top_p,
113
+ top_k=top_k,
114
+ num_beams=num_beams,
115
+ **kwargs,
116
+ )
117
+ with torch.no_grad():
118
+ # generation_output = model.generate(
119
+ # input_ids=input_ids,
120
+ # generation_config=generation_config,
121
+ # return_dict_in_generate=True,
122
+ # output_scores=True,
123
+ # max_new_tokens=max_new_tokens,
124
+ # )
125
+ gen_tokens = model.generate(
126
+ input_ids=input_ids,
127
+ max_length=max_new_tokens,
128
+ do_sample=True,
129
+ temperature=0.9,
130
+ top_k=20
131
+ )
132
+ # s = generation_output.sequences[0]
133
+ # output = tokenizer.decode(s)
134
+ output = tokenizer.batch_decode(gen_tokens)[0]
135
+
136
+ return output.split("### Response:")[1].strip()
137
+
138
+
139
+ gr.Interface(
140
+ fn=evaluate,
141
+ inputs=[
142
+ gr.components.Textbox(
143
+ lines=2, label="Instruction", value="3 điều cần làm để duy trì sức khỏe."
144
+ ),
145
+ gr.components.Textbox(lines=2, label="Input", placeholder="none"),
146
+ gr.components.Slider(minimum=0, maximum=1, value=0.1, label="Temperature"),
147
+ gr.components.Slider(minimum=0, maximum=1, value=0.75, label="Top p"),
148
+ gr.components.Slider(minimum=0, maximum=100, step=1, value=40, label="Top k"),
149
+ gr.components.Slider(minimum=1, maximum=4, step=1, value=4, label="Beams"),
150
+ gr.components.Slider(
151
+ minimum=1, maximum=2000, step=1, value=128, label="Max tokens"
152
+ ),
153
+ ],
154
+ outputs=[
155
+ gr.inputs.Textbox(
156
+ lines=5,
157
+ label="Output",
158
+ )
159
+ ],
160
+ title="🦙🌲 Instruct-tune `VietAI/gpt-j-6B-vietnamese-news` on Alpaca dataset (Vietnamese version) using Alpaca-LoRA",
161
+ # 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).",
162
+ ).launch(share=True)
163
+
164
+ # Old testing code follows.
165
+
166
+ """
167
+ if __name__ == "__main__":
168
+ # testing code for readme
169
+ for instruction in [
170
+ "Tell me about alpacas.",
171
+ "Tell me about the president of Mexico in 2019.",
172
+ "Tell me about the king of France in 2019.",
173
+ "List all Canadian provinces in alphabetical order.",
174
+ "Write a Python program that prints the first 10 Fibonacci numbers.",
175
+ "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'.",
176
+ "Tell me five words that rhyme with 'shock'.",
177
+ "Translate the sentence 'I have no mouth but I must scream' into Spanish.",
178
+ "Count up from 1 to 500.",
179
+ ]:
180
+ print("Instruction:", instruction)
181
+ print("Response:", evaluate(instruction))
182
+ print()
183
+ """