Spaces:
Running
Running
Download eval/run_eval.py from AnilNiraula/FinChat: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/spaces/AnilNiraula/FinChat/resolve/main/eval/run_eval.py
- Command line
-
hf download hf://spaces/AnilNiraula/FinChat/eval/run_eval.py
-
curl -L -o run_eval.py https://huggingface.co/spaces/AnilNiraula/FinChat/resolve/main/eval/run_eval.py
10.2 kB
| """Evaluate FinChat. Usage: | |
| python eval/run_eval.py --label qwen1.5b | |
| python eval/run_eval.py --label phi2 --model-repo TheBloke/phi-2-GGUF --model-file phi-2.Q4_K_M.gguf --chat-format chatml | |
| Writes eval/results/<label>.csv and appends a row to eval/results/summary_tool_calling.md | |
| (summary.md holds the earlier regex-routing results for comparison). | |
| Numeric truth is recomputed independently here with yfinance (auto-adjusted Close) / plain math.""" | |
| import argparse, csv, json, os, re, sys, time | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent.parent | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--label", required=True) | |
| ap.add_argument("--model-repo"); ap.add_argument("--model-file"); ap.add_argument("--model-path") | |
| ap.add_argument("--chat-format"); ap.add_argument("--limit", type=int) | |
| ap.add_argument("--only", choices=["numeric", "text"]) | |
| ap.add_argument("--basic", action="store_true", help="only the basic ticker/price phrasings") | |
| ap.add_argument("--new", action="store_true", help="only dividend, multi-turn and invalid-ticker cases") | |
| ap.add_argument("--followup", action="store_true", help="only follow-up context cases") | |
| ap.add_argument("--max-new-tokens", type=int, default=200) | |
| a = ap.parse_args() | |
| for k, v in {"MODEL_REPO": a.model_repo, "MODEL_FILE": a.model_file, "MODEL_PATH": a.model_path, | |
| "CHAT_FORMAT": a.chat_format}.items(): | |
| if v: os.environ[k] = v | |
| sys.path.insert(0, str(ROOT)) | |
| import app # noqa: E402 | |
| STOP = set("the a an of to and or in on is are for with by as it its be that this can your you at from may not".split()) | |
| def words(s): | |
| return {w for w in re.findall(r"[a-z0-9]+", s.lower()) if w not in STOP and len(w) > 2} | |
| def support(answer, passages): | |
| """Fraction of answer sentences whose content words are >=60% present in retrieved passages.""" | |
| body = answer.split("**Sources:**")[0] | |
| pw = words(" ".join(passages)) | |
| sents = [s for s in re.split(r"(?<=[.!?])\s+|\n+", body) if len(words(s)) >= 3] | |
| if not sents: return 0.0 | |
| return sum(len(words(s) & pw) / len(words(s)) >= 0.6 for s in sents) / len(sents) | |
| def truth_cagr(t, s, e): | |
| import yfinance as yf | |
| h = yf.Ticker(t).history(start=f"{s}-01-01", end=f"{e}-12-31", auto_adjust=True)["Close"].dropna() | |
| yrs = (h.index[-1] - h.index[0]).days / 365.25 | |
| return ((h.iloc[-1] / h.iloc[0]) ** (1 / yrs) - 1) * 100 | |
| def first_num(text, pat): | |
| m = re.search(pat, text.replace(",", "")) | |
| return float(m.group(1)) if m else None | |
| def truth_price(t): | |
| import yfinance as yf | |
| return float(yf.Ticker(t).history(period="5d")["Close"].dropna().iloc[-1]) | |
| def truth_ttm_yield(t): | |
| import yfinance as yf | |
| tk = yf.Ticker(t); h = tk.history(period="1y")["Close"].dropna(); d = tk.dividends | |
| d.index = d.index.tz_localize(None); last = h.index[-1].tz_localize(None) | |
| return float(d[d.index > last - __import__("pandas").Timedelta(days=365)].sum()) / float(h.iloc[-1]) * 100 | |
| def tick_val(text, t): | |
| m = re.search(rf"{re.escape(t)}: ~(-?[\d.]+)%", text) | |
| return float(m.group(1)) if m else None | |
| qs = [json.loads(l) for l in open(ROOT / "eval/questions.jsonl")] | |
| if a.only: qs = [q for q in qs if q["type"] == a.only] | |
| if a.basic: qs = [q for q in qs if q.get("basic")] | |
| if a.new: qs = [q for q in qs if q.get("dividend") or q.get("multiturn") or q.get("invalid")] | |
| if a.followup: qs = [q for q in qs if q.get("followup")] | |
| if a.limit: qs = qs[: a.limit] | |
| rows = [] | |
| for q in qs: | |
| r = {"id": q["id"], "type": q["type"], "kind": q.get("kind", "concept" if not q.get("expect_refusal") else "out_of_scope"), | |
| "basic": q.get("basic", False), "paraphrase": q.get("paraphrase", False), | |
| "dividend": q.get("dividend", False), "multiturn": q.get("multiturn", False), "invalid": q.get("invalid", False), "followup": q.get("followup", False), "question": q["question"]} | |
| info, final, t0, t_first, ntok = {}, "", time.time(), None, 0 | |
| for final, _ in app.answer_stream(q["question"], q.get("history") or None, max_new_tokens=a.max_new_tokens, | |
| temperature=0.0, info=info): | |
| if t_first is None: t_first = time.time() - t0 | |
| dt = time.time() - t0 | |
| tools_called = sorted({c["tool"] for c in info.get("calls", [])}) | |
| r.update(latency_s=round(dt, 2), ttft_s=round(t_first or 0, 2), tools=";".join(tools_called), | |
| fallback=info.get("fallback"), tool_ok=set(q["expected_tools"]) <= set(tools_called), | |
| tool_exact=set(q["expected_tools"]) == set(tools_called), | |
| dropped=info.get("dropped_sentences", 0), gen_tokens=info.get("gen_tokens", 0)) | |
| if q["type"] == "numeric": | |
| if q["kind"] == "cagr": | |
| truth = truth_cagr(q["ticker"], q["start"], q["end"]); got = tick_val(final, q["ticker"]) | |
| ok = got is not None and abs(got - truth) <= q["tolerance_pct_points"] + 0.006 | |
| if q.get("second_ticker"): | |
| t2 = truth_cagr(q["second_ticker"], q["start"], q["end"]); g2 = tick_val(final, q["second_ticker"]) | |
| ok = ok and g2 is not None and abs(g2 - t2) <= 0.056 | |
| elif q["kind"] == "compound": | |
| g = (1 + q["rate"] / 100) ** q["years"] | |
| truth = q["principal"] * g + q.get("contribution", 0) * (g - 1) / (q["rate"] / 100) | |
| got = first_num(final, r"Final Balance[^$]*\$([\d.]+)") | |
| ok = got is not None and abs(got - truth) <= q["tolerance_usd"] + 0.006 | |
| elif q["kind"] == "dividend": | |
| c = next((c for c in info.get("calls", []) if c["tool"] == "get_dividends"), {}) | |
| parse_ok = (str(c.get("ticker", "")).upper() == q["ticker"] and | |
| all((c.get(k) or None) == (q.get(k2) or None) for k, k2 in | |
| (("amount", "amount"), ("gain_pct", "gain_pct"), ("price_growth", "price_growth"), ("div_growth", "div_growth"))) and | |
| int(c.get("years") or 5) == q["years"]) | |
| truth = truth_ttm_yield(q["ticker"]); got = first_num(final, r"12-month yield: ([\d.]+)%") | |
| ok = parse_ok and got is not None and abs(got - truth) <= 0.05 | |
| if q.get("amount") and ok: | |
| pay = first_num(final, r"annual dividend payment now: \$([\d.]+)") | |
| ok = pay is not None and abs(pay - q["amount"] * truth / 100) <= max(1.0, 0.002 * q["amount"]) | |
| if ok and q.get("div_growth"): | |
| p1 = first_num(final, r"Year 1: \$([\d.]+)") | |
| ok = ("assumed dividend growth" in final and p1 is not None | |
| and abs(p1 - pay * (1 + q["div_growth"] / 100)) <= 0.02) | |
| r["parse_ok"] = parse_ok | |
| elif q["kind"] == "no_data": | |
| truth, got = None, None | |
| ok = f"Data is not available for {q['ticker']}" in final | |
| else: | |
| truth = truth_price(q["ticker"]); got = first_num(final, rf"{q['ticker']}: \$([\d.]+)") | |
| ok = got is not None and abs(got - truth) / truth <= q["tolerance_rel"] | |
| r.update(truth=round(truth, 4) if truth is not None else None, got=got, pass_=ok and "don't have that" not in final) | |
| else: | |
| hits = info.get("hits", []) | |
| ids = [h["doc_id"] for h in hits] | |
| declined = bool(info.get("declined")) | |
| r.update(retrieved=";".join(ids), declined=declined) | |
| if q["expect_refusal"]: | |
| r["pass_"] = declined | |
| else: | |
| r["recall_at_k"] = float(any(g in ids for g in q["gold_docs"])) | |
| r["support"] = round(support(info.get("answer_text", ""), [h["text"] for h in hits]), 2) | |
| r["keyword_hit"] = all(k.lower() in final.lower() for k in q["keywords"]) | |
| r["cited"] = bool(info.get("cited")) | |
| r["pass_"] = (not declined) and r["recall_at_k"] == 1 and r["cited"] and r["support"] >= 0.5 | |
| r["answer"] = final.replace("\n", " ")[:600] | |
| rows.append(r); print(q["id"], r.get("pass_"), r["tools"], r["latency_s"], flush=True) | |
| out = ROOT / "eval/results"; out.mkdir(exist_ok=True) | |
| keys = list(dict.fromkeys(k for r in rows for k in r)) | |
| with open(out / f"{a.label}.csv", "w", newline="") as f: | |
| w = csv.DictWriter(f, fieldnames=keys); w.writeheader(); w.writerows(rows) | |
| def mean(xs): xs = [x for x in xs if x is not None]; return round(sum(xs) / len(xs), 3) if xs else None | |
| num = [r for r in rows if r["type"] == "numeric"] | |
| ins = [r for r in rows if r["type"] == "text" and "recall_at_k" in r] | |
| oos = [r for r in rows if r["type"] == "text" and "recall_at_k" not in r] | |
| summ = dict(model=a.label, n=len(rows), numeric_acc=mean([float(r["pass_"]) for r in num]), | |
| basic_ticker_acc=mean([float(r["pass_"]) for r in num if r["basic"]]), | |
| paraphrase_acc=mean([float(r["pass_"]) for r in rows if r["paraphrase"]]), | |
| tool_select_acc=mean([float(r["tool_ok"]) for r in rows]), tool_exact=mean([float(r["tool_exact"]) for r in rows]), | |
| dividend_acc=mean([float(r["pass_"]) for r in rows if r["dividend"]]), | |
| multiturn_acc=mean([float(r["pass_"]) for r in rows if r["multiturn"]]), | |
| followup_acc=mean([float(r["pass_"]) for r in rows if r["followup"]]), | |
| followup_latency_s=mean([r["latency_s"] for r in rows if r["followup"] and r["type"] == "numeric"]), | |
| invalid_ticker_acc=mean([float(r["pass_"]) for r in rows if r["invalid"]]), | |
| fallback_used=sum(bool(r["fallback"]) for r in rows), | |
| recall_at_k=mean([r["recall_at_k"] for r in ins]), support=mean([r["support"] for r in ins]), | |
| cited=mean([float(r["cited"]) for r in ins]), wrongly_declined=mean([float(r["declined"]) for r in ins]), | |
| text_pass=mean([float(r["pass_"]) for r in ins]), refusal_acc=mean([float(r["pass_"]) for r in oos]), | |
| avg_latency_s=mean([r["latency_s"] for r in rows]), avg_ttft_s=mean([r["ttft_s"] for r in rows])) | |
| md = out / ("summary_v3_dividends.md" if (a.new or "dividend" in a.label) else "summary_tool_calling.md") | |
| if not md.exists(): md.write_text("| " + " | ".join(summ) + " |\n|" + "---|" * len(summ) + "\n") | |
| with open(md, "a") as f: f.write("| " + " | ".join(str(v) for v in summ.values()) + " |\n") | |
| print(json.dumps(summ, indent=1)) | |