jmullings commited on
Commit
422468d
·
1 Parent(s): 3ef9957

Base DB added

Browse files
Files changed (5) hide show
  1. app.py +13 -6
  2. requirements.txt +3 -1
  3. src/db.py +94 -0
  4. src/leaderboard/read_evals.py +39 -20
  5. src/submission/submit.py +36 -20
app.py CHANGED
@@ -13,6 +13,12 @@ for sub in ["src", "src/display", "src/submission", "src/leaderboard", "src/audi
13
  if os.path.exists(p):
14
  sys.path.insert(0, p)
15
 
 
 
 
 
 
 
16
  # About
17
  try:
18
  from src.about import CITATION_BUTTON_LABEL, CITATION_BUTTON_TEXT, INTRODUCTION_TEXT, TITLE
@@ -84,7 +90,9 @@ def seed_demo_results():
84
  if not os.path.exists(EVAL_RESULTS_PATH):
85
  os.makedirs(EVAL_RESULTS_PATH, exist_ok=True)
86
 
87
- if not os.listdir(EVAL_RESULTS_PATH):
 
 
88
  mock_cert = {
89
  "status": "ok",
90
  "config": {
@@ -128,8 +136,10 @@ def seed_demo_results():
128
  "disclaimer": "Diagnostic signal only.",
129
  },
130
  }
 
131
  with open(os.path.join(EVAL_RESULTS_PATH, "Qwen__Qwen2.5-0.5B-Instruct_main.json"), "w", encoding="utf-8") as f:
132
  json.dump(mock_cert, f, indent=2)
 
133
 
134
 
135
  seed_demo_results()
@@ -289,10 +299,7 @@ with demo:
289
  with gr.Accordion("📙 Methodology & Limitations", open=False):
290
  gr.Textbox(value=CITATION_BUTTON_TEXT, label=CITATION_BUTTON_LABEL, lines=8, show_copy_button=True)
291
 
292
- # if __name__ == "__main__":
293
- # demo.launch()
294
-
295
  # if __name__ == "__main__":
296
  # demo.launch(server_name="0.0.0.0", server_port=7860)
297
- if __name__ == "__main__":
298
- demo.launch()
 
13
  if os.path.exists(p):
14
  sys.path.insert(0, p)
15
 
16
+ # DB Integration
17
+ try:
18
+ from src.db import mongo_get_all_certificates, mongo_save_certificate
19
+ except ImportError:
20
+ from db import mongo_get_all_certificates, mongo_save_certificate
21
+
22
  # About
23
  try:
24
  from src.about import CITATION_BUTTON_LABEL, CITATION_BUTTON_TEXT, INTRODUCTION_TEXT, TITLE
 
90
  if not os.path.exists(EVAL_RESULTS_PATH):
91
  os.makedirs(EVAL_RESULTS_PATH, exist_ok=True)
92
 
93
+ # Check if we already have records in MongoDB or local disk
94
+ existing_docs = mongo_get_all_certificates()
95
+ if not existing_docs and not os.listdir(EVAL_RESULTS_PATH):
96
  mock_cert = {
97
  "status": "ok",
98
  "config": {
 
136
  "disclaimer": "Diagnostic signal only.",
137
  },
138
  }
139
+ # Save to local and MongoDB Atlas
140
  with open(os.path.join(EVAL_RESULTS_PATH, "Qwen__Qwen2.5-0.5B-Instruct_main.json"), "w", encoding="utf-8") as f:
141
  json.dump(mock_cert, f, indent=2)
142
+ mongo_save_certificate(mock_cert)
143
 
144
 
145
  seed_demo_results()
 
299
  with gr.Accordion("📙 Methodology & Limitations", open=False):
300
  gr.Textbox(value=CITATION_BUTTON_TEXT, label=CITATION_BUTTON_LABEL, lines=8, show_copy_button=True)
301
 
302
+ if __name__ == "__main__":
303
+ demo.launch()
 
304
  # if __name__ == "__main__":
305
  # demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
requirements.txt CHANGED
@@ -12,4 +12,6 @@ tokenizers>=0.15.0
12
  accelerate
13
  datasets
14
  python-dateutil
15
- apscheduler
 
 
 
12
  accelerate
13
  datasets
14
  python-dateutil
15
+ apscheduler
16
+ pymongo>=4.6.0
17
+ dnspython>=2.4.0
src/db.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Dict, List, Optional
3
+
4
+ try:
5
+ import pymongo
6
+ HAS_PYMONGO = True
7
+ except ImportError:
8
+ HAS_PYMONGO = False
9
+
10
+ # MongoDB Connection String from Atlas
11
+ DEFAULT_URI = None
12
+ MONGODB_URI = os.environ.get("MONGODB_URI", DEFAULT_URI)
13
+ DB_NAME = os.environ.get("MONGODB_DB_NAME", "llm_xray_db")
14
+ COLLECTION_NAME = "audit_certificates"
15
+
16
+ _mongo_client = None
17
+
18
+ def get_db_collection():
19
+ global _mongo_client
20
+ if not HAS_PYMONGO:
21
+ return None
22
+ try:
23
+ if _mongo_client is None:
24
+ _mongo_client = pymongo.MongoClient(
25
+ MONGODB_URI,
26
+ serverSelectionTimeoutMS=4000,
27
+ connectTimeoutMS=4000,
28
+ )
29
+ db = _mongo_client[DB_NAME]
30
+ return db[COLLECTION_NAME]
31
+ except Exception as e:
32
+ print(f"[MongoDB] Connection warning: {e}", flush=True)
33
+ return None
34
+
35
+
36
+ def mongo_save_certificate(cert: Dict) -> bool:
37
+ """Saves or updates an audit certificate in MongoDB."""
38
+ col = get_db_collection()
39
+ if col is None:
40
+ return False
41
+ try:
42
+ config = cert.get("config", {})
43
+ model_name = config.get("model_name", "unknown")
44
+ model_sha = config.get("model_sha", "main")
45
+ doc_id = f"{model_name}__{model_sha}".replace("/", "__")
46
+
47
+ doc = dict(cert)
48
+ doc["_id"] = doc_id
49
+ doc["model_name"] = model_name
50
+ doc["model_sha"] = model_sha
51
+
52
+ col.replace_one({"_id": doc_id}, doc, upsert=True)
53
+ print(f"[MongoDB] ✅ Successfully persisted audit certificate for '{model_name}'", flush=True)
54
+ return True
55
+ except Exception as e:
56
+ print(f"[MongoDB] ⚠️ Could not save certificate to MongoDB: {e}", flush=True)
57
+ return False
58
+
59
+
60
+ def mongo_get_certificate(clean_model_name: str) -> Optional[Dict]:
61
+ """Retrieves an audit certificate by model name from MongoDB."""
62
+ col = get_db_collection()
63
+ if col is None or not clean_model_name:
64
+ return None
65
+ try:
66
+ # Search by exact name, normalized id, or regex
67
+ doc = col.find_one({
68
+ "$or": [
69
+ {"config.model_name": clean_model_name},
70
+ {"model_name": clean_model_name},
71
+ {"_id": {"$regex": f"^{clean_model_name.replace('/', '__')}", "$options": "i"}}
72
+ ]
73
+ })
74
+ if doc:
75
+ doc.pop("_id", None)
76
+ return doc
77
+ except Exception as e:
78
+ print(f"[MongoDB] ⚠️ Error retrieving '{clean_model_name}': {e}", flush=True)
79
+ return None
80
+
81
+
82
+ def mongo_get_all_certificates() -> List[Dict]:
83
+ """Recalls all saved certificates from MongoDB."""
84
+ col = get_db_collection()
85
+ if col is None:
86
+ return []
87
+ try:
88
+ docs = list(col.find({}))
89
+ for d in docs:
90
+ d.pop("_id", None)
91
+ return docs
92
+ except Exception as e:
93
+ print(f"[MongoDB] ⚠️ Error loading all certificates: {e}", flush=True)
94
+ return []
src/leaderboard/read_evals.py CHANGED
@@ -2,6 +2,11 @@ import json
2
  import os
3
  from dataclasses import dataclass
4
 
 
 
 
 
 
5
  try:
6
  from src.display.formatting import make_clickable_model
7
  except ImportError:
@@ -43,14 +48,8 @@ class EvalResult:
43
  sample_adequate: bool = True
44
 
45
  @classmethod
46
- def init_from_json_file(cls, json_filepath):
47
- try:
48
- with open(json_filepath, "r", encoding="utf-8") as fp:
49
- data = json.load(fp)
50
- except Exception:
51
- return None
52
-
53
- if data.get("status") not in ("ok", None):
54
  return None
55
 
56
  config = data.get("config", {})
@@ -135,8 +134,16 @@ class EvalResult:
135
  precision=precision_enum,
136
  )
137
 
 
 
 
 
 
 
 
 
 
138
  def to_dict(self):
139
- # "T" column hyperlinks directly to the model HF repo
140
  symbol_link = f'<a href="https://huggingface.co/{self.full_model}" target="_blank" title="View on Hugging Face" style="text-decoration: none;">{self.model_type.value.symbol}</a>'
141
 
142
  data_dict = {
@@ -159,16 +166,28 @@ class EvalResult:
159
 
160
 
161
  def get_raw_eval_results(results_path: str, requests_path: str = "") -> list[EvalResult]:
 
162
  results = []
163
- if not os.path.exists(results_path):
164
- return results
165
- for root, _, files in os.walk(results_path):
166
- for file in files:
167
- if file.endswith(".json"):
168
- try:
169
- res = EvalResult.init_from_json_file(os.path.join(root, file))
170
- if res is not None:
171
- results.append(res)
172
- except Exception as e:
173
- print(f"Error reading {file}: {e}")
 
 
 
 
 
 
 
 
 
 
 
174
  return results
 
2
  import os
3
  from dataclasses import dataclass
4
 
5
+ try:
6
+ from src.db import mongo_get_all_certificates
7
+ except ImportError:
8
+ from db import mongo_get_all_certificates
9
+
10
  try:
11
  from src.display.formatting import make_clickable_model
12
  except ImportError:
 
48
  sample_adequate: bool = True
49
 
50
  @classmethod
51
+ def init_from_dict(cls, data: dict):
52
+ if not isinstance(data, dict) or data.get("status") not in ("ok", None):
 
 
 
 
 
 
53
  return None
54
 
55
  config = data.get("config", {})
 
134
  precision=precision_enum,
135
  )
136
 
137
+ @classmethod
138
+ def init_from_json_file(cls, json_filepath):
139
+ try:
140
+ with open(json_filepath, "r", encoding="utf-8") as fp:
141
+ data = json.load(fp)
142
+ return cls.init_from_dict(data)
143
+ except Exception:
144
+ return None
145
+
146
  def to_dict(self):
 
147
  symbol_link = f'<a href="https://huggingface.co/{self.full_model}" target="_blank" title="View on Hugging Face" style="text-decoration: none;">{self.model_type.value.symbol}</a>'
148
 
149
  data_dict = {
 
166
 
167
 
168
  def get_raw_eval_results(results_path: str, requests_path: str = "") -> list[EvalResult]:
169
+ seen_evals = set()
170
  results = []
171
+
172
+ # 1. Recall directly from MongoDB Atlas
173
+ mongo_docs = mongo_get_all_certificates()
174
+ for doc in mongo_docs:
175
+ res = EvalResult.init_from_dict(doc)
176
+ if res and res.eval_name not in seen_evals:
177
+ seen_evals.add(res.eval_name)
178
+ results.append(res)
179
+
180
+ # 2. Merge any local disk files
181
+ if os.path.exists(results_path):
182
+ for root, _, files in os.walk(results_path):
183
+ for file in files:
184
+ if file.endswith(".json"):
185
+ try:
186
+ res = EvalResult.init_from_json_file(os.path.join(root, file))
187
+ if res is not None and res.eval_name not in seen_evals:
188
+ seen_evals.add(res.eval_name)
189
+ results.append(res)
190
+ except Exception as e:
191
+ print(f"Error reading {file}: {e}")
192
+
193
  return results
src/submission/submit.py CHANGED
@@ -21,6 +21,12 @@ def gpu_decorator(duration=120):
21
  return fn
22
  return decorator
23
 
 
 
 
 
 
 
24
  # Engine import
25
  try:
26
  from src.audit.engine import AuditError, check_feasibility, run_full_audit
@@ -120,30 +126,44 @@ def clean_model_name(raw_name: str) -> str:
120
 
121
  def get_certificate_by_model_name(model_name: str) -> dict:
122
  clean_name = clean_model_name(model_name)
123
- if not clean_name or not os.path.exists(EVAL_RESULTS_PATH):
124
  return {}
125
 
126
- safe_prefix = clean_name.replace("/", "__")
127
- for f in os.listdir(EVAL_RESULTS_PATH):
128
- if f.startswith(safe_prefix) and f.endswith(".json"):
129
- try:
130
- with open(os.path.join(EVAL_RESULTS_PATH, f), "r", encoding="utf-8") as fp:
131
- return json.load(fp)
132
- except Exception:
133
- continue
 
 
 
 
 
 
 
134
  return {}
135
 
136
 
137
  def _save_cert(model_id: str, revision: str, cert: dict) -> str:
 
138
  os.makedirs(EVAL_RESULTS_PATH, exist_ok=True)
139
  safe_name = model_id.replace("/", "__") + f"_{revision}.json"
140
  out_path = os.path.join(EVAL_RESULTS_PATH, safe_name)
141
- with open(out_path, "w", encoding="utf-8") as f:
142
- json.dump(cert, f, indent=2)
 
 
 
 
 
 
 
143
  return out_path
144
 
145
 
146
- # Pure, pickleable function signature for ZeroGPU multiprocessing
147
  @gpu_decorator(duration=120)
148
  def execute_direct_xray_audit(model_id: str, revision: str = "main", trust_remote_code: bool = False) -> dict:
149
  now_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
@@ -162,7 +182,6 @@ def execute_direct_xray_audit(model_id: str, revision: str = "main", trust_remot
162
  _save_cert(model_id, revision, cert)
163
  return cert
164
 
165
- # Run multi-layer audit (logs automatically stream to console with flush=True)
166
  result = run_full_audit(
167
  model_id=model_id,
168
  revision=revision,
@@ -216,18 +235,17 @@ def audit_or_search_model(url_or_id: str, trust_remote_code: bool = False):
216
  )
217
  return
218
 
219
- # Check for existing cert first (instant load)
220
  existing_cert = get_certificate_by_model_name(clean_model)
221
  if existing_cert and existing_cert.get("status") == "ok":
222
  yield (
223
- styled_message(f"Loaded existing audit certificate for <b>{clean_model}</b>."),
224
  current_df,
225
  current_top3,
226
  render_audit_details_panel(existing_cert),
227
  )
228
  return
229
 
230
- # Initial loading feedback
231
  yield (
232
  styled_loading(f"Connecting to HF Hub for <b>{clean_model}</b>...", "Requesting ZeroGPU slice & downloading model weights..."),
233
  current_df,
@@ -240,7 +258,6 @@ def audit_or_search_model(url_or_id: str, trust_remote_code: bool = False):
240
 
241
  def _worker():
242
  try:
243
- # Arguments are pure primitives (str, str, bool) -> 100% pickleable on ZeroGPU
244
  result_holder["cert"] = execute_direct_xray_audit(
245
  clean_model, "main", trust_remote_code=trust_remote_code
246
  )
@@ -258,13 +275,12 @@ def audit_or_search_model(url_or_id: str, trust_remote_code: bool = False):
258
  thread = threading.Thread(target=_worker, daemon=True)
259
  thread.start()
260
 
261
- # Informative UI stage cycle while ZeroGPU finishes audit
262
  stages = [
263
  "Downloading model weights and tokenizer tensors...",
264
  "Layer A: Performing SVD Spectral Tomography across weight tensors...",
265
  "Layer B: Streaming activations and calculating operator covariance...",
266
  "Layer C: Running empirical factual probe battery...",
267
- "Finalizing operator risk and registering certificate...",
268
  ]
269
  stage_idx = 0
270
 
@@ -296,7 +312,7 @@ def audit_or_search_model(url_or_id: str, trust_remote_code: bool = False):
296
  )
297
  else:
298
  yield (
299
- styled_message(f"🎉 <b>Audit Complete for {clean_model}!</b> Certificate registered below."),
300
  updated_df,
301
  updated_top3,
302
  updated_panel,
 
21
  return fn
22
  return decorator
23
 
24
+ # Database integration
25
+ try:
26
+ from src.db import mongo_get_certificate, mongo_save_certificate
27
+ except ImportError:
28
+ from db import mongo_get_certificate, mongo_save_certificate
29
+
30
  # Engine import
31
  try:
32
  from src.audit.engine import AuditError, check_feasibility, run_full_audit
 
126
 
127
  def get_certificate_by_model_name(model_name: str) -> dict:
128
  clean_name = clean_model_name(model_name)
129
+ if not clean_name:
130
  return {}
131
 
132
+ # 1. Check MongoDB first
133
+ cert = mongo_get_certificate(clean_name)
134
+ if cert and cert.get("status") == "ok":
135
+ return cert
136
+
137
+ # 2. Local filesystem fallback
138
+ if os.path.exists(EVAL_RESULTS_PATH):
139
+ safe_prefix = clean_name.replace("/", "__")
140
+ for f in os.listdir(EVAL_RESULTS_PATH):
141
+ if f.startswith(safe_prefix) and f.endswith(".json"):
142
+ try:
143
+ with open(os.path.join(EVAL_RESULTS_PATH, f), "r", encoding="utf-8") as fp:
144
+ return json.load(fp)
145
+ except Exception:
146
+ continue
147
  return {}
148
 
149
 
150
  def _save_cert(model_id: str, revision: str, cert: dict) -> str:
151
+ # 1. Save to local disk cache
152
  os.makedirs(EVAL_RESULTS_PATH, exist_ok=True)
153
  safe_name = model_id.replace("/", "__") + f"_{revision}.json"
154
  out_path = os.path.join(EVAL_RESULTS_PATH, safe_name)
155
+ try:
156
+ with open(out_path, "w", encoding="utf-8") as f:
157
+ json.dump(cert, f, indent=2)
158
+ except Exception as e:
159
+ print(f"Local file write error: {e}", flush=True)
160
+
161
+ # 2. Persist permanently to MongoDB Atlas
162
+ mongo_save_certificate(cert)
163
+
164
  return out_path
165
 
166
 
 
167
  @gpu_decorator(duration=120)
168
  def execute_direct_xray_audit(model_id: str, revision: str = "main", trust_remote_code: bool = False) -> dict:
169
  now_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
 
182
  _save_cert(model_id, revision, cert)
183
  return cert
184
 
 
185
  result = run_full_audit(
186
  model_id=model_id,
187
  revision=revision,
 
235
  )
236
  return
237
 
238
+ # Check for existing cert in MongoDB / local cache
239
  existing_cert = get_certificate_by_model_name(clean_model)
240
  if existing_cert and existing_cert.get("status") == "ok":
241
  yield (
242
+ styled_message(f"Loaded existing audit certificate for <b>{clean_model}</b> from MongoDB."),
243
  current_df,
244
  current_top3,
245
  render_audit_details_panel(existing_cert),
246
  )
247
  return
248
 
 
249
  yield (
250
  styled_loading(f"Connecting to HF Hub for <b>{clean_model}</b>...", "Requesting ZeroGPU slice & downloading model weights..."),
251
  current_df,
 
258
 
259
  def _worker():
260
  try:
 
261
  result_holder["cert"] = execute_direct_xray_audit(
262
  clean_model, "main", trust_remote_code=trust_remote_code
263
  )
 
275
  thread = threading.Thread(target=_worker, daemon=True)
276
  thread.start()
277
 
 
278
  stages = [
279
  "Downloading model weights and tokenizer tensors...",
280
  "Layer A: Performing SVD Spectral Tomography across weight tensors...",
281
  "Layer B: Streaming activations and calculating operator covariance...",
282
  "Layer C: Running empirical factual probe battery...",
283
+ "Finalizing operator risk and registering certificate to MongoDB...",
284
  ]
285
  stage_idx = 0
286
 
 
312
  )
313
  else:
314
  yield (
315
+ styled_message(f"🎉 <b>Audit Complete for {clean_model}!</b> Persisted in MongoDB Atlas."),
316
  updated_df,
317
  updated_top3,
318
  updated_panel,