netmouse commited on
Commit
c2930d6
·
verified ·
1 Parent(s): be78ad9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -144
app.py CHANGED
@@ -1,150 +1,146 @@
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("yentinglin/Llama-3-Taiwan-8B-Instruct")
12
-
13
- BASE_MODEL = "yentinglin/Llama-3-Taiwan-8B-Instruct"
14
- LORA_WEIGHTS = "netmouse/Llama-3-Taiwan-8B-Instruct-finetuning-by-promisedchat"
15
-
16
- if torch.cuda.is_available():
17
- device = "cuda"
18
- else:
19
- device = "cpu"
20
-
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=True,
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
- pass
76
- #model.half()
77
- model.eval()
78
- if torch.__version__ >= "2":
79
- model = torch.compile(model)
80
-
81
-
82
- def evaluate(
83
- instruction,
84
- input=None,
85
- temperature=0.1,
86
- top_p=0.75,
87
- top_k=40,
88
- num_beams=4,
89
- max_new_tokens=128,
90
- **kwargs,
91
- ):
92
- if instruction == '' or instruction == None:
93
- return 'Instruction not found. Please enter your instruction.\nInstructionを入力してください。'
94
- prompt = generate_prompt(instruction, input)
95
- inputs = tokenizer(prompt, return_tensors="pt")
96
- input_ids = inputs["input_ids"].to(device)
97
- generation_config = GenerationConfig(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  temperature=temperature,
99
- top_p=top_p,
100
- top_k=top_k,
101
- num_beams=num_beams,
102
- **kwargs,
103
  )
104
- with torch.no_grad():
105
- generation_output = model.generate(
106
- input_ids=input_ids,
107
- generation_config=generation_config,
108
- return_dict_in_generate=True,
109
- output_scores=True,
110
- max_new_tokens=max_new_tokens,
111
- )
112
- s = generation_output.sequences[0]
113
- output = tokenizer.decode(s)
114
- return output.split("### Response:")[1].strip().replace('</s>', '')
115
-
116
-
117
- g = gr.Interface(
118
- fn=evaluate,
119
- inputs=[
120
- gr.components.Textbox(
121
- lines=2, label="Instruction", placeholder="例1:日本語から英語に翻訳してください。\n\
122
- 例2:このテキストを要約してください。\n\
123
- 例3:英語から日本語に翻訳してください。"
124
- ),
125
- gr.components.Textbox(lines=2, label="Input", placeholder="例1:日本語のテキスト\n\
126
- 例2:日本語の長いテキスト\n\
127
- 例3:英語のテキスト"),
128
- gr.components.Slider(minimum=0, maximum=1, value=0.1, label="Temperature"),
129
- gr.components.Slider(minimum=0, maximum=1, value=0.75, label="Top p"),
130
- gr.components.Slider(minimum=0, maximum=100, step=1, value=40, label="Top k"),
131
- gr.components.Slider(minimum=1, maximum=4, step=1, value=4, label="Beams"),
132
- gr.components.Slider(
133
- minimum=1, maximum=1000, step=1, value=128, label="Max tokens"
134
- ),
135
- ],
136
- outputs=[
137
- gr.inputs.Textbox(
138
- lines=5,
139
- label="Output",
140
- )
141
- ],
142
- title="Llama2_13b_chat_Japanese_Lora",
143
- description="Llama-2-13b-chat-Japanese-LoRA is a multi-purpose large language model for Japanese text.\n\
144
- This model is presented by the joint effort of Sparticle Inc. and A. I. Hakusan Inc.\n\
145
- Llama-2-13b-chat-Japanese-LoRAは日本語テキストのための多目的大規模言語モデルです。\n\
146
- このモデルは日本語を話せます。日本語で指示を入力することができます。\n\
147
- このモデルは、Sparticle株式会社と株式会社白山人工知能の共同開発により発表されました。",
148
- )
149
- g.queue(concurrency_count=1)
150
- g.launch()
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ import spaces
4
+ from transformers import GemmaTokenizer, AutoModelForCausalLM
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
+ from threading import Thread
7
 
8
+ # Set an environment variable
9
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
10
+
11
+
12
+ DESCRIPTION = '''
13
+ <div>
14
+ <h1 style="text-align: center;">Meta Llama3 8B</h1>
15
+ <p>This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct"><b>Meta Llama3 8b Chat</b></a>. Meta Llama3 is the new open LLM and comes in two sizes: 8b and 70b. Feel free to play with it, or duplicate to run privately!</p>
16
+ <p>🔎 For more details about the Llama3 release and how to use the model with <code>transformers</code>, take a look <a href="https://huggingface.co/blog/llama3">at our blog post</a>.</p>
17
+ <p>🦕 Looking for an even more powerful model? Check out the <a href="https://huggingface.co/chat/"><b>Hugging Chat</b></a> integration for Meta Llama 3 70b</p>
18
+ </div>
19
+ '''
20
+
21
+ LICENSE = """
22
+ <p/>
23
+
24
+ ---
25
+ Built with Meta Llama 3
26
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ PLACEHOLDER = """
29
+ <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
30
+ <img src="https://ysharma-dummy-chat-app.hf.space/file=/tmp/gradio/8e75e61cc9bab22b7ce3dec85ab0e6db1da5d107/Meta_lockup_positive%20primary_RGB.jpg" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
31
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Meta llama3</h1>
32
+ <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
33
+ </div>
34
+ """
35
 
36
+
37
+ css = """
38
+ h1 {
39
+ text-align: center;
40
+ display: block;
41
+ }
42
+
43
+ #duplicate-button {
44
+ margin: auto;
45
+ color: white;
46
+ background: #1565c0;
47
+ border-radius: 100vh;
48
+ }
49
+ """
50
+
51
+ # Load the tokenizer and model
52
+ tokenizer = AutoTokenizer.from_pretrained("yentinglin/Llama-3-Taiwan-8B-Instruct")
53
+ model = AutoModelForCausalLM.from_pretrained("netmouse/Llama-3-Taiwan-8B-Instruct-finetuning-by-promisedchat", device_map="auto") # to("cuda:0")
54
+ terminators = [
55
+ tokenizer.eos_token_id,
56
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
57
+ ]
58
+
59
+ @spaces.GPU(duration=120)
60
+ def chat_llama3_8b(message: str,
61
+ history: list,
62
+ temperature: float,
63
+ max_new_tokens: int
64
+ ) -> str:
65
+ """
66
+ Generate a streaming response using the llama3-8b model.
67
+ Args:
68
+ message (str): The input message.
69
+ history (list): The conversation history used by ChatInterface.
70
+ temperature (float): The temperature for generating the response.
71
+ max_new_tokens (int): The maximum number of new tokens to generate.
72
+ Returns:
73
+ str: The generated response.
74
+ """
75
+ conversation = []
76
+ for user, assistant in history:
77
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
78
+ conversation.append({"role": "user", "content": message})
79
+
80
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
81
+
82
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
83
+
84
+ generate_kwargs = dict(
85
+ input_ids= input_ids,
86
+ streamer=streamer,
87
+ max_new_tokens=max_new_tokens,
88
+ do_sample=True,
89
  temperature=temperature,
90
+ eos_token_id=terminators,
 
 
 
91
  )
92
+ # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
93
+ if temperature == 0:
94
+ generate_kwargs['do_sample'] = False
95
+
96
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
97
+ t.start()
98
+
99
+ outputs = []
100
+ for text in streamer:
101
+ outputs.append(text)
102
+ #print(outputs)
103
+ yield "".join(outputs)
104
+
105
+
106
+ # Gradio block
107
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
108
+
109
+ with gr.Blocks(fill_height=True, css=css) as demo:
110
+
111
+ gr.Markdown(DESCRIPTION)
112
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
113
+ gr.ChatInterface(
114
+ fn=chat_llama3_8b,
115
+ chatbot=chatbot,
116
+ fill_height=True,
117
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
118
+ additional_inputs=[
119
+ gr.Slider(minimum=0,
120
+ maximum=1,
121
+ step=0.1,
122
+ value=0.95,
123
+ label="Temperature",
124
+ render=False),
125
+ gr.Slider(minimum=128,
126
+ maximum=4096,
127
+ step=1,
128
+ value=512,
129
+ label="Max new tokens",
130
+ render=False ),
131
+ ],
132
+ examples=[
133
+ ['How to setup a human base on Mars? Give short answer.'],
134
+ ['Explain theory of relativity to me like I’m 8 years old.'],
135
+ ['What is 9,000 * 9,000?'],
136
+ ['Write a pun-filled happy birthday message to my friend Alex.'],
137
+ ['Justify why a penguin might make a good king of the jungle.']
138
+ ],
139
+ cache_examples=False,
140
+ )
141
+
142
+ gr.Markdown(LICENSE)
143
+
144
+ if __name__ == "__main__":
145
+ demo.launch()
146
+