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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""bench v2 重跑: 只重跑"未判对"的 IP, 吃全部已落地的改进。
|
| 3 |
+
|
| 4 |
+
改进清单 (相对 9-26 基线):
|
| 5 |
+
- D4 指纹截断 (util.truncate_fingerprint_for_llm)
|
| 6 |
+
- D6 弃权回退 adapter 判决 (agent._maybe_adapter_fallback)
|
| 7 |
+
- 特征端口硬信号进 prompt (agent._port_signals)
|
| 8 |
+
- 类型串空白规范化 (decision.normalize_decision)
|
| 9 |
+
- KB 去重: 跨类型重复 IP 不再作为 local 近邻 (retrieval._ambiguous_kb_ips)
|
| 10 |
+
- PM/CONTROLLER/ALARM 社区层重建 (10-18 晨, 簇摘要已再生)
|
| 11 |
+
|
| 12 |
+
用法 (worker, 每卡一个):
|
| 13 |
+
CUDA_VISIBLE_DEVICES=1 HF_HOME=/dev/shm/ft_v2/hf \
|
| 14 |
+
python evaluation/bench_100/run_bench_v2.py --worker 1
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import fcntl
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import shutil
|
| 22 |
+
import sys
|
| 23 |
+
import time
|
| 24 |
+
|
| 25 |
+
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 26 |
+
sys.path.insert(0, os.path.join(REPO, "agent"))
|
| 27 |
+
sys.path.insert(0, REPO)
|
| 28 |
+
|
| 29 |
+
TYPES = json.load(open(os.path.join(REPO, "config", "rag_devices.json")))["IoT"]
|
| 30 |
+
VALID = os.path.join(REPO, "evaluation", "validation")
|
| 31 |
+
PRED = os.path.join(REPO, "evaluation", "predict")
|
| 32 |
+
BENCH = os.path.join(REPO, "evaluation", "bench_100")
|
| 33 |
+
ADAPTER = os.path.join(REPO, "evaluation/unseen/llama3/results_v2/final_model")
|
| 34 |
+
DRIFT = os.path.join(REPO, "drift_data/autoencoder_drift")
|
| 35 |
+
QUEUE = "/tmp/bench_v2_queue.txt"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def append_record(t, rec):
|
| 39 |
+
os.makedirs(os.path.join(BENCH, t), exist_ok=True)
|
| 40 |
+
with open(os.path.join(BENCH, t, "records.jsonl"), "a") as fh:
|
| 41 |
+
fh.write(json.dumps(rec, ensure_ascii=False, default=str) + "\n")
|
| 42 |
+
fh.flush()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def pop_type():
|
| 46 |
+
fd = os.open(QUEUE, os.O_RDWR)
|
| 47 |
+
try:
|
| 48 |
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
| 49 |
+
content = os.read(fd, 65536).decode()
|
| 50 |
+
lines = [l.strip() for l in content.splitlines() if l.strip()]
|
| 51 |
+
if not lines:
|
| 52 |
+
return None
|
| 53 |
+
nxt, rest = lines[0], lines[1:]
|
| 54 |
+
os.pwrite(fd, "\n".join(rest).encode(), 0)
|
| 55 |
+
os.ftruncate(fd, len("\n".join(rest)))
|
| 56 |
+
return nxt
|
| 57 |
+
finally:
|
| 58 |
+
os.close(fd)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def load_predictions(t):
|
| 62 |
+
"""predict JSON 兼容 list/dict 两种形态, 统一为 (type_map, vendor_map)。
|
| 63 |
+
|
| 64 |
+
注意文件名 `POWER_METER_type_prediction.json` 按 '_' 切分会切进类型名
|
| 65 |
+
内部 (POWER|METER), 必须按前后缀判别, 不能用 split 取段。
|
| 66 |
+
"""
|
| 67 |
+
maps = {}
|
| 68 |
+
for kind, suffix in (("type", "_type_prediction.json"),
|
| 69 |
+
("vendor", "_vendor_prediction.json")):
|
| 70 |
+
p = os.path.join(PRED, f"{t}{suffix}")
|
| 71 |
+
try:
|
| 72 |
+
data = json.load(open(p))
|
| 73 |
+
except (OSError, ValueError):
|
| 74 |
+
continue
|
| 75 |
+
if isinstance(data, list):
|
| 76 |
+
maps[kind] = {str(r.get("ip")): r for r in data if isinstance(r, dict)}
|
| 77 |
+
else:
|
| 78 |
+
maps[kind] = {str(k): v for k, v in data.items()}
|
| 79 |
+
return maps.get("type"), maps.get("vendor")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def targets_for(t):
|
| 83 |
+
"""sample 中"最后一条记录判错/弃权/无记录"的 IP → 待重跑子集。"""
|
| 84 |
+
import pandas as pd
|
| 85 |
+
sample = pd.read_csv(os.path.join(BENCH, f"sample_{t}_100.csv"), low_memory=False)
|
| 86 |
+
last = {}
|
| 87 |
+
p = os.path.join(BENCH, t, "records.jsonl")
|
| 88 |
+
if os.path.exists(p):
|
| 89 |
+
for l in open(p):
|
| 90 |
+
try:
|
| 91 |
+
r = json.loads(l)
|
| 92 |
+
except ValueError:
|
| 93 |
+
continue
|
| 94 |
+
last[str(r.get("ip"))] = r
|
| 95 |
+
todo = [ip for ip in sample["ip"].astype(str)
|
| 96 |
+
if last.get(ip, {}).get("predicted_type") != t]
|
| 97 |
+
return sample[sample["ip"].astype(str).isin(todo)], todo
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def run_type(t, limit=None):
|
| 101 |
+
from agent import IdentificationAgent
|
| 102 |
+
sub, todo = targets_for(t)
|
| 103 |
+
if limit:
|
| 104 |
+
todo = todo[:limit]
|
| 105 |
+
sub = sub[sub["ip"].astype(str).isin(todo)]
|
| 106 |
+
if not todo:
|
| 107 |
+
print(f"[{t}] 无待重跑 IP", flush=True)
|
| 108 |
+
return
|
| 109 |
+
print(f"[{t}] 待重跑 {len(todo)} IP", flush=True)
|
| 110 |
+
|
| 111 |
+
path = os.path.join(VALID, f"test_{t}_1.csv")
|
| 112 |
+
bak = path + ".bench_bak"
|
| 113 |
+
if os.path.exists(path) and not os.path.exists(bak):
|
| 114 |
+
shutil.copy2(path, bak)
|
| 115 |
+
sub.to_csv(path, index=False)
|
| 116 |
+
try:
|
| 117 |
+
agent = IdentificationAgent(llm="DEEPSEEK", gpu=0)
|
| 118 |
+
agent.run_retrieval(whether_decompose=True, whether_local=True,
|
| 119 |
+
whether_community=True, whether_reasoning=True,
|
| 120 |
+
devices=[t], top_k=5, quick_resume=True)
|
| 121 |
+
agent.run_decision(devices=[t], whether_local=True, whether_community=True,
|
| 122 |
+
whether_reasoning=True, top_k=5, enable_first_stage=True,
|
| 123 |
+
unseen_adapter_path=ADAPTER, unseen_load_in_4bit=True,
|
| 124 |
+
drift_model_dir=DRIFT, gpu=0)
|
| 125 |
+
tp_all, vp_all = load_predictions(t)
|
| 126 |
+
tp_all, vp_all = tp_all or {}, vp_all or {}
|
| 127 |
+
n = ok = fb = 0
|
| 128 |
+
for ip in todo:
|
| 129 |
+
r = tp_all.get(ip) or {}
|
| 130 |
+
pred = r.get("predicted_device_type")
|
| 131 |
+
if not pred:
|
| 132 |
+
continue
|
| 133 |
+
n += 1
|
| 134 |
+
ok += (pred == t)
|
| 135 |
+
used_fb = r.get("decision_source") == "adapter_fallback"
|
| 136 |
+
fb += used_fb
|
| 137 |
+
vp = vp_all.get(ip) or {}
|
| 138 |
+
append_record(t, {
|
| 139 |
+
"ip": ip, "true_type": t,
|
| 140 |
+
"predicted_type": pred,
|
| 141 |
+
"confidence": r.get("final_confidence", r.get("confidence")),
|
| 142 |
+
"winning_llm": r.get("winning_llm"),
|
| 143 |
+
"gemini_type": r.get("gemini_device_type"),
|
| 144 |
+
"claude_type": r.get("claude_device_type"),
|
| 145 |
+
"predicted_vendor": vp.get("predicted_vendor"),
|
| 146 |
+
"decision_source": r.get("decision_source"),
|
| 147 |
+
"adapter_fallback": r.get("adapter_fallback"),
|
| 148 |
+
"first_stage": r.get("first_stage"),
|
| 149 |
+
"elapsed_sec": r.get("elapsed_sec"),
|
| 150 |
+
"pipeline_version": "v2_improved",
|
| 151 |
+
"ts": time.strftime("%m-%d %H:%M:%S"),
|
| 152 |
+
})
|
| 153 |
+
print(f"[{t}] v2 完成: 判决 {n}/{len(todo)}, 对 {ok}, adapter回退 {fb}",
|
| 154 |
+
flush=True)
|
| 155 |
+
finally:
|
| 156 |
+
if os.path.exists(bak):
|
| 157 |
+
shutil.move(bak, path)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def main():
|
| 161 |
+
ap = argparse.ArgumentParser()
|
| 162 |
+
ap.add_argument("--worker", type=int, default=None)
|
| 163 |
+
ap.add_argument("--types", nargs="*", default=None,
|
| 164 |
+
help="直接指定类型 (冒烟用), 忽略队列")
|
| 165 |
+
ap.add_argument("--limit", type=int, default=None)
|
| 166 |
+
args = ap.parse_args()
|
| 167 |
+
|
| 168 |
+
if args.types:
|
| 169 |
+
for t in args.types:
|
| 170 |
+
run_type(t, limit=args.limit)
|
| 171 |
+
return
|
| 172 |
+
|
| 173 |
+
while True:
|
| 174 |
+
t = pop_type()
|
| 175 |
+
if t is None:
|
| 176 |
+
print("[worker] 队列空, 退出", flush=True)
|
| 177 |
+
return
|
| 178 |
+
try:
|
| 179 |
+
run_type(t)
|
| 180 |
+
except Exception as exc: # noqa: BLE001 — 单类型失败不拖垮 worker
|
| 181 |
+
print(f"[{t}] FAILED: {exc}", flush=True)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
main()
|