mrpoons-studio commited on
Commit
5711651
·
verified ·
1 Parent(s): 7ba9d4b

Rebuild the file

Browse files
Files changed (1) hide show
  1. app.py +120 -45
app.py CHANGED
@@ -1,64 +1,139 @@
 
 
 
 
 
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("deepseek-ai/DeepSeek-R1")
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="", label="System message"),
50
- gr.Slider(minimum=0, maximum=128000, value=2048, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0, maximum=4.0, value=0, step=0.001, label="Temperature"),
 
 
 
 
 
 
 
 
 
 
 
 
52
  gr.Slider(
 
53
  minimum=0,
54
  maximum=1.0,
 
55
  value=0,
 
 
 
 
 
 
 
 
 
 
 
 
56
  step=0.001,
57
- label="Top-p (nucleus sampling)",
58
  ),
59
  ],
 
 
 
 
 
 
60
  )
61
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
+ import os
2
+
3
+ from threading import Thread
4
+ from typing import Iterator
5
+
6
  import gradio as gr
7
+ import spaces
8
+ import torch
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
10
 
11
+ MAX_MAX_NEW_TOKENS = 128000
12
+ DEFAULT_MAX_NEW_TOKENS = 4096
13
+ total_count=0
14
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
15
+
16
+ DESCRIPTION = """\
17
+ # DeepSeek-R1-Chat
18
+
19
+ This space demonstrates model [DeepSeek-R1](https://huggingface.co/deepseek-ai/deepseek-r1) by DeepSeek, a reasoning model with 6xxB parameters fine-tuned for chat instructions.
20
+
21
+ **You can also try our R1 model in [official homepage](https://r1.deepseek.com/chat).**
22
  """
23
+
24
+ if not torch.cuda.is_available():
25
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
26
+
27
+
28
+ if torch.cuda.is_available():
29
+ model_id = "deepseek-ai/deepseek-r1"
30
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="auto")
31
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
32
+ tokenizer.use_default_system_prompt = False
33
+
34
+
35
+
36
+ @spaces.GPU
37
+ def generate(
38
+ message: str,
39
+ chat_history: list[tuple[str, str]],
40
+ system_prompt: str,
41
+ max_new_tokens: int = 4096,
42
+ temperature: float = 0,
43
+ top_p: float = 0,
44
+ top_k: int = 0,
45
+ repetition_penalty: float = 4,
46
+ ) -> Iterator[str]:
47
+ global total_count
48
+ total_count += 1
49
+ print(total_count)
50
+ os.system("nvidia-smi")
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=400.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=False,
70
  top_p=top_p,
71
+ top_k=top_k,
72
+ num_beams=1,
73
+ # temperature=temperature,
74
+ repetition_penalty=repetition_penalty,
75
+ eos_token_id=32021
76
+ )
77
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
78
+ t.start()
79
 
80
+ outputs = []
81
+ for text in streamer:
82
+ outputs.append(text)
83
+ yield "".join(outputs).replace("<|EOT|>","")
84
 
85
 
86
+ chat_interface = gr.ChatInterface(
87
+ fn=generate,
 
 
 
88
  additional_inputs=[
89
+ gr.Textbox(label="System prompt", lines=6),
90
+ gr.Slider(
91
+ label="Max new tokens",
92
+ minimum=1,
93
+ maximum=MAX_MAX_NEW_TOKENS,
94
+ step=1,
95
+ value=DEFAULT_MAX_NEW_TOKENS,
96
+ ),
97
+ # gr.Slider(
98
+ # label="Temperature",
99
+ # minimum=0,
100
+ # maximum=4.0,
101
+ # step=0.1,
102
+ # value=0,
103
+ # ),
104
  gr.Slider(
105
+ label="Top-p (nucleus sampling)",
106
  minimum=0,
107
  maximum=1.0,
108
+ step=0.001,
109
  value=0,
110
+ ),
111
+ gr.Slider(
112
+ label="Top-k",
113
+ minimum=0,
114
+ maximum=400,
115
+ step=1,
116
+ value=0,
117
+ ),
118
+ gr.Slider(
119
+ label="Repetition penalty",
120
+ minimum=1.0,
121
+ maximum=4.0,
122
  step=0.001,
123
+ value=4,
124
  ),
125
  ],
126
+ stop_btn=gr.Button("Stop"),
127
+ examples=[
128
+ ["implement snake game using pygame"],
129
+ ["Can you explain briefly to me what is the Python programming language?"],
130
+ ["write a program to find the factorial of a number"],
131
+ ],
132
  )
133
 
134
+ with gr.Blocks(css="style.css") as demo:
135
+ gr.Markdown(DESCRIPTION)
136
+ chat_interface.render()
137
 
138
  if __name__ == "__main__":
139
+ demo.queue(max_size=16384).launch()