Metal3d commited on
Commit
77b8f3c
·
unverified ·
1 Parent(s): 377362b

Initial commit

Browse files
Files changed (4) hide show
  1. .gitignore +1 -0
  2. README.md +2 -2
  3. app.py +197 -0
  4. requirements.txt +5 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ test.py
README.md CHANGED
@@ -8,7 +8,7 @@ sdk_version: 5.22.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
- short_description: Force any model to think like reasoning models
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ short_description: Force any model to think like a reasoning models
12
  ---
13
 
14
+ Check out the configuration reference at <https://huggingface.co/docs/hub/spaces-config-reference>
app.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import threading
3
+
4
+ import gradio as gr
5
+ import spaces
6
+ import transformers
7
+ from transformers import pipeline
8
+
9
+ # loading model and tokenizer
10
+ model_name = "Qwen/Qwen2-1.5B-Instruct"
11
+ if gr.NO_RELOAD:
12
+ pipe = pipeline(
13
+ "text-generation",
14
+ model=model_name,
15
+ device_map="auto",
16
+ torch_dtype="auto",
17
+ )
18
+
19
+ # the sentences starting the reasoning step by step
20
+ rethink_prepends = [
21
+ "OK, I need to figure out ",
22
+ "I think ",
23
+ "Wait, I think ",
24
+ "Let me check if ",
25
+ "I should also remember that ",
26
+ "Another thing to note is that ",
27
+ "I also recall that ",
28
+ "I think I have a good grasp ",
29
+ "Now, using all the above information, I can answer the question using the original language used for the question:"
30
+ "\n{question}\n"
31
+ "\n**ANSWER**\n",
32
+ ]
33
+
34
+
35
+ # to fix some problems with math display
36
+ latex_delimiters = [
37
+ {"left": "$$", "right": "$$", "display": True},
38
+ {"left": "$", "right": "$", "display": False},
39
+ ]
40
+
41
+
42
+ def reformat_math(text):
43
+ """Fix MathJax delimiters to use the Gradio syntax (Katex).
44
+
45
+ This is a workaround to display math formulas in Gradio. For now, I havn't found a way to
46
+ make it work as expected using others latex_delimiters...
47
+ """
48
+ text = re.sub(r"\\\[\s*(.*?)\s*\\\]", r"$$\1$$", text, flags=re.DOTALL)
49
+ text = re.sub(r"\\\(\s*(.*?)\s*\\\)", r"$\1$", text, flags=re.DOTALL)
50
+ return text
51
+
52
+
53
+ def user_input(message, history: list):
54
+ """Append the user input in the history and clean the input textbox"""
55
+ return "", history + [gr.ChatMessage(role="user", content=message)]
56
+
57
+
58
+ def rebuild_messages(history: list):
59
+ """Rebuid the messages from the history to be used by the model without the intermediate thoughs"""
60
+ messages = []
61
+ for h in history:
62
+ if isinstance(h, dict) and not h.get("metadata", {}).get("title", False):
63
+ messages.append(h)
64
+ elif (
65
+ isinstance(h, gr.ChatMessage)
66
+ and h.metadata.get("title")
67
+ and isinstance(h.content, str)
68
+ ):
69
+ messages.append({"role": h.role, "content": h.content})
70
+ return messages
71
+
72
+
73
+ @spaces.GPU
74
+ def bot(history: list, max_num_tokens: int, final_num_tokens: int):
75
+ """Make the model answering the question"""
76
+
77
+ # to get token as a stream, later in a thread
78
+ streamer = transformers.TextIteratorStreamer(
79
+ pipe.tokenizer, # pyright: ignore
80
+ skip_special_tokens=True,
81
+ skip_prompt=True,
82
+ )
83
+
84
+ # to reinsert the question in the reasoning if needed
85
+ question = history[-1]["content"]
86
+
87
+ # prepare the assistant message
88
+ history.append(
89
+ gr.ChatMessage(
90
+ role="assistant",
91
+ content=str(""),
92
+ metadata={
93
+ "title": "Thinking",
94
+ },
95
+ )
96
+ )
97
+
98
+ # for the moment, make the reasoning to be displayed in the chat
99
+ messages = rebuild_messages(history)
100
+ for i, prepend in enumerate(rethink_prepends):
101
+ if i > 0:
102
+ messages[-1]["content"] += "\n\n"
103
+ messages[-1]["content"] += prepend.format(question=question)
104
+
105
+ num_tokens = int(
106
+ max_num_tokens if "**ANSWER**" not in prepend else final_num_tokens
107
+ )
108
+ t = threading.Thread(
109
+ target=pipe,
110
+ args=(messages,),
111
+ kwargs=dict(
112
+ max_new_tokens=num_tokens,
113
+ streamer=streamer,
114
+ ),
115
+ )
116
+ t.start()
117
+
118
+ # rebuild the history with the new content
119
+ history[-1].content += prepend
120
+ if "**ANSWER**" in prepend:
121
+ # stop thinking, this is the answer now (no metadata for intermediate steps)
122
+ history.append(gr.ChatMessage(role="assistant", content=""))
123
+ for token in streamer:
124
+ history[-1].content += token
125
+ history[-1].content = reformat_math(history[-1].content)
126
+ yield history
127
+ t.join()
128
+
129
+ yield history
130
+
131
+
132
+ with gr.Blocks(fill_height=True, title="Making any model reasoning") as demo:
133
+ with gr.Row(scale=1):
134
+ with gr.Column(scale=5):
135
+ gr.Markdown(f"""
136
+ # Force reasoning for any model
137
+
138
+ This is a simple proof-of-concept to get any LLM model to reason ahead of its response.
139
+ This interface uses *{model_name}* model which is **not** a reasoning model. The used method
140
+ is only to force some "reasoning" steps with prefixes to help the model to enhance the answer.
141
+ """)
142
+ chatbot = gr.Chatbot(
143
+ scale=1,
144
+ type="messages",
145
+ latex_delimiters=latex_delimiters,
146
+ )
147
+ msg = gr.Textbox(
148
+ submit_btn=True,
149
+ label="",
150
+ show_label=False,
151
+ placeholder="Type your question here.",
152
+ )
153
+ with gr.Column(scale=1):
154
+ gr.Markdown("""## Tweaks""")
155
+ num_tokens = gr.Slider(
156
+ 50,
157
+ 255,
158
+ 100,
159
+ step=1,
160
+ label="Max tokens per reasoning step",
161
+ interactive=True,
162
+ )
163
+ final_num_tokens = gr.Slider(
164
+ 50,
165
+ 255,
166
+ 200,
167
+ step=1,
168
+ label="Max token for the final answer",
169
+ interactive=True,
170
+ )
171
+ gr.Markdown("""
172
+ Using smaller number of tokens in the reasoning steps will make the model
173
+ faster to answer, but it may not be able to go deep enough in its reasoning.
174
+ A good value is 100.
175
+
176
+ Using smaller number of tokens for the final answer will make the model
177
+ to be less verbose, but it may not be able to give a complete answer.
178
+ A good value is 200 to 255.
179
+ """)
180
+ gr.Markdown("""
181
+ This interface can work on personal computer with 6Go VRAM (e.g. NVidia 30NV). Feel free to fork
182
+ the application and try others instruct models.
183
+ """)
184
+
185
+ # when the user submit a message, the bot will answer
186
+ msg.submit(
187
+ user_input,
188
+ [msg, chatbot], # inputs
189
+ [msg, chatbot], # outputs
190
+ ).then(
191
+ bot,
192
+ [chatbot, num_tokens, final_num_tokens], # actually, the "history" input
193
+ chatbot, # to store the new history from the output
194
+ )
195
+
196
+ if __name__ == "__main__":
197
+ demo.queue().launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ accelerate
2
+ gradio
3
+ spaces
4
+ torch
5
+ transformers