nxphi47 commited on
Commit
7379780
β€’
1 Parent(s): 97f6a3e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -0
app.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from threading import Thread
3
+ from typing import Iterator
4
+
5
+ import gradio as gr
6
+ import spaces
7
+ import torch
8
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
9
+
10
+ MAX_MAX_NEW_TOKENS = 2048
11
+ DEFAULT_MAX_NEW_TOKENS = 1024
12
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
13
+
14
+ DESCRIPTION = """\
15
+ # Llama-2 13B Chat
16
+ This Space demonstrates model [Llama-2-13b-chat](https://huggingface.co/meta-llama/Llama-2-13b-chat) by Meta, a Llama 2 model with 13B 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).
17
+ πŸ”Ž 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).
18
+ πŸ”¨ Looking for an even more powerful model? Check out the large [**70B** model demo](https://huggingface.co/spaces/ysharma/Explore_llamav2_with_TGI).
19
+ πŸ‡ For a smaller model that you can run on many GPUs, check our [7B model demo](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat).
20
+ """
21
+
22
+ LICENSE = """
23
+ <p/>
24
+ ---
25
+ As a derivate work of [Llama-2-13b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta,
26
+ this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat/blob/main/USE_POLICY.md).
27
+ """
28
+
29
+ if not torch.cuda.is_available():
30
+ DESCRIPTION += "\n<p>Running on CPU πŸ₯Ά This demo does not work on CPU.</p>"
31
+
32
+
33
+ if torch.cuda.is_available():
34
+ model_id = "meta-llama/Llama-2-7b-chat-hf"
35
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16)
36
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
37
+ tokenizer.use_default_system_prompt = False
38
+
39
+
40
+ @spaces.GPU
41
+ def generate(
42
+ message: str,
43
+ chat_history: list[tuple[str, str]],
44
+ system_prompt: str,
45
+ max_new_tokens: int = 1024,
46
+ temperature: float = 0.6,
47
+ top_p: float = 0.9,
48
+ top_k: int = 50,
49
+ repetition_penalty: float = 1.2,
50
+ ) -> Iterator[str]:
51
+ conversation = []
52
+ if system_prompt:
53
+ conversation.append({"role": "system", "content": system_prompt})
54
+ for user, assistant in chat_history:
55
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
56
+ conversation.append({"role": "user", "content": message})
57
+
58
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
59
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
60
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
61
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
62
+ input_ids = input_ids.to(model.device)
63
+
64
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
65
+ generate_kwargs = dict(
66
+ {"input_ids": input_ids},
67
+ streamer=streamer,
68
+ max_new_tokens=max_new_tokens,
69
+ do_sample=True,
70
+ top_p=top_p,
71
+ top_k=top_k,
72
+ temperature=temperature,
73
+ num_beams=1,
74
+ repetition_penalty=repetition_penalty,
75
+ )
76
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
77
+ t.start()
78
+
79
+ outputs = []
80
+ for text in streamer:
81
+ outputs.append(text)
82
+ yield "".join(outputs)
83
+
84
+
85
+ chat_interface = gr.ChatInterface(
86
+ fn=generate,
87
+ additional_inputs=[
88
+ gr.Textbox(label="System prompt", lines=6),
89
+ gr.Slider(
90
+ label="Max new tokens",
91
+ minimum=1,
92
+ maximum=MAX_MAX_NEW_TOKENS,
93
+ step=1,
94
+ value=DEFAULT_MAX_NEW_TOKENS,
95
+ ),
96
+ gr.Slider(
97
+ label="Temperature",
98
+ minimum=0.1,
99
+ maximum=4.0,
100
+ step=0.1,
101
+ value=0.6,
102
+ ),
103
+ gr.Slider(
104
+ label="Top-p (nucleus sampling)",
105
+ minimum=0.05,
106
+ maximum=1.0,
107
+ step=0.05,
108
+ value=0.9,
109
+ ),
110
+ gr.Slider(
111
+ label="Top-k",
112
+ minimum=1,
113
+ maximum=1000,
114
+ step=1,
115
+ value=50,
116
+ ),
117
+ gr.Slider(
118
+ label="Repetition penalty",
119
+ minimum=1.0,
120
+ maximum=2.0,
121
+ step=0.05,
122
+ value=1.2,
123
+ ),
124
+ ],
125
+ stop_btn=None,
126
+ examples=[
127
+ ["Hello there! How are you doing?"],
128
+ ["Can you explain briefly to me what is the Python programming language?"],
129
+ ["Explain the plot of Cinderella in a sentence."],
130
+ ["How many hours does it take a man to eat a Helicopter?"],
131
+ ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
132
+ ],
133
+ )
134
+
135
+ with gr.Blocks(css="style.css") as demo:
136
+ gr.Markdown(DESCRIPTION)
137
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
138
+ chat_interface.render()
139
+ gr.Markdown(LICENSE)
140
+
141
+ if __name__ == "__main__":
142
+ demo.queue(max_size=20).launch()