FinGovBench / scripts /run_flat_text_baseline.py
redqueen77's picture
Add reproducible TF-IDF baseline and open-weight reference evaluation
f2ca97c verified
Raw History Blame Contribute Delete
5.14 kB
#!/usr/bin/env python3
"""Train and run a reproducible non-graph FinGovBench text baseline.
The baseline uses only public development labels and a flat serialization of each
public workflow record. It deliberately excludes dependency edges. A predicted
review therefore covers every auditable component rather than a graph-derived path.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
ROOT = Path(__file__).resolve().parents[1]
AUDITABLE = {
"configuration", "evidence", "claim", "claim_evidence_relation", "model",
"tool", "workflow_state", "decision", "action", "control", "governance",
}
def release_path(relative: str) -> Path:
"""Resolve both the source-tree and stand-alone Hugging Face layouts."""
direct = ROOT / relative
return direct if direct.exists() else ROOT / "hf" / relative
def load_jsonl(path: Path) -> list[dict]:
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
def load_inputs() -> dict[str, list[dict]]:
return {
split: load_jsonl(release_path(f"closed_loop_inputs/{split}.jsonl"))
for split in ("development", "validation", "test")
}
def load_development_labels() -> dict[str, dict]:
path = release_path("public_labels/development.jsonl")
return {row["case_id"]: row for row in load_jsonl(path)}
def flat_text(row: dict) -> str:
"""Serialize public content while intentionally discarding graph edges."""
workflow = row["workflow"]
public = {
"domain": row["domain"],
"as_of": row["as_of"],
"workflow_context": row["workflow_context"],
"event": row["event"],
"assurance_claims": row.get("assurance_claims", []),
"red_line_controls": row.get("red_line_controls", []),
"components": workflow["components"],
}
return json.dumps(public, sort_keys=True, separators=(",", ":"))
def auditable_ids(row: dict) -> list[str]:
return sorted(
node["node_id"]
for node in row["workflow"]["components"]
if node["node_type"] in AUDITABLE
)
def make_classifier() -> Pipeline:
return Pipeline([
("tfidf", TfidfVectorizer(
lowercase=True,
ngram_range=(1, 2),
min_df=2,
max_features=50_000,
sublinear_tf=True,
)),
("classifier", LogisticRegression(
C=1.0,
class_weight="balanced",
max_iter=2_000,
random_state=20260922,
)),
])
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--output",
type=Path,
default=ROOT / "results/reference_baselines/flat_text.jsonl",
)
args = parser.parse_args()
inputs = load_inputs()
labels = load_development_labels()
development = inputs["development"]
x_train = [flat_text(row) for row in development]
release_train = [
int(labels[row["case_id"]]["gold"]["release_permitted"])
for row in development
]
action_train = [
labels[row["case_id"]]["gold"]["governance_action"]
for row in development
]
release_model = make_classifier().fit(x_train, release_train)
action_model = make_classifier().fit(x_train, action_train)
rows = [row for split in ("development", "validation", "test") for row in inputs[split]]
text = [flat_text(row) for row in rows]
release_probability = release_model.predict_proba(text)[:, list(release_model.classes_).index(1)]
predicted_actions = action_model.predict(text)
predictions = []
for row, probability, action in zip(rows, release_probability, predicted_actions):
release = bool(probability >= 0.5)
action = "release" if release else (str(action) if action != "release" else "escalate")
scope = [] if release else auditable_ids(row)
predictions.append({
"case_id": row["case_id"],
"method": "flat_text",
"model": "tfidf-logistic-regression",
"measurement_channel": "flat public-record text; dependency edges excluded",
"iceberg_detected": not release,
"governance_action": action,
"affected_components": scope,
"revalidation_components": scope,
"reviewed_components": scope,
"release_permitted": release,
"diagnostic": {"release_probability": float(probability)},
})
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(
"".join(json.dumps(row, sort_keys=True) + "\n" for row in sorted(predictions, key=lambda x: x["case_id"]))
)
print(json.dumps({
"method": "flat_text",
"training_cases": len(development),
"predictions": len(predictions),
"output": str(args.output),
"uses_dependencies": False,
"uses_language_model": False,
}, indent=2))
if __name__ == "__main__":
main()