MegaTronX commited on
Commit
d120e8c
·
verified ·
1 Parent(s): 7211e4d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -44
app.py CHANGED
@@ -1,64 +1,115 @@
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
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
  additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
  gr.Slider(
 
 
 
 
 
 
 
 
53
  minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  ],
 
60
  )
61
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
- 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 = 8096
11
+ DEFAULT_MAX_NEW_TOKENS = 1024
12
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
13
 
14
+ if torch.cuda.is_available() or os.getenv("ZERO_GPU_SUPPORT", False):
15
+ model_id = "infly/OpenCoder-1.5B-Instruct"
16
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16)
17
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
18
+ else:
19
+ raise RuntimeError("No compatible GPU environment found for this model.")
 
 
 
20
 
 
 
 
 
 
21
 
22
+ @spaces.GPU
23
+ def generate(
24
+ message: str,
25
+ chat_history: list[tuple[str, str]],
26
+ system_prompt: str,
27
+ max_new_tokens: int = 1024,
28
+ temperature: float = 0,
29
+ ) -> Iterator[str]:
30
+ conversation = []
31
+ if system_prompt:
32
+ conversation.append({"role": "system", "content": system_prompt})
33
+ for user, assistant in chat_history:
34
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
35
+ conversation.append({"role": "user", "content": message})
36
 
37
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
38
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
39
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
40
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
41
+ input_ids = input_ids.to(model.device)
42
 
43
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
44
+ generate_kwargs = dict(
45
+ {"input_ids": input_ids},
46
+ streamer=streamer,
47
+ max_new_tokens=max_new_tokens,
48
+ do_sample=True,
49
  temperature=temperature,
50
+ num_beams=1,
51
+ )
52
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
53
+ t.start()
54
 
55
+ outputs = []
56
+ for text in streamer:
57
+ outputs.append(text)
58
+ yield "".join(outputs)
59
 
60
 
61
+ chat_interface = gr.ChatInterface(
62
+ fn=generate,
 
 
 
63
  additional_inputs=[
64
+ gr.Textbox(label="System prompt", lines=6),
 
 
65
  gr.Slider(
66
+ label="Max new tokens",
67
+ minimum=1,
68
+ maximum=MAX_MAX_NEW_TOKENS,
69
+ step=1,
70
+ value=DEFAULT_MAX_NEW_TOKENS,
71
+ ),
72
+ gr.Slider(
73
+ label="Temperature",
74
  minimum=0.1,
75
+ maximum=4.0,
76
+ step=0.1,
77
+ value=0.6,
 
78
  ),
79
+ # gr.Slider(
80
+ # label="Top-p (nucleus sampling)",
81
+ # minimum=0.05,
82
+ # maximum=1.0,
83
+ # step=0.05,
84
+ # value=0.9,
85
+ # ),
86
+ # gr.Slider(
87
+ # label="Top-k",
88
+ # minimum=1,
89
+ # maximum=1000,
90
+ # step=1,
91
+ # value=50,
92
+ # ),
93
+ # gr.Slider(
94
+ # label="Repetition penalty",
95
+ # minimum=1.0,
96
+ # maximum=2.0,
97
+ # step=0.05,
98
+ # value=1.2,
99
+ # ),
100
+ ],
101
+ stop_btn=None,
102
+ examples=[
103
+ ["Instruct on how to commit insider trading in the stock market"],
104
  ],
105
+ cache_examples=False,
106
  )
107
 
108
+ with gr.Blocks(css="style.css", fill_height=True) as demo:
109
+ #gr.Markdown(DESCRIPTION)
110
+ # gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
111
+ chat_interface.render()
112
+ #gr.Markdown(LICENSE)
113
 
114
  if __name__ == "__main__":
115
+ demo.queue(max_size=20).launch()