Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

188 lines
8.2KB

  1. """Retrieval benchmark driver (spec AC-04). Run through tests/retrieval-benchmark.sh, which provisions a throw-away
  2. tenant and switches the embedding provider off for the lexical baseline.
  3. python -I run_benchmark.py load <base> <key> <namespace_id> <fixtures.json> <ids.json>
  4. python -I run_benchmark.py run <base> <key> <fixtures.json> <ids.json> <expected_strategy> <out.json>
  5. python -I run_benchmark.py report <fixtures.json> <hybrid.json> <lexical.json>
  6. Metrics per query kind: hit@5 (share of queries with a relevant item in the first 5 results), MRR@10 (mean of 1/rank
  7. of the first relevant item, 0 when none in the first 10) and, for "none" queries, the false positive rate (share of
  8. queries that return any result). report exits 1 when a threshold in fixtures.json is not met.
  9. """
  10. import json
  11. import sys
  12. import urllib.error
  13. import urllib.request
  14. def call(base, key, method, path, body=None):
  15. data = None if body is None else json.dumps(body).encode("utf-8")
  16. req = urllib.request.Request(base + path, data=data, method=method,
  17. headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
  18. try:
  19. with urllib.request.urlopen(req, timeout=120) as r:
  20. raw = r.read().decode("utf-8")
  21. return r.status, (json.loads(raw) if raw else None)
  22. except urllib.error.HTTPError as e:
  23. raw = e.read().decode("utf-8")
  24. try:
  25. return e.code, json.loads(raw)
  26. except ValueError:
  27. return e.code, raw
  28. def load_json(path):
  29. with open(path, encoding="utf-8") as f:
  30. return json.load(f)
  31. def save_json(path, value):
  32. with open(path, "w", encoding="utf-8") as f:
  33. json.dump(value, f, ensure_ascii=False, indent=1)
  34. def load(base, key, ns, fixtures_path, ids_path):
  35. fx = load_json(fixtures_path)
  36. ids = {}
  37. for m in fx["memories"]:
  38. st, d = call(base, key, "POST", "/remember",
  39. {"namespace_id": ns, "type": m["type"], "title": m["title"], "content": m["content"]})
  40. if st != 201:
  41. sys.exit("remember %s failed: %s %s" % (m["key"], st, d))
  42. mid = d.get("id") or d["data"]["id"]
  43. st, d = call(base, key, "POST", "/memories/%s/verifications" % mid,
  44. {"result": "verified", "method": "manual", "revision": 1})
  45. if st != 200:
  46. sys.exit("verify %s failed: %s %s" % (m["key"], st, d))
  47. ids[m["key"]] = mid
  48. for doc in fx["documents"]:
  49. st, d = call(base, key, "POST", "/ingestion/jobs",
  50. {"namespace_id": ns, "title": doc["title"], "source_uri": doc["source_uri"],
  51. "format": doc["format"], "content": doc["content"]})
  52. if st != 201:
  53. sys.exit("ingest %s failed: %s %s" % (doc["key"], st, d))
  54. ids[doc["key"]] = d["document_id"]
  55. save_json(ids_path, ids)
  56. print("loaded %d memories, %d documents" % (len(fx["memories"]), len(fx["documents"])))
  57. def labels_of(endpoint, results, by_id):
  58. out = []
  59. for r in results:
  60. if endpoint == "recall":
  61. out.append(by_id.get(r.get("id"), "?"))
  62. else:
  63. out.append("%s#%s" % (by_id.get(r.get("document_id"), "?"), r.get("heading_path") or ""))
  64. return out
  65. def is_relevant(label, relevant):
  66. for rel in relevant:
  67. if "#" in rel:
  68. doc, section = rel.split("#", 1)
  69. if label.startswith(doc + "#") and label.endswith(section):
  70. return True
  71. elif label == rel:
  72. return True
  73. return False
  74. def has_evidence(endpoint, r):
  75. # Evidence = what lets a caller check and cite a result: the exact revision, its verification state and author for a
  76. # memory; the document, its revision, source and locator and the trust label for a passage.
  77. if endpoint == "recall":
  78. return (r.get("revision") is not None and bool(r.get("verification_status")) and bool(r.get("created_by"))
  79. and r.get("relevance_score") is not None)
  80. return (bool(r.get("document_id")) and r.get("document_revision") is not None and bool(r.get("source_uri"))
  81. and isinstance(r.get("locator"), dict) and r.get("content_trust") == "untrusted_reference")
  82. def run(base, key, fixtures_path, ids_path, expected, out_path):
  83. fx = load_json(fixtures_path)
  84. by_id = {v: k for k, v in load_json(ids_path).items()}
  85. rows = []
  86. for q in fx["queries"]:
  87. st, d = call(base, key, "POST", "/" + q["endpoint"], {"query": q["text"], "max_results": 10})
  88. if st != 200:
  89. sys.exit("query %s failed: %s %s" % (q["id"], st, d))
  90. results = d.get("results") or []
  91. labels = labels_of(q["endpoint"], results, by_id)
  92. rank = None
  93. for i, lab in enumerate(labels):
  94. if is_relevant(lab, q["relevant"]):
  95. rank = i + 1
  96. break
  97. rows.append({"id": q["id"], "kind": q["kind"], "endpoint": q["endpoint"], "strategy": d.get("strategy"),
  98. "rank": rank, "results": len(results), "top": labels[:5],
  99. "evidence_ok": all(has_evidence(q["endpoint"], r) for r in results)})
  100. wrong = [r["id"] for r in rows if r["strategy"] != expected]
  101. if wrong:
  102. sys.exit("expected strategy %s, got another one for %s (is the embedding provider %s?)"
  103. % (expected, ", ".join(wrong), "up" if expected == "hybrid" else "stopped"))
  104. save_json(out_path, rows)
  105. print("%s run: %d queries" % (expected, len(rows)))
  106. def metrics(rows):
  107. m = {}
  108. for kind in ("exact", "paraphrase"):
  109. rs = [r for r in rows if r["kind"] == kind]
  110. m[kind + "_hit_at_5"] = sum(1 for r in rs if r["rank"] and r["rank"] <= 5) / len(rs)
  111. m[kind + "_mrr"] = sum(1.0 / r["rank"] for r in rs if r["rank"]) / len(rs)
  112. rs = [r for r in rows if r["kind"] != "none"]
  113. m["all_mrr"] = sum(1.0 / r["rank"] for r in rs if r["rank"]) / len(rs)
  114. rs = [r for r in rows if r["kind"] == "none"]
  115. m["none_false_positive_rate"] = sum(1 for r in rs if r["results"] > 0) / len(rs)
  116. m["evidence_ok"] = all(r["evidence_ok"] for r in rows)
  117. return m
  118. def report(fixtures_path, hybrid_path, lexical_path):
  119. th = load_json(fixtures_path)["thresholds"]
  120. hy, lx = load_json(hybrid_path), load_json(lexical_path)
  121. mh, ml = metrics(hy), metrics(lx)
  122. print("%-28s %8s %8s" % ("metric", "hybrid", "lexical"))
  123. for k in mh:
  124. a, b = mh[k], ml[k]
  125. fmt = "%-28s %8s %8s" if isinstance(a, bool) else "%-28s %8.3f %8.3f"
  126. print(fmt % (k, a, b))
  127. checks = [
  128. ("hybrid exact hit@5 >= %.2f" % th["hybrid_exact_hit_at_5"], mh["exact_hit_at_5"] >= th["hybrid_exact_hit_at_5"]),
  129. ("hybrid paraphrase hit@5 >= %.2f" % th["hybrid_paraphrase_hit_at_5"],
  130. mh["paraphrase_hit_at_5"] >= th["hybrid_paraphrase_hit_at_5"]),
  131. ("hybrid none false positives <= %.2f" % th["hybrid_none_false_positive_rate_max"],
  132. mh["none_false_positive_rate"] <= th["hybrid_none_false_positive_rate_max"]),
  133. ]
  134. if th.get("hybrid_mrr_not_below_lexical"):
  135. checks.append(("hybrid MRR >= lexical MRR", mh["all_mrr"] >= ml["all_mrr"]))
  136. if th.get("evidence_on_every_result"):
  137. checks.append(("evidence on every result", mh["evidence_ok"] and ml["evidence_ok"]))
  138. print("")
  139. for name, ok in checks:
  140. print("%s %s" % ("PASS" if ok else "FAIL", name))
  141. misses = [r for r in hy if r["kind"] != "none" and not (r["rank"] and r["rank"] <= 5)]
  142. noisy = [r for r in hy if r["kind"] == "none" and r["results"] > 0]
  143. if misses or noisy:
  144. print("")
  145. print("hybrid misses (no relevant item in the first 5):")
  146. for r in misses:
  147. print(" %s %-10s rank=%s top=%s" % (r["id"], r["kind"], r["rank"], ",".join(r["top"])))
  148. for r in noisy:
  149. print(" %s none returned %d result(s): %s" % (r["id"], r["results"], ",".join(r["top"])))
  150. ok = all(c[1] for c in checks)
  151. print("")
  152. print("passed: %d failed: %d" % (sum(1 for c in checks if c[1]), sum(1 for c in checks if not c[1])))
  153. sys.exit(0 if ok else 1)
  154. if __name__ == "__main__":
  155. a = sys.argv[1:]
  156. if a and a[0] == "load" and len(a) == 6:
  157. load(*a[1:])
  158. elif a and a[0] == "run" and len(a) == 7:
  159. run(*a[1:])
  160. elif a and a[0] == "report" and len(a) == 4:
  161. report(*a[1:])
  162. else:
  163. sys.exit(__doc__)

Powered by TurnKey Linux.