hvme 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hvme/__init__.py +2 -0
- hvme/api.py +243 -0
- hvme/bench/__init__.py +4 -0
- hvme/bench/calm.py +48 -0
- hvme/bench/datasets.py +83 -0
- hvme/bench/general.py +53 -0
- hvme/bench/metrics.py +66 -0
- hvme/bench/prompts.py +35 -0
- hvme/bench/runner.py +55 -0
- hvme/engine/__init__.py +10 -0
- hvme/engine/discovery.py +57 -0
- hvme/engine/dsep.py +36 -0
- hvme/engine/estimate.py +93 -0
- hvme/engine/identify.py +172 -0
- hvme/engine/refute.py +32 -0
- hvme/engine/scm.py +161 -0
- hvme/fast/__init__.py +6 -0
- hvme/fast/calibrate.py +59 -0
- hvme/fast/data.py +59 -0
- hvme/fast/distill.py +109 -0
- hvme/fast/judge.py +121 -0
- hvme/fast/lora.py +49 -0
- hvme/fast/router.py +41 -0
- hvme/fast/seed_worker.py +63 -0
- hvme/fast/train.py +106 -0
- hvme/graph/__init__.py +5 -0
- hvme/graph/schema.py +172 -0
- hvme/graph/serialize.py +29 -0
- hvme/graph/tabular/__init__.py +10 -0
- hvme/graph/tabular/networks.py +24 -0
- hvme/graph/tabular/oracle.py +38 -0
- hvme/graph/tabular/pc.py +172 -0
- hvme/graph/tabular/pipeline.py +106 -0
- hvme/graph/tabular/prior.py +106 -0
- hvme/graph/tabular/profile.py +18 -0
- hvme/graph/text/__init__.py +13 -0
- hvme/graph/text/aggregate.py +31 -0
- hvme/graph/text/canonical.py +45 -0
- hvme/graph/text/evaluate.py +35 -0
- hvme/graph/text/extract.py +68 -0
- hvme/graph/text/merge.py +63 -0
- hvme/graph/text/oracle.py +58 -0
- hvme/graph/text/pipeline.py +54 -0
- hvme/graph/text/synth.py +147 -0
- hvme/graph/text/verify.py +21 -0
- hvme/gym/__init__.py +9 -0
- hvme/gym/ancestry.py +80 -0
- hvme/gym/check.py +80 -0
- hvme/gym/dataset.py +89 -0
- hvme/gym/evaluate.py +36 -0
- hvme/gym/formats.py +91 -0
- hvme/gym/graphid.py +162 -0
- hvme/gym/graphs.py +63 -0
- hvme/gym/kosurf.py +209 -0
- hvme/gym/prob.py +166 -0
- hvme/gym/queries.py +363 -0
- hvme/gym/v3.py +517 -0
- hvme/gym/verbalize.py +85 -0
- hvme/gym/vocab.py +83 -0
- hvme/lm/__init__.py +7 -0
- hvme/lm/data.py +65 -0
- hvme/lm/grpo.py +244 -0
- hvme/lm/jobs.py +168 -0
- hvme/lm/sample.py +100 -0
- hvme/lm/sft.py +107 -0
- hvme/lm/solutions.py +469 -0
- hvme/lm/tools.py +674 -0
- hvme/lm/trajectories.py +554 -0
- hvme/mcp/__init__.py +1 -0
- hvme/mcp/__main__.py +3 -0
- hvme/mcp/server.py +128 -0
- hvme/orchestrator/__init__.py +6 -0
- hvme/orchestrator/analysis.py +193 -0
- hvme/orchestrator/core.py +85 -0
- hvme/orchestrator/demo.py +162 -0
- hvme/orchestrator/explain.py +160 -0
- hvme/orchestrator/query.py +88 -0
- hvme/orchestrator/route.py +104 -0
- hvme/paths.py +15 -0
- hvme/providers/__init__.py +4 -0
- hvme/providers/anthropic_api.py +25 -0
- hvme/providers/base.py +15 -0
- hvme/providers/cache.py +50 -0
- hvme/providers/hf.py +43 -0
- hvme/providers/remote.py +40 -0
- hvme/providers/spec.py +39 -0
- hvme/validate/__init__.py +10 -0
- hvme/validate/benchmark.py +28 -0
- hvme/validate/ci.py +58 -0
- hvme/validate/experiment.py +29 -0
- hvme/validate/falsify.py +59 -0
- hvme/validate/report.py +141 -0
- hvme/validate/structure.py +14 -0
- hvme-0.1.0.dist-info/METADATA +190 -0
- hvme-0.1.0.dist-info/RECORD +99 -0
- hvme-0.1.0.dist-info/WHEEL +5 -0
- hvme-0.1.0.dist-info/entry_points.txt +2 -0
- hvme-0.1.0.dist-info/licenses/LICENSE +202 -0
- hvme-0.1.0.dist-info/top_level.txt +1 -0
hvme/__init__.py
ADDED
hvme/api.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Path-based Hvme API. MCP tools, notebooks and scripts use the same functions.
|
|
2
|
+
|
|
3
|
+
- Graphs are stored in data/graphs/<graph_id>.hcg.json and passed around by graph_id.
|
|
4
|
+
- Data is given as a CSV path; documents as a JSONL ({"id", "text"}) path or a folder of .txt/.md files.
|
|
5
|
+
- All return values are JSON-serializable dicts.
|
|
6
|
+
- llm: providers.from_spec format ("hf:Qwen/Qwen3.5-9B@cuda:1", "anthropic:claude-sonnet-5-5", "replay:<path>"). Defaults to the HVME_LLM environment variable.
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
from .engine import BinarySCM, estimate, identify, refute
|
|
16
|
+
from .graph.schema import HCG
|
|
17
|
+
from .graph.tabular import tabular_to_hcg
|
|
18
|
+
from .graph.text import link_nodes, merge_hcg, text_to_hcg
|
|
19
|
+
from .orchestrator import Orchestrator
|
|
20
|
+
from .orchestrator.analysis import fit_scm, latent_of
|
|
21
|
+
from .paths import GRAPHS, RESULTS, ROOT
|
|
22
|
+
from .providers.spec import from_spec
|
|
23
|
+
from .validate import validate_hcg
|
|
24
|
+
|
|
25
|
+
LLM_CACHE = RESULTS / "llm_cache" / "api.json"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _path(graph_id: str) -> Path:
|
|
29
|
+
return GRAPHS / f"{graph_id}.hcg.json"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _load(graph_id: str) -> HCG:
|
|
33
|
+
return HCG.load(_path(graph_id))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _llm(spec: str | None):
|
|
37
|
+
return from_spec(spec or os.environ.get("HVME_LLM"), cache=LLM_CACHE)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _done(llm) -> None:
|
|
41
|
+
"""If the provider is a recording one, save its responses."""
|
|
42
|
+
getattr(llm, "save", lambda: None)()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def read_docs(path: str | Path) -> list[dict]:
|
|
46
|
+
path = Path(path)
|
|
47
|
+
if path.is_dir():
|
|
48
|
+
return [{"id": f.stem, "text": f.read_text(encoding="utf-8")} for f in sorted(path.iterdir()) if f.suffix in (".txt", ".md")]
|
|
49
|
+
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def graph_summary(hcg: HCG) -> dict:
|
|
53
|
+
return {"graph_id": hcg.graph_id, "path": str(_path(hcg.graph_id)),
|
|
54
|
+
"nodes": [{"id": n.id, "label": n.label, "aliases": n.aliases[:5]} for n in hcg.nodes],
|
|
55
|
+
"edges": [{"src": e.src, "dst": e.dst, "sign": e.sign, "status": e.status.value, "confidence": round(e.confidence, 3),
|
|
56
|
+
"evidence": sorted({x.kind.value for x in e.evidence})} for e in hcg.edges]}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ---------- graphs ----------
|
|
60
|
+
def graph_from_table(csv: str, graph_id: str, domain: str = "", alpha: float = 0.01, mode: str = "hybrid", llm: str | None = None) -> dict:
|
|
61
|
+
"""Tabular data -> HCG (PC + optional LLM pairwise prior + L1/L2 validation)."""
|
|
62
|
+
provider = _llm(llm)
|
|
63
|
+
r = tabular_to_hcg(pd.read_csv(csv), graph_id, domain, provider=provider, alpha=alpha, mode=mode, n_boot=10, validate_kw={"n_perm": 50})
|
|
64
|
+
_done(provider)
|
|
65
|
+
r.hcg.save(_path(graph_id))
|
|
66
|
+
return graph_summary(r.hcg) | {"verdict": r.report.verdict, "conflicts": r.conflicts}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def graph_from_text(docs: str, graph_id: str, domain: str = "", llm: str | None = None) -> dict:
|
|
70
|
+
"""Documents -> HCG (causal claim extraction -> canonicalization -> cross-document aggregation -> counterfactual verification evidence). Requires an LLM."""
|
|
71
|
+
provider = _llm(llm)
|
|
72
|
+
r = text_to_hcg(read_docs(docs), graph_id, domain, provider)
|
|
73
|
+
_done(provider)
|
|
74
|
+
r.hcg.save(_path(graph_id))
|
|
75
|
+
return graph_summary(r.hcg) | {"claims": len(r.claims)}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def graph_merge(text_graph: str, table_graph: str, graph_id: str, column_aliases: dict | None = None) -> dict:
|
|
79
|
+
"""Merge a text HCG into a tabular HCG. Nodes are linked by name/alias similarity; opposing edges are reconciled using direction evidence."""
|
|
80
|
+
text, table = _load(text_graph), _load(table_graph)
|
|
81
|
+
link = link_nodes(text, table, column_aliases)
|
|
82
|
+
merged = merge_hcg(text, table, link, graph_id)
|
|
83
|
+
merged.save(_path(graph_id))
|
|
84
|
+
return graph_summary(merged) | {"link": link}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def graph_get(graph_id: str) -> dict:
|
|
88
|
+
return graph_summary(_load(graph_id))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def graph_list() -> list[str]:
|
|
92
|
+
return sorted(p.name.removesuffix(".hcg.json") for p in GRAPHS.glob("*.hcg.json"))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# ---------- validation ----------
|
|
96
|
+
def validate_run(graph_id: str, csv: str, n_perm: int = 100) -> dict:
|
|
97
|
+
"""L1 structure + L2 data falsification. Updates edge status (supported/verified/refuted) and saves."""
|
|
98
|
+
hcg = _load(graph_id)
|
|
99
|
+
report, changes = validate_hcg(hcg, pd.read_csv(csv), n_perm=n_perm)
|
|
100
|
+
hcg.save(_path(graph_id))
|
|
101
|
+
report.save(RESULTS / "validation" / f"{graph_id}.json")
|
|
102
|
+
return {"summary": report.summary(), "notes": report.notes, "missing_edge_candidates": report.missing_edge_candidates(),
|
|
103
|
+
"changes": changes.to_dict("records")}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ---------- causal engine ----------
|
|
107
|
+
def engine_identify(graph_id: str, treatment: str, outcome: str, csv: str | None = None) -> dict:
|
|
108
|
+
"""Identification (backdoor -> frontdoor -> IV). If csv is given, nodes missing from the data are treated as unobserved."""
|
|
109
|
+
g = _load(graph_id).to_networkx()
|
|
110
|
+
lat = latent_of(g, pd.read_csv(csv, nrows=1)) if csv else []
|
|
111
|
+
e = identify(g, treatment, outcome, lat)
|
|
112
|
+
return {"strategy": e.strategy, "variables": sorted(e.variables), "expression": e.expression, "latent": lat}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def engine_estimate(graph_id: str, csv: str, treatment: str, outcome: str, n_boot: int = 200) -> dict:
|
|
116
|
+
g, df = _load(graph_id).to_networkx(), pd.read_csv(csv)
|
|
117
|
+
est = estimate(g, df, treatment, outcome, latent_of(g, df), n_boot=n_boot)
|
|
118
|
+
return {"strategy": est.estimand.strategy, "variables": sorted(est.estimand.variables), "method": est.method,
|
|
119
|
+
"value": est.value, "se": est.se, "ci": list(est.ci)}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def engine_refute(graph_id: str, csv: str, treatment: str, outcome: str) -> list[dict]:
|
|
123
|
+
g, df = _load(graph_id).to_networkx(), pd.read_csv(csv)
|
|
124
|
+
return refute(g, df, treatment, outcome, latent_of(g, df)).to_dict("records")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def engine_counterfactual(graph_id: str, csv: str, treatment: str, outcome: str, query: str = "ett", mediators: list | None = None) -> dict:
|
|
128
|
+
"""Compute a counterfactual query on a binary SCM fitted from the data. query: ate, ett, nde, nie, pn, ps."""
|
|
129
|
+
g, df = _load(graph_id).to_networkx(), pd.read_csv(csv)
|
|
130
|
+
scm: BinarySCM = fit_scm(g, df, [treatment, outcome, *(mediators or [])])
|
|
131
|
+
args = (treatment, outcome, mediators or []) if query in ("nde", "nie") else (treatment, outcome)
|
|
132
|
+
return {"query": query, "value": getattr(scm, query)(*args), "exact": scm.exact, "nodes": sorted(scm.graph.nodes)}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ---------- orchestrator ----------
|
|
136
|
+
def ask(question: str, graph_id: str, csv: str, experiment_csv: str | None = None, experiment_treatment: str | None = None,
|
|
137
|
+
llm: str | None = None, n_perm: int = 100) -> dict:
|
|
138
|
+
"""Handle one question end to end: query analysis -> validation -> identification -> estimation -> refutation -> sensitivity -> an answer with evidence and assumptions."""
|
|
139
|
+
provider = _llm(llm)
|
|
140
|
+
exps = {experiment_treatment: pd.read_csv(experiment_csv)} if experiment_csv else {}
|
|
141
|
+
orch = Orchestrator(_load(graph_id), pd.read_csv(csv), provider, experiments=exps, n_perm=n_perm)
|
|
142
|
+
out = orch.ask(question).to_dict()
|
|
143
|
+
_done(provider)
|
|
144
|
+
return out
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# ---------- v1: Hvme-Fast and Hvme-LM ----------
|
|
148
|
+
# Model paths and devices are set through environment variables. Loaded once on first use and reused within the process.
|
|
149
|
+
FAST_PATH = os.environ.get("HVME_FAST", str(ROOT / "models" / "hvme-fast-4b-v2-story-distill"))
|
|
150
|
+
LM_PATH = os.environ.get("HVME_LM", str(ROOT / "models" / "hvme-lm-9b-sft-v217b"))
|
|
151
|
+
THRESHOLD = float(os.environ.get("HVME_FAST_THRESHOLD", "0.8")) # escalate if Fast confidence (max option probability) is below this
|
|
152
|
+
# Rung classification is handled by a router further trained on Rung items (CLadder Rung 0.515 -> 0.967). Yes/no judgment stays on FAST_PATH because Corr2Cause regresses with the router.
|
|
153
|
+
_ROUTER = ROOT / "models" / "hvme-fast-4b-v2-router-ko"
|
|
154
|
+
ROUTER_PATH = os.environ.get("HVME_ROUTER", str(_ROUTER) if _ROUTER.exists() else FAST_PATH)
|
|
155
|
+
ROUTER_THRESHOLD = float(os.environ.get("HVME_ROUTER_THRESHOLD", "0.9")) # if router confidence is below this, Hvme-LM picks the Rung
|
|
156
|
+
_MODELS: dict = {}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _fast():
|
|
160
|
+
if "fast" not in _MODELS:
|
|
161
|
+
from .fast.judge import FastJudge
|
|
162
|
+
_MODELS["fast"] = FastJudge.load(FAST_PATH, device=os.environ.get("HVME_FAST_DEVICE", "cuda:0"))
|
|
163
|
+
return _MODELS["fast"]
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _router():
|
|
167
|
+
if ROUTER_PATH == FAST_PATH:
|
|
168
|
+
return _fast()
|
|
169
|
+
if "router" not in _MODELS:
|
|
170
|
+
from .fast.judge import FastJudge
|
|
171
|
+
_MODELS["router"] = FastJudge.load(ROUTER_PATH, device=os.environ.get("HVME_FAST_DEVICE", "cuda:0"))
|
|
172
|
+
return _MODELS["router"]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _lm():
|
|
176
|
+
"""Load remotely if HVME_LM_URL (an OpenAI-compatible server, e.g. vLLM at http://127.0.0.1:8011/v1) is set, otherwise load with HF."""
|
|
177
|
+
if "lm" not in _MODELS:
|
|
178
|
+
if os.environ.get("HVME_LM_URL"):
|
|
179
|
+
from .providers.remote import RemoteProvider
|
|
180
|
+
_MODELS["lm"] = RemoteProvider(os.environ["HVME_LM_URL"], os.environ.get("HVME_LM_NAME", "hvme-lm"), tokenizer=LM_PATH)
|
|
181
|
+
else:
|
|
182
|
+
from .providers.hf import HFProvider
|
|
183
|
+
_MODELS["lm"] = HFProvider(LM_PATH, device=os.environ.get("HVME_LM_DEVICE", "cuda:0"), batch_size=4)
|
|
184
|
+
return _MODELS["lm"]
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _fast_ask(context: str, question: str, kind: str, options: list[str]) -> list[float]:
|
|
188
|
+
from .gym.formats import option_labels, render
|
|
189
|
+
item = {"context": context, "question": question, "kind": kind, "options": options, "lang": "en"}
|
|
190
|
+
return _fast().option_probs([render(item)], option_labels(item))[0]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def fast_noul(proposition: str, context: str = "") -> dict:
|
|
194
|
+
"""A single true/false judgment. Escalate if p_yes is between 1 - threshold and threshold (low confidence)."""
|
|
195
|
+
p = _fast_ask(context, proposition, "noul", [])
|
|
196
|
+
return {"p_yes": p[0], "confidence": max(p), "escalate": max(p) < THRESHOLD}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def fast_choice(question: str, options: list[str], context: str = "") -> dict:
|
|
200
|
+
p = _fast_ask(context, question, "choice", options)
|
|
201
|
+
k = max(range(len(p)), key=p.__getitem__)
|
|
202
|
+
return {"choice": options[k], "probs": dict(zip(options, p)), "confidence": p[k], "escalate": p[k] < THRESHOLD}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def fast_score(question: str, levels: int = 5, context: str = "") -> dict:
|
|
206
|
+
p = _fast_ask(context, question, "score", [f"level {k}" for k in range(1, levels + 1)])
|
|
207
|
+
return {"score": sum((k + 1) * x for k, x in enumerate(p)), "dist": p, "confidence": max(p), "escalate": max(p) < THRESHOLD}
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def classify_question(question: str, graph_id: str = "") -> dict:
|
|
211
|
+
"""Rung classification (Fast; Hvme-LM if low confidence). If graph_id is given, treatment, outcome and mediators are also decided from graph variables in the question."""
|
|
212
|
+
from .orchestrator.query import KEYWORDS, parse_rules
|
|
213
|
+
from .orchestrator.route import QueryRouter
|
|
214
|
+
r = QueryRouter(_router(), _lm(), ROUTER_THRESHOLD).classify([question])[0]
|
|
215
|
+
out = {"rung": r["rung"], "kind": r["kind"], "confidence": r["confidence"], "router": r["router"], "treatment": None, "outcome": None, "mediators": []}
|
|
216
|
+
if graph_id:
|
|
217
|
+
q = parse_rules(question, _load(graph_id))
|
|
218
|
+
kind = q.kind if any(re.search(p, question, re.I) for _, p in KEYWORDS) else r["kind"]
|
|
219
|
+
out |= {"kind": kind, "treatment": q.treatment, "outcome": q.outcome, "mediators": q.mediators}
|
|
220
|
+
return out
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def lm_verify(graph_id: str, csv: str, treatment: str, outcome: str) -> dict:
|
|
224
|
+
"""Hvme-LM (tool mode) reads the probability table fitted from the graph + data, solves 'does the treatment raise the outcome?' independently, and compares with the engine ATE sign."""
|
|
225
|
+
from .orchestrator.route import lm_verify as verify
|
|
226
|
+
hcg, df = _load(graph_id), pd.read_csv(csv)
|
|
227
|
+
g = hcg.to_networkx()
|
|
228
|
+
lat = latent_of(g, df)
|
|
229
|
+
est = estimate(g, df, treatment, outcome, lat, n_boot=200, estimand=identify(g, treatment, outcome, lat))
|
|
230
|
+
return verify(_lm(), hcg, df, treatment, outcome, est.value, tuple(map(float, est.ci)))
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def ask_v1(question: str, graph_id: str, csv: str, experiment_csv: str | None = None, experiment_treatment: str | None = None,
|
|
234
|
+
llm: str | None = None, n_perm: int = 100, verify: bool = True) -> dict:
|
|
235
|
+
"""Same as ask, plus Fast Rung classification (Hvme-LM if low confidence) for query analysis and an independent Hvme-LM solution for verification."""
|
|
236
|
+
from .orchestrator.route import QueryRouter
|
|
237
|
+
provider = _llm(llm) if (llm or os.environ.get("HVME_LLM")) else None
|
|
238
|
+
exps = {experiment_treatment: pd.read_csv(experiment_csv)} if experiment_csv else {}
|
|
239
|
+
orch = Orchestrator(_load(graph_id), pd.read_csv(csv), provider, experiments=exps, n_perm=n_perm,
|
|
240
|
+
router=QueryRouter(_router(), _lm(), ROUTER_THRESHOLD), verifier=_lm() if verify else None)
|
|
241
|
+
out = orch.ask(question).to_dict()
|
|
242
|
+
_done(provider)
|
|
243
|
+
return out
|
hvme/bench/__init__.py
ADDED
hvme/bench/calm.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""CaLM-lite (45 English tasks, excluding open-ended CEG-O): uses the original repository's (data/bench/calm_repo) prompt-generation and scoring functions as is.
|
|
2
|
+
|
|
3
|
+
Both the result of applying the original function to the whole response (correct) and to the final answer only (correct_tail) are recorded.
|
|
4
|
+
The original scorer reads the first yes/no or option string in the response, so for models that write the solution first, an intermediate sentence gets read as the answer.
|
|
5
|
+
In tool mode the variable-state yes/no appears first, so the original scorer almost always reads a state name. The final answer is what follows the last 'Final answer:', or else the last paragraph.
|
|
6
|
+
"""
|
|
7
|
+
import random
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .datasets import BENCH
|
|
13
|
+
|
|
14
|
+
REPO = BENCH / "calm_repo"
|
|
15
|
+
sys.path.insert(0, str(REPO / "calm"))
|
|
16
|
+
|
|
17
|
+
from data_processing.generate_questions import generate_question_list # noqa: E402
|
|
18
|
+
from data_processing.task_hiearchy import task_hiearchy_dict # noqa: E402
|
|
19
|
+
from evaluation.core_metrics import initialize_core_metric_evaluation_components, task_to_accuracy_module_map # noqa: E402
|
|
20
|
+
|
|
21
|
+
TASKS = [t for t in task_hiearchy_dict if t.endswith("_EN") and task_to_accuracy_module_map[t] != "open-ended"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def questions(task: str, style: str = "basic", n: int | None = None, seed: int = 0) -> list[dict]:
|
|
25
|
+
"""Items of one task (including the original prompt 'question'). If n is given, only n items with a fixed seed."""
|
|
26
|
+
items = generate_question_list(dataset_path=REPO / "calm_lite_dataset" / f"{task_hiearchy_dict[task]}{task}.json", prompt_style=style)
|
|
27
|
+
return items if n is None else sorted(random.Random(seed).sample(items, n), key=lambda d: d["index"])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def correct(task: str, item: dict, response: str, style: str = "basic") -> bool:
|
|
31
|
+
"""Score one item with the original scoring function."""
|
|
32
|
+
gt, pred, acc = initialize_core_metric_evaluation_components(task)
|
|
33
|
+
return acc([gt(item)], [pred(response, item, style, task.split("-")[0])]) == 1
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def tail(response: str) -> str:
|
|
37
|
+
"""Final answer: text after the last 'Final answer:', or else the paragraph after the last blank line."""
|
|
38
|
+
i = response.lower().rfind("final answer:")
|
|
39
|
+
return response[i + len("final answer:"):].strip() if i >= 0 else response.strip().split("\n\n")[-1]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
GIVEN = re.compile(r"direct effect on|probability|causes|->", re.I)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def needs_tools(question: str) -> bool:
|
|
46
|
+
"""Routing rule: tools are given only to problems that state causal relations (a graph) or probabilities. Textual and commonsense causality (COPA, e-CARE, ECI, CRASS, etc.) is solved without tools.
|
|
47
|
+
Previously, tool mode forced a graph onto commonsense causality and scored poorly (CRASS 80 → 17)."""
|
|
48
|
+
return bool(GIVEN.search(question))
|
hvme/bench/datasets.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Benchmark loaders. Originals are downloaded once and cached in data/bench/."""
|
|
2
|
+
import urllib.request
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import networkx as nx
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from ..paths import BENCH
|
|
9
|
+
|
|
10
|
+
DATA_DIR = BENCH
|
|
11
|
+
HF = "https://huggingface.co/datasets"
|
|
12
|
+
CAUGYM = "https://raw.githubusercontent.com/OpenCausaLab/CauGym/main/eval/test_datasets/{}_dataset.json"
|
|
13
|
+
CAUGYM_SETS = ("base", "rephrased", "omitted", "deconfounding", "redundant", "insufficient")
|
|
14
|
+
|
|
15
|
+
CORR2CAUSE_FILES = {
|
|
16
|
+
"default": "test.csv",
|
|
17
|
+
"dev": "dev.csv",
|
|
18
|
+
"paraphrasing": "perturbation_by_paraphrasing_test.csv",
|
|
19
|
+
"refactorization": "perturbation_by_refactorization_test.csv",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _cached(url: str, name: str) -> Path:
|
|
24
|
+
path = DATA_DIR / name
|
|
25
|
+
if not path.exists():
|
|
26
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
27
|
+
urllib.request.urlretrieve(url, path)
|
|
28
|
+
return path
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load_cladder(n_per_rung: int | None = None, seed: int = 0) -> pd.DataFrame:
|
|
32
|
+
"""CLadder v1.5 (Jin et al., NeurIPS 2023). label: 1=yes, 0=no. Uses full_v1.5_default, which includes the questions."""
|
|
33
|
+
df = pd.read_csv(_cached(f"{HF}/causal-nlp/CLadder/resolve/main/data/full_v1.5_default.csv", "cladder_full_v1.5.csv"))
|
|
34
|
+
df = df.assign(label=(df.label == "yes").astype(int))
|
|
35
|
+
return df if n_per_rung is None else df.groupby("rung").sample(n_per_rung, random_state=seed).reset_index(drop=True)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_corr2cause(variant: str = "default", n: int | None = None, seed: int = 0) -> pd.DataFrame:
|
|
39
|
+
"""Corr2Cause (Jin et al., ICLR 2024). variant: default·dev·paraphrasing·refactorization. label: 1=entailed.
|
|
40
|
+
|
|
41
|
+
The data is imbalanced (15-30% label 1), so F1 is reported along with accuracy.
|
|
42
|
+
"""
|
|
43
|
+
name = CORR2CAUSE_FILES[variant]
|
|
44
|
+
df = pd.read_csv(_cached(f"{HF}/causal-nlp/corr2cause/resolve/main/{name}", f"corr2cause_{name}"))[["input", "label"]]
|
|
45
|
+
df = df.assign(label=(df.label == 1).astype(int)) # the paraphrasing variant has labels 0/1/2, and only 1 means 'entailed'
|
|
46
|
+
return df if n is None else df.sample(n, random_state=seed).reset_index(drop=True)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
KMMLU_SUBJECTS = [
|
|
50
|
+
"Accounting", "Agricultural-Sciences", "Aviation-Engineering-and-Maintenance", "Biology", "Chemical-Engineering", "Chemistry", "Civil-Engineering",
|
|
51
|
+
"Computer-Science", "Construction", "Criminal-Law", "Ecology", "Economics", "Education", "Electrical-Engineering", "Electronics-Engineering",
|
|
52
|
+
"Energy-Management", "Environmental-Science", "Fashion", "Food-Processing", "Gas-Technology-and-Engineering", "Geomatics", "Health",
|
|
53
|
+
"Industrial-Engineer", "Information-Technology", "Interior-Architecture-and-Design", "Law", "Machine-Design-and-Manufacturing", "Management",
|
|
54
|
+
"Maritime-Engineering", "Marketing", "Materials-Engineering", "Mechanical-Engineering", "Nondestructive-Testing", "Patent",
|
|
55
|
+
"Political-Science-and-Sociology", "Psychology", "Public-Safety", "Railway-and-Automotive-Engineering", "Real-Estate", "Refrigerating-Machinery",
|
|
56
|
+
"Social-Welfare", "Taxation", "Telecommunications-and-Wireless-Technology", "korean-history", "math",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def load_math500(n: int | None = None, seed: int = 0) -> pd.DataFrame:
|
|
61
|
+
"""MATH-500 (Lightman et al., 2023). For general-ability (math) checks. answer: the answer string."""
|
|
62
|
+
df = pd.read_json(_cached(f"{HF}/HuggingFaceH4/MATH-500/resolve/main/test.jsonl", "math500_test.jsonl"), lines=True)
|
|
63
|
+
return df if n is None else df.sample(n, random_state=seed).reset_index(drop=True)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def load_kmmlu(n_per_subject: int = 7, seed: int = 0, split: str = "test") -> pd.DataFrame:
|
|
67
|
+
"""KMMLU (Son et al., 2024) n items from each of 45 subjects. answer: 1-4 (A-D). split 'train' is for Korean general-ability trajectories."""
|
|
68
|
+
dfs = {s: pd.read_csv(_cached(f"{HF}/HAERAE-HUB/KMMLU/resolve/main/data/{s}-{split}.csv", f"kmmlu/{s}-{split}.csv")) for s in KMMLU_SUBJECTS}
|
|
69
|
+
return pd.concat([df.sample(min(n_per_subject, len(df)), random_state=seed).assign(subject=s) for s, df in dfs.items()], ignore_index=True) # some subjects have only one train item
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def load_bnlearn(name: str) -> nx.DiGraph:
|
|
73
|
+
"""bnlearn ground-truth graphs (asia, sachs, alarm, insurance, child ...). Requires pgmpy."""
|
|
74
|
+
from pgmpy.example_models import load_model
|
|
75
|
+
|
|
76
|
+
return nx.DiGraph(load_model(f"bnlearn/{name}").edges())
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def load_caugym(name: str, n_per_type: int | None = None, seed: int = 0) -> pd.DataFrame:
|
|
80
|
+
"""CauGym test set (Chen et al., 2026). 7 types (ATE, CDE, ETT, NDE, NIE, PN, PS) × 100 each. answer is {"ANSWER": …, "PROB": …} or LACK_CONDITION (insufficient)."""
|
|
81
|
+
df = pd.read_json(_cached(CAUGYM.format(name), f"caugym/{name}.json")).assign(set=name)
|
|
82
|
+
df["qid"] = [f"{name}-{i}" for i in range(len(df))]
|
|
83
|
+
return df if n_per_type is None else df.groupby("Type").sample(n_per_type, random_state=seed).sort_index()
|
hvme/bench/general.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""General-ability check (MATH-500, KMMLU): verify that causal training did not erode general ability (criterion: at most 2pt drop from the base model).
|
|
2
|
+
|
|
3
|
+
Scoring is a simple rule applied identically to the base and trained models. The difference between the two matters more than absolute scores.
|
|
4
|
+
"""
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
MATH_PROMPT = "{problem}\n\nSolve the problem step by step, then write the final answer in \\boxed{{}}."
|
|
8
|
+
KMMLU_PROMPT = "{question}\nA. {A}\nB. {B}\nC. {C}\nD. {D}\n\n단계별로 짧게 생각한 뒤 마지막 줄에 'Final answer: <A|B|C|D>' 형식으로 답하라."
|
|
9
|
+
CHOICE = re.compile(r"final answer\s*[::]?\s*\**\s*\(?([ABCD])\b", re.I)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def boxed(text: str) -> str | None:
|
|
13
|
+
"""Contents of the last \\boxed{...} (matching braces)."""
|
|
14
|
+
i = text.rfind("\\boxed{")
|
|
15
|
+
if i < 0:
|
|
16
|
+
return None
|
|
17
|
+
depth, j = 0, i + len("\\boxed")
|
|
18
|
+
for k in range(j, len(text)):
|
|
19
|
+
depth += {"{": 1, "}": -1}.get(text[k], 0)
|
|
20
|
+
if depth == 0:
|
|
21
|
+
return text[j + 1:k]
|
|
22
|
+
return None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def norm_math(s: str) -> str:
|
|
26
|
+
s = re.sub(r"\\text\{([^}]*)\}", r"\1", s)
|
|
27
|
+
for a, b in [("\\left", ""), ("\\right", ""), ("\\!", ""), ("\\,", ""), ("dfrac", "frac"), ("tfrac", "frac"), ("^\\circ", ""), ("^{\\circ}", ""),
|
|
28
|
+
("\\%", ""), ("$", ""), (" ", "")]:
|
|
29
|
+
s = s.replace(a, b)
|
|
30
|
+
s = s.rstrip(".")
|
|
31
|
+
return re.sub(r"\\frac(\d)(\d)", r"\\frac{\1}{\2}", s)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def math_correct(out: str, answer: str) -> bool:
|
|
35
|
+
b = boxed(out)
|
|
36
|
+
return b is not None and norm_math(b) == norm_math(str(answer))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_choice(out: str) -> int:
|
|
40
|
+
"""Option number 1-4 from 'Final answer: X', or -1 if absent."""
|
|
41
|
+
hits = CHOICE.findall(out)
|
|
42
|
+
return "ABCD".index(hits[-1].upper()) + 1 if hits else -1
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
PROB = re.compile(r'\{[^{}]*"prob"\s*:\s*"?(-?[0-9.]+)"?[^{}]*\}', re.I)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def caugym_correct(out: str, answer: str) -> bool:
|
|
49
|
+
"""CauGym scoring: correct if any PROB in the output JSON is within 0.0005 of the answer. For insufficient, checks whether LACK_CONDITION was written."""
|
|
50
|
+
if answer == "LACK_CONDITION":
|
|
51
|
+
return "LACK_CONDITION" in out
|
|
52
|
+
gold = float(PROB.search(answer).group(1))
|
|
53
|
+
return any(abs(float(v) - gold) < 0.0005 for v in PROB.findall(re.sub(r"\s+", "", out)) if v.count(".") <= 1 and v not in ("-", "."))
|
hvme/bench/metrics.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Graph metrics (SHD, SID, F1) and probability metrics (accuracy, Brier, ECE)."""
|
|
2
|
+
import networkx as nx
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from ..engine.identify import is_valid_adjustment
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# ---------- Graph structure metrics ----------
|
|
9
|
+
def _pairs(g):
|
|
10
|
+
return {frozenset(e) for e in g.edges}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def shd(true: nx.DiGraph, est: nx.DiGraph) -> int:
|
|
14
|
+
"""Structural Hamming Distance: each missing edge, extra edge and reversal counts as 1."""
|
|
15
|
+
t, e = set(true.edges), set(est.edges)
|
|
16
|
+
reversed_ = {(u, v) for u, v in e - t if (v, u) in t}
|
|
17
|
+
return len(_pairs(true) ^ _pairs(est)) + len(reversed_)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _prf(t: set, e: set) -> dict:
|
|
21
|
+
tp = len(t & e)
|
|
22
|
+
p = tp / max(len(e), 1)
|
|
23
|
+
r = tp / max(len(t), 1)
|
|
24
|
+
return {"precision": p, "recall": r, "f1": 2 * p * r / max(p + r, 1e-12)}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def edge_f1(true: nx.DiGraph, est: nx.DiGraph) -> dict:
|
|
28
|
+
"""Returns both the direction-aware edge score and the direction-agnostic skeleton score."""
|
|
29
|
+
return {"directed": _prf(set(true.edges), set(est.edges)), "skeleton": _prf(_pairs(true), _pairs(est))}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def sid(true: nx.DiGraph, est: nx.DiGraph) -> int:
|
|
33
|
+
"""Structural Intervention Distance (Peters & Bühlmann, 2015), DAG vs. DAG.
|
|
34
|
+
|
|
35
|
+
Number of (i, j) pairs whose p(x_j | do(x_i)) is wrong when computed with i's parent set in the estimated graph.
|
|
36
|
+
- If j is a parent of i in the estimated graph, it means 'no effect', so this is wrong when j is a descendant of i in the true graph.
|
|
37
|
+
- Otherwise it is wrong if the estimated graph's parent set is not a valid adjustment set in the true graph.
|
|
38
|
+
"""
|
|
39
|
+
wrong = 0
|
|
40
|
+
desc = {i: nx.descendants(true, i) for i in true.nodes}
|
|
41
|
+
for i in true.nodes:
|
|
42
|
+
pa = set(est.predecessors(i))
|
|
43
|
+
for j in true.nodes - {i}:
|
|
44
|
+
wrong += (j in desc[i]) if j in pa else not is_valid_adjustment(true, i, j, pa)
|
|
45
|
+
return int(wrong)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def graph_report(true: nx.DiGraph, est: nx.DiGraph) -> dict:
|
|
49
|
+
f1 = edge_f1(true, est)
|
|
50
|
+
return {"shd": shd(true, est), "sid": sid(true, est), "f1_directed": f1["directed"]["f1"], "f1_skeleton": f1["skeleton"]["f1"],
|
|
51
|
+
"n_true": true.number_of_edges(), "n_est": est.number_of_edges()}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# ---------- Probability calibration metrics ----------
|
|
55
|
+
def brier(p, y) -> float:
|
|
56
|
+
p, y = np.asarray(p, float), np.asarray(y, float)
|
|
57
|
+
return float(np.mean((p - y) ** 2))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def ece(p, y, bins: int = 10) -> float:
|
|
61
|
+
"""Expected Calibration Error (binary: p = probability of true). Bins by the confidence of the predicted class."""
|
|
62
|
+
p, y = np.asarray(p, float), np.asarray(y, int)
|
|
63
|
+
conf = np.maximum(p, 1 - p)
|
|
64
|
+
correct = ((p >= 0.5).astype(int) == y).astype(float)
|
|
65
|
+
idx = np.minimum((conf - 0.5) * 2 * bins, bins - 1).astype(int)
|
|
66
|
+
return float(sum(abs(correct[idx == b].mean() - conf[idx == b].mean()) * (idx == b).mean() for b in np.unique(idx)))
|
hvme/bench/prompts.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Baseline prompts. The Noul (logit) mode reads a single answer token; the CoT mode generates following the CausalCoT (Jin et al., 2023) steps."""
|
|
2
|
+
|
|
3
|
+
NOUL_SUFFIX = "\n\nAnswer with Yes or No only."
|
|
4
|
+
|
|
5
|
+
CAUSAL_COT = """{question}
|
|
6
|
+
|
|
7
|
+
Solve this step by step.
|
|
8
|
+
Step 1. Extract the causal graph: list the variables and the direct causal edges.
|
|
9
|
+
Step 2. Classify the query type (e.g., marginal, conditional, ATE, ATT, NDE, NIE, backdoor adjustment set, collider bias, counterfactual).
|
|
10
|
+
Step 3. Formalize the query in symbolic form (e.g., E[Y | do(X=1)] - E[Y | do(X=0)]).
|
|
11
|
+
Step 4. Collect the available data (probabilities) from the question.
|
|
12
|
+
Step 5. Derive an estimand from the causal graph using causal inference rules.
|
|
13
|
+
Step 6. Compute the estimand with the data and answer the question.
|
|
14
|
+
|
|
15
|
+
End with a line in the form "Final answer: yes" or "Final answer: no"."""
|
|
16
|
+
|
|
17
|
+
CORR2CAUSE_NOUL = """{input}
|
|
18
|
+
|
|
19
|
+
Does the premise imply the hypothesis?"""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def cladder_noul(row) -> str:
|
|
23
|
+
return row["prompt"] + NOUL_SUFFIX
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cladder_cot(row) -> str:
|
|
27
|
+
return CAUSAL_COT.format(question=row["prompt"])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def corr2cause_noul(row) -> str:
|
|
31
|
+
return CORR2CAUSE_NOUL.format(input=row["input"]) + NOUL_SUFFIX
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def corr2cause_cot(row) -> str:
|
|
35
|
+
return CAUSAL_COT.format(question=CORR2CAUSE_NOUL.format(input=row["input"]))
|
hvme/bench/runner.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Baseline runner. Produces results in one format for the Noul mode (option-token probabilities) and the CoT mode (generate, then parse the answer)."""
|
|
2
|
+
import re
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
from ..paths import RESULTS
|
|
8
|
+
from .metrics import brier, ece
|
|
9
|
+
|
|
10
|
+
YES_NO = ["Yes", "No"]
|
|
11
|
+
FINAL = re.compile(r"final answer\s*(?:is)?\s*[::]?\s*\**\s*(yes|no)\b", re.I)
|
|
12
|
+
ANSWER = re.compile(r"\banswer\s*(?:is)?\s*[::]?\s*\**\s*(yes|no)\b", re.I)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse_yes_no(text: str) -> int:
|
|
16
|
+
"""Look for 'Final answer: yes/no' first, then 'answer is yes/no'. -1 (parse failure) if neither is found.
|
|
17
|
+
|
|
18
|
+
Stray yes/no words in the body are not taken as the answer, so that truncated solutions count as parse failures rather than wrong answers.
|
|
19
|
+
"""
|
|
20
|
+
hits = FINAL.findall(text) or ANSWER.findall(text)
|
|
21
|
+
return {"yes": 1, "no": 0}[hits[-1].lower()] if hits else -1
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def run_noul(provider, df: pd.DataFrame, prompt_fn) -> pd.DataFrame:
|
|
25
|
+
probs = provider.option_probs([prompt_fn(r) for _, r in df.iterrows()], YES_NO)
|
|
26
|
+
p_yes = [p[0] for p in probs]
|
|
27
|
+
return df.assign(p_yes=p_yes, pred=[int(p >= 0.5) for p in p_yes], mode="noul", model=provider.name)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def run_cot(provider, df: pd.DataFrame, prompt_fn, max_new_tokens: int = 1024) -> pd.DataFrame:
|
|
31
|
+
outs = provider.complete([prompt_fn(r) for _, r in df.iterrows()], max_new_tokens=max_new_tokens)
|
|
32
|
+
return df.assign(output=outs, pred=[parse_yes_no(o) for o in outs], mode="cot", model=provider.name)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def summarize(res: pd.DataFrame, by: list[str] | None = None) -> pd.DataFrame:
|
|
36
|
+
"""Accuracy, F1 (positive=1) and parse-failure rate, plus Brier and ECE for Noul results."""
|
|
37
|
+
def stats(d):
|
|
38
|
+
tp = ((d.pred == 1) & (d.label == 1)).sum()
|
|
39
|
+
p = tp / max((d.pred == 1).sum(), 1)
|
|
40
|
+
r = tp / max((d.label == 1).sum(), 1)
|
|
41
|
+
pos = d.label.mean()
|
|
42
|
+
row = {"n": len(d), "acc": (d.pred == d.label).mean(), "majority": max(pos, 1 - pos), "f1": 2 * p * r / max(p + r, 1e-12),
|
|
43
|
+
"parse_fail": (d.pred == -1).mean()}
|
|
44
|
+
has_p = "p_yes" in d and d.p_yes.notna().all()
|
|
45
|
+
return row | ({"brier": brier(d.p_yes, d.label), "ece": ece(d.p_yes, d.label)} if has_p else {})
|
|
46
|
+
|
|
47
|
+
groups = ["model", "mode"] + (by or [])
|
|
48
|
+
return pd.DataFrame([dict(zip(groups, key)) | stats(d) for key, d in res.groupby(groups)])
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def save(res: pd.DataFrame, name: str, out_dir: str | Path = RESULTS) -> Path:
|
|
52
|
+
path = Path(out_dir) / f"{name}.csv"
|
|
53
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
res.to_csv(path, index=False)
|
|
55
|
+
return path
|
hvme/engine/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Symbolic causal engine: identification, estimation, refutation, counterfactuals, d-separation. The reference for Hvme-Gym answers and RL rewards."""
|
|
2
|
+
from .dsep import d_separated, local_markov
|
|
3
|
+
from .estimate import Estimate, estimate
|
|
4
|
+
from .identify import (Estimand, adjustment_sets, frontdoor_sets, id_identifiable, identify, instruments, is_frontdoor, is_instrument,
|
|
5
|
+
is_valid_adjustment, optimal_adjustment)
|
|
6
|
+
from .refute import refute
|
|
7
|
+
from .scm import BinarySCM, LinearSCM
|
|
8
|
+
|
|
9
|
+
__all__ = ["d_separated", "local_markov", "Estimate", "estimate", "Estimand", "adjustment_sets", "frontdoor_sets", "id_identifiable", "identify",
|
|
10
|
+
"instruments", "is_frontdoor", "is_instrument", "is_valid_adjustment", "optimal_adjustment", "refute", "BinarySCM", "LinearSCM"]
|