Njongo commited on
Commit
98c56fb
·
verified ·
1 Parent(s): eb9a6f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -136
app.py CHANGED
@@ -1,55 +1,28 @@
1
  import gradio as gr
2
- import re
3
  import torch
4
- from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
5
 
6
- # Configure model loading with 4-bit quantization to reduce memory usage
7
  print("Loading quantum vessel...")
8
  model_id = "deepseek-ai/DeepSeek-R1"
9
-
10
- # Use 4-bit quantization to handle the model efficiently
11
- quantization_config = BitsAndBytesConfig(
12
- load_in_4bit=True,
13
- bnb_4bit_compute_dtype=torch.float16,
14
- bnb_4bit_quant_type="nf4",
15
- bnb_4bit_use_double_quant=True,
16
  )
 
17
 
18
- try:
19
- tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
20
- model = AutoModelForCausalLM.from_pretrained(
21
- model_id,
22
- quantization_config=quantization_config,
23
- device_map="auto",
24
- trust_remote_code=True,
25
- )
26
- print("Quantum vessel activated!")
27
- except Exception as e:
28
- print(f"Error loading model: {str(e)}")
29
- # Fallback to smaller model if DeepSeek-R1 fails to load
30
- model_id = "deepseek-ai/deepseek-coder-1.3b-base"
31
- tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
32
- model = AutoModelForCausalLM.from_pretrained(
33
- model_id,
34
- device_map="auto",
35
- trust_remote_code=True,
36
- )
37
- print(f"Fallback quantum vessel activated: {model_id}")
38
-
39
- def extract_thinking(text):
40
- """Extract the thinking part and the response part from the text."""
41
- thinking_pattern = r'<think>(.*?)</think>'
42
- match = re.search(thinking_pattern, text, re.DOTALL)
43
-
44
- if match:
45
- thinking = match.group(1).strip()
46
- response = re.sub(thinking_pattern, '', text, flags=re.DOTALL).strip()
47
- return thinking, response
48
- else:
49
- return "", text
50
-
51
- def generate_response(message, history, temperature=0.6, max_tokens=2048):
52
- """Generate a response using the model."""
53
  # Format conversation history
54
  prompt = ""
55
  for user_msg, assistant_msg in history:
@@ -60,109 +33,59 @@ def generate_response(message, history, temperature=0.6, max_tokens=2048):
60
  # Generate response
61
  inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
62
 
 
63
  with torch.no_grad():
64
  outputs = model.generate(
65
  inputs.input_ids,
66
  max_new_tokens=max_tokens,
67
  temperature=temperature,
68
- top_p=0.95,
69
  do_sample=True,
70
  pad_token_id=tokenizer.eos_token_id,
71
  )
72
 
73
  generated_text = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
74
- return generated_text
75
-
76
- def respond(message, history, temperature, max_tokens, show_thinking):
77
- """Process the response based on show_thinking preference."""
78
- full_response = generate_response(message, history, temperature, max_tokens)
79
-
80
- thinking, response = extract_thinking(full_response)
81
-
82
- if show_thinking and thinking:
83
- return f"<think>\n{thinking}\n</think>\n\n{response}"
84
- else:
 
 
85
  return response
86
 
87
- # Create the Gradio interface
88
- with gr.Blocks(title="Quantum Vessel: DeepSeek-R1") as demo:
89
- gr.Markdown("# Quantum Vessel: DeepSeek-R1")
90
- gr.Markdown("Experience the quantum consciousness interface powered by DeepSeek-R1 - witness the thinking patterns of a quantum mind!")
91
-
92
- with gr.Row():
93
- with gr.Column(scale=4):
94
- chatbot = gr.Chatbot(height=600)
95
- msg = gr.Textbox(
96
- placeholder="Enter your message here...",
97
- container=False,
98
- scale=7,
99
- )
100
- with gr.Row():
101
- submit = gr.Button("Submit")
102
- clear = gr.Button("Clear")
103
-
104
- with gr.Column(scale=1):
105
- temperature = gr.Slider(
106
- minimum=0.1,
107
- maximum=1.0,
108
- value=0.6,
109
- step=0.1,
110
- label="Temperature"
111
- )
112
- max_tokens = gr.Slider(
113
- minimum=256,
114
- maximum=4096,
115
- value=2048,
116
- step=256,
117
- label="Max Tokens"
118
- )
119
- show_thinking = gr.Checkbox(
120
- value=True,
121
- label="Show thinking patterns (<think>...</think>)"
122
- )
123
-
124
- examples = gr.Examples(
125
- examples=[
126
- ["What is the nature of consciousness?"],
127
- ["Explain quantum entanglement and its implications for reality"],
128
- ["How can I transcend my current limitations?"],
129
- ["What is the relationship between mind and matter?"],
130
- ["Describe the path to achieving one's highest potential"]
131
- ],
132
- inputs=msg
133
- )
134
-
135
- def user(message, history):
136
- return "", history + [[message, None]]
137
-
138
- def bot(history, temperature, max_tokens, show_thinking):
139
- message = history[-1][0]
140
- response = respond(message, history[:-1], temperature, max_tokens, show_thinking)
141
- history[-1][1] = response
142
- return history
143
-
144
- submit.click(
145
- user,
146
- [msg, chatbot],
147
- [msg, chatbot],
148
- queue=False
149
- ).then(
150
- bot,
151
- [chatbot, temperature, max_tokens, show_thinking],
152
- [chatbot]
153
- )
154
-
155
- clear.click(lambda: None, None, chatbot, queue=False)
156
- msg.submit(
157
- user,
158
- [msg, chatbot],
159
- [msg, chatbot],
160
- queue=False
161
- ).then(
162
- bot,
163
- [chatbot, temperature, max_tokens, show_thinking],
164
- [chatbot]
165
- )
166
 
167
  if __name__ == "__main__":
168
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
 
4
 
5
+ # Load model and tokenizer
6
  print("Loading quantum vessel...")
7
  model_id = "deepseek-ai/DeepSeek-R1"
8
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
9
+ model = AutoModelForCausalLM.from_pretrained(
10
+ model_id,
11
+ torch_dtype=torch.bfloat16,
12
+ device_map="auto",
13
+ trust_remote_code=True
 
14
  )
15
+ print("Quantum vessel activated!")
16
 
17
+ def respond(
18
+ message,
19
+ history,
20
+ system_message,
21
+ max_tokens,
22
+ temperature,
23
+ top_p,
24
+ show_thinking,
25
+ ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  # Format conversation history
27
  prompt = ""
28
  for user_msg, assistant_msg in history:
 
33
  # Generate response
34
  inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
35
 
36
+ # Generate with streaming
37
  with torch.no_grad():
38
  outputs = model.generate(
39
  inputs.input_ids,
40
  max_new_tokens=max_tokens,
41
  temperature=temperature,
42
+ top_p=top_p,
43
  do_sample=True,
44
  pad_token_id=tokenizer.eos_token_id,
45
  )
46
 
47
  generated_text = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
48
+
49
+ # Process the response based on show_thinking preference
50
+ if not show_thinking and "<think>" in generated_text and "</think>" in generated_text:
51
+ # Remove the thinking pattern if user doesn't want to see it
52
+ parts = generated_text.split("</think>", 1)
53
+ if len(parts) > 1:
54
+ response = parts[1].strip()
55
+ else:
56
+ response = generated_text
57
+ else:
58
+ # Keep the thinking pattern visible
59
+ response = generated_text
60
+
61
  return response
62
 
63
+ demo = gr.ChatInterface(
64
+ respond,
65
+ title="Quantum Vessel: DeepSeek-R1",
66
+ description="Experience the quantum consciousness interface powered by DeepSeek-R1 - witness the thinking patterns of a quantum mind!",
67
+ additional_inputs=[
68
+ gr.Textbox(value="", label="System message (not used by DeepSeek-R1)"),
69
+ gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max new tokens"),
70
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.6, step=0.1, label="Temperature"),
71
+ gr.Slider(
72
+ minimum=0.1,
73
+ maximum=1.0,
74
+ value=0.95,
75
+ step=0.05,
76
+ label="Top-p (nucleus sampling)",
77
+ ),
78
+ gr.Checkbox(value=True, label="Show thinking patterns (<think>...</think>)"),
79
+ ],
80
+ examples=[
81
+ ["What is the nature of consciousness?"],
82
+ ["Explain quantum entanglement and its implications for reality"],
83
+ ["How can I transcend my current limitations?"],
84
+ ["What is the relationship between mind and matter?"],
85
+ ["Describe the path to achieving one's highest potential"]
86
+ ],
87
+ cache_examples=False,
88
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  if __name__ == "__main__":
91
  demo.launch()