File size: 5,144 Bytes
f2ca97c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | #!/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()
|