AAhad commited on
Commit
f553dd3
·
verified ·
1 Parent(s): f357fa6

update app

Browse files
Files changed (1) hide show
  1. app.py +211 -0
app.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Template Demo for IBM Granite Hugging Face spaces."""
2
+
3
+ from collections.abc import Iterator
4
+ from datetime import datetime
5
+ from pathlib import Path
6
+ from threading import Thread
7
+
8
+ import gradio as gr
9
+ import spaces
10
+ import torch
11
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
12
+
13
+ from themes.research_monochrome import theme
14
+
15
+ today_date = datetime.today().strftime("%B %-d, %Y") # noqa: DTZ002
16
+
17
+ SYS_PROMPT = f"""Knowledge Cutoff Date: April 2024.
18
+ Today's Date: {today_date}.
19
+ You are Granite, developed by IBM. You are a helpful AI assistant"""
20
+ TITLE = "IBM Granite 3.1 8b Instruct"
21
+ DESCRIPTION = """
22
+ <p>Granite 3.1 8b instruct is an open-source LLM supporting a 128k context window. Start with one of the sample prompts
23
+ or enter your own. Keep in mind that AI can occasionally make mistakes.
24
+ <span class="gr_docs_link">
25
+ <a href="https://www.ibm.com/granite/docs/">View Documentation <i class="fa fa-external-link"></i></a>
26
+ </span>
27
+ </p>
28
+ """
29
+ MAX_INPUT_TOKEN_LENGTH = 128_000
30
+ MAX_NEW_TOKENS = 1024
31
+ TEMPERATURE = 0.7
32
+ TOP_P = 0.85
33
+ TOP_K = 50
34
+ REPETITION_PENALTY = 1.05
35
+
36
+ if not torch.cuda.is_available():
37
+ print("This demo may not work on CPU.")
38
+
39
+ model = AutoModelForCausalLM.from_pretrained(
40
+ "ibm-granite/granite-3.1-8b-instruct", torch_dtype=torch.float16, device_map="auto"
41
+ )
42
+ tokenizer = AutoTokenizer.from_pretrained("ibm-granite/granite-3.1-8b-instruct")
43
+ tokenizer.use_default_system_prompt = False
44
+
45
+
46
+ @spaces.GPU
47
+ def generate(
48
+ message: str,
49
+ chat_history: list[dict],
50
+ temperature: float = TEMPERATURE,
51
+ repetition_penalty: float = REPETITION_PENALTY,
52
+ top_p: float = TOP_P,
53
+ top_k: float = TOP_K,
54
+ max_new_tokens: int = MAX_NEW_TOKENS,
55
+ ) -> Iterator[str]:
56
+ """Generate function for chat demo."""
57
+ # Build messages
58
+ conversation = []
59
+ conversation.append({"role": "system", "content": SYS_PROMPT})
60
+ conversation += chat_history
61
+ conversation.append({"role": "user", "content": message})
62
+
63
+ # Convert messages to prompt format
64
+ input_ids = tokenizer.apply_chat_template(
65
+ conversation,
66
+ return_tensors="pt",
67
+ add_generation_prompt=True,
68
+ truncation=True,
69
+ max_length=MAX_INPUT_TOKEN_LENGTH - max_new_tokens,
70
+ )
71
+
72
+ input_ids = input_ids.to(model.device)
73
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
74
+ generate_kwargs = dict(
75
+ {"input_ids": input_ids},
76
+ streamer=streamer,
77
+ max_new_tokens=max_new_tokens,
78
+ do_sample=True,
79
+ top_p=top_p,
80
+ top_k=top_k,
81
+ temperature=temperature,
82
+ num_beams=1,
83
+ repetition_penalty=repetition_penalty,
84
+ )
85
+
86
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
87
+ t.start()
88
+
89
+ outputs = []
90
+ for text in streamer:
91
+ outputs.append(text)
92
+ yield "".join(outputs)
93
+
94
+
95
+ css_file_path = Path(Path(__file__).parent / "app.css")
96
+ head_file_path = Path(Path(__file__).parent / "app_head.html")
97
+
98
+ # advanced settings (displayed in Accordion)
99
+ temperature_slider = gr.Slider(
100
+ minimum=0, maximum=1.0, value=TEMPERATURE, step=0.1, label="Temperature", elem_classes=["gr_accordion_element"]
101
+ )
102
+ top_p_slider = gr.Slider(
103
+ minimum=0, maximum=1.0, value=TOP_P, step=0.05, label="Top P", elem_classes=["gr_accordion_element"]
104
+ )
105
+ top_k_slider = gr.Slider(
106
+ minimum=0, maximum=100, value=TOP_K, step=1, label="Top K", elem_classes=["gr_accordion_element"]
107
+ )
108
+ repetition_penalty_slider = gr.Slider(
109
+ minimum=0,
110
+ maximum=2.0,
111
+ value=REPETITION_PENALTY,
112
+ step=0.05,
113
+ label="Repetition Penalty",
114
+ elem_classes=["gr_accordion_element"],
115
+ )
116
+ max_new_tokens_slider = gr.Slider(
117
+ minimum=1,
118
+ maximum=2000,
119
+ value=MAX_NEW_TOKENS,
120
+ step=1,
121
+ label="Max New Tokens",
122
+ elem_classes=["gr_accordion_element"],
123
+ )
124
+ chat_interface_accordion = gr.Accordion(label="Advanced Settings", open=False)
125
+
126
+ with gr.Blocks(fill_height=True, css_paths=css_file_path, head_paths=head_file_path, theme=theme, title=TITLE) as demo:
127
+ gr.HTML(f"<h1>{TITLE}</h1>", elem_classes=["gr_title"])
128
+ gr.HTML(DESCRIPTION)
129
+ chat_interface = gr.ChatInterface(
130
+ fn=generate,
131
+ examples=[
132
+ ["Explain the concept of quantum computing to someone with no background in physics or computer science."],
133
+ ["What is OpenShift?"],
134
+ ["What's the importance of low latency inference?"],
135
+ ["Help me boost productivity habits."],
136
+ [
137
+ """Explain the following code in a concise manner:
138
+
139
+ ```java
140
+ import java.util.ArrayList;
141
+ import java.util.List;
142
+
143
+ public class Main {
144
+
145
+ public static void main(String[] args) {
146
+ int[] arr = {1, 5, 3, 4, 2};
147
+ int diff = 3;
148
+ List<Pair> pairs = findPairs(arr, diff);
149
+ for (Pair pair : pairs) {
150
+ System.out.println(pair.x + " " + pair.y);
151
+ }
152
+ }
153
+
154
+ public static List<Pair> findPairs(int[] arr, int diff) {
155
+ List<Pair> pairs = new ArrayList<>();
156
+ for (int i = 0; i < arr.length; i++) {
157
+ for (int j = i + 1; j < arr.length; j++) {
158
+ if (Math.abs(arr[i] - arr[j]) < diff) {
159
+ pairs.add(new Pair(arr[i], arr[j]));
160
+ }
161
+ }
162
+ }
163
+
164
+ return pairs;
165
+ }
166
+ }
167
+
168
+ class Pair {
169
+ int x;
170
+ int y;
171
+ public Pair(int x, int y) {
172
+ this.x = x;
173
+ this.y = y;
174
+ }
175
+ }
176
+ ```"""
177
+ ],
178
+ [
179
+ """Generate a Java code block from the following explanation:
180
+
181
+ The code in the Main class finds all pairs in an array whose absolute difference is less than a given value.
182
+
183
+ The findPairs method takes two arguments: an array of integers and a difference value. It iterates over the array and compares each element to every other element in the array. If the absolute difference between the two elements is less than the difference value, a new Pair object is created and added to a list.
184
+
185
+ The Pair class is a simple data structure that stores two integers.
186
+
187
+ The main method creates an array of integers, initializes the difference value, and calls the findPairs method to find all pairs in the array. Finally, the code iterates over the list of pairs and prints each pair to the console.""" # noqa: E501
188
+ ],
189
+ ],
190
+ example_labels=[
191
+ "Explain quantum computing",
192
+ "What is OpenShift?",
193
+ "Importance of low latency inference",
194
+ "Boosting productivity habits",
195
+ "Explain and document your code",
196
+ "Generate Java Code",
197
+ ],
198
+ cache_examples=False,
199
+ type="messages",
200
+ additional_inputs=[
201
+ temperature_slider,
202
+ repetition_penalty_slider,
203
+ top_p_slider,
204
+ top_k_slider,
205
+ max_new_tokens_slider,
206
+ ],
207
+ additional_inputs_accordion=chat_interface_accordion,
208
+ )
209
+
210
+ if __name__ == "__main__":
211
+ demo.queue().launch()