Repository navigation
Expand file tree
/
Copy pathkgfm_zero_shot.py
More file actions
282 lines (263 loc) · 15.3 KB
/
Copy pathkgfm_zero_shot.py
File metadata and controls
282 lines (263 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""Run frozen KGFM entity evaluation with DICE's existing loader and ranking.
Example: python benchmarks/kgfm_zero_shot.py --model Flock --dataset Countries-S1
Progress is saved after each evaluation batch; identical runs resume safely.
"""
# ruff: noqa: E402
# The source checkout must precede installed packages when run as a script.
import argparse
import hashlib
import json
import logging
import os
import platform
import resource
import shlex
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import torch
from dicee.evaluation._filtering import TIE_POLICIES
from dicee.evaluation._graph_inference import GraphRankPlan
from dicee.evaluation.link_prediction import evaluate_lp
from dicee.knowledge_graph import KG
from dicee.models import TRIX, ULTRA, Flock
MODELS = {"ULTRA": ULTRA, "TRIX": TRIX, "Flock": Flock}
CHECKPOINTS = {
"ULTRA": "checkpoints/ultra_3g.pth",
"TRIX": "checkpoints/trix/entity_prediction.pth",
"Flock": "checkpoints/flock/flock_entity.pth",
}
METRICS = ("MRR", "H@1", "H@3", "H@10")
def digest(path):
with open(path, "rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def write_json(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(json.dumps(value, indent=2) + "\n")
temporary.replace(path)
def check_split_overlap(train, valid, test, *, allow=False):
"""Count distinct shared facts; require an explicit override for test leakage."""
facts = [set(map(tuple, split.tolist())) for split in (train, valid, test)]
counts = {
"train_valid": len(facts[0] & facts[1]),
"train_test": len(facts[0] & facts[2]),
"valid_test": len(facts[1] & facts[2]),
}
if counts["train_test"] and not allow:
raise ValueError("Training and test facts overlap; use --allow-test-overlap "
"only to report original-split results with explicit leakage")
return counts
# Author-provided 50g training configuration:
# https://github.com/DeepGraphLearning/ULTRA/issues/15#issuecomment-2024326922
ULTRA_50G_GRAPHS = frozenset((
'FB15k237', 'WN18RR', 'CoDExMedium', 'NELL995',
'YAGO310', 'DBpedia100k', 'AristoV4', 'Hetionet',
'WDsinger', 'CoDExSmall', 'NELL23k', 'ConceptNet100k',
'FB15k237_10', 'FB15k237Inductive:v1', 'FB15k237Inductive:v2', 'FB15k237Inductive:v3',
'FB15k237Inductive:v4', 'WN18RRInductive:v1', 'WN18RRInductive:v2', 'WN18RRInductive:v3',
'WN18RRInductive:v4', 'NELLInductive:v1', 'NELLInductive:v2', 'NELLInductive:v3',
'NELLInductive:v4', 'ILPC2022:small', 'ILPC2022:large', 'FBIngram:25',
'FBIngram:50', 'FBIngram:75', 'FBIngram:100', 'WKIngram:25',
'WKIngram:50', 'WKIngram:75', 'WKIngram:100', 'NLIngram:0',
'NLIngram:25', 'NLIngram:50', 'NLIngram:75', 'NLIngram:100',
'WikiTopicsMT1:tax', 'WikiTopicsMT1:health', 'WikiTopicsMT2:org', 'WikiTopicsMT2:sci',
'WikiTopicsMT3:art', 'WikiTopicsMT3:infra', 'WikiTopicsMT4:sci', 'WikiTopicsMT4:health',
'Metafam:None', 'FBNELL:None',
))
def pretraining_status(model, variant, dataset):
dataset = {"FB15k-237": "FB15k237", "CoDEx-Medium": "CoDExMedium",
"YAGO3-10": "YAGO310", "NELL-995": "NELL995"}.get(dataset, dataset)
if model == "ULTRA" and variant in ("4g", "50g") and dataset.startswith("NELL-995-"):
# Exact triples audited against RED-GNN's facts.txt + train.txt; see the protocol.
if dataset in ("NELL-995-h25", "NELL-995-h50", "NELL-995-h75", "NELL-995-h100"):
return "yes"
return "related"
if model == "ULTRA" and variant == "50g":
return "yes" if dataset in ULTRA_50G_GRAPHS else "no"
if dataset in ("FB15k237", "WN18RR", "CoDExMedium"):
return "yes"
if model == "ULTRA" and variant == "4g" and dataset == "NELL995":
return "yes"
return "no"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", choices=MODELS, required=True)
parser.add_argument("--dataset", required=True)
parser.add_argument("--ultra-checkpoint", choices=("3g", "4g", "50g"), default="3g")
parser.add_argument("--allow-test-overlap", action="store_true",
help="Keep original splits despite training/test leakage; record overlap in the report")
parser.add_argument("--device", default="cpu")
parser.add_argument("--batch-size", type=int, default=128)
parser.add_argument("--query-batch-size", type=int, default=1)
parser.add_argument("--threads", type=int, default=4)
parser.add_argument("--walk-num", type=int, default=128)
parser.add_argument("--test-samples", type=int, default=1)
parser.add_argument('--inference-backend', choices=['auto', 'torch', 'triton'], default='auto')
parser.add_argument('--relation-cache-mb', type=int, default=64)
parser.add_argument('--projection-cache-mb', type=int, default=64)
parser.add_argument('--compile-inference', action=argparse.BooleanOptionalAction, default=False)
parser.add_argument('--compact-state', action=argparse.BooleanOptionalAction, default=True)
parser.add_argument('--compile-sampler', action=argparse.BooleanOptionalAction, default=True)
parser.add_argument('--pack-walks', action=argparse.BooleanOptionalAction, default=True)
parser.add_argument('--reuse-queries', action=argparse.BooleanOptionalAction, default=True)
parser.add_argument('--prefetch-walks', action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--tie-policy", choices=TIE_POLICIES, default="sort")
parser.add_argument("--tie-seed", type=int, default=None,
help="Independent random tie seed; defaults to --seed")
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
if args.model != "ULTRA" and args.ultra_checkpoint != "3g":
parser.error("--ultra-checkpoint applies only to ULTRA")
if args.tie_seed is None:
args.tie_seed = args.seed
if min(args.batch_size, args.query_batch_size, args.threads, args.walk_num, args.test_samples) < 1:
parser.error("Batch sizes, threads, and sampling counts must be positive")
if min(args.relation_cache_mb, args.projection_cache_mb) < 0:
parser.error('Graph cache sizes must be nonnegative')
os.chdir(ROOT)
torch.set_num_threads(args.threads)
torch.manual_seed(args.seed)
if hasattr(torch.backends.cuda.matmul, 'fp32_precision'):
torch.backends.cuda.matmul.fp32_precision = 'ieee'
torch.backends.mkldnn.matmul.fp32_precision = 'ieee'
torch.backends.cudnn.conv.fp32_precision = 'ieee'
torch.backends.cudnn.rnn.fp32_precision = 'ieee'
else:
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cudnn.benchmark = False
device = torch.device(args.device)
if device.type == "cuda" and not torch.cuda.is_available():
raise RuntimeError("CUDA was requested but is unavailable")
logging.basicConfig(level=logging.WARNING)
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=True)
dataset_dir = ROOT / "KGs" / args.dataset
checkpoint = ROOT / (f"checkpoints/ultra_{args.ultra_checkpoint}.pth"
if args.model == "ULTRA" else CHECKPOINTS[args.model])
model_label = f"ULTRA-{args.ultra_checkpoint}" if args.model == "ULTRA" else args.model
pretraining = pretraining_status(args.model, args.ultra_checkpoint, args.dataset)
sources = sorted((ROOT / "dicee").rglob("*.py")) + [Path(__file__).resolve()]
cpu_name = next((line.split(":", 1)[1].strip() for line in
Path("/proc/cpuinfo").read_text().splitlines() if line.startswith("model name")), "unknown")
config = {
**{k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()},
"model_label": model_label, "pretraining_status": pretraining,
"checkpoint": str(checkpoint.relative_to(ROOT)),
"checkpoint_sha256": digest(checkpoint),
"split_sha256": {name: digest(dataset_dir / f"{name}.txt") for name in ("train", "valid", "test")},
"source_sha256": {str(path.relative_to(ROOT)): digest(path) for path in sources},
"git_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
"torch": torch.__version__, "python": platform.python_version(),
"cuda": torch.version.cuda, "cudnn": torch.backends.cudnn.version(),
"hardware": torch.cuda.get_device_name(device) if device.type == "cuda" else cpu_name,
"cpu": cpu_name, "dtype": "float32", "tf32": False,
"num_epochs": 0, "optimizer_updates": 0,
"inference_edges": "train plus generated inverses, deduplicated",
"filter_positives": ["train", "valid", "test"],
"candidates": "all entities in the combined split vocabulary",
"directions": ["head", "tail"], "tie_policy": args.tie_policy,
"flock_walk_len": 128, "flock_refinements": 6,
}
config_path = output / "configuration.json"
if config_path.exists() and json.loads(config_path.read_text()) != config:
raise RuntimeError(f"Configuration/source changed; use a new output directory: {output}")
write_json(config_path, config)
(output / "command.txt").write_text(shlex.join([sys.executable, *sys.argv]) + "\n")
if (output / "result.json").exists():
print((output / "result.json").read_text(), flush=True)
return
start = time.perf_counter()
kg = KG(dataset_dir=str(dataset_dir), add_reciprocal=False, eval_model="test",
training_technique="NegSample", separator=r"\s+", backend="pandas",
path_for_serialization=str(output))
if kg.valid_set is None or kg.test_set is None or not len(kg.test_set):
raise ValueError("The benchmark requires nonempty test and available validation splits")
overlap = check_split_overlap(kg.train_set, kg.valid_set, kg.test_set,
allow=args.allow_test_overlap)
write_json(output / "split_overlap.json", overlap)
if overlap["train_test"]:
logging.warning("Original-split evaluation includes %d distinct test facts in the "
"inference graph; these results contain leakage", overlap["train_test"])
settings = dict(num_entities=kg.num_entities, num_relations=kg.num_relations,
**{f"{args.model.lower()}_query_batch_size": args.query_batch_size},
flock_walk_num=args.walk_num, flock_test_samples=args.test_samples,
flock_seed=args.seed, flock_prefetch_walks=args.prefetch_walks,
graph_inference_backend=args.inference_backend, graph_relation_cache_mb=args.relation_cache_mb,
graph_projection_cache_mb=args.projection_cache_mb, graph_inference_compile=args.compile_inference,
flock_compact_state=args.compact_state, flock_compile_sampler=args.compile_sampler,
flock_pack_walks=args.pack_walks)
model = MODELS[args.model](settings).load_pretrained(checkpoint)
model.set_graph(kg.train_set).eval().requires_grad_(False)
initial_weights = {key: value.clone() for key, value in model.state_dict().items()}
model.to(device)
er_vocab = kg.er_vocab if isinstance(kg.er_vocab, dict) else kg.er_vocab.result()
re_vocab = kg.re_vocab if isinstance(kg.re_vocab, dict) else kg.re_vocab.result()
# Persist filter vocabularies to permit independent evaluation of the run.
import pickle
for name, vocab in (("er_vocab", er_vocab), ("re_vocab", re_vocab)):
with (output / f"{name}.p").open("wb") as stream:
pickle.dump(vocab, stream)
progress_path = output / "progress.json"
progress = json.loads(progress_path.read_text()) if progress_path.exists() else {}
batches = progress.get("batches", [])
tie_generator = None
if args.tie_policy == "random":
tie_generator = torch.Generator(device="cpu").manual_seed(args.tie_seed)
if batches:
tie_generator.set_state(torch.tensor(progress["tie_rng_state"], dtype=torch.uint8))
completed = sum(batch["triples"] for batch in batches)
rank_plan = (GraphRankPlan(kg.test_set[completed:])
if args.reuse_queries and getattr(model, 'deterministic_inference', False) else None)
if device.type == "cuda":
torch.cuda.synchronize(device)
torch.cuda.reset_peak_memory_stats(device)
print(f"START {args.model} {args.dataset}: {completed}/{len(kg.test_set)} test triples; {device}", flush=True)
with torch.no_grad():
for offset in range(completed, len(kg.test_set), args.batch_size):
triples = kg.test_set[offset:offset + args.batch_size]
batch_start = time.perf_counter()
scores = evaluate_lp(model, triples, kg.num_entities, er_vocab, re_vocab,
batch_size=args.batch_size, tie_policy=args.tie_policy,
tie_seed=args.tie_seed, tie_generator=tie_generator,
graph_rank_plan=rank_plan, reuse_graph_queries=args.reuse_queries)
if device.type == "cuda":
torch.cuda.synchronize(device)
batches.append({"offset": offset, "triples": len(triples), "metrics": scores,
"seconds": time.perf_counter() - batch_start})
completed += len(triples)
progress = {"completed": completed, "total": len(kg.test_set), "batches": batches}
if tie_generator is not None:
progress["tie_rng_state"] = tie_generator.get_state().tolist()
write_json(progress_path, progress)
print(f"PROGRESS {args.model} {args.dataset}: {completed}/{len(kg.test_set)}", flush=True)
for key, value in model.state_dict().items():
if not torch.equal(value.cpu(), initial_weights[key]):
raise AssertionError(f"Frozen weights changed: {key}")
metrics = {key: sum(batch["metrics"][key] * batch["triples"] for batch in batches) / len(kg.test_set)
for key in METRICS}
result = {
"status": "complete", "dataset": args.dataset, "model": args.model,
"split_overlap": overlap, "test_facts_in_inference_graph": bool(overlap["train_test"]),
"model_label": model_label, "pretraining_status": pretraining,
"target_graph_in_pretraining": {"yes": True, "no": False}.get(pretraining),
"test_triples": len(kg.test_set), "ranked_queries": 2 * len(kg.test_set),
"num_entities": kg.num_entities, "num_relations": kg.num_relations,
"inference_edges": model.edge_type.numel(), "metrics": metrics,
"evaluation_seconds": sum(batch["seconds"] for batch in batches),
"invocation_seconds": time.perf_counter() - start,
"peak_process_rss_mib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024,
"peak_cuda_allocated_mib": torch.cuda.max_memory_allocated(device) / 2**20 if device.type == "cuda" else None,
"weights_unchanged": True, "configuration": config,
}
write_json(output / "eval_report.json", {"Test": metrics})
write_json(output / "result.json", result)
print(f"COMPLETE {args.model} {args.dataset}: {json.dumps(metrics)}", flush=True)
if __name__ == "__main__":
main()