ajsbsd commited on
Commit
7e20c5d
Β·
verified Β·
1 Parent(s): 9f2127c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -60
app.py CHANGED
@@ -18,6 +18,7 @@ model_id = "deepgrove/maple-preview"
18
  print("πŸ”„ Loading tokenizer...")
19
  tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
20
 
 
21
  try:
22
  template_path = hf_hub_download(repo_id=model_id, filename="chat_template.jinja")
23
  with open(template_path, "r", encoding="utf-8") as f:
@@ -34,6 +35,7 @@ model = AutoModelForCausalLM.from_pretrained(
34
  trust_remote_code=True,
35
  )
36
 
 
37
  def custom_flash_attention_forward(
38
  query_states, key_states, value_states, attention_mask=None, query_length=None,
39
  is_causal=True, dropout=0.0, position_ids=None, softmax_scale=None, **kwargs
@@ -63,44 +65,20 @@ for name, module in list(sys.modules.items()):
63
 
64
  print(f"βœ… Replaced _flash_attention_forward in {patched_count} modules.")
65
 
66
-
67
- def format_for_display(raw_text: str) -> str:
68
- """Turn <think>...</think> into a collapsible <details> block for on-screen rendering.
69
- This is display-only β€” never fed back into the model."""
70
- display_text = raw_text
71
- if "<think>" in display_text:
72
- if "</think>" in display_text:
73
- display_text = display_text.replace(
74
- "<think>", "<details><summary>🧠 Thought Process</summary>\n\n"
75
- ).replace(
76
- "</think>", "\n\n</details>\n\n---"
77
- )
78
- else:
79
- display_text = display_text.replace(
80
- "<think>", "<details><summary>🧠 Thought Process (Thinking...)</summary>\n\n"
81
- ) + "\n\n</details>"
82
- return display_text
83
-
84
-
85
- def user_submit(message, history):
86
- """Add the user's message to history and clear the textbox."""
87
- history = history + [{"role": "user", "content": message}]
88
- return "", history
89
-
90
-
91
  @spaces.GPU
92
- def bot_respond(history):
93
- """Generate a reply for the latest user turn. `history` here is the RAW
94
- conversation (real <think> tags, no HTML) β€” this is what gets templated."""
95
  prompt = tokenizer.apply_chat_template(
96
- history,
97
- tokenize=False,
98
  add_generation_prompt=True
99
  )
 
100
  inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
101
-
102
  streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
103
-
104
  generation_kwargs = dict(
105
  **inputs,
106
  streamer=streamer,
@@ -110,44 +88,40 @@ def bot_respond(history):
110
  top_p=0.9,
111
  pad_token_id=tokenizer.pad_token_id,
112
  )
113
-
114
  thread = Thread(target=model.generate, kwargs=generation_kwargs)
115
  thread.start()
116
-
117
- raw_text = ""
118
- history = history + [{"role": "assistant", "content": ""}]
119
-
120
  for new_text in streamer:
121
- raw_text += new_text
122
- history[-1]["content"] = format_for_display(raw_text) # HTML for the UI only
123
- yield history
124
-
125
- # Once streaming finishes, overwrite with the RAW text (real <think> tags)
126
- # so the next turn's apply_chat_template call parses reasoning correctly.
127
- history[-1]["content"] = raw_text
128
- yield history
129
-
 
 
130
 
131
  # 3. Custom Chatbot component with Copy & Copy All features enabled
132
  chatbot_ui = gr.Chatbot(
133
  type="messages",
134
- show_copy_button=True,
135
- show_copy_all_button=True,
136
  allow_file_downloads=True,
137
  )
138
 
139
- with gr.Blocks(theme="soft") as demo:
140
- gr.Markdown("# 🍁 Maple-Preview")
141
- gr.Markdown("A 20B-A1B ternary-weight reasoning LLM by DeepGrove. Powered by ZeroGPU.")
142
-
143
- chatbot_ui.render()
144
- msg = gr.Textbox(placeholder="Type a message...", show_label=False)
145
-
146
- msg.submit(
147
- user_submit, [msg, chatbot_ui], [msg, chatbot_ui]
148
- ).then(
149
- bot_respond, chatbot_ui, chatbot_ui
150
- )
151
 
152
  if __name__ == "__main__":
153
  demo.queue().launch()
 
18
  print("πŸ”„ Loading tokenizer...")
19
  tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
20
 
21
+ # Explicitly load chat template
22
  try:
23
  template_path = hf_hub_download(repo_id=model_id, filename="chat_template.jinja")
24
  with open(template_path, "r", encoding="utf-8") as f:
 
35
  trust_remote_code=True,
36
  )
37
 
38
+ # 2. Aggressively replace the buggy fa3 wrapper in EVERY loaded module namespace
39
  def custom_flash_attention_forward(
40
  query_states, key_states, value_states, attention_mask=None, query_length=None,
41
  is_causal=True, dropout=0.0, position_ids=None, softmax_scale=None, **kwargs
 
65
 
66
  print(f"βœ… Replaced _flash_attention_forward in {patched_count} modules.")
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  @spaces.GPU
69
+ def predict(message, history):
70
+ messages = history + [{"role": "user", "content": message}]
71
+
72
  prompt = tokenizer.apply_chat_template(
73
+ messages,
74
+ tokenize=False,
75
  add_generation_prompt=True
76
  )
77
+
78
  inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
79
+
80
  streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
81
+
82
  generation_kwargs = dict(
83
  **inputs,
84
  streamer=streamer,
 
88
  top_p=0.9,
89
  pad_token_id=tokenizer.pad_token_id,
90
  )
91
+
92
  thread = Thread(target=model.generate, kwargs=generation_kwargs)
93
  thread.start()
94
+
95
+ generated_text = ""
 
 
96
  for new_text in streamer:
97
+ generated_text += new_text
98
+
99
+ # Format thinking tags into a collapsible HTML dropdown element
100
+ formatted_text = generated_text
101
+ if "<think>" in formatted_text:
102
+ if "</think>" in formatted_text:
103
+ formatted_text = formatted_text.replace("<think>", "<details><summary>🧠 Thought Process</summary>\n\n").replace("</think>", "\n\n</details>\n\n---")
104
+ else:
105
+ formatted_text = formatted_text.replace("<think>", "<details><summary>🧠 Thought Process (Thinking...)</summary>\n\n") + "\n\n</details>"
106
+
107
+ yield formatted_text
108
 
109
  # 3. Custom Chatbot component with Copy & Copy All features enabled
110
  chatbot_ui = gr.Chatbot(
111
  type="messages",
112
+ show_copy_button=True, # Adds a copy button to individual messages
113
+ show_copy_all_button=True, # Adds a button to copy the entire conversation history
114
  allow_file_downloads=True,
115
  )
116
 
117
+ demo = gr.ChatInterface(
118
+ fn=predict,
119
+ type="messages",
120
+ chatbot=chatbot_ui,
121
+ title="🍁 Maple-Preview",
122
+ description="A 20B-A1B ternary-weight reasoning LLM by DeepGrove. Powered by ZeroGPU.",
123
+ theme="soft",
124
+ )
 
 
 
 
125
 
126
  if __name__ == "__main__":
127
  demo.queue().launch()