Add single-file unseen-detector demo (ALARM/CONTROLLER: non-empty community/reasoning evidence, live 4-bit detector, ranked top-3 vendors)
Browse files
evaluation/demo/unseen_detector_demo.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Single-file runnable demo: unseen detector on an ALARM / CONTROLLER device.
|
| 3 |
+
|
| 4 |
+
This is the artifact-evaluation example for the paper's first-stage unseen
|
| 5 |
+
detector. For one fixed-seed validation device it shows, end to end:
|
| 6 |
+
|
| 7 |
+
1. the recorded three-layer retrieval evidence — LOCAL neighbours,
|
| 8 |
+
COMMUNITY cluster matches and REASONING-path matches — all non-empty
|
| 9 |
+
(schema 2026-09-25-v3 caches of the reference run);
|
| 10 |
+
2. a live run of UnseenDeviceDetector (Llama-3.1-8B-Instruct + the released
|
| 11 |
+
LoRA adapter, 4-bit) on exactly that evidence;
|
| 12 |
+
3. a RANKED top-3 vendor prediction (detector label first, then
|
| 13 |
+
evidence-scored candidates from the fingerprint and the community
|
| 14 |
+
cluster report, lexicon = the adapter's known_vendors.json contract),
|
| 15 |
+
plus a top-3 check against a reference vendor label.
|
| 16 |
+
|
| 17 |
+
No LLM API keys are needed. With --skip-model the detector call is skipped
|
| 18 |
+
(and rank 1 comes from evidence only) so the evidence part runs on any CPU.
|
| 19 |
+
|
| 20 |
+
ALARM is the complete example (v3 evidence at all three levels). CONTROLLER's
|
| 21 |
+
community/reasoning cache is the disclosed legacy v2 run and does not cover
|
| 22 |
+
the demo pool, so for CONTROLLER the demo degrades to local evidence +
|
| 23 |
+
fingerprint ranking and prints how to regenerate v3 evidence.
|
| 24 |
+
|
| 25 |
+
Usage (from the repository root):
|
| 26 |
+
python demo/unseen_detector_demo.py # ALARM showcase
|
| 27 |
+
python demo/unseen_detector_demo.py --device CONTROLLER
|
| 28 |
+
python demo/unseen_detector_demo.py --ip 107.89.86.78
|
| 29 |
+
python demo/unseen_detector_demo.py --skip-model # no GPU needed
|
| 30 |
+
python demo/unseen_detector_demo.py --true-vendor Bosch # override label
|
| 31 |
+
|
| 32 |
+
Expected resources (see evaluation/REBUTTAL_ADDENDUM.md §1.3):
|
| 33 |
+
./Meta-Llama-3.1-8B-Instruct/ (gated HF download)
|
| 34 |
+
evaluation/unseen/llama3/results_v2/final_model/ (released adapter)
|
| 35 |
+
demo/{DEVICE}/validation_cases.json (fixed-seed pool)
|
| 36 |
+
agent/query_db/{local,community,reasoning}/{DEVICE}_*.json (evidence cache)
|
| 37 |
+
"""
|
| 38 |
+
import argparse
|
| 39 |
+
import hashlib
|
| 40 |
+
import json
|
| 41 |
+
import os
|
| 42 |
+
import sys
|
| 43 |
+
import time
|
| 44 |
+
|
| 45 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 46 |
+
sys.path[:0] = [ROOT, os.path.join(ROOT, "agent")]
|
| 47 |
+
|
| 48 |
+
QUERY_DB = os.path.join(ROOT, "agent", "query_db")
|
| 49 |
+
DEFAULT_BASE = os.path.join(ROOT, "Meta-Llama-3.1-8B-Instruct")
|
| 50 |
+
DEFAULT_ADAPTER = os.path.join(ROOT, "evaluation", "unseen", "llama3",
|
| 51 |
+
"results_v2", "final_model")
|
| 52 |
+
KNOWN_VENDORS = os.path.join(DEFAULT_ADAPTER, "known_vendors.json")
|
| 53 |
+
|
| 54 |
+
# Vendor-bearing fingerprint/report fields used for evidence scoring.
|
| 55 |
+
VENDOR_FIELDS = ["cert-issuers", "cert-subjects", "cert-info", "hw-products",
|
| 56 |
+
"hw-vendor", "http-tags", "http-info", "http-titles",
|
| 57 |
+
"sw-products", "sw-vendor"]
|
| 58 |
+
|
| 59 |
+
# Paper Table 3 dominant vendor per type — the DEFAULT top-3 reference label.
|
| 60 |
+
# (The demo pool carries no per-IP vendor label; override with --true-vendor.)
|
| 61 |
+
DOMINANT_VENDOR = {"ALARM": "Bosch", "CONTROLLER": "Schneider Electric"}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def canon(obj):
|
| 65 |
+
return json.dumps(obj, sort_keys=True, ensure_ascii=False, default=str)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def fingerprint_id(fp):
|
| 69 |
+
return hashlib.sha256(canon(fp).encode()).hexdigest()[:16]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def load_cases(device):
|
| 73 |
+
path = os.path.join(ROOT, "demo", device, "validation_cases.json")
|
| 74 |
+
return json.load(open(path))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def load_evidence(device):
|
| 78 |
+
"""Return {fingerprint_id: entry} for each non-empty retrieval level."""
|
| 79 |
+
ev = {}
|
| 80 |
+
for lvl in ("local", "community", "reasoning"):
|
| 81 |
+
path = os.path.join(QUERY_DB, lvl, f"{device}_{lvl}.json")
|
| 82 |
+
if not os.path.exists(path):
|
| 83 |
+
sys.exit(f"missing evidence cache: {path}\n"
|
| 84 |
+
f"(hf download IoTProber/raw_dataset --repo-type dataset "
|
| 85 |
+
f"--include 'evaluation/*' does not ship agent/query_db; "
|
| 86 |
+
f"re-run demo/run_fullflow_demo.py to rebuild it)")
|
| 87 |
+
entries = json.load(open(path))
|
| 88 |
+
ev[lvl] = {fingerprint_id(e.get("query_fingerprint", {})): e for e in entries}
|
| 89 |
+
return ev
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _hint_regen(device):
|
| 93 |
+
return (f"(no cached entry for this case — {device}'s community/reasoning "
|
| 94 |
+
f"cache is the disclosed legacy v2 run; regenerate v3 evidence with "
|
| 95 |
+
f"`python demo/run_fullflow_demo.py --types {device}`)")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def show_evidence(device, case, ev):
|
| 99 |
+
fid = fingerprint_id(case["fingerprint"])
|
| 100 |
+
ok = True
|
| 101 |
+
|
| 102 |
+
loc = ev["local"].get(fid)
|
| 103 |
+
print("\n== 1. LOCAL retrieval evidence (cache schema "
|
| 104 |
+
f"{loc['cache_metadata']['schema_version'] if loc else '?'}) ==")
|
| 105 |
+
if loc and loc.get("similar_devices"):
|
| 106 |
+
for n in loc["similar_devices"][:3]:
|
| 107 |
+
print(f" neighbour {n['ip']:<16} type={n['device_type']:<8} "
|
| 108 |
+
f"sim={n['similarity_score']:.3f}")
|
| 109 |
+
else:
|
| 110 |
+
ok = False
|
| 111 |
+
print(" ", _hint_regen(device))
|
| 112 |
+
|
| 113 |
+
com = ev["community"].get(fid)
|
| 114 |
+
print(f"\n== 2. COMMUNITY retrieval evidence "
|
| 115 |
+
f"({com['cache_metadata']['schema_version'] if com else 'none'}) ==")
|
| 116 |
+
if com and com.get("matched_clusters"):
|
| 117 |
+
for c in com["matched_clusters"][:2]:
|
| 118 |
+
print(f" cluster {c.get('cluster_id')} type={c.get('device_type')} "
|
| 119 |
+
f"sim={c.get('similarity_score')}")
|
| 120 |
+
patterns = c.get("report", {}).get("common_patterns") or {}
|
| 121 |
+
shown = 0
|
| 122 |
+
for field in list(VENDOR_FIELDS) + ["as-name", "os-product", "http-titles"]:
|
| 123 |
+
values = patterns.get(field)
|
| 124 |
+
if values and shown < 4:
|
| 125 |
+
print(f" {field}: " + "; ".join(
|
| 126 |
+
f"{v.get('value')} x{v.get('count')}" for v in values[:2]))
|
| 127 |
+
shown += 1
|
| 128 |
+
else:
|
| 129 |
+
ok = False
|
| 130 |
+
print(" (empty)")
|
| 131 |
+
|
| 132 |
+
rea = ev["reasoning"].get(fid)
|
| 133 |
+
print(f"\n== 3. REASONING-path evidence "
|
| 134 |
+
f"({rea['cache_metadata']['schema_version'] if rea else 'none'}) ==")
|
| 135 |
+
if rea and rea.get("path_matching_results"):
|
| 136 |
+
for p in rea["path_matching_results"][:2]:
|
| 137 |
+
info = p.get("cluster_info", {})
|
| 138 |
+
print(f" path {p.get('cluster_key')} sim={info.get('similarity_score')} "
|
| 139 |
+
f"type={info.get('device_type')}")
|
| 140 |
+
gist = str((info.get("report") or {}).get("common_patterns", ""))[:160]
|
| 141 |
+
if gist:
|
| 142 |
+
print(f" gist: {gist}")
|
| 143 |
+
top = (rea.get("summary") or {}).get("top_cluster") or {}
|
| 144 |
+
print(f" summary top cluster: {top.get('cluster_key')} "
|
| 145 |
+
f"({(top.get('cluster_info') or {}).get('similarity_score')})")
|
| 146 |
+
else:
|
| 147 |
+
ok = False
|
| 148 |
+
print(" (empty)")
|
| 149 |
+
|
| 150 |
+
print(f"\n evidence non-empty: {'YES' if ok else 'NO — pick another --index'}")
|
| 151 |
+
return ok, (loc, com, rea)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def run_detector(device, case, loc, com, rea, args):
|
| 155 |
+
print(f"\n== 4. UnseenDeviceDetector (live, "
|
| 156 |
+
f"{'4-bit' if not args.gpu < 0 else 'cpu'}) ==")
|
| 157 |
+
from unseen import UnseenDeviceDetector # noqa: E402 (agent/unseen.py)
|
| 158 |
+
det = UnseenDeviceDetector(
|
| 159 |
+
model_path=args.base_model,
|
| 160 |
+
adapter_path=DEFAULT_ADAPTER,
|
| 161 |
+
gpu=args.gpu,
|
| 162 |
+
load_in_4bit=args.gpu >= 0,
|
| 163 |
+
max_new_tokens=512,
|
| 164 |
+
)
|
| 165 |
+
t0 = time.time()
|
| 166 |
+
out = det.detect_unseen(rea, loc, com, allow_web_search=False)
|
| 167 |
+
print(f" new_type_probability = {out['new_type_probability']}")
|
| 168 |
+
print(f" new_vendor_probability= {out['new_vendor_probability']}")
|
| 169 |
+
print(f" is_unseen = {out['is_unseen']}")
|
| 170 |
+
if out.get("classified_vendor") is not None:
|
| 171 |
+
print(f" classified_type = {out.get('classified_type')} "
|
| 172 |
+
f"(conf {out.get('type_confidence')}, "
|
| 173 |
+
f"registry match: {out.get('matched_rag_type')})")
|
| 174 |
+
print(f" classified_vendor = {out.get('classified_vendor')} "
|
| 175 |
+
f"(conf {out.get('vendor_confidence')}, "
|
| 176 |
+
f"registry match: {out.get('matched_known_vendor')})")
|
| 177 |
+
else:
|
| 178 |
+
print(f" detector vendor = {out.get('predicted_vendor')}")
|
| 179 |
+
print(f" latency = {time.time() - t0:.1f}s "
|
| 180 |
+
f"(model {out.get('generation_time_sec', float('nan'))}s)")
|
| 181 |
+
return out
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def evidence_vendor_scores(device, case, com):
|
| 185 |
+
"""Count lexicon-vendor mentions across fingerprint + community report."""
|
| 186 |
+
lex = json.load(open(KNOWN_VENDORS))["known_vendors_by_type"].get(device, [])
|
| 187 |
+
lex = sorted(lex, key=len, reverse=True) # longest match first
|
| 188 |
+
scores, sources = {}, {}
|
| 189 |
+
|
| 190 |
+
def scan(text, weight, where):
|
| 191 |
+
low = str(text).lower()
|
| 192 |
+
for v in lex:
|
| 193 |
+
if v.lower() in low:
|
| 194 |
+
scores[v] = scores.get(v, 0.0) + weight
|
| 195 |
+
sources.setdefault(v, []).append(where)
|
| 196 |
+
|
| 197 |
+
for f in VENDOR_FIELDS:
|
| 198 |
+
if case["fingerprint"].get(f):
|
| 199 |
+
scan(case["fingerprint"][f], 3.0, f"fingerprint:{f}")
|
| 200 |
+
if com and com.get("matched_clusters"):
|
| 201 |
+
for c in com["matched_clusters"][:3]:
|
| 202 |
+
sim = float(c.get("similarity_score") or 0)
|
| 203 |
+
for field, values in (c.get("report", {}).get("common_patterns") or {}).items():
|
| 204 |
+
if field in VENDOR_FIELDS:
|
| 205 |
+
for v in values[:5]:
|
| 206 |
+
scan(v.get("value", ""), 1.0 * sim, f"community:{field}")
|
| 207 |
+
return scores, sources
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def ranked_top3(device, detector_out, case, com):
|
| 211 |
+
scores, sources = evidence_vendor_scores(device, case, com)
|
| 212 |
+
ranking = []
|
| 213 |
+
if detector_out:
|
| 214 |
+
# For a known vendor the novelty fields are "none" by design; the
|
| 215 |
+
# classifier's classified_vendor is the detector's top-1 vendor label.
|
| 216 |
+
v = detector_out.get("classified_vendor")
|
| 217 |
+
score = detector_out.get("vendor_confidence")
|
| 218 |
+
src = "detector (classified_vendor, conf)"
|
| 219 |
+
if not v: # genuinely unseen vendor
|
| 220 |
+
v = detector_out.get("predicted_vendor")
|
| 221 |
+
score = detector_out.get("new_vendor_probability")
|
| 222 |
+
src = "detector (novel vendor, prob)"
|
| 223 |
+
if v and v not in ("none", "None", "UNKNOWN", ""):
|
| 224 |
+
ranking.append((v, float(score or 0), src))
|
| 225 |
+
for v, s in sorted(scores.items(), key=lambda kv: -kv[1]):
|
| 226 |
+
if len(ranking) >= 3:
|
| 227 |
+
break
|
| 228 |
+
if any(v == r[0] for r in ranking):
|
| 229 |
+
continue
|
| 230 |
+
ranking.append((v, round(s, 2), "evidence: " + ",".join(
|
| 231 |
+
sorted(set(sources[v]))[:3])))
|
| 232 |
+
while len(ranking) < 3:
|
| 233 |
+
ranking.append(("-", 0.0, "no further evidence"))
|
| 234 |
+
return ranking
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def main():
|
| 238 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 239 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 240 |
+
ap.add_argument("--device", choices=["ALARM", "CONTROLLER"], default="ALARM")
|
| 241 |
+
ap.add_argument("--index", type=int, default=None,
|
| 242 |
+
help="case index in the pool (default: the case with the "
|
| 243 |
+
"strongest community match — ALARM 32 / CONTROLLER 0)")
|
| 244 |
+
ap.add_argument("--ip", help="select the case by IP instead of --index")
|
| 245 |
+
ap.add_argument("--gpu", type=int, default=0, help="-1 for CPU")
|
| 246 |
+
ap.add_argument("--base-model", default=DEFAULT_BASE)
|
| 247 |
+
ap.add_argument("--skip-model", action="store_true",
|
| 248 |
+
help="evidence + ranking only, no GPU / model needed")
|
| 249 |
+
ap.add_argument("--true-vendor", default=None,
|
| 250 |
+
help="reference vendor for the top-3 check "
|
| 251 |
+
f"(default: Table-3 dominant vendor "
|
| 252 |
+
f"{DOMINANT_VENDOR})")
|
| 253 |
+
args = ap.parse_args()
|
| 254 |
+
|
| 255 |
+
cases = load_cases(args.device)
|
| 256 |
+
if args.index is None:
|
| 257 |
+
args.index = 32 if args.device == "ALARM" else 0
|
| 258 |
+
case = next((c for c in cases if c.get("ip") == args.ip), None) if args.ip \
|
| 259 |
+
else cases[args.index]
|
| 260 |
+
ref = args.true_vendor or DOMINANT_VENDOR[args.device]
|
| 261 |
+
ref_note = "override" if args.true_vendor else (
|
| 262 |
+
"dominant vendor of this type, paper Table 3; "
|
| 263 |
+
"the pool carries no per-IP vendor label")
|
| 264 |
+
print(f"device={args.device} ip={case['ip']} "
|
| 265 |
+
f"fingerprint_id={fingerprint_id(case['fingerprint'])}")
|
| 266 |
+
print(f"top-3 reference label: {ref!r} ({ref_note})")
|
| 267 |
+
|
| 268 |
+
ev = load_evidence(args.device)
|
| 269 |
+
ok, (loc, com, rea) = show_evidence(args.device, case, ev)
|
| 270 |
+
|
| 271 |
+
det_out = None
|
| 272 |
+
if args.skip_model:
|
| 273 |
+
print("\n== 4. UnseenDeviceDetector: SKIPPED (--skip-model) ==")
|
| 274 |
+
elif rea is None:
|
| 275 |
+
print("\n== 4. UnseenDeviceDetector: SKIPPED (no reasoning evidence for "
|
| 276 |
+
"this case — the detector consumes reasoning-path output; "
|
| 277 |
+
"see the hint in section 3) ==")
|
| 278 |
+
else:
|
| 279 |
+
det_out = run_detector(args.device, case, loc, com, rea, args)
|
| 280 |
+
|
| 281 |
+
ranking = ranked_top3(args.device, det_out, case, com)
|
| 282 |
+
print("\n== 5. RANKED vendor predictions (top-3) ==")
|
| 283 |
+
for i, (v, s, src) in enumerate(ranking, 1):
|
| 284 |
+
print(f" {i}. {v:<20} score={s:<8} source={src}")
|
| 285 |
+
|
| 286 |
+
hit = next((i for i, (v, _, _) in enumerate(ranking, 1) if v == ref), None)
|
| 287 |
+
verdict = f"HIT (rank {hit})" if hit else "MISS (not in top-3)"
|
| 288 |
+
print(f"\n TOP-3 CHECK: reference {ref!r} -> {verdict}")
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
if __name__ == "__main__":
|
| 292 |
+
main()
|