BigDoge commited on
Commit
a12f61e
·
1 Parent(s): ea7c74d

Add application file

Browse files
Files changed (2) hide show
  1. app.py +404 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This script refers to the dialogue example of streamlit, the interactive
2
+ generation code of chatglm2 and transformers.
3
+
4
+ We mainly modified part of the code logic to adapt to the
5
+ generation of our model.
6
+ Please refer to these links below for more information:
7
+ 1. streamlit chat example:
8
+ https://docs.streamlit.io/knowledge-base/tutorials/build-conversational-apps
9
+ 2. chatglm2:
10
+ https://github.com/THUDM/ChatGLM2-6B
11
+ 3. transformers:
12
+ https://github.com/huggingface/transformers
13
+ Please run with the command `streamlit run path/to/web_demo.py
14
+ --server.address=0.0.0.0 --server.port 7860`.
15
+ Using `python path/to/web_demo.py` may cause unknown problems.
16
+ """
17
+
18
+ # isort: skip_file
19
+ import copy
20
+ import re
21
+ import warnings
22
+ from dataclasses import asdict, dataclass
23
+ from typing import Callable, List, Optional
24
+
25
+ import streamlit as st
26
+ import torch
27
+ from torch import nn
28
+
29
+ from transformers.generation.utils import LogitsProcessorList
30
+ from transformers.utils import logging
31
+
32
+ from transformers import AutoTokenizer, AutoModelForCausalLM # isort: skip
33
+
34
+ logger = logging.get_logger(__name__)
35
+ st.set_page_config(layout='wide')
36
+
37
+
38
+ @dataclass
39
+ class GenerationConfig:
40
+ # this config is used for chat to provide more diversity
41
+ max_length: int = 32768
42
+ top_p: float = 0.8
43
+ temperature: float = 0.8
44
+ do_sample: bool = True
45
+ repetition_penalty: float = 1.005
46
+
47
+
48
+ @torch.inference_mode()
49
+ def generate_interactive(
50
+ model,
51
+ tokenizer,
52
+ prompt,
53
+ generation_config: Optional[GenerationConfig] = None,
54
+ logits_processor: Optional[LogitsProcessorList] = None,
55
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
56
+ additional_eos_token_id: Optional[int] = None,
57
+ **kwargs,
58
+ ):
59
+ inputs = tokenizer([prompt], padding=True, return_tensors='pt')
60
+ input_length = len(inputs['input_ids'][0])
61
+ for k, v in inputs.items():
62
+ inputs[k] = v.cuda()
63
+ input_ids = inputs['input_ids']
64
+ _, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
65
+ if generation_config is None:
66
+ generation_config = model.generation_config
67
+ generation_config = copy.deepcopy(generation_config)
68
+ generation_config._eos_token_tensor = generation_config.eos_token_id
69
+ model_kwargs = generation_config.update(**kwargs)
70
+ if generation_config.temperature == 0.0:
71
+ generation_config.do_sample = False
72
+ eos_token_id = generation_config.eos_token_id
73
+ if isinstance(eos_token_id, int):
74
+ eos_token_id = [eos_token_id]
75
+ if additional_eos_token_id is not None:
76
+ eos_token_id.append(additional_eos_token_id)
77
+ has_default_max_length = kwargs.get('max_length') is None and generation_config.max_length is not None
78
+ if has_default_max_length and generation_config.max_new_tokens is None:
79
+ warnings.warn(
80
+ f"Using 'max_length''s default \
81
+ ({repr(generation_config.max_length)}) \
82
+ to control the generation length. "
83
+ 'This behaviour is deprecated and will be removed from the \
84
+ config in v5 of Transformers -- we'
85
+ ' recommend using `max_new_tokens` to control the maximum \
86
+ length of the generation.',
87
+ UserWarning,
88
+ )
89
+ elif generation_config.max_new_tokens is not None:
90
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
91
+ if not has_default_max_length:
92
+ logger.warn( # pylint: disable=W4902
93
+ f"Both 'max_new_tokens' (={generation_config.max_new_tokens}) "
94
+ f"and 'max_length'(={generation_config.max_length}) seem to "
95
+ "have been set. 'max_new_tokens' will take precedence. "
96
+ 'Please refer to the documentation for more information. '
97
+ '(https://huggingface.co/docs/transformers/main/'
98
+ 'en/main_classes/text_generation)',
99
+ UserWarning,
100
+ )
101
+
102
+ if input_ids_seq_length >= generation_config.max_length:
103
+ input_ids_string = 'input_ids'
104
+ logger.warning(
105
+ f'Input length of {input_ids_string} is {input_ids_seq_length}, '
106
+ f"but 'max_length' is set to {generation_config.max_length}. "
107
+ 'This can lead to unexpected behavior. You should consider'
108
+ " increasing 'max_new_tokens'."
109
+ )
110
+
111
+ # 2. Set generation parameters if not already defined
112
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
113
+ logits_processor = model._get_logits_processor(
114
+ generation_config=generation_config,
115
+ input_ids_seq_length=input_ids_seq_length,
116
+ encoder_input_ids=input_ids,
117
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
118
+ logits_processor=logits_processor,
119
+ )
120
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
121
+ while True:
122
+ model_inputs = model.prepare_inputs_for_generation(input_ids, **model_kwargs)
123
+ # forward pass to get next token
124
+ outputs = model(
125
+ **model_inputs,
126
+ return_dict=True,
127
+ output_attentions=False,
128
+ output_hidden_states=False,
129
+ )
130
+
131
+ next_token_logits = outputs.logits[:, -1, :]
132
+
133
+ # pre-process distribution
134
+ next_token_scores = logits_processor(input_ids, next_token_logits)
135
+
136
+ # sample
137
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
138
+ if generation_config.do_sample:
139
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
140
+ else:
141
+ next_tokens = torch.argmax(probs, dim=-1)
142
+
143
+ # update generated ids, model inputs, and length for next step
144
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
145
+ unfinished_sequences = unfinished_sequences.mul((min(next_tokens != i for i in eos_token_id)).long())
146
+
147
+ output_token_ids = input_ids[0].cpu().tolist()
148
+ output_token_ids = output_token_ids[input_length:]
149
+ for each_eos_token_id in eos_token_id:
150
+ if output_token_ids[-1] == each_eos_token_id:
151
+ output_token_ids = output_token_ids[:-1]
152
+ response = tokenizer.decode(output_token_ids)
153
+
154
+ yield response
155
+ # stop when each sentence is finished
156
+ # or if we exceed the maximum length
157
+ if unfinished_sequences.max() == 0:
158
+ break
159
+
160
+
161
+ def on_btn_click():
162
+ del st.session_state.messages
163
+ del st.session_state.deepthink_messages
164
+
165
+
166
+ def postprocess(text, add_prefix=True, deepthink=False):
167
+ text = re.sub(r'\\\(|\\\)', r'$', text)
168
+ text = re.sub(r'\\\[|\\\]', r'$$', text)
169
+ if add_prefix:
170
+ text = (':red[[Deep Thinking]]\n\n' if deepthink else ':blue[[Normal Response]]\n\n') + text
171
+ return text
172
+
173
+
174
+ @st.cache_resource
175
+ def load_model():
176
+ model_path = 'internlm/internlm3-8b-instruct'
177
+ model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True).to(torch.bfloat16).cuda()
178
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
179
+ return model, tokenizer
180
+
181
+
182
+ def prepare_generation_config():
183
+ with st.sidebar:
184
+ max_length = st.slider('Max Length', min_value=8, max_value=32768, value=32768)
185
+ top_p = st.slider('Top P', 0.0, 1.0, 0.8, step=0.01)
186
+ temperature = st.slider('Temperature', 0.0, 1.0, 0.7, step=0.01)
187
+ radio = st.radio('Inference Mode', ['Normal Response', 'Deep Thinking'], key='mode')
188
+ st.button('Clear Chat History', on_click=on_btn_click)
189
+
190
+ st.session_state['inference_mode'] = radio
191
+ generation_config = GenerationConfig(max_length=max_length, top_p=top_p, temperature=temperature)
192
+
193
+ return generation_config
194
+
195
+
196
+ user_prompt = '<|im_start|>user\n{user}<|im_end|>\n'
197
+ robot_prompt = '<|im_start|>assistant\n{robot}<|im_end|>\n'
198
+ cur_query_prompt = '<|im_start|>user\n{user}<|im_end|>\n\
199
+ <|im_start|>assistant\n'
200
+
201
+
202
+ def combine_history(prompt, deepthink=False, start=0, stop=None):
203
+ if stop is None:
204
+ stop = len(st.session_state.messages)
205
+ elif stop < 0:
206
+ stop = len(st.session_state.messages) + stop
207
+ messages = []
208
+ for idx in range(start, stop):
209
+ message, deepthink_message = st.session_state.messages[idx], st.session_state.deepthink_messages[idx]
210
+ if deepthink:
211
+ if deepthink_message['content'] is not None:
212
+ messages.append(deepthink_message)
213
+ else:
214
+ messages.append(message)
215
+ else:
216
+ if message['content'] is not None:
217
+ messages.append(message)
218
+ else:
219
+ messages.append(deepthink_message)
220
+ meta_instruction = (
221
+ 'You are InternLM (书生·浦语), a helpful, honest, '
222
+ 'and harmless AI assistant developed by Shanghai '
223
+ 'AI Laboratory (上海人工智能实验室).'
224
+ )
225
+ if deepthink:
226
+ meta_instruction += """You are an expert mathematician with extensive experience in mathematical competitions. You approach problems through systematic thinking and rigorous reasoning. When solving problems, follow these thought processes:
227
+ ## Deep Understanding
228
+ Take time to fully comprehend the problem before attempting a solution. Consider:
229
+ - What is the real question being asked?
230
+ - What are the given conditions and what do they tell us?
231
+ - Are there any special restrictions or assumptions?
232
+ - Which information is crucial and which is supplementary?
233
+ ## Multi-angle Analysis
234
+ Before solving, conduct thorough analysis:
235
+ - What mathematical concepts and properties are involved?
236
+ - Can you recall similar classic problems or solution methods?
237
+ - Would diagrams or tables help visualize the problem?
238
+ - Are there special cases that need separate consideration?
239
+ ## Systematic Thinking
240
+ Plan your solution path:
241
+ - Propose multiple possible approaches
242
+ - Analyze the feasibility and merits of each method
243
+ - Choose the most appropriate method and explain why
244
+ - Break complex problems into smaller, manageable steps
245
+ ## Rigorous Proof
246
+ During the solution process:
247
+ - Provide solid justification for each step
248
+ - Include detailed proofs for key conclusions
249
+ - Pay attention to logical connections
250
+ - Be vigilant about potential oversights
251
+ ## Repeated Verification
252
+ After completing your solution:
253
+ - Verify your results satisfy all conditions
254
+ - Check for overlooked special cases
255
+ - Consider if the solution can be optimized or simplified
256
+ - Review your reasoning process
257
+ Remember:
258
+ 1. Take time to think thoroughly rather than rushing to an answer
259
+ 2. Rigorously prove each key conclusion
260
+ 3. Keep an open mind and try different approaches
261
+ 4. Summarize valuable problem-solving methods
262
+ 5. Maintain healthy skepticism and verify multiple times
263
+ Your response should reflect deep mathematical understanding and precise logical thinking, making your solution path and reasoning clear to others.
264
+ When you're ready, present your complete solution with:
265
+ - Clear problem understanding
266
+ - Detailed solution process
267
+ - Key insights
268
+ - Thorough verification
269
+ Focus on clear, logical progression of ideas and thorough explanation of your mathematical reasoning. Provide answers in the same language as the user asking the question, repeat the final answer using a '\\boxed{}' without any units, you have [[8192]] tokens to complete the answer.
270
+ """ # noqa: E501
271
+ total_prompt = f'<s><|im_start|>system\n{meta_instruction}<|im_end|>\n'
272
+ for message in messages:
273
+ cur_content = message['content']
274
+ if message['role'] == 'user':
275
+ cur_prompt = user_prompt.format(user=cur_content)
276
+ elif message['role'] == 'robot':
277
+ cur_prompt = robot_prompt.format(robot=cur_content)
278
+ else:
279
+ raise RuntimeError
280
+ total_prompt += cur_prompt
281
+ total_prompt = total_prompt + cur_query_prompt.format(user=prompt)
282
+ return total_prompt
283
+
284
+
285
+ def main():
286
+ # torch.cuda.empty_cache()
287
+ print('load model begin.')
288
+ model, tokenizer = load_model()
289
+ print('load model end.')
290
+
291
+ user_avator = 'assets/user.png'
292
+ robot_avator = 'assets/robot.png'
293
+
294
+ st.title('InternLM3-8B-Instruct')
295
+
296
+ generation_config = prepare_generation_config()
297
+
298
+ def render_message(msg, msg_idx, deepthink):
299
+ if msg['content'] is None:
300
+ real_prompt = combine_history(
301
+ st.session_state.messages[msg_idx - 1]['content'], deepthink=deepthink, stop=msg_idx - 1
302
+ )
303
+ placeholder = st.empty()
304
+ for cur_response in generate_interactive(
305
+ model=model,
306
+ tokenizer=tokenizer,
307
+ prompt=real_prompt,
308
+ additional_eos_token_id=92542,
309
+ **asdict(generation_config),
310
+ ):
311
+ placeholder.markdown(postprocess(cur_response, deepthink=deepthink) + '▌')
312
+ placeholder.markdown(postprocess(cur_response, deepthink=deepthink))
313
+ msg['content'] = cur_response
314
+ torch.cuda.empty_cache()
315
+ else:
316
+ st.markdown(postprocess(msg['content'], deepthink=deepthink))
317
+
318
+ # Initialize chat history
319
+ if 'messages' not in st.session_state:
320
+ st.session_state.messages = []
321
+ if 'deepthink_messages' not in st.session_state:
322
+ st.session_state.deepthink_messages = []
323
+
324
+ # Display chat messages from history on app rerun
325
+ for idx, (message, deepthink_message) in enumerate(
326
+ zip(st.session_state.messages, st.session_state.deepthink_messages)
327
+ ):
328
+ with st.chat_message(message['role'], avatar=message.get('avatar')):
329
+ if message['role'] == 'user':
330
+ st.markdown(postprocess(message['content'], add_prefix=False))
331
+ else:
332
+ if st.toggle('compare', key=f'compare_{idx}'):
333
+ cols = st.columns(2)
334
+ if st.session_state['inference_mode'] == 'Deep Thinking':
335
+ with cols[1]:
336
+ render_message(deepthink_message, idx, True)
337
+ with cols[0]:
338
+ render_message(message, idx, False)
339
+ else:
340
+ with cols[0]:
341
+ render_message(message, idx, False)
342
+ with cols[1]:
343
+ render_message(deepthink_message, idx, True)
344
+ else:
345
+ if st.session_state['inference_mode'] == 'Deep Thinking':
346
+ if deepthink_message['content'] is not None:
347
+ st.markdown(postprocess(deepthink_message['content'], deepthink=True))
348
+ else:
349
+ st.markdown(postprocess(message['content']))
350
+ else:
351
+ if message['content'] is not None:
352
+ st.markdown(postprocess(message['content']))
353
+ else:
354
+ st.markdown(postprocess(deepthink_message['content'], deepthink=True))
355
+
356
+ # Accept user input
357
+ if prompt := st.chat_input('What is up?'):
358
+ # Display user message in chat message container
359
+ with st.chat_message('user', avatar=user_avator):
360
+ st.markdown(postprocess(prompt, add_prefix=False))
361
+ real_prompt = combine_history(prompt, deepthink=st.session_state['inference_mode'] == 'Deep Thinking')
362
+ # Add user message to chat history
363
+ st.session_state.messages.append({'role': 'user', 'content': prompt, 'avatar': user_avator})
364
+ st.session_state.deepthink_messages.append({'role': 'user', 'content': prompt, 'avatar': user_avator})
365
+
366
+ with st.chat_message('robot', avatar=robot_avator):
367
+ st.toggle('compare', key=f'compare_{len(st.session_state.messages)}')
368
+ message_placeholder = st.empty()
369
+ for cur_response in generate_interactive(
370
+ model=model,
371
+ tokenizer=tokenizer,
372
+ prompt=real_prompt,
373
+ additional_eos_token_id=92542,
374
+ **asdict(generation_config),
375
+ ):
376
+ # Display robot response in chat message container
377
+ message_placeholder.markdown(
378
+ postprocess(cur_response, deepthink=st.session_state['inference_mode'] == 'Deep Thinking') + '▌'
379
+ )
380
+ message_placeholder.markdown(
381
+ postprocess(cur_response, deepthink=st.session_state['inference_mode'] == 'Deep Thinking')
382
+ )
383
+ # Add robot response to chat history
384
+ response, deepthink_response = (
385
+ (None, cur_response) if st.session_state['inference_mode'] == 'Deep Thinking' else (cur_response, None)
386
+ )
387
+ st.session_state.messages.append(
388
+ {
389
+ 'role': 'robot',
390
+ 'content': response, # pylint: disable=undefined-loop-variable
391
+ 'avatar': robot_avator,
392
+ }
393
+ )
394
+ st.session_state.deepthink_messages.append(
395
+ {
396
+ 'role': 'robot',
397
+ 'content': deepthink_response,
398
+ 'avatar': robot_avator,
399
+ }
400
+ )
401
+ torch.cuda.empty_cache()
402
+
403
+
404
+ main()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ transformers>=4.48
2
+ streamlit>=1.41.1