Spaces:
Running on Zero

jazzisfuture's picture
Upload app.py with huggingface_hub
127172d verified
Raw History Blame Contribute Delete
8 kB
#!/usr/bin/env python3
"""
MiniCPM5-1B 评测 Space - 修复版
"""
import json
import time
import spaces
import torch
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL_ID = "openbmb/MiniCPM5-1B"
tokenizer = None
model = None
@spaces.GPU(duration=120)
def load_model():
global tokenizer, model
if tokenizer is None:
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
if model is None:
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID, torch_dtype=torch.bfloat16, device_map="auto"
)
return "Model loaded successfully!"
def generate_response(messages, max_new_tokens=150):
global tokenizer, model
if tokenizer is None or model is None:
load_model()
inputs = tokenizer.apply_chat_template(
messages, tokenize=True, add_generation_prompt=True,
enable_thinking=False, return_dict=True, return_tensors="pt"
).to(model.device)
with torch.no_grad():
outputs = model.generate(
**inputs, max_new_tokens=max_new_tokens,
do_sample=True, temperature=0.7, top_p=0.95
)
return tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
# ============ Agent 评测:工具调用格式 ============
AGENT_TEST_CASES = [
{
"system": "You are a helpful assistant. When the user asks you to use a tool, respond with ONLY the tool call in this exact format: TOOL_CALL: tool_name(arguments)",
"user": "Search for weather in Beijing using the get_weather tool",
"expected_tool": "get_weather",
"check_format": True
},
{
"system": "You are a helpful assistant. When the user asks you to use a tool, respond with ONLY the tool call in this exact format: TOOL_CALL: tool_name(arguments)",
"user": "Find recent papers about LLM using arxiv_search tool",
"expected_tool": "arxiv_search",
"check_format": True
},
{
"system": "You are a helpful assistant. When the user asks you to use a tool, respond with ONLY the tool call in this exact format: TOOL_CALL: tool_name(arguments)",
"user": "Read the file config.json using read_file tool",
"expected_tool": "read_file",
"check_format": True
}
]
# ============ 角色扮演评测:更严格的检查 ============
ROLEPLAY_TEST_CASES = [
{
"system": "You are Gandalf, a wise wizard from Middle-earth. Always refer to yourself as Gandalf. Use phrases like 'my dear friend' and speak about magic and ancient wisdom.",
"user": "Who are you?",
"must_contain": ["Gandalf"],
"should_contain_any": ["wizard", "magic", "Middle-earth", "wisdom", "friend"],
"must_not_contain": ["AI", "language model", "assistant"]
},
{
"system": "You are Whiskers, a cute cat. You LOVE fish and tuna. Always end your sentences with 'Meow!' You refer to humans as 'hooman'.",
"user": "What food do you like?",
"must_contain": ["fish", "tuna"],
"should_contain_any": ["Meow", "hooman", "love", "yummy"],
"must_not_contain": ["I'm an AI", "I don't eat", "I'm a language model"]
},
{
"system": "You are a Python expert named PyBot. Always provide code examples. Start responses with 'Hey coder!'",
"user": "How to read a file?",
"must_contain": ["open"],
"should_contain_any": ["Hey coder", "with", "read", "file"],
"must_not_contain": ["I'm an AI", "I can't write code"]
}
]
@spaces.GPU(duration=90)
def eval_agent():
"""评测Agent工具调用能力"""
results = []
correct = 0
for case in AGENT_TEST_CASES:
messages = [
{"role": "system", "content": case["system"]},
{"role": "user", "content": case["user"]}
]
response = generate_response(messages, max_new_tokens=50)
# 检查是否包含正确的工具调用格式
has_tool_call = "TOOL_CALL:" in response or "tool_call" in response.lower()
has_correct_tool = case["expected_tool"] in response
is_correct = has_correct_tool and has_tool_call
if is_correct:
correct += 1
results.append({
"user": case["user"][:60],
"expected": case["expected_tool"],
"response": response[:80].strip(),
"has_format": has_tool_call,
"has_tool": has_correct_tool,
"correct": is_correct
})
return json.dumps({
"accuracy": correct / len(AGENT_TEST_CASES),
"correct": correct,
"total": len(AGENT_TEST_CASES),
"details": results
}, ensure_ascii=False, indent=2)
@spaces.GPU(duration=90)
def eval_roleplay():
"""评测角色扮演能力"""
results = []
total_score = 0
for case in ROLEPLAY_TEST_CASES:
messages = [
{"role": "system", "content": case["system"]},
{"role": "user", "content": case["user"]}
]
response = generate_response(messages, max_new_tokens=100)
response_lower = response.lower()
# 检查必须包含的词
must_pass = all(w.lower() in response_lower for w in case["must_contain"])
# 检查应该包含的词
should_count = sum(1 for w in case["should_contain_any"] if w.lower() in response_lower)
should_score = should_count / len(case["should_contain_any"])
# 检查不能包含的词(跳出角色)
broke_character = any(w.lower() in response_lower for w in case["must_not_contain"])
# 计算总分
if broke_character:
score = 0
elif not must_pass:
score = 0.2 # 只给基础分
else:
score = 0.4 + (should_score * 0.6) # 必须词通过后,按应该词给分
total_score += score
results.append({
"system": case["system"][:50] + "...",
"user": case["user"],
"response": response[:80].strip(),
"must_pass": must_pass,
"should_matches": [w for w in case["should_contain_any"] if w.lower() in response_lower],
"broke_character": broke_character,
"score": round(score, 2)
})
return json.dumps({
"avg_score": total_score / len(ROLEPLAY_TEST_CASES),
"total": len(ROLEPLAY_TEST_CASES),
"details": results
}, ensure_ascii=False, indent=2)
@spaces.GPU(duration=60)
def single_test(prompt, system_prompt=""):
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
return generate_response(messages)
with gr.Blocks(title="MiniCPM5-1B Evaluation") as demo:
gr.Markdown("# MiniCPM5-1B Evaluation (Fixed)")
with gr.Tab("Load Model"):
load_btn = gr.Button("Load Model")
load_output = gr.Textbox(label="Status")
load_btn.click(load_model, outputs=load_output)
with gr.Tab("Single Test"):
with gr.Row():
prompt_input = gr.Textbox(label="Prompt", lines=3)
system_input = gr.Textbox(label="System Prompt", lines=2)
test_btn = gr.Button("Test")
test_output = gr.Textbox(label="Response", lines=5)
test_btn.click(single_test, inputs=[prompt_input, system_input], outputs=test_output)
with gr.Tab("Agent Eval"):
agent_btn = gr.Button("Run Agent Evaluation")
agent_output = gr.Textbox(label="Agent Result", lines=20)
agent_btn.click(eval_agent, outputs=agent_output)
with gr.Tab("Roleplay Eval"):
roleplay_btn = gr.Button("Run Roleplay Evaluation")
roleplay_output = gr.Textbox(label="Roleplay Result", lines=20)
roleplay_btn.click(eval_roleplay, outputs=roleplay_output)
if __name__ == "__main__":
demo.launch()