Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
+
from peft import PeftModel
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
app = Flask(__name__)
|
| 7 |
+
|
| 8 |
+
BASE_MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 9 |
+
ADAPTER = "your-username/math-qwen2.5-adapter" # your HF repo
|
| 10 |
+
|
| 11 |
+
SYSTEM_PROMPT = "You are a helpful math assistant."
|
| 12 |
+
|
| 13 |
+
print("Loading model...")
|
| 14 |
+
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
|
| 15 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
| 16 |
+
BASE_MODEL,
|
| 17 |
+
torch_dtype=torch.float32,
|
| 18 |
+
device_map="auto"
|
| 19 |
+
)
|
| 20 |
+
model = PeftModel.from_pretrained(base_model, ADAPTER)
|
| 21 |
+
model.eval()
|
| 22 |
+
print("✅ Model ready!")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@app.route("/", methods=["GET"])
|
| 26 |
+
def home():
|
| 27 |
+
return jsonify({"status": "ok", "message": "Math model API is running!"})
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@app.route("/generate", methods=["POST"])
|
| 31 |
+
def generate():
|
| 32 |
+
data = request.get_json()
|
| 33 |
+
if not data or "question" not in data:
|
| 34 |
+
return jsonify({"error": "Send JSON with 'question' key"}), 400
|
| 35 |
+
|
| 36 |
+
question = data["question"].strip()
|
| 37 |
+
max_new_tokens = data.get("max_new_tokens", 256)
|
| 38 |
+
|
| 39 |
+
prompt = f"""<|im_start|>system
|
| 40 |
+
{SYSTEM_PROMPT}<|im_end|>
|
| 41 |
+
<|im_start|>user
|
| 42 |
+
{question}<|im_end|>
|
| 43 |
+
<|im_start|>assistant
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 47 |
+
|
| 48 |
+
with torch.no_grad():
|
| 49 |
+
outputs = model.generate(
|
| 50 |
+
**inputs,
|
| 51 |
+
max_new_tokens=max_new_tokens,
|
| 52 |
+
do_sample=False,
|
| 53 |
+
temperature=1.0,
|
| 54 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# Decode only the new tokens
|
| 58 |
+
new_tokens = outputs[0][inputs["input_ids"].shape[1]:]
|
| 59 |
+
answer = tokenizer.decode(new_tokens, skip_special_tokens=True)
|
| 60 |
+
|
| 61 |
+
return jsonify({"question": question, "answer": answer})
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
if __name__ == "__main__":
|
| 65 |
+
app.run(host="0.0.0.0", port=7860)
|