longface commited on
Commit
79d2ca5
·
1 Parent(s): a6e7726

Upload App.py

Browse files
Files changed (1) hide show
  1. App.py +153 -0
App.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """llama-app.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1drm6JrPwLOtVwFGnbpORz-Mulo777Evn
8
+ """
9
+
10
+ from threading import Thread
11
+ from typing import Iterator
12
+
13
+ import gradio as gr
14
+ import spaces
15
+ import torch
16
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
17
+ from peft import PeftModel
18
+
19
+ DEFAULT_SYSTEM_PROMPT = "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
20
+ MAX_MAX_NEW_TOKENS = 2048
21
+ DEFAULT_MAX_NEW_TOKENS = 1024
22
+ MAX_INPUT_TOKEN_LENGTH = 4096
23
+
24
+ DESCRIPTION = """\
25
+ # Llama-2 7B Chat
26
+ This Space demonstrates model [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta, a Llama 2 model with 7B parameters fine-tuned for chat instructions. Feel free to play with it, or duplicate to run generations without a queue! If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://huggingface.co/inference-endpoints).
27
+ 🔎 For more details about the Llama 2 family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/llama2).
28
+ 🔨 Looking for an even more powerful model? Check out the [13B version](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat) or the large [70B model demo](https://huggingface.co/spaces/ysharma/Explore_llamav2_with_TGI).
29
+ """
30
+
31
+ LICENSE = """
32
+ <p/>
33
+ ---
34
+ As a derivate work of [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta,
35
+ this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/USE_POLICY.md).
36
+ """
37
+
38
+ if not torch.cuda.is_available():
39
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
40
+
41
+
42
+ if torch.cuda.is_available():
43
+ model_id = "meta-llama/Llama-2-7b-chat-hf"
44
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
45
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
46
+ #model = PeftModel.from_pretrained(model, "longface/LR-model",device_map="auto")
47
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
48
+ tokenizer.use_default_system_prompt = False
49
+
50
+
51
+ @spaces.GPU
52
+ def generate(
53
+ message: str,
54
+ chat_history: list[tuple[str, str]],
55
+ system_prompt: str,
56
+ max_new_tokens: int = 1024,
57
+ temperature: float = 0.6,
58
+ top_p: float = 0.9,
59
+ top_k: int = 50,
60
+ repetition_penalty: float = 1.2,
61
+ ) -> Iterator[str]:
62
+ conversation = []
63
+ if system_prompt:
64
+ conversation.append({"role": "system", "content": system_prompt})
65
+ for user, assistant in chat_history:
66
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
67
+ conversation.append({"role": "user", "content": message})
68
+
69
+ chat = tokenizer.apply_chat_template(conversation, tokenize=False)
70
+ inputs = tokenizer(chat, return_tensors="pt", add_special_tokens=False).to("cuda")
71
+ if len(inputs) > MAX_INPUT_TOKEN_LENGTH:
72
+ inputs = inputs[-MAX_INPUT_TOKEN_LENGTH:]
73
+ gr.Warning("Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
74
+
75
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
76
+ generate_kwargs = dict(
77
+ inputs,
78
+ streamer=streamer,
79
+ max_new_tokens=max_new_tokens,
80
+ do_sample=True,
81
+ top_p=top_p,
82
+ top_k=top_k,
83
+ temperature=temperature,
84
+ num_beams=1,
85
+ repetition_penalty=repetition_penalty,
86
+ )
87
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
88
+ t.start()
89
+
90
+ outputs = []
91
+ for text in streamer:
92
+ outputs.append(text)
93
+ yield "".join(outputs)
94
+
95
+
96
+ chat_interface = gr.ChatInterface(
97
+ fn=generate,
98
+ additional_inputs=[
99
+ gr.Textbox(label="System prompt", value=DEFAULT_SYSTEM_PROMPT, lines=6),
100
+ gr.Slider(
101
+ label="Max new tokens",
102
+ minimum=1,
103
+ maximum=MAX_MAX_NEW_TOKENS,
104
+ step=1,
105
+ value=DEFAULT_MAX_NEW_TOKENS,
106
+ ),
107
+ gr.Slider(
108
+ label="Temperature",
109
+ minimum=0.1,
110
+ maximum=4.0,
111
+ step=0.1,
112
+ value=0.6,
113
+ ),
114
+ gr.Slider(
115
+ label="Top-p (nucleus sampling)",
116
+ minimum=0.05,
117
+ maximum=1.0,
118
+ step=0.05,
119
+ value=0.9,
120
+ ),
121
+ gr.Slider(
122
+ label="Top-k",
123
+ minimum=1,
124
+ maximum=1000,
125
+ step=1,
126
+ value=50,
127
+ ),
128
+ gr.Slider(
129
+ label="Repetition penalty",
130
+ minimum=1.0,
131
+ maximum=2.0,
132
+ step=0.05,
133
+ value=1.2,
134
+ ),
135
+ ],
136
+ stop_btn=None,
137
+ examples=[
138
+ ["Hello there! How are you doing?"],
139
+ ["Can you explain briefly to me what is the Python programming language?"],
140
+ ["Explain the plot of Cinderella in a sentence."],
141
+ ["How many hours does it take a man to eat a Helicopter?"],
142
+ ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
143
+ ],
144
+ )
145
+
146
+ with gr.Blocks(css="style.css") as demo:
147
+ gr.Markdown(DESCRIPTION)
148
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
149
+ chat_interface.render()
150
+ gr.Markdown(LICENSE)
151
+
152
+ if __name__ == "__main__":
153
+ demo.queue(max_size=20).launch()