AndreaAlessandrelli4 commited on
Commit
4c90268
·
verified ·
1 Parent(s): 22377ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -48
app.py CHANGED
@@ -1,63 +1,129 @@
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
38
 
39
- response += token
40
- yield response
41
 
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
  additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
  gr.Slider(
 
 
 
 
 
 
 
 
52
  minimum=0.1,
 
 
 
 
 
 
 
53
  maximum=1.0,
54
- value=0.95,
55
  step=0.05,
56
- label="Top-p (nucleus sampling)",
57
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  ],
59
  )
60
 
 
 
 
 
61
 
62
  if __name__ == "__main__":
63
- demo.launch()
 
 
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
+
15
+
16
+ if not torch.cuda.is_available():
17
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
18
+
19
+
20
+ if torch.cuda.is_available():
21
+ model_id = "AndreaAlessandrelli4/AvvoChat_AITA_v04"
22
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", load_in_4bit=True)
23
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
24
+ tokenizer.use_default_system_prompt = False
25
+
26
+
27
+ @spaces.GPU
28
+ def generate(
29
+ message: str,
30
+ chat_history: list[tuple[str, str]],
31
+ system_prompt: str,
32
+ max_new_tokens: int = 1024,
33
+ temperature: float = 0.6,
34
+ top_p: float = 0.9,
35
+ top_k: int = 50,
36
+ repetition_penalty: float = 1.2,
37
+ ) -> Iterator[str]:
38
+ conversation = []
39
+ if system_prompt:
40
+ conversation.append({"role": "system", "content": system_prompt})
41
+ for user, assistant in chat_history:
42
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
43
+ conversation.append({"role": "user", "content": message})
44
+
45
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
46
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
47
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
48
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
49
+ input_ids = input_ids.to(model.device)
50
+
51
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
52
+ generate_kwargs = dict(
53
+ {"input_ids": input_ids},
54
+ streamer=streamer,
55
+ max_new_tokens=max_new_tokens,
56
+ do_sample=True,
57
  top_p=top_p,
58
+ top_k=top_k,
59
+ temperature=temperature,
60
+ num_beams=1,
61
+ repetition_penalty=repetition_penalty,
62
+ )
63
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
64
+ t.start()
65
+
66
+ outputs = []
67
+ for text in streamer:
68
+ outputs.append(text)
69
+ yield "".join(outputs)
70
 
 
 
71
 
72
+ chat_interface = gr.ChatInterface(
73
+ fn=generate,
 
 
 
74
  additional_inputs=[
75
+ gr.Textbox(label="System prompt", lines=6),
 
 
76
  gr.Slider(
77
+ label="Max new tokens",
78
+ minimum=1,
79
+ maximum=MAX_MAX_NEW_TOKENS,
80
+ step=1,
81
+ value=DEFAULT_MAX_NEW_TOKENS,
82
+ ),
83
+ gr.Slider(
84
+ label="Temperature",
85
  minimum=0.1,
86
+ maximum=4.0,
87
+ step=0.1,
88
+ value=0.6,
89
+ ),
90
+ gr.Slider(
91
+ label="Top-p (nucleus sampling)",
92
+ minimum=0.05,
93
  maximum=1.0,
 
94
  step=0.05,
95
+ value=0.9,
96
  ),
97
+ gr.Slider(
98
+ label="Top-k",
99
+ minimum=1,
100
+ maximum=1000,
101
+ step=1,
102
+ value=50,
103
+ ),
104
+ gr.Slider(
105
+ label="Repetition penalty",
106
+ minimum=1.0,
107
+ maximum=2.0,
108
+ step=0.05,
109
+ value=1.2,
110
+ ),
111
+ ],
112
+ stop_btn=None,
113
+ examples=[
114
+ ["Hello there! How are you doing?"],
115
+ ["Can you explain briefly to me what is the Python programming language?"],
116
+ ["Explain the plot of Cinderella in a sentence."],
117
+ ["How many hours does it take a man to eat a Helicopter?"],
118
+ ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
119
  ],
120
  )
121
 
122
+ with gr.Blocks(css="style.css") as demo:
123
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
124
+ chat_interface.render()
125
+
126
 
127
  if __name__ == "__main__":
128
+ demo.queue(max_size=20).launch()
129
+