| """Text2KGBench-style eval of the fine-tuned model on held-out test.jsonl. |
| Metrics per task family: |
| IES Turtle : syntactic validity, ontology conformance (our validator), hallucinated-term rate |
| multi-standard: syntactic validity, relation conformance (predicates within the given ontology) |
| Usage: python eval_ies.py --model <base> --adapter adapters (omit --adapter for baseline) |
| Runs under .venv (mlx_lm).""" |
| import sys, json, argparse, pathlib, re |
| sys.path.insert(0, str(pathlib.Path(__file__).parent)) |
| from iesval import validate_turtle, structural_conformance, REAL, IES |
| from rdflib import Graph |
| from mlx_lm import load, generate |
|
|
| ROOT = pathlib.Path("/Users/fabio/projects/qwen-ies-ft") |
|
|
| def extract_turtle(txt): |
| m = re.search(r"```(?:turtle|ttl)?\s*(.*?)```", txt, re.S) |
| if m: txt = m.group(1) |
| return txt.strip() |
|
|
| def ies_metrics(ttl, user_turn=""): |
| ok, reason, n, used = validate_turtle(ttl, min_triples=3) |
| |
| syn = True |
| try: Graph().parse(data=ttl, format="turtle") |
| except Exception: syn = False |
| |
| terms = set(re.findall(r"ies:(\w+)", ttl)) |
| halluc = (len(terms - REAL)/len(terms)) if terms else 1.0 |
| |
| sc, checked, _ = structural_conformance(ttl) if syn else (0.0, 0, []) |
| |
| m = re.search(r"Use <(\S+)> as the namespace", user_turn) |
| ns_ok = (m.group(1) in ttl) if m else None |
| return {"syntactic": syn, "conformant": ok, "halluc_rate": halluc, |
| "struct_conf": sc, "ns_ok": ns_ok, "triples": n} |
|
|
| def multistd_metrics(ttl, allowed_slugs): |
| syn = True |
| try: Graph().parse(data=ttl, format="turtle") |
| except Exception: syn = False |
| |
| flat = set() |
| try: |
| _g = Graph(); _g.parse(data=ttl, format="turtle") |
| EXNS = "http://example.org/kg#" |
| flat = {str(p).split("#")[-1] for _, p, _ in _g if str(p).startswith(EXNS)} |
| except Exception: |
| pass |
| |
| ies_bleed = bool(re.search(r"\bies:\w+", ttl)) |
| bad = flat - allowed_slugs |
| return {"syntactic": syn, "rel_conformant": len(bad)==0, "ies_bleed": ies_bleed, |
| "off_ontology": sorted(bad)[:5]} |
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--model", default="mlx-community/Qwen3-Coder-30B-A3B-Instruct-8bit") |
| ap.add_argument("--adapter", default=None) |
| ap.add_argument("--max", type=int, default=200) |
| a = ap.parse_args() |
| kw = {"adapter_path": a.adapter} if a.adapter else {} |
| model, tok = load(a.model, **kw) |
|
|
| test = [json.loads(l) for l in (ROOT/"data"/"mlx"/"test.jsonl").open()][:a.max] |
| ood_p = ROOT/"data"/"mlx"/"ood_test.jsonl" |
| ood_rows = [json.loads(l) for l in ood_p.open()] if ood_p.exists() else [] |
| ies, multi, ood = [], [], [] |
| for r, bucket_ood in [(x, False) for x in test] + [(x, True) for x in ood_rows]: |
| msgs = r["messages"] |
| sysp = msgs[0]["content"] |
| prompt = tok.apply_chat_template(msgs[:-1], add_generation_prompt=True, tokenize=False) |
| out = generate(model, tok, prompt=prompt, max_tokens=1400, verbose=False) |
| ttl = extract_turtle(out) |
| if sysp.startswith("You extract ontology-conformant"): |
| um = msgs[1]["content"] |
| rels = re.search(r"Allowed relations: (.+?)\.", um) |
| allowed = set() |
| if rels: |
| for x in rels.group(1).split(","): |
| allowed.add(re.sub(r"[^0-9A-Za-z]+","_",x.strip()).strip("_")) |
| multi.append(multistd_metrics(ttl, allowed)) |
| elif "@prefix ies" in msgs[-1]["content"] or "a ies:" in msgs[-1]["content"]: |
| (ood if bucket_ood else ies).append(ies_metrics(ttl, msgs[1]["content"])) |
|
|
| def pct(rows, key): return 100.0*sum(1 for r in rows if r[key])/max(1,len(rows)) |
| def mean(rows, key): return sum(r[key] for r in rows)/max(1,len(rows)) |
| def block(name, rows): |
| print(f"=== {name} (n={len(rows)}) ===") |
| if not rows: return |
| print(f" syntactic validity : {pct(rows,'syntactic'):.1f}%") |
| print(f" term conformance : {pct(rows,'conformant'):.1f}%") |
| print(f" structural conf : {mean(rows,'struct_conf'):.3f}") |
| print(f" halluc-term rate : {mean(rows,'halluc_rate'):.3f}") |
| ns = [r for r in rows if r["ns_ok"] is not None] |
| if ns: print(f" namespace fidelity : {pct(ns,'ns_ok'):.1f}% (n={len(ns)})") |
| print() |
| block("IES Turtle (in-distribution)", ies) |
| block("IES Turtle (OUT-OF-DISTRIBUTION, gold dstl)", ood) |
| print(f"=== Multi-standard (n={len(multi)}) ===") |
| if multi: |
| print(f" syntactic validity : {pct(multi,'syntactic'):.1f}%") |
| print(f" relation conformance: {pct(multi,'rel_conformant'):.1f}%") |
| print(f" IES-bleed rate : {pct(multi,'ies_bleed'):.1f}% (should be 0)") |
| out = { |
| "ies_n": len(ies), "ood_n": len(ood), "multi_n": len(multi), |
| "ies_syn": f"{pct(ies,'syntactic'):.1f}%" if ies else "-", |
| "ies_conf": f"{pct(ies,'conformant'):.1f}%" if ies else "-", |
| "ies_struct": f"{mean(ies,'struct_conf'):.3f}" if ies else "-", |
| "ies_hall": f"{mean(ies,'halluc_rate'):.3f}" if ies else "-", |
| "ood_syn": f"{pct(ood,'syntactic'):.1f}%" if ood else "-", |
| "ood_conf": f"{pct(ood,'conformant'):.1f}%" if ood else "-", |
| "ood_struct": f"{mean(ood,'struct_conf'):.3f}" if ood else "-", |
| "multi_syn": f"{pct(multi,'syntactic'):.1f}%" if multi else "-", |
| "multi_rel": f"{pct(multi,'rel_conformant'):.1f}%" if multi else "-", |
| "multi_bleed": f"{pct(multi,'ies_bleed'):.1f}%" if multi else "-", |
| "adapter": a.adapter or "baseline", |
| } |
| (ROOT/"data"/("eval.json" if a.adapter else "eval_baseline.json")).write_text(json.dumps(out, indent=2)) |
| print("wrote", "eval.json" if a.adapter else "eval_baseline.json") |
|
|
| if __name__=="__main__": |
| main() |
|
|