647. Al Mathematical Olympiad - Progress Prize 2 | ai-mathematical-olympiad-progress-prize-2
使用的 LLM:
deepseek-r1-distill-qwen-14b-awq-casperhansen
我认为有些问题通过运行 Python 代码可以更高效地解决——所以我探索了用 DeepSeek R1 生成代码。然而,简单地在提示词中添加“制作 Python 代码”效果不佳。
以下是我发现对 DeepSeek 和 QWQ 有效的方法:
将问题文本作为提示提供给模型。
设置输出长度在 2000 到 4000 tokens 之间。
这样可以在 1-2 分钟内获得输出。
输出文本总是会被截断,但这对后续代码生成没有影响。
使用模型之前的输出构建一个新的 retry_prompt:
结构:
content = <根据之前的思考制作代码的指令文本>
(例如:"请简要总结你的方法,包括 Python 代码。")
content += question
content += output
prompt = [{"role": "user", "content": content}]
prompt = tokenizer.apply_chat_template(
conversation=retry_prompt,
tokenize=False,
add_generation_prompt=True)
然后,添加以下内容之一:
为了更好的代码(更详细,包含推理):
prompt += '</think>\n'
prompt += "Here's a structured approach to solve the problem:\n### Approach\n"
为了更快的代码(但有时质量较低):
prompt += '</think>\n'
prompt += '```python\n'
这样可以在大约 1 分钟内获得代码。
如果生成的代码在通过 subprocess 运行时失败,构建一个新的错误修复提示:
content = <一些修复代码的指令>
(例如:"请修正下面的 Python 代码,并将其放在 ```python\n{{corrected code here}}``` 中。")
content += question
content += <带有错误的代码>
content += <错误信息>
使用这个新提示重试生成。
有时有效,但有时会遇到另一个错误,需要重复此修复过程。
演示使用参考集生成代码和错误修复的 Notebook:
https://www.kaggle.com/code/ippeiogawa/generate-code-from-deepseekr1
样本 (Samples):
总共 16 个样本 —
→ 4 个用于获取代码(如上所述)
→ 12 个用于获取 boxed 答案
分块推理 (Chunked Reasoning):
每 2000 tokens 输出一次 → 组合 3–4 个输出 → 提示:
"Please think again from combined previous thought."(请结合之前的思考重新思考。)
vLLM.LLMEngine:
用于一旦样本完成就流式传输结果。
LLMEngine 代码片段:
from vllm import EngineArgs, LLMEngine, SamplingParams
# 初始化引擎
engine_args = EngineArgs(
llm_model_path,
max_model_len=max_len,
trust_remote_code=True,
tensor_parallel_size=4,
gpu_memory_utilization=0.96,
seed=2025,
)
engine = LLMEngine.from_engine_args(engine_args)
# 主循环
while <某些条件以继续生成或停止>:
if prompt:
engine.add_request(str(request_id), prompt, sampling_params)
request_id +=1
#
request_outputs = engine.step()
#
for request_output in request_outputs:
if request_output.finished:
output_text = request_output[0].text
# 提取答案
# 处理输出
if Code in output_text:
run via subprocess (通过 subprocess 运行)
#
# 构建新提示以生成或修复代码,或结合思考重新思考。
new_prompt = <构建新提示>
engine.add_request(str(request_id), new_prompt, new_sampling_params)
request_id +=1
早期停止 (Early stopping):
如果产生了 3 个相同的答案,我将其视为最终答案并继续处理下一个问题。
感谢阅读!