vkatg commited on
Commit
85801be
·
verified ·
1 Parent(s): 51fa183

Upload 3 files

Browse files
Files changed (3) hide show
  1. config_dag.json +42 -0
  2. dagplanner.py +182 -0
  3. inference_dag.py +66 -0
config_dag.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "dagplanner",
3
+ "architecture": "rule_dag",
4
+ "action_catalog_size": 14,
5
+ "modalities": [
6
+ "text",
7
+ "image",
8
+ "audio",
9
+ "ehr"
10
+ ],
11
+ "planner": {
12
+ "default_risk_threshold": 0.2,
13
+ "default_budget": 1.0,
14
+ "scoring": "roi_urgency",
15
+ "roi_formula": "(reduces * modality_weight + retok_boost) / base_cost * log1p(risk * 5)",
16
+ "dag_constraints": "topological_sort with PRECEDE rules"
17
+ },
18
+ "inputs": {
19
+ "risk_score": "float [0,1] from FedCRDT-Distill or DCPG Encoder",
20
+ "retok_prob": "float [0,1] retokenization probability from FedCRDT-Distill",
21
+ "active_modalities": "list of str",
22
+ "patient_id": "str, optional"
23
+ },
24
+ "outputs": {
25
+ "plan": "list of action dicts in execution order",
26
+ "estimated_residual_risk": "float",
27
+ "total_cost": "float, total cost including injected dependency actions",
28
+ "status": "below_threshold | plan_ready | partial_plan | no_actions_applicable",
29
+ "selected_cost": "float, cost of directly selected actions within budget",
30
+ "plan_item_injected": "bool, true if action was injected to satisfy a dependency"
31
+ },
32
+ "upstream_models": [
33
+ "vkatg/exposureguard-fedcrdt-distill",
34
+ "vkatg/exposureguard-dcpg-encoder"
35
+ ],
36
+ "datasets": [
37
+ "vkatg/dag-remediation-traces",
38
+ "vkatg/multimodal-phi-masking-benchmark"
39
+ ],
40
+ "dependencies": [],
41
+ "framework": "pure_python"
42
+ }
dagplanner.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import json
5
+ from dataclasses import dataclass, field
6
+ from typing import Dict, List, Optional
7
+
8
+
9
+ ACTION_CATALOG = {
10
+ "mask_direct_id": {"base_cost": 0.05, "modalities": ["text", "image"], "reduces": 0.35},
11
+ "generalize_dob": {"base_cost": 0.03, "modalities": ["text", "ehr"], "reduces": 0.12},
12
+ "suppress_geo": {"base_cost": 0.04, "modalities": ["text", "ehr"], "reduces": 0.10},
13
+ "redact_image_face": {"base_cost": 0.12, "modalities": ["image"], "reduces": 0.20},
14
+ "redact_image_tag": {"base_cost": 0.08, "modalities": ["image"], "reduces": 0.14},
15
+ "strip_audio_voice": {"base_cost": 0.15, "modalities": ["audio"], "reduces": 0.18},
16
+ "anon_audio_content": {"base_cost": 0.10, "modalities": ["audio"], "reduces": 0.12},
17
+ "drop_rare_code": {"base_cost": 0.06, "modalities": ["ehr"], "reduces": 0.09},
18
+ "k_anon_table": {"base_cost": 0.20, "modalities": ["ehr", "text"], "reduces": 0.22},
19
+ "perturb_numerics": {"base_cost": 0.07, "modalities": ["ehr"], "reduces": 0.07},
20
+ "retokenize_text": {"base_cost": 0.09, "modalities": ["text"], "reduces": 0.11},
21
+ "cross_modal_unlink": {"base_cost": 0.18, "modalities": ["text", "image", "audio", "ehr"], "reduces": 0.28},
22
+ "federated_noise": {"base_cost": 0.25, "modalities": ["text", "image", "audio", "ehr"], "reduces": 0.15},
23
+ "audit_log_purge": {"base_cost": 0.02, "modalities": ["text", "image", "audio", "ehr"], "reduces": 0.03},
24
+ }
25
+
26
+ PRECEDE = {
27
+ "retokenize_text": ["mask_direct_id"],
28
+ "k_anon_table": ["generalize_dob", "suppress_geo", "drop_rare_code"],
29
+ "cross_modal_unlink": ["redact_image_face", "strip_audio_voice", "mask_direct_id"],
30
+ "federated_noise": ["k_anon_table", "cross_modal_unlink"],
31
+ "audit_log_purge": ["federated_noise"],
32
+ "redact_image_tag": ["redact_image_face"],
33
+ "anon_audio_content": ["strip_audio_voice"],
34
+ }
35
+
36
+
37
+ class ExposureGuardDAGPlanner:
38
+
39
+ def __init__(
40
+ self,
41
+ risk_threshold: float = 0.20,
42
+ budget: float = 1.0,
43
+ modality_weights: Optional[Dict[str, float]] = None,
44
+ ):
45
+ self.risk_threshold = risk_threshold
46
+ self.budget = budget
47
+ self.mw = modality_weights or {}
48
+
49
+ def _score(self, action: str, meta: Dict, risk: float, retok: float, active: List[str]) -> float:
50
+ overlap = [m for m in meta["modalities"] if m in active]
51
+ if not overlap:
52
+ return 0.0
53
+ w = max(self.mw.get(m, 1.0) for m in overlap)
54
+ rb = 0.15 if action == "retokenize_text" and retok > 0.55 else 0.0
55
+ return ((meta["reduces"] * w + rb) / (meta["base_cost"] + 1e-9)) * math.log1p(risk * 5.0)
56
+
57
+ def _select(self, risk: float, retok: float, active: List[str]) -> Dict:
58
+ scored = sorted(
59
+ [(a, m, self._score(a, m, risk, retok, active)) for a, m in ACTION_CATALOG.items()],
60
+ key=lambda x: -x[2],
61
+ )
62
+ selected = {}
63
+ cumcost = cumred = 0.0
64
+ target = max(0.0, risk - self.risk_threshold)
65
+ for action, meta, s in scored:
66
+ if s <= 0 or cumcost + meta["base_cost"] > self.budget:
67
+ continue
68
+ selected[action] = (s, meta)
69
+ cumcost += meta["base_cost"]
70
+ cumred += meta["reduces"]
71
+ if cumred >= target and cumcost >= 0.1:
72
+ break
73
+ return selected
74
+
75
+ def _build_nodes(self, selected: Dict) -> Dict:
76
+ nodes = {a: {"score": s, "meta": m, "deps": []} for a, (s, m) in selected.items()}
77
+ for action in list(nodes.keys()):
78
+ for dep in PRECEDE.get(action, []):
79
+ if dep not in nodes and dep in ACTION_CATALOG:
80
+ nodes[dep] = {"score": 0.01, "meta": ACTION_CATALOG[dep], "deps": []}
81
+ if dep in nodes:
82
+ nodes[action]["deps"].append(dep)
83
+ return nodes
84
+
85
+ def _topo(self, nodes: Dict) -> List[str]:
86
+ visited, order = set(), []
87
+ def visit(n):
88
+ if n in visited:
89
+ return
90
+ visited.add(n)
91
+ for dep in nodes[n]["deps"]:
92
+ if dep in nodes:
93
+ visit(dep)
94
+ order.append(n)
95
+ for n in sorted(nodes.keys(), key=lambda x: -nodes[x]["score"]):
96
+ visit(n)
97
+ return order
98
+
99
+ def plan(
100
+ self,
101
+ risk_score: float,
102
+ retok_prob: float = 0.0,
103
+ active_modalities: Optional[List[str]] = None,
104
+ patient_id: Optional[str] = None,
105
+ ) -> Dict:
106
+ if active_modalities is None:
107
+ active_modalities = ["text", "image", "audio", "ehr"]
108
+
109
+ if risk_score <= self.risk_threshold:
110
+ return {
111
+ "patient_id": patient_id,
112
+ "risk_score": risk_score,
113
+ "retok_prob": retok_prob,
114
+ "plan": [],
115
+ "estimated_residual_risk": risk_score,
116
+ "total_cost": 0.0,
117
+ "status": "below_threshold",
118
+ }
119
+
120
+ selected = self._select(risk_score, retok_prob, active_modalities)
121
+ if not selected:
122
+ return {
123
+ "patient_id": patient_id,
124
+ "risk_score": round(risk_score, 4),
125
+ "retok_prob": round(retok_prob, 4),
126
+ "plan": [],
127
+ "estimated_residual_risk": round(risk_score, 4),
128
+ "total_cost": 0.0,
129
+ "status": "no_actions_applicable",
130
+ }
131
+
132
+ nodes = self._build_nodes(selected)
133
+ order = self._topo(nodes)
134
+ plan_out = [
135
+ {
136
+ "action": a,
137
+ "priority": round(nodes[a]["score"], 4),
138
+ "cost": nodes[a]["meta"]["base_cost"],
139
+ "risk_delta":nodes[a]["meta"]["reduces"],
140
+ "deps": nodes[a]["deps"],
141
+ "injected": nodes[a]["score"] == 0.01,
142
+ }
143
+ for a in order
144
+ ]
145
+ total_red = sum(nodes[a]["meta"]["reduces"] for a in nodes)
146
+ selected_cost = sum(nodes[a]["meta"]["base_cost"] for a in nodes if nodes[a]["score"] != 0.01)
147
+ total_cost = sum(nodes[a]["meta"]["base_cost"] for a in nodes)
148
+ residual = round(max(0.0, risk_score - total_red), 4)
149
+
150
+ return {
151
+ "patient_id": patient_id,
152
+ "risk_score": round(risk_score, 4),
153
+ "retok_prob": round(retok_prob, 4),
154
+ "plan": plan_out,
155
+ "estimated_residual_risk":residual,
156
+ "selected_cost": round(selected_cost, 4),
157
+ "total_cost": round(total_cost, 4),
158
+ "status": "plan_ready" if residual <= self.risk_threshold else "partial_plan",
159
+ }
160
+
161
+ def batch_plan(self, records: List[Dict]) -> List[Dict]:
162
+ results = [
163
+ self.plan(
164
+ risk_score=r["risk_score"],
165
+ retok_prob=r.get("retok_prob", 0.0),
166
+ active_modalities=r.get("active_modalities"),
167
+ patient_id=r.get("patient_id"),
168
+ )
169
+ for r in records
170
+ ]
171
+ results.sort(key=lambda x: -x["risk_score"])
172
+ return results
173
+
174
+ def summary(self, result: Dict) -> str:
175
+ return "patient=%s risk=%.3f->%.3f actions=%d cost=%.3f status=%s" % (
176
+ result["patient_id"] or "?",
177
+ result["risk_score"],
178
+ result["estimated_residual_risk"],
179
+ len(result["plan"]),
180
+ result["total_cost"],
181
+ result["status"],
182
+ )
inference_dag.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+
6
+ from dagplanner import ExposureGuardDAGPlanner
7
+
8
+
9
+ def demo_single():
10
+ planner = ExposureGuardDAGPlanner(risk_threshold=0.20, budget=1.0)
11
+ result = planner.plan(
12
+ risk_score=0.74,
13
+ retok_prob=0.68,
14
+ active_modalities=["text", "image", "ehr"],
15
+ patient_id="P-0042",
16
+ )
17
+ print(planner.summary(result))
18
+ print(json.dumps(result, indent=2))
19
+ return result
20
+
21
+
22
+ def demo_batch():
23
+ planner = ExposureGuardDAGPlanner(
24
+ risk_threshold=0.20,
25
+ budget=1.2,
26
+ modality_weights={"image": 1.4, "audio": 1.2},
27
+ )
28
+ records = [
29
+ {"patient_id": "P-001", "risk_score": 0.82, "retok_prob": 0.71,
30
+ "active_modalities": ["text", "image", "audio", "ehr"]},
31
+ {"patient_id": "P-002", "risk_score": 0.45, "retok_prob": 0.30,
32
+ "active_modalities": ["text", "ehr"]},
33
+ {"patient_id": "P-003", "risk_score": 0.15, "retok_prob": 0.10,
34
+ "active_modalities": ["ehr"]},
35
+ {"patient_id": "P-004", "risk_score": 0.61, "retok_prob": 0.58,
36
+ "active_modalities": ["text", "audio"]},
37
+ ]
38
+ results = planner.batch_plan(records)
39
+ for r in results:
40
+ print(planner.summary(r))
41
+ return results
42
+
43
+
44
+ def demo_pipeline():
45
+ fedcrdt_out = {"patient_id": "P-0099", "risk_score": 0.67, "retok_prob": 0.61}
46
+ encoder_out = {"risk_score": 0.70}
47
+ merged_risk = 0.5 * fedcrdt_out["risk_score"] + 0.5 * encoder_out["risk_score"]
48
+
49
+ planner = ExposureGuardDAGPlanner(risk_threshold=0.20, budget=1.0)
50
+ result = planner.plan(
51
+ risk_score=merged_risk,
52
+ retok_prob=fedcrdt_out["retok_prob"],
53
+ active_modalities=["text", "image", "ehr"],
54
+ patient_id=fedcrdt_out["patient_id"],
55
+ )
56
+ print("\n--- Pipeline demo ---")
57
+ print(planner.summary(result))
58
+ return result
59
+
60
+
61
+ if __name__ == "__main__":
62
+ print("=== Single ===")
63
+ demo_single()
64
+ print("\n=== Batch ===")
65
+ demo_batch()
66
+ demo_pipeline()